"""
Advance/OF-DFT example: deformation density (SCF density minus superposed atomic densities).

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

import matplotlib.pyplot as plt
import numpy as np
from ase.build import bulk
from ase.io.cube import 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"

a     = 5.43
atoms = bulk("Si", crystalstructure="diamond", a=a, cubic=True)

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

calc = atoms.calc

# SCF electron density
rho_scf = calc.rho[0].detach().cpu().numpy()

# superposition of the neutral atomic densities on the same grid
rho_atom = calc.aofdft.charge_density.neutral_density().detach().cpu().numpy()

# deformation density: where electrons accumulate (> 0) or deplete (< 0) by bonding
delta = rho_scf - rho_atom

dv = atoms.get_volume() / Bohr**3 / delta.size  # volume of a grid cell (Bohr^3)
print(f"Integral of SCF density    : {rho_scf.sum() * dv:.6f}")
print(f"Integral of atomic density : {rho_atom.sum() * dv:.6f}")
print(f"Electrons moved by bonding : {0.5 * np.abs(delta).sum() * dv:.4f}")

with open("si_deformation.cube", "w") as f:
    write_cube(f, atoms, data=delta, comment="Deformation density (e/Bohr^3) by Advance/OF-DFT")
print("Saved si_deformation.cube")

# 2D map on the (1-10) plane (x = y), which contains the Si-Si bonds
na, nb, nc = delta.shape
idx   = np.arange(na)
plane = delta[idx, idx, :]
plane = np.vstack([plane, plane[:1]])
plane = np.hstack([plane, plane[:, :1]])

u = np.linspace(0.0, a * np.sqrt(2.0), na + 1)
z = np.linspace(0.0, a, nc + 1)
vmax = np.abs(plane).max()

fig, ax = plt.subplots(figsize=(6.4, 4.6))
cs = ax.contourf(u, z, plane.T, levels=np.linspace(-vmax, vmax, 25), cmap="RdBu_r")
fig.colorbar(cs, ax=ax, label=r"Deformation density ($e$/Bohr$^3$)")

for p in atoms.positions:
    if abs(p[0] - p[1]) < 1.0e-6:
        for du in (0.0, a * np.sqrt(2.0)):
            for dz in (0.0, a):
                uu, zz = p[0] * np.sqrt(2.0) + du, p[2] + dz
                if uu <= u[-1] + 1.0e-6 and zz <= z[-1] + 1.0e-6:
                    ax.plot(uu, zz, "o", color="black", markersize=6)

ax.set_xlabel("[110] (Angstrom)")
ax.set_ylabel("[001] (Angstrom)")
ax.set_aspect("equal")
fig.tight_layout()
fig.savefig("si_deformation_plane.png", dpi=150)
print("Saved si_deformation_plane.png")
