"""
Advance/OF-DFT example: what to do when the SCF calculation does not converge.

The same Al(111) slab is calculated with several sets of SCF parameters, and the
convergence histories are compared.

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

import re

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

# a metal slab with a vacuum region (8 layers, 2x2 in the surface plane, 32 atoms):
# none of the three presets is made for this kind of system
slab = fcc111("Al", size=(2, 2, 8), a=4.05, vacuum=10.0)

SETTINGS = {
    "bulk preset"               : dict(scf_style="bulk"),
    "magnetic preset"           : dict(scf_style="magnetic"),
    "molecule preset"           : dict(scf_style="molecule"),
    "magnetic, mix_nstored=32"  : dict(scf_style="magnetic", mix_nstored=32),
    "molecule, mix_nstored=32"  : dict(scf_style="molecule", mix_nstored=32),
}

ROW = re.compile(r"^\s*(\d+) \|\s*(\S+) \|\s*(\S+) \|")


def read_history(log_file):
    """(iteration, SCF error in eV) from the log file"""
    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(3)) * Hartree))
    return history


fig, ax = plt.subplots(figsize=(6.4, 4.2))
print(f"{'setting':24s} | conv. | iter. | energy (eV)")
for label, params in SETTINGS.items():
    log_file = "scf_" + re.sub(r"\W+", "_", label).strip("_") + ".log"
    atoms = slab.copy()
    atoms.calc = AOFDFTCalculator(
        console      = False,
        logging_file = log_file,
        kin_type     = "AS26",
        kin_model    = "Crystal26",
        vps_dir      = VPS_DIR,
        pao_dir      = PAO_DIR,
        max_iter     = 150,
        **params,
    )
    energy = atoms.get_potential_energy()  # scf_must_conv=False: returns even if not converged
    hist   = read_history(log_file)
    print(f"{label:24s} | {str(atoms.calc.scf_converged):5s} | {len(hist):5d} | {energy:.6f}", flush=True)
    ax.semilogy([h[0] for h in hist], [abs(h[1]) for h in hist], label=label)

ax.axhline(1.0e-6 * Hartree, color="gray", linestyle="--", linewidth=0.8)
ax.set_xlabel("SCF iteration")
ax.set_ylabel("SCF error (eV)")
ax.legend(fontsize=8)
fig.tight_layout()
fig.savefig("al111_scf_settings.png", dpi=150)
print("Saved al111_scf_settings.png")
