"""
Advance/OF-DFT example: spin density of bcc Fe (CUBE files and a 2D map).

For a spin-polarized calculation `rho` has two components:
rho[0] = up + down (electron density), rho[1] = up - down (spin density).

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

import matplotlib.pyplot as plt
import numpy as np
from ase.build import bulk
from ase.io.cube import write_cube
from ase.units import Bohr, 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     = 2.87
atoms = bulk("Fe", "bcc", a=a, cubic=True).repeat((3, 3, 3))  # 3x3x3 cubic cells, 54 atoms
atoms.arrays["spin"] = [1.0] * len(atoms)

atoms.calc = AOFDFTCalculator(
    console      = False,
    logging_file = "fe_spin_density.log",
    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
    spin_type    = "polarized",
    scf_style    = "magnetic",
)
atoms.get_potential_energy()

rho = atoms.calc.rho.detach().cpu().numpy()  # shape (2, na, nb, nc), e/Bohr^3
total, spin = rho[0], rho[1]
up, down    = 0.5 * (total + spin), 0.5 * (total - spin)

dv = atoms.get_volume() / Bohr**3 / total.size
print(f"Shape of rho           : {rho.shape}")
print(f"Electrons (up / down)  : {up.sum() * dv:.4f} / {down.sum() * dv:.4f}")
print(f"Integrated spin density: {spin.sum() * dv:.4f}  (total_magmom = {atoms.calc.total_magmom:.4f})")

for name, data in [("total", total), ("spin", spin), ("up", up), ("down", down)]:
    with open(f"fe_density_{name}.cube", "w") as f:
        write_cube(f, atoms, data=data, comment=f"{name} density (e/Bohr^3) by Advance/OF-DFT")
print("Saved fe_density_{total,spin,up,down}.cube")

# 2D map of the spin density on the (1-10) plane (x = y) of one cubic cell,
# which contains the Fe atoms at the corners and at the body center
n     = spin.shape[0] // 3  # grid points along one cubic cell
idx   = np.arange(n + 1)
plane = spin[idx, idx, : n + 1]

u = np.linspace(0.0, a * np.sqrt(2.0), n + 1)
z = np.linspace(0.0, a, n + 1)
vmax = np.abs(plane).max()

fig, ax = plt.subplots(figsize=(6.0, 4.2))
cs = ax.contourf(u, z, plane.T, levels=np.linspace(-vmax, vmax, 25), cmap="RdBu_r")
fig.colorbar(cs, ax=ax, label=r"Spin density ($e$/Bohr$^3$)")
ax.set_xlabel("[110] (Angstrom)")
ax.set_ylabel("[001] (Angstrom)")
ax.set_aspect("equal")
fig.tight_layout()
fig.savefig("fe_spin_density.png", dpi=150)
print("Saved fe_spin_density.png")
