"""
Advance/OF-DFT example: electron doping of GaAs with an As vacancy.

Compares the neutral and the electron-doped states: Mulliken charges of each atom
and the difference of the electron densities (saved as a CUBE file).

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

from ase.build import bulk
from ase.io.cube import write_cube

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"

# zincblende GaAs (8 atoms) with one As atom removed
atoms   = bulk("GaAs", crystalstructure="zincblende", a=5.65, cubic=True)
vacancy = [atom.index for atom in atoms if atom.symbol == "As"][0]
del atoms[vacancy]

states   = {"neutral": 0.0, "doped": -1.0}  # total charge of the cell; -1.0 = one extra electron
charges  = {}
density  = {}

for label, total_charge in states.items():
    system = atoms.copy()
    system.calc = AOFDFTCalculator(
        console      = False,
        logging_file = f"gaas_{label}.log",
        kin_type     = "AS26",
        kin_model    = "Crystal26",
        vps_dir      = VPS_DIR,
        pao_dir      = PAO_DIR,
        total_charge = total_charge,
    )
    system.get_potential_energy()

    charges[label] = system.arrays["charge"].copy()                    # Mulliken charges
    density[label] = system.calc.rho[0].detach().cpu().numpy().copy()  # electron density (e/Bohr^3)
    print(f"{label:8s}: E_Fermi = {system.calc.e_fermi:8.4f} eV")

# where did the doped electron go?  (negative = gained electrons)
print("\nChange of Mulliken charge by doping (q_doped - q_neutral)")
print(f"{'index':>5s} {'symbol':>6s} {'dq':>10s}")
for i, atom in enumerate(atoms):
    print(f"{i:5d} {atom.symbol:>6s} {charges['doped'][i] - charges['neutral'][i]:+10.4f}")

# density difference on the common grid
delta = density["doped"] - density["neutral"]
with open("gaas_doping_difference.cube", "w") as f:
    write_cube(f, atoms, data=delta, comment="rho(doped) - rho(neutral) (e/Bohr^3)")
print("\nSaved gaas_doping_difference.cube")
