"""
Advance/OF-DFT example: surface energy of fcc Al from slab calculations.

    gamma = (E_slab(N) - N * E_bulk) / (2 A)    N: number of atoms in the slab

E_bulk is calculated with a bulk cell that has the orientation of the slab, with
the same SCF parameters as the slabs, so that the slab and bulk energies are
consistent. It is compared with the slope of a linear fit of E_slab against N.

Copyright (C) 2026 AdvanceSoft Corporation, All rights reserved.
"""

import numpy as np
from ase.build import fcc100, fcc110, fcc111

from aofdft.calculator import AOFDFTCalculator

VPS_DIR = "path/to/DFT_DATA19_AS/VPS"  # edit these two paths for your environment
PAO_DIR = "path/to/DFT_DATA19_AS/PAO"

A_LAT  = 4.05   # lattice constant of fcc Al (Angstrom)
EV_A2  = 16.0218  # 1 eV/Angstrom^2 = 16.0218 J/m^2


def energy(atoms, label):
    atoms.calc = AOFDFTCalculator(
        console       = False,
        logging_file  = f"{label}.log",
        kin_type      = "AS26",
        kin_model     = "Crystal26",
        vps_dir       = VPS_DIR,
        pao_dir       = PAO_DIR,
        scf_must_conv = True,
        scf_style     = "bulk",  # the preset for bulk crystals also suits these metal slabs
        mix_precond   = None,    # without the Thomas-Fermi preconditioner of the preset
    )
    return atoms.get_potential_energy()


# (surface, builder, number of layers of the bulk cell: a multiple of the stacking period)
for name, build, n_bulk in (("111", fcc111, 6), ("100", fcc100, 4), ("110", fcc110, 6)):
    # bulk energy per atom: a bulk cell with the same orientation as the slab (periodic=True
    # makes the cell periodic along the surface normal), calculated with the same settings
    bulk_cell = build("Al", size=(2, 2, n_bulk), a=A_LAT, periodic=True)
    e_bulk = energy(bulk_cell, f"al{name}_bulk") / len(bulk_cell)

    n_layers, n_atoms, energies = [], [], []
    for n in (4, 6, 8):
        slab = build("Al", size=(2, 2, n), a=A_LAT, vacuum=8.0)  # 2x2 in the surface plane
        n_layers.append(n)
        n_atoms.append(len(slab))
        energies.append(energy(slab, f"al{name}_{n}"))

    area = np.linalg.norm(np.cross(slab.cell[0], slab.cell[1]))  # Angstrom^2

    print(f"\nAl({name})  area = {area:.3f} A^2, E_bulk = {e_bulk:.4f} eV/atom")
    print("  layers | atoms | E_slab (eV)  | gamma (J/m^2)")
    for n, n_at, e in zip(n_layers, n_atoms, energies):
        gamma = (e - n_at * e_bulk) / (2.0 * area) * EV_A2
        print(f"  {n:6d} | {n_at:5d} | {e:12.4f} | {gamma:.3f}")

    # check with a linear fit: E_slab(N) = N * E_bulk + 2 * gamma * A
    e_bulk_fit, intercept = np.polyfit(n_atoms, energies, 1)
    gamma_fit = intercept / (2.0 * area) * EV_A2
    print(f"  fit: E_bulk = {e_bulk_fit:.4f} eV/atom, gamma = {gamma_fit:.3f} J/m^2", flush=True)
