Electron density analysis

Density maps and line profiles

Take the density as a NumPy array and draw a 2D map on a plane containing the bonds and a 1D profile along a bond.

Category
Electron density analysis
APIs used
calc.rhomatplotlibscipy.ndimage.map_coordinates
Script
density_plot.py

Because the electron density is available as a NumPy array, it can be visualized directly with Matplotlib. Taking crystalline Si as an example, this script draws the density on the (1-10) plane, which contains the zigzag chain of Si-Si bonds, and a line profile along a bond.

density_plot.pyDownload
"""
Advance/OF-DFT example: plot the electron density on a plane and along a bond.

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

import matplotlib.pyplot as plt
import numpy as np
from ase.build import bulk
from scipy.ndimage import map_coordinates

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     = 5.43
atoms = bulk("Si", crystalstructure="diamond", a=a, 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,
)
atoms.get_potential_energy()

density    = atoms.calc.rho[0].detach().cpu().numpy()  # (na, nb, nc), e/Bohr^3
na, nb, nc = density.shape

# ---------------------------------------------------------------------------
# 1) 2D map on the (1-10) plane, which contains the zigzag chain of Si-Si bonds.
#    In the cubic cell this plane is x = y, i.e. the grid points density[i, i, k].
# ---------------------------------------------------------------------------
idx   = np.arange(na)
plane = density[idx, idx, :]              # shape (na, nc)
plane = np.vstack([plane, plane[:1]])     # close the periodic image along [110]
plane = np.hstack([plane, plane[:, :1]])  # ... and along [001]

u = np.linspace(0.0, a * np.sqrt(2.0), na + 1)  # distance along [110] (Angstrom)
z = np.linspace(0.0, a, nc + 1)                 # distance along [001] (Angstrom)

fig, ax = plt.subplots(figsize=(6.4, 4.6))
cs = ax.contourf(u, z, plane.T, levels=24, cmap="viridis")
fig.colorbar(cs, ax=ax, label=r"Electron density ($e$/Bohr$^3$)")

# mark the atoms lying on the plane (x = y), including periodic images at the cell edges
on_plane = [p for p in atoms.positions if abs(p[0] - p[1]) < 1.0e-6]
for p in on_plane:
    for du in (0.0, a * np.sqrt(2.0)):
        for dz in (0.0, a):
            uu, zz = p[0] * np.sqrt(2.0) + du, p[2] + dz
            if uu <= u[-1] + 1.0e-6 and zz <= z[-1] + 1.0e-6:
                ax.plot(uu, zz, "o", color="white", markeredgecolor="black", markersize=7)

ax.set_xlabel("[110] (Angstrom)")
ax.set_ylabel("[001] (Angstrom)")
ax.set_aspect("equal")
fig.tight_layout()
fig.savefig("si_density_plane.png", dpi=150)
print("Saved si_density_plane.png")

# ---------------------------------------------------------------------------
# 2) line profile along a Si-Si bond: from the atom at (0, 0, 0) to (a/4, a/4, a/4).
#    The density is interpolated on the periodic grid.
# ---------------------------------------------------------------------------
start, end = np.array([0.0, 0.0, 0.0]), np.array([a / 4, a / 4, a / 4])
t          = np.linspace(-0.5, 1.5, 201)  # extend the line beyond both atoms
points     = start + t[:, None] * (end - start)

frac   = points @ np.linalg.inv(atoms.cell.array)              # fractional coordinates
coords = (frac * np.array([na, nb, nc])).T                     # grid coordinates, shape (3, npoint)
line   = map_coordinates(density, coords, order=3, mode="grid-wrap")
dist   = t * np.linalg.norm(end - start)

fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.plot(dist, line)
ax.axvline(0.0, color="gray", linestyle=":")
ax.axvline(np.linalg.norm(end - start), color="gray", linestyle=":")
ax.set_xlabel("Distance along the Si-Si bond (Angstrom)")
ax.set_ylabel(r"Electron density ($e$/Bohr$^3$)")
fig.tight_layout()
fig.savefig("si_density_line.png", dpi=150)
print("Saved si_density_line.png")

Example output

Electron density of Si on the (1-10) plane. White circles are the Si atoms on the plane; the electrons accumulate on the bonds between them.
Electron density of Si on the (1-10) plane. White circles are the Si atoms on the plane; the electrons accumulate on the bonds between them.
Electron density profile along the Si-Si bond. Dotted lines mark the Si atoms.
Electron density profile along the Si-Si bond. Dotted lines mark the Si atoms.

Notes

  • In the cubic cell the (1-10) plane is the set of points with x = y. Since the a and b axes have the same number of grid points, the slice is simply density[i, i, k].
  • For values at arbitrary points, interpolate the gridded density with scipy.ndimage.map_coordinates. mode="grid-wrap" applies the periodic boundary condition.
  • The interpolation takes grid coordinates (fractional coordinates times the number of grid points). Cartesian points are converted to fractional coordinates with points @ inv(cell).
  • This is the valence density of a norm-conserving pseudopotential, so it is small at the nuclei.