"""
Advance/OF-DFT example: energy-volume curve and bulk modulus.

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

import numpy as np
from ase.build import bulk
from ase.eos import EquationOfState
from ase.units import GPa

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"

# fcc Al: 2x2x2 repetition of the primitive cell (8 atoms)
reference = bulk("Al", "fcc", a=4.05).repeat((2, 2, 2))

volumes, energies = [], []

for scale in np.linspace(0.94, 1.06, 7):  # scaling factor of the lattice constant
    atoms = reference.copy()
    atoms.set_cell(reference.cell * scale, scale_atoms=True)

    atoms.calc = AOFDFTCalculator(
        console      = False,
        logging_file = f"al_{scale:.2f}.log",
        kin_type     = "AS26",
        kin_model    = "Crystal26",
        vps_dir      = VPS_DIR,
        pao_dir      = PAO_DIR,
    )

    volumes.append(atoms.get_volume() / len(atoms))             # per atom
    energies.append(atoms.get_potential_energy() / len(atoms))  # per atom
    print(f"V = {volumes[-1]:7.3f} Angstrom^3/atom, E = {energies[-1]:.5f} eV/atom")

# fit the equation of state
eos = EquationOfState(volumes, energies, eos="birchmurnaghan")
v0, e0, B = eos.fit()

print(f"Equilibrium volume : {v0:.3f} Angstrom^3/atom")
print(f"Lattice constant   : {(4.0 * v0) ** (1.0 / 3.0):.3f} Angstrom")
print(f"Bulk modulus       : {B / GPa:.1f} GPa")

ax = eos.plot()
ax.set_xlabel("Volume (Angstrom^3/atom)")
ax.set_ylabel("Energy (eV/atom)")
ax.figure.tight_layout()
ax.figure.savefig("al_eos.png", dpi=150)
print("Saved al_eos.png")
