"""
Advance/OF-DFT example: Fermi energy and smearing.

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

from ase.build import bulk
from ase.units import Hartree

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_FCC = 4.05                        # lattice constant of fcc Al (angstrom)
A_BCC = A_FCC / 2.0 ** (1.0 / 3.0)  # bcc Al with the same volume per atom

# (smearing method, width in Hartree)
# In general, use the default in your own calculations. The other settings are listed only
# to show that the results depend on the setting.
settings = [
    ("fermi", 0.02),  # default: Fermi-Dirac, 0.02 Hartree
    ("fermi", 0.01),
    ("gauss", 0.01),  # Gaussian
    ("m-p",   0.01),  # Methfessel-Paxton
    ("m-v",   0.01),  # Marzari-Vanderbilt
]


def calculate(structure, a, smearing, width):
    """Return the total energy and the -TS term per atom, and the Fermi energy of bulk Al (all in eV)."""
    atoms = bulk("Al", structure, a=a).repeat((3, 3, 3))  # 27 atoms

    atoms.calc = AOFDFTCalculator(
        console      = False,
        logging_file = f"al_{structure}_{smearing}_{width}.log",
        kin_type     = "AS26",
        kin_model    = "Crystal26",
        vps_dir      = VPS_DIR,
        pao_dir      = PAO_DIR,
        smearing     = smearing,
        degauss      = width * Hartree,  # smearing width in eV
    )

    energy = atoms.get_potential_energy()  # includes the smearing correction -TS
    calc   = atoms.calc

    return energy / len(atoms), calc.smeared_energy / len(atoms), calc.e_fermi


# E and -TS (per atom) and E_F are the values of fcc Al; the last column is the energy difference bcc - fcc
print(f"{'smearing':8s} {'width/Ha':>8s} {'E (eV/atom)':>13s} {'-TS (eV/atom)':>14s} {'E_F (eV)':>9s} {'bcc - fcc (meV/atom)':>21s}")

for smearing, width in settings:
    e_fcc, minus_ts, e_fermi = calculate("fcc", A_FCC, smearing, width)
    e_bcc, _, _              = calculate("bcc", A_BCC, smearing, width)

    print(f"{smearing:8s} {width:8.3f} {e_fcc:13.6f} {minus_ts:14.6f} {e_fermi:9.4f} {(e_bcc - e_fcc) * 1000.0:21.1f}")
