"""
Advance/OF-DFT example: save the electron density to a CUBE file.

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

from ase.build import bulk
from ase.io.cube import read_cube_data, write_cube
from ase.units import Bohr

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("Si", crystalstructure="diamond", a=5.43, cubic=True)

atoms.calc = AOFDFTCalculator(
    console      = False,
    logging_file = "si_density.log",
    kin_type     = "AS26",
    kin_model    = "Crystal26",
    vps_dir      = VPS_DIR,
    pao_dir      = PAO_DIR,
)

# run SCF
atoms.get_potential_energy()

# electron density on the FFT grid: torch.Tensor of shape (n_rho, na, nb, nc), in electrons/Bohr^3
rho = atoms.calc.rho
print(f"Shape of rho       : {tuple(rho.shape)}")

# rho[0] is the total electron density; convert torch.Tensor -> numpy.ndarray
density = rho[0].detach().cpu().numpy()

# sanity check: the density integrates to the number of valence electrons
volume = atoms.get_volume() / Bohr**3  # Bohr^3
print(f"Number of electrons: {density.mean() * volume:.6f}")
print(f"Max. / min. density: {density.max():.5f} / {density.min():.5f} e/Bohr^3")

# save in the Gaussian CUBE format (readable by NanoLabo, VESTA, VMD, ...)
with open("si_density.cube", "w") as f:
    write_cube(f, atoms, data=density, comment="Electron density (e/Bohr^3) by Advance/OF-DFT")
print("Saved si_density.cube")

# read the file back with ASE
data, atoms_read = read_cube_data("si_density.cube")
print(f"Read back          : grid {data.shape}, {len(atoms_read)} atoms")
