"""
Advance/OF-DFT example: vacancy formation energy of fcc Al.

    E_f = E(N-1 atoms, with vacancy) - (N-1)/N * E(N atoms, perfect)

The supercell size is increased to check the convergence of E_f,
and the atoms around the vacancy are relaxed with an ASE optimizer.

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

import time

from ase.build import bulk
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"

A_LAT = 4.05  # lattice constant of fcc Al (Angstrom)


def make_calc(label):
    return 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,  # stop if the SCF does not converge
    )


print(" size  N  | E_f unrelaxed | E_f relaxed |  time")
for n in (3, 4, 5):
    t0 = time.perf_counter()

    # perfect supercell: n x n x n primitive cells (n^3 atoms)
    perfect = bulk("Al", "fcc", a=A_LAT).repeat((n, n, n))
    perfect.calc = make_calc(f"al_perfect_{n}")
    e_perfect = perfect.get_potential_energy()
    n_atoms = len(perfect)

    # remove one atom -> vacancy
    vacancy = perfect.copy()
    del vacancy[0]
    vacancy.calc = make_calc(f"al_vacancy_{n}")
    e_unrelaxed = vacancy.get_potential_energy()

    # relax the atomic positions (the cell is kept fixed)
    BFGS(vacancy, logfile=f"al_vacancy_{n}_opt.log").run(fmax=0.05)
    e_relaxed = vacancy.get_potential_energy()

    ef_unrelaxed = e_unrelaxed - (n_atoms - 1) / n_atoms * e_perfect
    ef_relaxed   = e_relaxed   - (n_atoms - 1) / n_atoms * e_perfect
    print(f" {n}x{n}x{n} {n_atoms:4d} | {ef_unrelaxed:10.3f} eV | {ef_relaxed:8.3f} eV "
          f"| {time.perf_counter() - t0:5.0f} s", flush=True)
