"""
Advance/OF-DFT example: adsorption energy and preferred site of Na on Al(111).

The slab is relaxed with the bottom layers fixed (FixAtoms). The lateral
position of the adsorbate is fixed (FixCartesian) so that each site is kept.

    E_ads = E(slab + Na) - E(slab) - E(Na, bcc bulk per atom)

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

from ase.build import add_adsorbate, bulk, fcc111
from ase.constraints import FixAtoms, FixCartesian
from ase.optimize import BFGS

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"

N_LAYERS = 4  # Al layers; the bottom 2 layers are fixed
FMAX     = 0.05  # convergence of the structure optimization (eV/Angstrom)


def attach_calc(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
    )


def make_slab():
    slab = fcc111("Al", size=(3, 3, N_LAYERS), a=4.05, vacuum=8.0)  # 3x3 in the surface plane, 36 atoms
    # fix the bottom two layers (tag 1 = top layer, tag N_LAYERS = bottom layer)
    slab.set_constraint(FixAtoms(mask=slab.get_tags() > N_LAYERS - 2))
    return slab


# 1) reference: bulk Na (bcc) per atom, in a 2x2x2 repetition of the cubic cell (16 atoms)
na_bulk = bulk("Na", "bcc", a=4.23, cubic=True).repeat((2, 2, 2))
attach_calc(na_bulk, "na_bulk")
e_na = na_bulk.get_potential_energy() / len(na_bulk)

# 2) clean slab, relaxed
slab = make_slab()
attach_calc(slab, "al111_clean")
BFGS(slab, logfile="al111_clean_opt.log").run(fmax=FMAX)
e_slab = slab.get_potential_energy()

# 3) Na on each site, relaxed
print(" site   | E_ads (eV) | rel. (eV) | height (A)")
results = {}
for site in ("ontop", "bridge", "fcc", "hcp"):
    atoms = make_slab()
    add_adsorbate(atoms, "Na", height=2.5, position=site)
    i_na = len(atoms) - 1
    atoms.set_constraint([atoms.constraints[0], FixCartesian(i_na, mask=(True, True, False))])

    attach_calc(atoms, f"na_{site}")
    BFGS(atoms, logfile=f"na_{site}_opt.log").run(fmax=FMAX)

    e_ads  = atoms.get_potential_energy() - e_slab - e_na
    height = atoms.positions[i_na, 2] - atoms.positions[:-1, 2].max()
    results[site] = (e_ads, height)

e_min = min(e for e, _ in results.values())
for site, (e_ads, height) in results.items():
    print(f" {site:6s} | {e_ads:10.3f} | {e_ads - e_min:9.3f} | {height:6.2f}", flush=True)
