"""
Advance/OF-DFT example: convergence with respect to the cutoff energy.

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

import matplotlib.pyplot as plt
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"

cutoffs  = [50, 100, 150, 200, 250, 300]  # Hartree
energies = []

for e_cut in cutoffs:
    atoms = bulk("Si", crystalstructure="diamond", a=5.43, cubic=True)  # 8 atoms

    atoms.calc = AOFDFTCalculator(
        console      = False,
        logging_file = f"si_ecut{e_cut}.log",
        kin_type     = "AS26",
        kin_model    = "Crystal26",
        vps_dir      = VPS_DIR,
        pao_dir      = PAO_DIR,
        e_cut        = e_cut * Hartree,  # e_cut is given in eV
    )

    energy = atoms.get_potential_energy() / len(atoms)
    energies.append(energy)

    # the FFT grid that was generated from e_cut
    n_grids = atoms.calc.aofdft.lattice.n_grids
    print(f"e_cut = {e_cut:4d} Ha  grid = {n_grids}  E = {energy:.6f} eV/atom")

# energy difference from the largest cutoff, in meV/atom
diffs = [(e - energies[-1]) * 1000.0 for e in energies]

plt.plot(cutoffs, diffs, marker="o")
plt.axhline(0.0, color="gray", linewidth=0.8)
plt.xlabel("Cutoff energy (Hartree)")
plt.ylabel("E - E(300 Ha) (meV/atom)")
plt.tight_layout()
plt.savefig("si_cutoff_convergence.png", dpi=150)
print("Saved si_cutoff_convergence.png")
