"""
Advance/OF-DFT example: band gap estimated from the total energy of doped systems.

The charge per formula unit is varied and the energy per formula unit is fitted
with a quadratic function. Its second derivative corresponds to the band gap.

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

import matplotlib.pyplot as plt
import numpy as np
from ase.build import bulk
from numpy.polynomial import Polynomial

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"

# 2x2x2 repetitions of the primitive cell (16 atoms, 8 formula units)
materials = {
    "AlSb": bulk("AlSb", "zincblende", a=6.14).repeat((2, 2, 2)),
    "AlP" : bulk("AlP", "zincblende", a=5.46).repeat((2, 2, 2)),
    # you can add more materials
    # "CdSe": bulk("CdSe", "wurtzite", a=4.30, c=7.01).repeat((2, 2, 2)),
    # "CsCl": bulk("CsCl", "cesiumchloride", a=4.12).repeat((2, 2, 2)),
}

charges = np.arange(-1.0, 1.1, 0.5)  # charge per formula unit: -1.0 ... +1.0

for name, atoms in materials.items():
    print(f"--- {name} ---")
    n_units  = len(atoms) // 2  # number of formula units in the cell
    energies = []

    for charge in charges:
        atoms.calc = AOFDFTCalculator(
            console      = False,
            logging_file = f"{name}_{charge:+.1f}.log",
            kin_type     = "AS26",
            kin_model    = "Crystal26",
            vps_dir      = VPS_DIR,
            pao_dir      = PAO_DIR,
            total_charge = charge * n_units,  # negative: electron doping, positive: hole doping
        )
        energies.append(atoms.get_potential_energy() / n_units)  # per formula unit
        print(f"charge = {charge:+.1f}  E = {energies[-1]:.4f} eV")

    # energy relative to the neutral system, fitted by E = a q^2 + b q + c
    relative = np.array(energies) - energies[len(charges) // 2]
    fit      = Polynomial.fit(charges, relative, deg=2)
    c, b, a  = fit.convert().coef

    # the second derivative of the quadratic function corresponds to the band gap
    print(f"Band gap of {name}: {2.0 * a:.2f} eV\n")

    q = np.linspace(-1.0, 1.0, 100)
    plt.scatter(charges, relative, label=f"{name} ($E_g$ = {2.0 * a:.2f} eV)")
    plt.plot(q, fit(q), linestyle="--")

plt.xlabel("Charge per formula unit (e)")
plt.ylabel("Relative energy (eV)")
plt.legend()
plt.tight_layout()
plt.savefig("band_gap_EvsCharge.png", dpi=150)
print("Saved band_gap_EvsCharge.png")
