Solve a fixed eigenproblem
So far, sampling and differentiation have started from a known function.
An eigenproblem reverses that situation: the operator is given, and you
seek a field that it maps to a scalar multiple of itself. FLODI returns
the eigenvalue together with a physical orbital field, keeping the supplied
operator fixed throughout the solve. For a real local potential,
lowest_orbital(potential) solves
The result has unit physical norm and zero outer-face values. The solver does not choose occupations or update a density-dependent potential. Those choices belong to your model and iteration.
One state or several
This standalone example uses zero potential in a finite radial domain:
import numpy as np
from flodi import RadialGrid
grid = RadialGrid.uniform(n_r=120, r_max=5.0)
potential = grid.sample(0.0)
epsilon, psi = grid.lowest_orbital(potential)
energies, orbitals = grid.lowest_orbitals(potential, k=3)
overlap = np.array([
[grid.integrate(a.conj(), b) for b in orbitals]
for a in orbitals
])
print(overlap)
The returned energies are ordered from lowest to highest, with
orbitals[i] paired with energies[i]. Their overlap matrix should
agree with the identity, giving you a check of mutual orthogonality as well
as the individual norms. The eigenvalues describe this particular fixed
operator; deciding how its states enter an occupied model is a further
physical choice, made using the equations for your investigation.
A radial local-potential problem uses a direct tridiagonal solve.
Spherical and prolate problems use an iterative eigensolver. The optional
initial field supplies a nonzero physical starting orbital; tol
controls the iterative solve. The radial direct solver accepts these
arguments for interface compatibility. Its accuracy is not controlled by
iterative tol.
A complete operator action
Use action= when the operation cannot be represented by a local
potential alone. The callable takes a field and returns the complete
operator applied to it, including kinetic energy. For example, the
positive Laplacian operator in a ball is
def ball_action(field):
return -grid.laplacian(field)
values, modes = grid.lowest_orbitals(action=ball_action, k=3)
Here the eigenvalues refer to \(-\nabla^2\), whereas the zero-potential
local interface above uses \(-\tfrac12\nabla^2\). Identify the operator
before comparing the spectra. Supply either potential or action,
not both.
The Hermitian eigensolver relies on the action being linear and self-adjoint in the physical inner product. If its coefficients depend on a source or occupied state, that input must therefore remain fixed throughout the solve. Rebuilding a potential from each trial vector would make the operation depend on the vector itself, changing the eigenproblem the solver assumes.
Residuals and lower-level adapters
Check the equation with the same operator you supplied. For the local example above, a residual is
residual = -0.5 * grid.laplacian(psi) + potential * psi - epsilon * psi
residual_norm = np.sqrt(grid.integrate(residual.conj(), residual).real)
print(residual_norm)
This residual checks the supplied fixed operator on the chosen grid;
comparison with an independent reference also tests the spatial
approximation. On a prolate local-potential solve, use the same m in
the eigensolver and the residual’s Laplacian.
For direct SciPy use, grid.linear_operator(action) handles conversion
between physical fields and volume-weighted vectors. to_vector and
from_vector expose that conversion when needed. Specify
dtype=complex for a complex action. The ball example below demonstrates
this lower-level interface.
Request only the number of states you need. Requesting every state on an angular grid uses a dense solve and quadratic storage.
Radial modes in a ball
Solve \(-\nabla^2 f=\lambda f\) in a ball of radius \(R=6\), with regularity at the origin and f(R) = 0.
Fix \(R=6\) and construct a 200-cell radial grid.
Wrap the action f → −\(\nabla^2 f\) with grid.linear_operator and request three smallest eigenpairs with eigsh.
Convert the vectors back to Fields, align their signs with the analytical modes, and check the lowest mode’s norm and residual.
Plot each mode separately to compare its profile and interior nodes.
Lowest eigenvalue: 0.2741523254 a0^-2
Analytical eigenvalue: 0.2741556778 a0^-2
Physical norm: 1.0000000000
Volume-weighted residual norm: ~1e-12
200 cells, r_max = 6.0. Final digits and iterative residuals may vary.
NumPy defines \(\operatorname{sinc}(x)=\sin(\pi x)/(\pi x)\). Eigenvector signs are arbitrary; align them before comparing profiles. Changing R changes the physical problem.
Three aligned rows compare exact and numerical radial modes, showing zero, one, and two interior nodes.
Complete example
1"""Find spherically symmetric Dirichlet eigenmodes of -Laplacian on a ball.
2
3Regularity at r=0 and f(R)=0 give k_n=n*pi/R and eigenvalues k_n**2.
4These are the radial (angularly constant) modes, not the full angular spectrum.
5"""
6from pathlib import Path
7
8import matplotlib.pyplot as plt
9import numpy as np
10from scipy.sparse.linalg import eigsh
11
12from flodi import RadialGrid
13
14FIGURE_DIRECTORY = Path("figures")
15
16
17def main():
18 # 1. Fix the physical boundary and choose a radial resolution.
19 radius = 6.0
20 grid = RadialGrid.uniform(n_r=200, r_max=radius)
21
22 # 2. Supply a linear field action. The adapter imposes zero outer values
23 # and uses volume-weighted solver vectors for the physical inner product.
24 operator = grid.linear_operator(lambda f: -grid.laplacian(f))
25 initial = np.random.default_rng(7).normal(size=grid.r.size)
26 eigenvalues, vectors = eigsh(operator, k=3, which="SA", tol=1e-11, v0=initial)
27 order = np.argsort(eigenvalues)
28 eigenvalues, vectors = eigenvalues[order], vectors[:, order]
29
30 # 3. Recover the lowest physical mode and compare with the exact solution.
31 mode = grid.from_vector(vectors[:, 0])
32 exact = grid.sample(
33 lambda c: np.sqrt(np.pi / (2 * radius**3)) * np.sinc(c.r / radius)
34 )
35 # Eigenvectors have an arbitrary sign: align it before comparing profiles.
36 if grid.integrate(mode, exact) < 0:
37 mode = -mode
38 reference = (np.arange(1, 4) * np.pi / radius)**2
39 residual = -grid.laplacian(mode) - eigenvalues[0] * mode
40 residual_norm = np.sqrt(grid.integrate(residual, residual))
41 print(f"Lowest eigenvalue: {eigenvalues[0]:.10f} a0^-2")
42 print(f"Analytical eigenvalue: {reference[0]:.10f} a0^-2")
43 print(f"Physical norm: {grid.integrate(mode, mode):.10f}")
44 print(f"Volume-weighted residual norm: {residual_norm:.3e}")
45
46 # 4. Recover and sign-align all three modes to reveal their nodal structure.
47 modes, exact_modes = [], []
48 for index in range(3):
49 n = index + 1
50 numerical_mode = grid.from_vector(vectors[:, index])
51 exact_mode = grid.sample(
52 lambda c: n * np.sqrt(np.pi / (2 * radius**3)) * np.sinc(n * c.r / radius)
53 )
54 if grid.integrate(numerical_mode, exact_mode) < 0:
55 numerical_mode = -numerical_mode
56 modes.append(numerical_mode.values)
57 exact_modes.append(exact_mode.values)
58 plot_result(grid.r, modes, exact_modes)
59
60
61def plot_result(r, modes, exact_modes):
62 with plt.rc_context({
63 "font.family": "sans-serif", "font.sans-serif": ["Liberation Sans", "DejaVu Sans"],
64 "font.size": 11, "mathtext.fontset": "stixsans", "axes.labelsize": 11,
65 "axes.spines.top": False, "axes.spines.right": False, "axes.linewidth": 0.7,
66 "axes.edgecolor": "#aaa69e", "axes.labelcolor": "#444444", "text.color": "#444444",
67 "xtick.color": "#77736b", "ytick.color": "#77736b",
68 "xtick.labelsize": 10, "ytick.labelsize": 10, "svg.fonttype": "path",
69 "figure.facecolor": "none", "axes.facecolor": "none",
70 }):
71 fig, axes = plt.subplots(3, 1, figsize=(5.4, 4.4), sharex=True, layout="constrained")
72 for index, ax in enumerate(axes):
73 ax.axhline(0, color="#aaa69e", linewidth=0.7)
74 ax.plot(r, exact_modes[index], color="black", linewidth=1.5, label="Exact")
75 ax.plot(r[::8], modes[index][::8], "o", markersize=3.5,
76 markerfacecolor="white", color="#b8312f", label="FLODI")
77 ax.set(ylabel=f"$f_{index + 1}$", xlim=(0, 6), xticks=[0, 2, 4, 6])
78 axes[0].legend(frameon=False, fontsize=10, loc="upper right", ncol=2)
79 axes[-1].set_xlabel(r"$r/a_0$")
80 FIGURE_DIRECTORY.mkdir(parents=True, exist_ok=True)
81 for extension in ("png", "svg"):
82 fig.canvas.draw()
83 fig.savefig(FIGURE_DIRECTORY / f"eigenmodes_ball.{extension}", dpi=260,
84 transparent=True, bbox_inches="tight", pad_inches=0.12)
85 plt.close(fig)
86
87
88if __name__ == "__main__":
89 main()