Electron density analysis
Saving the electron density to a CUBE file
Take out the electron density from the SCF calculation and save it in the CUBE format for visualization tools.
The electron density is available from the rho property of AOFDFTCalculator. Passing it to ASE's write_cube produces a CUBE file that can be opened with NanoLabo, VESTA and other visualization tools.
"""
Advance/OF-DFT example: save the electron density to a CUBE file.
Copyright (C) 2026 AdvanceSoft Corporation, All rights reserved.
"""
from ase.build import bulk
from ase.io.cube import read_cube_data, write_cube
from ase.units import Bohr
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"
atoms = bulk("Si", crystalstructure="diamond", a=5.43, cubic=True)
atoms.calc = AOFDFTCalculator(
console = False,
logging_file = "si_density.log",
kin_type = "AS26",
kin_model = "Crystal26",
vps_dir = VPS_DIR,
pao_dir = PAO_DIR,
)
# run SCF
atoms.get_potential_energy()
# electron density on the FFT grid: torch.Tensor of shape (n_rho, na, nb, nc), in electrons/Bohr^3
rho = atoms.calc.rho
print(f"Shape of rho : {tuple(rho.shape)}")
# rho[0] is the total electron density; convert torch.Tensor -> numpy.ndarray
density = rho[0].detach().cpu().numpy()
# sanity check: the density integrates to the number of valence electrons
volume = atoms.get_volume() / Bohr**3 # Bohr^3
print(f"Number of electrons: {density.mean() * volume:.6f}")
print(f"Max. / min. density: {density.max():.5f} / {density.min():.5f} e/Bohr^3")
# save in the Gaussian CUBE format (readable by NanoLabo, VESTA, VMD, ...)
with open("si_density.cube", "w") as f:
write_cube(f, atoms, data=density, comment="Electron density (e/Bohr^3) by Advance/OF-DFT")
print("Saved si_density.cube")
# read the file back with ASE
data, atoms_read = read_cube_data("si_density.cube")
print(f"Read back : grid {data.shape}, {len(atoms_read)} atoms")
The rho property
| Item | Description |
|---|---|
| Type | torch.Tensor (double precision) |
| Shape | (n_rho, na, nb, nc); na, nb, nc are the numbers of FFT grid points along a, b and c |
| Unit | electrons / Bohr³ |
n_rho | 1 without spin polarization, 2 with collinear spin polarization |
| Components | rho[0]: total electron density, rho[1]: spin density (up − down) |
Notes
rhois a PyTorch tensor. Convert it to a NumPy array withdetach().cpu().numpy(); the same line works for GPU calculations.- It is the valence density of the pseudopotential calculation, and integrates to the number of valence electrons (checked in the script with
density.mean() * volume). - By convention the density in a CUBE file is in atomic units (Bohr⁻³), which is the unit of
rho. - Grid point
(i, j, k)is located at(i/na) a + (j/nb) b + (k/nc) c, wherea, b, care the cell vectors. - See Visualizing the spin density for the spin density and Deformation density for differences of densities.