"""
Advance/OF-DFT example: charge redistribution by adsorption.

    delta_rho = rho(slab + adsorbate) - rho(slab) - rho(adsorbate)

The three densities must be defined on the same FFT grid, so the grid of the
first calculation is reused with `n_grids`.

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

import matplotlib.pyplot as plt
import numpy as np
from ase.build import add_adsorbate, fcc111
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"

params = dict(
    console     = False,
    kin_type    = "AS26",
    kin_model   = "Crystal26",
    vps_dir     = VPS_DIR,
    pao_dir     = PAO_DIR,
    scf_style   = "bulk",  # the preset for bulk crystals also suits this metal slab
    mix_precond = None,    # without the Thomas-Fermi preconditioner of the preset
)

# Na on Al(111): 4 Al layers, 3x3 in the surface plane (36 Al atoms),
# and one Na atom on the fcc hollow site
total = fcc111("Al", size=(3, 3, 4), a=4.05, vacuum=8.0)
add_adsorbate(total, "Na", height=2.6, position="fcc")

is_ads    = np.array([atom.symbol == "Na" for atom in total])
substrate = total[~is_ads]  # same cell, Al atoms only
adsorbate = total[is_ads]   # same cell, Na atoms only


def electron_density(atoms, label, **kwargs):
    atoms.calc = AOFDFTCalculator(logging_file=f"{label}.log", **params, **kwargs)
    atoms.get_potential_energy()
    return atoms.calc.rho[0].detach().cpu().numpy()


# 1) full system: the FFT grid is decided by e_cut
rho_total = electron_density(total, "na_al111")
n_grids   = total.calc.aofdft.lattice.n_grids
print(f"FFT grid: {n_grids}")

# 2) fragments on the same grid
rho_substrate = electron_density(substrate, "al111", n_grids=n_grids)
rho_adsorbate = electron_density(adsorbate, "na_layer", n_grids=n_grids)

delta = rho_total - rho_substrate - rho_adsorbate

with open("na_al111_delta_rho.cube", "w") as f:
    write_cube(f, total, data=delta, comment="Charge density difference (e/Bohr^3)")
print("Saved na_al111_delta_rho.cube")

# 3) planar average along z, as electrons per Angstrom
area  = np.linalg.norm(np.cross(total.cell[0], total.cell[1])) / Bohr**2  # Bohr^2
dz    = total.cell[2, 2] / delta.shape[2]                                 # Angstrom
z     = np.arange(delta.shape[2]) * dz
lam   = delta.mean(axis=(0, 1)) * area / Bohr                             # e/Angstrom
moved = 0.5 * np.abs(lam).sum() * dz
print(f"Integral of delta_rho  : {lam.sum() * dz:+.2e} e (should be ~0)")
print(f"Redistributed electrons: {moved:.3f} e per cell")

fig, ax = plt.subplots(figsize=(6.4, 3.8))
ax.fill_between(z, lam, 0.0, where=lam >= 0, interpolate=True, color="#d1495b", alpha=0.6, label="accumulation")
ax.fill_between(z, lam, 0.0, where=lam < 0, interpolate=True, color="#3d5a80", alpha=0.6, label="depletion")
for atom in total:
    ax.axvline(atom.position[2], color="gray" if atom.symbol == "Al" else "goldenrod", linewidth=0.8)
ax.set_xlabel("z (Angstrom)")
ax.set_ylabel(r"Planar-integrated $\Delta\rho$ ($e$/Angstrom)")
ax.set_xlim(z[0], z[-1])
ax.legend()
fig.tight_layout()
fig.savefig("na_al111_delta_rho.png", dpi=150)
print("Saved na_al111_delta_rho.png")
