"""
Advance/OF-DFT example: compare AOF-DFT with Kohn-Sham DFT by OpenMX.

`CustomOpenMX` runs OpenMX with the same pseudopotentials, pseudo-atomic orbitals
and basis sets as AOFDFTCalculator. OpenMX must be installed separately and the
`openmx` command must be found in PATH.

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

import numpy as np
from ase.build import bulk

from aofdft.calculator import AOFDFTCalculator, CustomOpenMX

VPS_DIR = "path/to/DFT_DATA19_AS/VPS"  # edit these two paths for your environment
PAO_DIR = "path/to/DFT_DATA19_AS/PAO"

# parameters shared by both calculators
aofdft_params = {
    "console"  : False,
    "kin_type" : "AS26",
    "kin_model": "Crystal26",
    "vps_dir"  : VPS_DIR,
    "pao_dir"  : PAO_DIR,
}

# 1) AOF-DFT: one process with num_threads threads (cubic cell of Si, 8 atoms)
aof = bulk("Si", crystalstructure="diamond", a=5.43, cubic=True)
aof.calc = AOFDFTCalculator(logging_file="si_aofdft.log", num_threads=4, **aofdft_params)
e_aof   = aof.get_potential_energy()
rho_aof = aof.calc.rho.detach().cpu().numpy()

# 2) KS-DFT by OpenMX, on the same FFT grid: num_process MPI processes
ks = bulk("Si", crystalstructure="diamond", a=5.43, cubic=True)
ks.calc = CustomOpenMX(
    aofdft_params = aofdft_params,                 # converted to the OpenMX keywords
    label         = "omx_si",                      # working directory
    command       = "mpirun -np ${NP} openmx",     # ${NP} is replaced with num_process
    num_process   = 4,                             # number of MPI processes
    kpts          = 3.5,                           # k-point density
)
e_ks   = ks.get_potential_energy()
rho_ks = ks.calc.rho  # numpy.ndarray of shape (n_rho, na, nb, nc)

print(f"Fermi energy : AOF-DFT {aof.calc.e_fermi:8.4f} eV, KS-DFT {ks.calc.e_fermi:8.4f} eV")
print(f"SCF steps of KS-DFT: {ks.calc.scf_steps}")

# 3) normalized mean absolute error of the electron density
if rho_ks.shape == rho_aof.shape:
    nmae = np.abs(rho_aof[0] - rho_ks[0]).sum() / np.abs(rho_ks[0]).sum()
    print(f"Normalized MAE of the electron density: {nmae * 100.0:.2f} %")
else:
    print(f"Grids are different: AOF-DFT {rho_aof.shape}, KS-DFT {rho_ks.shape}")
