"""
Advance/OF-DFT example: orbital populations of each atom.

The populations are written to a text file by `population_file`. This script
also shows how to read the file and sum the populations for each shell.

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

import re
from collections import defaultdict

from ase.build import bulk

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"

POP_FILE = "sic_population.txt"


def read_population(filename):
    """
    Read the orbital population file.

    Returns:
        atoms (list[dict]): for each atom, {"element": str, "orbitals": {label: electrons}, "charge": float}
    """
    head  = re.compile(r"^Atom\s+index=\s*(\d+)\s+element=\s*(\w+)")
    orbit = re.compile(r"^\s+(\d+)\s+(\S+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)")
    chrg  = re.compile(r"^\s+Charge\s+(-?\d+\.\d+)")

    atoms = []
    with open(filename, encoding="utf-8") as f:
        for line in f:
            if m := head.match(line):
                atoms.append({"element": m.group(2), "orbitals": {}, "charge": None})
            elif m := orbit.match(line):
                atoms[-1]["orbitals"][f"{m.group(1)} {m.group(2)}"] = float(m.group(3))
            elif m := chrg.match(line):
                atoms[-1]["charge"] = float(m.group(1))
    return atoms


# SiC: 2x2x2 repetition of the primitive cell (16 atoms)
atoms = bulk("SiC", crystalstructure="zincblende", a=4.36).repeat((2, 2, 2))

atoms.calc = AOFDFTCalculator(
    console         = False,
    logging_file    = "sic.log",
    population_file = POP_FILE,  # orbital populations are written here after the SCF
    kin_type        = "AS26",
    kin_model       = "Crystal26",
    vps_dir         = VPS_DIR,
    pao_dir         = PAO_DIR,
)
atoms.get_potential_energy()

# print the file as it is
with open(POP_FILE, encoding="utf-8") as f:
    print(f.read())

# sum the populations of each shell (s, p, d)
for index, atom in enumerate(read_population(POP_FILE)):
    shells = defaultdict(float)
    for label, electrons in atom["orbitals"].items():
        shells[label.split()[1][0]] += electrons  # "2 px" -> "p"

    summary = "  ".join(f"{shell} = {n:.3f}" for shell, n in shells.items())
    print(f"atom {index} ({atom['element']}): {summary}  charge = {atom['charge']:+.3f}")
