"""
Advance/OF-DFT example: planar-averaged electrostatic potential and work function of a slab.

The electrostatic potential is obtained from the electron density by solving the
Poisson equation in reciprocal space. The work function is the vacuum level minus
the Fermi energy.

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

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


def hartree_potential(delta_rho, cell):
    """
    Solve the Poisson equation for a periodic charge distribution with FFT.

    Args:
        delta_rho (np.ndarray): density difference in e/Bohr^3. Its shape is (na, nb, nc).
        cell (np.ndarray): lattice vectors in Bohr. Its shape is (3, 3).
    Returns:
        potential (np.ndarray): potential energy of an electron in Hartree. Its shape is (na, nb, nc).
    """
    recip = 2.0 * np.pi * np.linalg.inv(cell).T
    freqs = [np.fft.fftfreq(n, d=1.0 / n) for n in delta_rho.shape]
    ia, ib, ic = np.meshgrid(*freqs, indexing="ij")

    g  = ia[..., None] * recip[0] + ib[..., None] * recip[1] + ic[..., None] * recip[2]
    g2 = np.sum(g * g, axis=-1)
    g2[0, 0, 0] = 1.0  # avoid division by zero

    v_g = 4.0 * np.pi * np.fft.fftn(delta_rho) / g2
    v_g[0, 0, 0] = 0.0  # the G = 0 term vanishes for a neutral cell

    return np.fft.ifftn(v_g).real


# 1) slab model: 6 layers of Al(111), 2x2 in the surface plane (24 atoms),
#    with 10 Angstrom of vacuum on both sides
slab = fcc111("Al", size=(2, 2, 6), a=4.05, vacuum=10.0)

slab.calc = AOFDFTCalculator(
    console      = False,
    logging_file = "al111.log",
    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
)
slab.get_potential_energy()

calc = slab.calc

# 2) density difference from the superposition of neutral atoms.
#    The potential of a neutral atom is short-ranged and vanishes in the vacuum,
#    so the vacuum level is given by the Hartree potential of this difference.
rho_scf   = calc.rho[0].detach().cpu().numpy()
rho_atom  = calc.aofdft.charge_density.neutral_density().detach().cpu().numpy()
potential = hartree_potential(rho_scf - rho_atom, slab.cell.array / Bohr) * Hartree  # eV

# 3) average over the xy plane
v_z = potential.mean(axis=(0, 1))
z   = np.arange(len(v_z)) * slab.cell[2, 2] / len(v_z)  # Angstrom

# 4) vacuum level: average over the grid points far (> 6 Angstrom) from the surfaces
z_atoms = slab.positions[:, 2]
in_vac  = (z < z_atoms.min() - 6.0) | (z > z_atoms.max() + 6.0)
e_vac   = v_z[in_vac].mean()
e_fermi = calc.e_fermi

print(f"Vacuum level  : {e_vac:8.4f} eV")
print(f"Fermi energy  : {e_fermi:8.4f} eV")
print(f"Work function : {e_vac - e_fermi:8.4f} eV")

# 5) plot
fig, ax = plt.subplots(figsize=(6.4, 4.0))
ax.plot(z, v_z, color="#40266e", label="Planar-averaged potential")
ax.axhline(e_vac, color="gray", linestyle="--", label="Vacuum level")
ax.axhline(e_fermi, color="#d1495b", linestyle="--", label="Fermi energy")
for za in z_atoms:
    ax.axvline(za, color="lightgray", linewidth=0.8, zorder=0)
ax.annotate("", xy=(z[-1] * 0.92, e_vac), xytext=(z[-1] * 0.92, e_fermi), arrowprops=dict(arrowstyle="<->"))
ax.text(z[-1] * 0.90, 0.5 * (e_vac + e_fermi), "work function", ha="right", va="center")
ax.set_xlabel("z (Angstrom)")
ax.set_ylabel("Energy (eV)")
ax.set_xlim(z[0], z[-1])
ax.legend(loc="center left")
fig.tight_layout()
fig.savefig("al111_potential.png", dpi=150)
print("Saved al111_potential.png")
