"""
Advance/OF-DFT example: compare magnetic orderings of bcc Fe.

The magnetic ordering is selected by the initial spins given in atoms.arrays["spin"].

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

import numpy as np
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"

params = dict(
    console   = False,
    kin_type  = "AS26",
    kin_model = "Crystal26",
    vps_dir   = VPS_DIR,
    pao_dir   = PAO_DIR,
    e_cut     = 180 * Hartree,
    n_grids   = (96, 96, 96),  # a multiple of 6, so that all atoms sit alike on the FFT grid
)

# label -> initial spins of the corner and body-center atoms of the cubic cell (None = non-magnetic)
orderings = {
    "NM" : None,
    "FM" : [1.0, 1.0],
    "AFM": [1.0, -1.0],
}

results = {}
for label, spins in orderings.items():
    atoms = bulk("Fe", "bcc", a=2.87, cubic=True).repeat((3, 3, 3))  # 54 atoms

    if spins is None:
        atoms.calc = AOFDFTCalculator(logging_file=f"fe_{label}.log", **params)
    else:
        atoms.arrays["spin"] = spins * (len(atoms) // 2)
        atoms.calc = AOFDFTCalculator(
            logging_file = f"fe_{label}.log",
            spin_type    = "polarized",
            scf_style    = "magnetic",
            **params,
        )

    results[label] = atoms.get_potential_energy() / len(atoms)

    # spins of the corner and body-center atoms, and the range of |spin| over all atoms
    spin = atoms.arrays["spin"] if spins is not None else np.zeros(len(atoms))
    print(f"{label:3s}: spins = [{spin[0]:+.3f}, {spin[1]:+.3f}], |spin| of all atoms = "
          f"{np.abs(spin).min():.3f} ... {np.abs(spin).max():.3f}, converged = {atoms.calc.scf_converged}")

print()
for label in ("NM", "AFM"):
    print(f"E({label}) - E(FM) = {(results[label] - results['FM']) * 1000.0:+.1f} meV/atom")
