"""
Advance/OF-DFT example: control and monitor the SCF calculation.

Shows the logging options, the SCF parameters, how to detect a failed SCF,
and how to plot the convergence history written in the log file.

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

import logging
import re

import matplotlib.pyplot as plt
from ase.build import bulk
from ase.units import 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"

LOG_FILE = "al_scf.log"

atoms = bulk("Al", "fcc", a=4.05).repeat((3, 3, 3))  # 27 atoms

atoms.calc = AOFDFTCalculator(
    kin_type      = "AS26",
    kin_model     = "Crystal26",
    vps_dir       = VPS_DIR,
    pao_dir       = PAO_DIR,
    # --- logging
    console       = False,             # do not print the SCF log on the screen
    logging_file  = LOG_FILE,          # write it to a file instead
    logging_level = logging.INFO,      # use logging.DEBUG for more details
    # --- SCF
    scf_style     = "bulk",            # preset of mixing parameters: "bulk" | "magnetic" | "molecule"
    max_iter      = 200,               # maximum number of SCF iterations
    conv_thr      = 1.0e-6 * Hartree,  # convergence threshold of the energy (in eV)
    scf_must_conv = True,              # raise RuntimeError when the SCF does not converge
)

try:
    energy = atoms.get_potential_energy()
except RuntimeError as err:
    raise SystemExit(f"SCF failed: {err}")

calc = atoms.calc
print(f"Converged          : {calc.scf_converged}")
print(f"SCF energy error   : {calc.scf_energy_err:.3e} eV")
print(f"Total energy       : {calc.total_energy:.6f} eV")
print(f"Fermi energy       : {calc.e_fermi:.4f} eV")

# read the SCF history (iteration, total energy / Ha, SCF error / Ha) from the log file
row = re.compile(r"^\s*(\d+) \|\s*(\S+) \|\s*(\S+) \|")
history = []
with open(LOG_FILE, encoding="utf-8") as f:
    for line in f:
        m = row.match(line)
        if m:
            history.append((int(m.group(1)), float(m.group(2)), float(m.group(3))))

iters  = [h[0] for h in history]
errors = [h[2] * Hartree for h in history]

plt.semilogy(iters, errors, marker="o")
plt.axhline(1.0e-6 * Hartree, linestyle="--", color="gray", label="conv_thr")
plt.xlabel("SCF iteration")
plt.ylabel("SCF error (eV)")
plt.legend()
plt.tight_layout()
plt.savefig("al_scf_convergence.png", dpi=150)
print("Saved al_scf_convergence.png")
