"""
Advance/OF-DFT example: save the electron density and reuse it as the initial guess.

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

import re

import numpy as np
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"

params = dict(
    console   = False,
    kin_type  = "AS26",
    kin_model = "Crystal26",
    vps_dir   = VPS_DIR,
    pao_dir   = PAO_DIR,
)


def scf_iterations(log_file):
    """Number of SCF iterations written in the log file."""
    with open(log_file, encoding="utf-8") as f:
        found = re.findall(r"SCF converged in (\d+) iterations", f.read())
    return int(found[-1]) if found else None


# 1) converge the density once and save it as a NumPy file
atoms = bulk("Si", crystalstructure="diamond", a=5.43, cubic=True)
atoms.calc = AOFDFTCalculator(logging_file="si_first.log", **params)
atoms.get_potential_energy()

rho = atoms.calc.rho.detach().cpu().numpy()  # shape (n_rho, na, nb, nc)
np.save("si_rho.npy", rho)
print(f"Saved si_rho.npy, shape = {rho.shape}")

# 2) slightly displaced structure, starting from the superposition of atomic densities (default)
displaced = atoms.copy()
displaced.rattle(stdev=0.02, seed=1)

displaced.calc = AOFDFTCalculator(logging_file="si_atomic_guess.log", **params)
e_atomic = displaced.get_potential_energy()

# 3) the same structure, starting from the saved density:
#    set the `rho` property before the calculation
calc     = AOFDFTCalculator(logging_file="si_saved_guess.log", **params)
calc.rho = np.load("si_rho.npy")
displaced.calc = calc
e_saved = displaced.get_potential_energy()

print(f"Atomic guess : {scf_iterations('si_atomic_guess.log')} iterations, E = {e_atomic:.6f} eV")
print(f"Saved density: {scf_iterations('si_saved_guess.log')} iterations, E = {e_saved:.6f} eV")

# 4) a density on a different grid is interpolated automatically (here: a finer grid)
calc     = AOFDFTCalculator(logging_file="si_fine_grid.log", e_cut=250 * Hartree, **params)
calc.rho = np.load("si_rho.npy")
displaced.calc = calc
displaced.get_potential_energy()
print(f"Finer grid   : {scf_iterations('si_fine_grid.log')} iterations, "
      f"grid {rho.shape[1:]} -> {tuple(calc.rho.shape[1:])}")
