Integrals, norms, and expectations
Once a function has been sampled, integration connects its local values to a physical total. Each cell contributes its sampled integrand multiplied by the volume it represents; adding those contributions produces a scalar. FLODI expresses this directly by multiplying the supplied fields pointwise and including the cell volumes once:
Supply the integrand from your equation, including any complex conjugation. An orbital normalization, an electron count, and an energy expectation use the same numerical operation but represent different quantities. The Representations and normalization explains their measures.
A complete small example
import numpy as np
from flodi import RadialGrid
grid = RadialGrid.uniform(n_r=200, r_max=6.0)
f = grid.sample(lambda c: np.exp(-c.r**2))
squared_norm = grid.integrate(f.conj(), f).real
normalized = f / np.sqrt(squared_norm)
check = grid.integrate(normalized.conj(), normalized)
print(check)
Dividing the field by the square root of its squared norm scales the centre and known face values together, preserving their relationship as you normalize the function. The same integration operation also appears in expectation values, where the defining expression tells you which factors belong under the integral. A local potential can multiply the field pointwise, while a differential or nonlocal operator first returns its action on the field. Combining that result with the bra field then follows the mathematical expression for the expectation.
Useful checks
The quantity you place under the integral determines what the result can
check. With no arguments, grid.integrate() gives the domain’s physical
volume; with an orbital and its conjugate, it gives a squared norm; with
a total density, it measures electron count. Naming the quantity being
checked helps you distinguish an integration problem from a normalization
or occupation error.
For several orbitals, extend the norm check to their mutual overlaps.
The matrix with entries
grid.integrate(orbitals[i].conj(), orbitals[j]) tests both normalization
and orthogonality within a sector, whereas separate norm checks only test
its diagonal. These amplitude overlaps apply within the same angular
sector.
Every cell contributes its value times its physical volume. Centre values alone are insufficient for a physical integral.
Gaussian integral
Compare the finite-grid integral of a normalized Gaussian with its infinite-space value, one.
Create a radial grid of 200 cells extending to r = 6.
Sample \(e^{-r^2}/\pi^{3/2}\) as a density per physical volume.
Integrate the field and compare with one.
Plot the accumulated shell integral against the exact reference.
Integral: 1.0001500000
Absolute error against infinite-space integral: 1.500e-04
200 cells, r_max = 6.0. Final digits and iterative residuals may vary.
The difference includes quadrature and finite-domain errors.
Accumulated numerical shell integrals compared with the exact cumulative integral.
Complete example
Download integrate_gaussian.py.
1"""Integrate a normalized Gaussian and plot its accumulated integral."""
2from pathlib import Path
3
4import matplotlib.pyplot as plt
5import numpy as np
6from scipy.special import erf
7
8from flodi import RadialGrid
9
10FIGURE_DIRECTORY = Path("figures")
11
12
13def main():
14 # 1. Choose the resolution and domain.
15 grid = RadialGrid.uniform(n_r=200, r_max=6.0)
16
17 # 2. Sample a Gaussian with infinite-space integral one.
18 f = grid.sample(lambda c: np.exp(-c.r**2) / np.pi**1.5)
19
20 # 3. Integrate with physical cell volumes and compare.
21 integral = grid.integrate(f)
22 print(f"Integral: {integral:.10f}")
23 print(f"Absolute error against infinite-space integral: {abs(integral - 1):.3e}")
24
25 # 4. Accumulate shell contributions at cell faces and compare with the exact integral.
26 radius = grid.r_faces[1:]
27 accumulated = np.cumsum(f.values * grid.cell_volumes)
28 exact = erf(radius) - 2 * radius * np.exp(-radius**2) / np.sqrt(np.pi)
29 plot_result(radius, accumulated, exact)
30
31
32def plot_result(radius, accumulated, exact):
33 with plt.rc_context({
34 "font.family": "sans-serif", "font.sans-serif": ["Liberation Sans", "DejaVu Sans"],
35 "font.size": 11, "mathtext.fontset": "stixsans", "axes.labelsize": 11,
36 "axes.spines.top": False, "axes.spines.right": False, "axes.linewidth": 0.7,
37 "axes.edgecolor": "#aaa69e", "axes.labelcolor": "#444444", "text.color": "#444444",
38 "xtick.color": "#77736b", "ytick.color": "#77736b",
39 "xtick.labelsize": 10, "ytick.labelsize": 10, "svg.fonttype": "path",
40 "figure.facecolor": "none", "axes.facecolor": "none",
41 }):
42 fig, ax = plt.subplots(figsize=(5.4, 3.0), layout="constrained")
43 ax.plot(radius, exact, color="black", linewidth=1.5, label="Exact")
44 ax.plot(radius[::8], accumulated[::8], "o", markersize=4,
45 markerfacecolor="white", color="#b8312f", label="FLODI")
46 ax.set(xlabel=r"$R/a_0$", ylabel=r"$\int_0^R 4\pi r^2 f(r)\,dr$",
47 xlim=(0, 4), ylim=(0, 1.06), xticks=[0, 1, 2, 3, 4], yticks=[0, 0.5, 1])
48 ax.legend(frameon=False, fontsize=10, loc="lower right")
49 FIGURE_DIRECTORY.mkdir(parents=True, exist_ok=True)
50 for extension in ("png", "svg"):
51 fig.canvas.draw()
52 fig.savefig(FIGURE_DIRECTORY / f"integrate_gaussian.{extension}", dpi=260,
53 transparent=True, bbox_inches="tight", pad_inches=0.12)
54 plt.close(fig)
55
56
57if __name__ == "__main__":
58 main()