"""
Advance/OF-DFT example: optimize atomic positions and cell using the stress tensor.

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

from ase.build import bulk
from ase.io import write
from ase.optimize import BFGS
from ase.units import GPa

try:
    from ase.filters import FrechetCellFilter as CellFilter  # ASE >= 3.23
except ImportError:
    from ase.constraints import ExpCellFilter as CellFilter

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"

atoms = bulk("Al", "fcc", a=4.05).repeat((3, 3, 3))  # 3x3x3 primitive cells, 27 atoms

atoms.calc = AOFDFTCalculator(
    console         = False,
    logging_file    = "al_cell_opt.log",
    kin_type        = "AS26",
    kin_model       = "Crystal26",
    vps_dir         = VPS_DIR,
    pao_dir         = PAO_DIR,
    max_cell_strain = 0.05,  # the FFT grid is rebuilt when the cell deforms more than this
)

# forces and stress are obtained by automatic differentiation
stress = atoms.get_stress()  # Voigt order (xx, yy, zz, yz, xz, xy), eV/Angstrom^3
print(f"Initial pressure: {-stress[:3].mean() / GPa:8.3f} GPa")

# relax the cell and the positions at the same time
opt = BFGS(CellFilter(atoms), logfile="al_cell_opt.txt")
opt.run(fmax=0.02, steps=50)

a, b, c, alpha, beta, gamma = atoms.cell.cellpar()
stress = atoms.get_stress()
print(f"Final pressure  : {-stress[:3].mean() / GPa:8.3f} GPa")
print(f"Cell lengths    : {a:.4f} {b:.4f} {c:.4f} Angstrom")
print(f"Cell angles     : {alpha:.2f} {beta:.2f} {gamma:.2f} deg")
volume = atoms.get_volume() / len(atoms)
print(f"Volume          : {volume:.3f} Angstrom^3/atom")
print(f"Lattice constant: {(4.0 * volume) ** (1.0 / 3.0):.3f} Angstrom (of the cubic fcc cell)")

write("al_optimized.cif", atoms)
