"""
Advance/OF-DFT example: fixed spin moment calculation (energy versus magnetization).

`total_spin` fixes the total spin moment of the cell. The up and down electrons
then have different Fermi energies.

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

import matplotlib.pyplot as plt
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"

# spin moment per atom: 0 - 2.0, with a finer step near the energy minimum
moments = np.concatenate([np.arange(0.0, 1.5, 0.25), np.arange(1.5, 2.01, 0.05)])
rows    = []

for moment in moments:
    atoms = bulk("Fe", "bcc", a=2.87).repeat((3, 3, 3))  # 3x3x3 primitive cells, 27 atoms
    atoms.arrays["spin"] = [moment] * len(atoms)

    atoms.calc = AOFDFTCalculator(
        console      = False,
        logging_file = f"fe_fsm_{moment:.2f}.log",
        kin_type     = "AS26",
        kin_model    = "Crystal26",
        vps_dir      = VPS_DIR,
        pao_dir      = PAO_DIR,
        e_cut        = 180 * Hartree,
        spin_type    = "polarized",
        scf_style    = "magnetic",
        total_spin   = moment * len(atoms),  # total spin moment of the cell is fixed
    )

    energy = atoms.get_potential_energy() / len(atoms)
    calc   = atoms.calc
    rows.append((moment, energy, calc.e_fermi_up, calc.e_fermi_dw))

# energy relative to the minimum, in meV/atom
relative = (np.array([row[1] for row in rows]) - min(row[1] for row in rows)) * 1000.0

print(" M/atom | E - E_min (meV/atom) | E_F(up) (eV) | E_F(down) (eV)")
for (moment, _, e_up, e_dw), e_rel in zip(rows, relative):
    print(f" {moment:6.2f} | {e_rel:20.2f} | {e_up:12.4f} | {e_dw:14.4f}")

plt.plot(moments, relative, marker="o")
plt.xlabel("Spin moment per atom")
plt.ylabel("Relative energy (meV/atom)")
plt.tight_layout()
plt.savefig("fe_fixed_spin_moment.png", dpi=150)
print("Saved fe_fixed_spin_moment.png")
