Atomic charges and spin

Visualizing the spin density

Extract the spin density and the up/down densities from a spin-polarized calculation and write CUBE files and a 2D map.

Category
Atomic charges and spin
APIs used
calc.rhospin_typetotal_magmomwrite_cube
Script
spin_density.py

In a spin-polarized calculation (spin_type="polarized"), calc.rho has the shape (2, na, nb, nc): the first component is the total electron density and the second the spin density.

ComponentMeaning
rho[0]total electron density ρ↑ + ρ↓
rho[1]spin density ρ↑ − ρ↓
(rho[0] + rho[1]) / 2density of up-spin electrons ρ↑
(rho[0] - rho[1]) / 2density of down-spin electrons ρ↓
spin_density.pyDownload
"""
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")

Example output

Spin density of bcc Fe on the (1-10) plane. Around the Fe atoms at the corners and the body centre of the cell, the spin density reflects the shape of the d orbitals.
Spin density of bcc Fe on the (1-10) plane. Around the Fe atoms at the corners and the body centre of the cell, the spin density reflects the shape of the d orbitals.

Notes

  • The spin density integrates to the total magnetic moment calc.total_magmom, which the script checks.
  • The spin density takes positive and negative values. Show positive and negative isosurfaces in different colours when visualizing the CUBE file.
  • In the cubic bcc cell, the plane x = y (the (1-10) plane) contains both the corner and the body-centre Fe atoms. The map shows the range of one cubic cell.
  • The cell is a 3×3×3 repetition of the cubic cell (54 atoms), and the FFT grid is set with n_grids=(96, 96, 96). See Comparing magnetic orderings for the reasons.
  • The same approach shows the spatial distribution for antiferromagnetic or ferrimagnetic arrangements (see Comparing magnetic orderings).