Electron density analysis

Saving and reusing the electron density

Save the converged density to a NumPy file and use it as the initial density of another calculation to reduce the number of SCF iterations.

Category
Electron density analysis
APIs used
calc.rho (setter)init_rhonumpy.save
Script
restart_density.py

The rho property can be set as well as read. A density assigned before the calculation is used as the initial density of the SCF. This reduces the number of iterations when repeating calculations on similar structures or re-running with different settings.

restart_density.pyDownload
"""
Advance/OF-DFT example: save the electron density and reuse it as the initial guess.

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

import re

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,
)


def scf_iterations(log_file):
    """Number of SCF iterations written in the log file."""
    with open(log_file, encoding="utf-8") as f:
        found = re.findall(r"SCF converged in (\d+) iterations", f.read())
    return int(found[-1]) if found else None


# 1) converge the density once and save it as a NumPy file
atoms = bulk("Si", crystalstructure="diamond", a=5.43, cubic=True)
atoms.calc = AOFDFTCalculator(logging_file="si_first.log", **params)
atoms.get_potential_energy()

rho = atoms.calc.rho.detach().cpu().numpy()  # shape (n_rho, na, nb, nc)
np.save("si_rho.npy", rho)
print(f"Saved si_rho.npy, shape = {rho.shape}")

# 2) slightly displaced structure, starting from the superposition of atomic densities (default)
displaced = atoms.copy()
displaced.rattle(stdev=0.02, seed=1)

displaced.calc = AOFDFTCalculator(logging_file="si_atomic_guess.log", **params)
e_atomic = displaced.get_potential_energy()

# 3) the same structure, starting from the saved density:
#    set the `rho` property before the calculation
calc     = AOFDFTCalculator(logging_file="si_saved_guess.log", **params)
calc.rho = np.load("si_rho.npy")
displaced.calc = calc
e_saved = displaced.get_potential_energy()

print(f"Atomic guess : {scf_iterations('si_atomic_guess.log')} iterations, E = {e_atomic:.6f} eV")
print(f"Saved density: {scf_iterations('si_saved_guess.log')} iterations, E = {e_saved:.6f} eV")

# 4) a density on a different grid is interpolated automatically (here: a finer grid)
calc     = AOFDFTCalculator(logging_file="si_fine_grid.log", e_cut=250 * Hartree, **params)
calc.rho = np.load("si_rho.npy")
displaced.calc = calc
displaced.get_potential_energy()
print(f"Finer grid   : {scf_iterations('si_fine_grid.log')} iterations, "
      f"grid {rho.shape[1:]} -> {tuple(calc.rho.shape[1:])}")

Example output

text
Saved si_rho.npy, shape = (1, 56, 56, 56)
Atomic guess : 18 iterations, E = -922.038343 eV
Saved density: 14 iterations, E = -922.038177 eV
Finer grid   : 14 iterations, grid (56, 56, 56) -> (73, 73, 73)

Starting from the saved density reduces the number of SCF iterations from 18 to 14.

Notes

  • calc.rho accepts a torch.Tensor, numpy.ndarray, list or tuple of shape (n_rho, na, nb, nc) or (na, nb, nc).
  • When the grid of the assigned density differs from that of the calculation, it is interpolated automatically with FFT. A density obtained on a coarse grid can therefore start a calculation on a finer grid.
  • The default initial density is the superposition of isolated neutral atomic densities (init_rho="atomic").
  • When the same calculator object is reused while the structure changes (structure optimization, molecular dynamics), the previous density matrix is used automatically as the initial guess, so this step is not needed.
  • Besides numpy.save, the density can be stored as a CUBE file.