Apply a Laplacian

Differentiation asks how a field varies across neighbouring samples, and the geometry determines how those variations combine into a Laplacian. Calling grid.laplacian(f) returns the resulting approximation to \(\nabla^2 f\) as another field on the same grid. For a radial physical field, the geometric coefficients represent

\[\nabla^2 f=\frac{1}{r^2}\frac{\mathrm d}{\mathrm dr} \left(r^2\frac{\mathrm df}{\mathrm dr}\right).\]

This is the operator on the physical radial field. The reduced radial function in the common preparation has a different differential equation; see Representations and normalization before comparing implementations.

Check a known smooth function

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))
numerical = grid.laplacian(f)
exact = grid.sample(lambda c: (4 * c.r**2 - 6) * np.exp(-c.r**2))
error = numerical - exact
error_norm = np.sqrt(grid.integrate(error.conj(), error).real)
print(error_norm)

Because the Gaussian is known analytically, sampling its callable also provides the outer-face values needed by the last derivative row. This lets the comparison test the derivative rule with a consistent boundary. The returned Laplacian has known centre values, ready to be integrated in the error norm, but its own face values are generally unknown. A second differentiation would therefore need additional boundary information.

The quantum kinetic operator includes a factor \(-1/2\) in atomic units. FLODI’s Laplacian call returns \(\nabla^2 f\) itself. Keep the factor in the equation or operator action you are implementing, and use the same differentiation rule when forming expectations and residuals.

For a prolate field with a specified nonzero angular sector, pass the same m as used by the orbital equation.

The analytical three-dimensional Gaussian Laplacian and its zero crossing.

A smooth reference separates derivative accuracy from the details of an electronic structure model.

Gaussian Laplacian

Compare the numerical Laplacian with its analytical expression using a volume-weighted L2 error norm.

\[\nabla^2 e^{-r^2}=(4r^2-6)e^{-r^2}\]
  1. Sample \(e^{-r^2}\), including its outer-face values.

  2. Apply the Laplacian and sample the analytical derivative.

  3. Subtract the fields and integrate the squared error to obtain its L2 norm.

  4. Plot the two Laplacians together, then inspect their difference on a separate axis.

Volume-weighted L2 error: 3.718e-03

200 cells, r_max = 6.0. Final digits and iterative residuals may vary.

Repeat at finer resolutions to check discretization error.

The numerical and analytical Laplacians agree closely; a separate panel resolves their difference.

The numerical and analytical Laplacians agree closely; a separate panel resolves their difference.

Complete example

Download laplacian_gaussian.py.

 1"""Compare the numerical Laplacian with an analytical derivative and plot both."""
 2from pathlib import Path
 3
 4import matplotlib.pyplot as plt
 5import numpy as np
 6
 7from flodi import RadialGrid
 8
 9FIGURE_DIRECTORY = Path("figures")
10
11
12def main():
13    # 1. Sample a smooth function, including its outer-face values.
14    grid = RadialGrid.uniform(n_r=200, r_max=6.0)
15    f = grid.sample(lambda c: np.exp(-c.r**2))
16
17    # 2. Compute the numerical and analytical Laplacians.
18    numerical = grid.laplacian(f)
19    exact = grid.sample(lambda c: (4 * c.r**2 - 6) * np.exp(-c.r**2))
20
21    # 3. Measure the error using physical volumes.
22    error = numerical - exact
23    l2_error = np.sqrt(grid.integrate(error.conj(), error).real)
24    print(f"Volume-weighted L2 error: {l2_error:.3e}")
25
26    # 4. Show agreement and the smaller difference on separate axes.
27    plot_result(grid.r, numerical.values, exact.values, error.values)
28
29
30def plot_result(r, numerical, exact, error):
31    with plt.rc_context({
32        "font.family": "sans-serif", "font.sans-serif": ["Liberation Sans", "DejaVu Sans"],
33        "font.size": 11, "mathtext.fontset": "stixsans", "axes.labelsize": 11,
34        "axes.spines.top": False, "axes.spines.right": False, "axes.linewidth": 0.7,
35        "axes.edgecolor": "#aaa69e", "axes.labelcolor": "#444444", "text.color": "#444444",
36        "xtick.color": "#77736b", "ytick.color": "#77736b",
37        "xtick.labelsize": 10, "ytick.labelsize": 10, "svg.fonttype": "path",
38        "figure.facecolor": "none", "axes.facecolor": "none",
39    }):
40        fig, (ax, difference) = plt.subplots(2, 1, figsize=(5.4, 3.8), sharex=True,
41                                            gridspec_kw={"height_ratios": [3, 1]}, layout="constrained")
42        ax.plot(r, exact, color="black", linewidth=1.5, label="Exact")
43        ax.plot(r[::6], numerical[::6], "o", markersize=4, markerfacecolor="white",
44                color="#b8312f", label="FLODI")
45        ax.set(ylabel=r"$\nabla^2 f\,/\,a_0^{-2}$", yticks=[-6, -3, 0])
46        ax.legend(frameon=False, fontsize=10, loc="lower right")
47        difference.axhline(0, color="#aaa69e", linewidth=0.7)
48        difference.plot(r, error, color="#b8312f", linewidth=1.4)
49        difference.set(xlabel=r"$r/a_0$", ylabel="Error", yticks=[0, 0.005],
50                       xticks=[0, 1, 2, 3, 4], xlim=(0, 4))
51        difference.ticklabel_format(axis="y", style="sci", scilimits=(0, 0), useMathText=True)
52        FIGURE_DIRECTORY.mkdir(parents=True, exist_ok=True)
53        for extension in ("png", "svg"):
54            fig.canvas.draw()
55            fig.savefig(FIGURE_DIRECTORY / f"laplacian_gaussian.{extension}", dpi=260,
56                        transparent=True, bbox_inches="tight", pad_inches=0.12)
57        plt.close(fig)
58
59
60if __name__ == "__main__":
61    main()

Download the plot as SVG or PNG.