"""
Advance/OF-DFT example: dipole moment of a molecule from the electron density.

    mu = sum_A Z_A R_A - integral r rho(r) dr

Z_A is the valence charge of the pseudo-atom A.

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

import numpy as np
from ase.build import molecule
from ase.units import Bohr, Debye

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"

# isolated molecule at the centre of a box: propyne (CH3-CCH), with the molecular axis along z
atoms = molecule("C3H4_C3v")
atoms.center(vacuum=4.0)

atoms.calc = AOFDFTCalculator(
    console      = False,
    logging_file = "propyne.log",
    kin_type     = "AS26",
    kin_model    = "Molecule26",
    vps_dir      = VPS_DIR,
    pao_dir      = PAO_DIR,
    scf_style    = "molecule",
)
atoms.get_potential_energy()

calc    = atoms.calc
density = calc.rho[0].detach().cpu().numpy()  # e/Bohr^3

# Cartesian coordinates of the grid points (Angstrom)
grids = [np.arange(n) / n for n in density.shape]
frac  = np.stack(np.meshgrid(*grids, indexing="ij"), axis=-1)
r     = frac @ atoms.cell.array

dv = atoms.get_volume() / Bohr**3 / density.size  # volume of a grid cell (Bohr^3)

# valence charge of each pseudo-atom
species = calc.aofdft.atomic_data.species
zval    = np.array([float(species(symbol).zval) for symbol in atoms.get_chemical_symbols()])

n_elec     = density.sum() * dv
mu_ion     = (zval[:, None] * atoms.positions).sum(axis=0)
mu_elec    = -(density[..., None] * r).sum(axis=(0, 1, 2)) * dv
mu         = mu_ion + mu_elec  # e * Angstrom

print(f"Valence charges      : {dict(zip(atoms.get_chemical_symbols(), zval.tolist()))}")
print(f"Number of electrons  : {n_elec:.6f}")
print(f"Dipole vector (Debye): {np.round(mu / Debye, 3)}")
print(f"Dipole moment        : {np.linalg.norm(mu) / Debye:.3f} Debye")
