In the projection methods for incompressible flow (Lectures 12 to 14), every time step requires the solution of an elliptic pressure Poisson equation , and this solution usually takes most of the computing time. If you use classical Jacobi relaxation, doubling the grid resolution in 2-D (, as many unknowns) multiplies the iteration count by ( iterations, total work) because local five-point averaging removes smooth, long-wavelength error very slowly. In this lecture, we benchmark five solvers in elliptic_multigrid, Jacobi, Young’s optimal Red–Black SOR, matrix-free Conjugate Gradient (Dirichlet & singular pure-Neumann), exact Fast Sine Transform, and recursive Geometric Multigrid V-Cycles achieving mesh-independent convergence across 172 through 1292 grids.
Learning objectives¶
Formulate the 5-point discrete Laplacian and verify truncation convergence using the direct spectral solver
poisson_2d_fast_sine.Compare spectral-radius convergence scaling of
poisson_2d_jacobi(), Young’s optimal Red–Blackpoisson_2d_sor(), and matrix-freepoisson_2d_cg.Resolve the nullspace compatibility condition of singular pure-Neumann pressure-Poisson systems via zero-mean gauge projection in
poisson_2d_cg(..., neumann=True).Demonstrate mesh-independent -cycle convergence () across dyadic grids using
poisson_2d_multigrid_vcycle.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engcfd
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engcfd" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engcfd.git"], check=True)
import engcfd
import inspect
import numpy as np
import matplotlib.pyplot as plt
from engcfd import (burgers_riemann, constants, convection_diffusion, elliptic_multigrid, grids_fvm,
lattice_boltzmann, navier_stokes, tvd_advection)
from engcfd.plotting import label_panels, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. The 5-Point Discrete Poisson Operator & Spectral Fast Sine Solver¶
1.1 Discrete Eigenfunctions & Eigenvalues on a Vertex Grid¶
On a uniform vertex grid covering with and , the 5-point finite-difference operator at interior vertex is:
With homogeneous Dirichlet walls ( on ), the sine modes diagonalize exactly with discrete eigenvalues:
elliptic_multigrid.poisson_2d_fast_sine(rhs_interior, dx, dy) applies the 2-D Discrete Sine Transform (DST-I via FFT), divides by , and transforms back in time with zero iterations.
heading("Demonstration 1: Fast Sine Direct Solver & O(h^2) Truncation Convergence")
errs_pde = []
ns_conv = [17, 33, 65, 129]
for n_v in ns_conv:
h = 1.0 / (n_v - 1)
xv = np.linspace(0.0, 1.0, n_v)
X, Y = np.meshgrid(xv, xv, indexing="ij")
u_true = np.sin(np.pi * X) * np.sin(2.0 * np.pi * Y)
f_full = 5.0 * (np.pi ** 2) * u_true # -lap(u_true) = (1^2 + 2^2)*pi^2 * u_true
u_int = elliptic_multigrid.poisson_2d_fast_sine(f_full[1:-1, 1:-1], h, h)
u_num = np.zeros_like(u_true)
u_num[1:-1, 1:-1] = u_int
# Verify exact discrete residual on interior 5-point stencil:
lap_res = np.max(np.abs(f_full[1:-1, 1:-1] - elliptic_multigrid._neg_laplacian_dirichlet(u_num, h, h)))
err_inf = float(np.max(np.abs(u_num - u_true)))
errs_pde.append(err_inf)
print(f"Grid {n_v:3d}x{n_v:<3d} (h = 1/{n_v-1:<3d}) | Discrete algebraic residual = {lap_res:.2e} | PDE error ||u_h - u||_inf = {err_inf:.4e}")
assert lap_res < 1.0e-10
orders_p = [np.log2(errs_pde[k] / errs_pde[k + 1]) for k in range(len(ns_conv) - 1)]
print("Observed PDE convergence orders:", [round(float(p), 4) for p in orders_p])
assert all(p > 1.995 for p in orders_p)
Demonstration 1: Fast Sine Direct Solver & O(h^2) Truncation Convergence
========================================================================
Grid 17x17 (h = 1/16 ) | Discrete algebraic residual = 2.13e-13 | PDE error ||u_h - u||_inf = 1.0989e-02
Grid 33x33 (h = 1/32 ) | Discrete algebraic residual = 9.81e-13 | PDE error ||u_h - u||_inf = 2.7350e-03
Grid 65x65 (h = 1/64 ) | Discrete algebraic residual = 3.62e-12 | PDE error ||u_h - u||_inf = 6.8297e-04
Grid 129x129 (h = 1/128) | Discrete algebraic residual = 1.58e-11 | PDE error ||u_h - u||_inf = 1.7069e-04
Observed PDE convergence orders: [2.0065, 2.0016, 2.0004]
n_plot = 65
h_plot = 1.0 / (n_plot - 1)
x_plot = np.linspace(0.0, 1.0, n_plot)
X_plot, Y_plot = np.meshgrid(x_plot, x_plot, indexing="ij")
f_plot = 50.0 * np.exp(-40.0 * ((X_plot - 0.3) ** 2 + (Y_plot - 0.6) ** 2))
u_plot = np.zeros_like(f_plot)
u_plot[1:-1, 1:-1] = elliptic_multigrid.poisson_2d_fast_sine(f_plot[1:-1, 1:-1], h_plot, h_plot)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.4, 4.2))
c1 = ax1.contourf(X_plot, Y_plot, f_plot, levels=12, cmap="Oranges")
fig.colorbar(c1, ax=ax1, label="source $f$ [-]")
c2 = ax2.contourf(X_plot, Y_plot, u_plot, levels=12, cmap="Blues")
fig.colorbar(c2, ax=ax2, label="solution $u$ [-]")
for ax in (ax1, ax2):
ax.set_xlabel("$x$ [-]"); ax.set_ylabel("$y$ [-]"); ax.set_aspect("equal")
label_panels(fig)
plt.show()
Figure 3.1. A Poisson problem with on the boundary, solved with the fast sine transform on a grid. (a) A localized source. (b) The solution, which is much smoother than the source and extends over the whole domain.
What Demonstration 1 shows. Two errors must be distinguished: the algebraic residual (, meaning poisson_2d_fast_sine solved the discrete linear system to rounding error) and PDE discretization error (it falls by a factor close to 4 whenever is halved).
2. Relaxation vs. Krylov Solvers: Jacobi, Optimal Red–Black SOR & Conjugate Gradient¶
When irregular geometry or variable density precludes FFTs, we turn to iterative solvers:
Jacobi (
poisson_2d_jacobi): Spectral radius requires iterations.Young’s Optimal Red–Black SOR (
poisson_2d_sor): Colors vertices like a checkerboard(i + j) % 2for full NumPy vectorization and applies Young’s exact optimal over-relaxation factor:
Matrix-Free Conjugate Gradient (
poisson_2d_cg): Minimizes the SPD energy norm over Krylov subspaces in iterations without tuning , and solves singular pure-Neumann pressure equations (neumann=True) by projecting both RHS and iterates onto the zero-mean subspace .
heading("Demonstration 2: Comparing Jacobi, Optimal Red-Black SOR, and CG (Dirichlet & Pure Neumann) on 33x33")
n33 = 33
h33 = 1.0 / (n33 - 1)
xv33 = np.linspace(0.0, 1.0, n33)
X33, Y33 = np.meshgrid(xv33, xv33, indexing="ij")
# Right-hand side: a smooth (1,1) mode, an oscillatory (7,5) mode and a localized source:
f33 = 2.0 * (np.pi ** 2) * np.sin(np.pi * X33) * np.sin(np.pi * Y33) + 74.0 * (np.pi ** 2) * 0.2 * np.sin(7 * np.pi * X33) * np.sin(5 * np.pi * Y33)
f33 += 50.0 * np.exp(-40.0 * ((X33 - 0.3) ** 2 + (Y33 - 0.6) ** 2)) # a localized source, so that many eigenmodes are excited
u_ref33 = np.zeros_like(f33)
u_ref33[1:-1, 1:-1] = elliptic_multigrid.poisson_2d_fast_sine(f33[1:-1, 1:-1], h33, h33)
out_jac = elliptic_multigrid.poisson_2d_jacobi(f33, h33, h33, tol=1e-9, max_iter=8000)
out_sor = elliptic_multigrid.poisson_2d_sor(f33, h33, h33, omega=None, tol=1e-9, max_iter=2000)
out_cg = elliptic_multigrid.poisson_2d_cg(f33, h33, h33, neumann=False, tol=1e-9, max_iter=1000)
out_mg = elliptic_multigrid.poisson_2d_multigrid_vcycle(f33, L=1.0, n_cycles=12, tol=1e-9)
print(f"Jacobi : {out_jac['iterations']:4d} iters | max diff vs FastSine = {np.max(np.abs(out_jac['u'] - u_ref33)):.2e}")
print(f"Optimal SOR : {out_sor['iterations']:4d} iters (omega_opt = {out_sor['omega']:.4f}) | max diff = {np.max(np.abs(out_sor['u'] - u_ref33)):.2e}")
print(f"Conjugate Grad: {out_cg['iterations']:4d} iters | max diff vs FastSine = {np.max(np.abs(out_cg['u'] - u_ref33)):.2e}")
print(f"Multigrid V(2,2): {out_mg['cycles']:2d} V-cycles (rho = {out_mg['convergence_factor']:.4f}) | max diff = {np.max(np.abs(out_mg['u'] - u_ref33)):.2e}")
# Pure-Neumann test on cell-centered 32x32 pressure field u_neu = cos(2*pi*xc)*cos(pi*yc):
g_neu = grids_fvm.uniform_fvm_grid_2d(1.0, 1.0, 32, 32)
f_neu = 5.0 * (np.pi ** 2) * np.cos(2.0 * np.pi * g_neu["XC"]) * np.cos(np.pi * g_neu["YC"]) + 3.5 # includes a non-zero mean, +3.5
f_neu += 30.0 * np.exp(-40.0 * ((g_neu["XC"] - 0.3) ** 2 + (g_neu["YC"] - 0.6) ** 2)) # a localized source, so that many eigenmodes are excited
out_cg_neu = elliptic_multigrid.poisson_2d_cg(f_neu, g_neu["dx"], g_neu["dy"], neumann=True, tol=1e-11)
print(f"Pure-Neumann CG (32x32): {out_cg_neu['iterations']} iters, mean(u) = {np.mean(out_cg_neu['u']):+.2e}, final res = {out_cg_neu['residual_history'][-1]:.2e}")
assert out_jac["iterations"] > 15 * out_sor["iterations"]
assert out_mg["cycles"] <= 10
assert np.allclose(out_sor["u"], u_ref33, atol=1e-8)
assert np.allclose(out_cg["u"], u_ref33, atol=1e-8)
assert abs(np.mean(out_cg_neu["u"])) < 1.0e-14 and out_cg_neu["residual_history"][-1] < 1.0e-11
Demonstration 2: Comparing Jacobi, Optimal Red-Black SOR, and CG (Dirichlet & Pure Neumann) on 33x33
====================================================================================================
Jacobi : 5001 iters | max diff vs FastSine = 5.07e-11
Optimal SOR : 156 iters (omega_opt = 1.8215) | max diff = 2.43e-12
Conjugate Grad: 108 iters | max diff vs FastSine = 7.18e-13
Multigrid V(2,2): 9 V-cycles (rho = 0.0542) | max diff = 1.84e-11
Pure-Neumann CG (32x32): 150 iters, mean(u) = +1.39e-17, final res = 9.65e-12
What Demonstration 2 shows. On the mesh, Jacobi needs 5001 sweeps to bring the residual below 10-9, red–black SOR with the optimal factor () needs 156 sweeps (32 times fewer), conjugate gradients need 108 iterations and multigrid needs 9 V-cycles. The right-hand side contains a localized source so that many eigenmodes are excited; conjugate gradients would otherwise finish in as many iterations as there are distinct eigenvalues in the right-hand side.
3. Geometric Multigrid V-Cycles: Mesh-Independent Convergence¶
Why does Multigrid win so decisively as ?
High-frequency smoothing: 2 sweeps of Red–Black Gauss–Seidel rapidly damp oscillatory error modes () on grid .
Coarse-grid aliasing (
_restrict_full_weighting): Smooth error on grid appears twice as oscillatory () when restricted to coarse grid , recursive down to the single-interior-node grid where is solved directly in 1 division.Bilinear prolongation (
_prolong_bilinear) & post-smoothing: Interpolates the coarse error correction back to grid and cleans up interpolation ripples.
We benchmark iteration/cycle scaling across four dyadic grids: .
heading("Demonstration 3: Mesh-Refinement Scaling Benchmark Across 17^2, 33^2, 65^2, and 129^2 Grids")
grids_mg = [17, 33, 65, 129]
sor_iters, cg_iters, mg_cycles, mg_rhos, jac_theory = [], [], [], [], []
print(f"{'Grid':9s} | {'DOFs':>7s} | {'Jacobi(th)':>10s} | {'Opt SOR':>8s} | {'CG':>6s} | {'MG V(2,2)':>9s} | {'MG rho':>8s}")
print("-" * 72)
for nv in grids_mg:
hv = 1.0 / (nv - 1)
xv = np.linspace(0.0, 1.0, nv)
Xv, Yv = np.meshgrid(xv, xv, indexing="ij")
fv = 2.0 * (np.pi ** 2) * np.sin(np.pi * Xv) * np.sin(np.pi * Yv) + 20.0 * np.sin(6 * np.pi * Xv) * np.sin(4 * np.pi * Yv)
fv += 50.0 * np.exp(-40.0 * ((Xv - 0.3) ** 2 + (Yv - 0.6) ** 2))
rho_j = np.cos(np.pi * hv)
j_est = int(np.ceil(np.log(1.0e-10) / np.log(rho_j)))
# Absolute tolerance 1e-8 on the residual, about 1e-10 of its initial size (1e-10 absolute is below rounding error on the finest grid):
s_res = elliptic_multigrid.poisson_2d_sor(fv, hv, hv, tol=1e-8, max_iter=4000)
c_res = elliptic_multigrid.poisson_2d_cg(fv, hv, hv, tol=1e-8, max_iter=2000)
m_res = elliptic_multigrid.poisson_2d_multigrid_vcycle(fv, L=1.0, n_cycles=15, pre_smooth=2, post_smooth=2, tol=1e-8)
jac_theory.append(j_est); sor_iters.append(s_res["iterations"])
cg_iters.append(c_res["iterations"]); mg_cycles.append(m_res["cycles"]); mg_rhos.append(m_res["convergence_factor"])
print(f"{nv:3d}x{nv:<5d} | {(nv-2)**2:7d} | {j_est:10d} | {s_res['iterations']:8d} | {c_res['iterations']:6d} | {m_res['cycles']:9d} | {m_res['convergence_factor']:8.4f}")
assert m_res["convergence_factor"] < 0.12
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.2, 4.3))
ax1.semilogy(np.arange(1, len(out_jac["residual_history"]) + 1), out_jac["residual_history"], "-", color="#7f7f7f", lw=1.6, label="Jacobi ($33^2$)")
ax1.semilogy(np.arange(1, len(out_sor["residual_history"]) + 1), out_sor["residual_history"], "--", color="#ff7f0e", lw=2.0, label="Optimal SOR ($33^2$)")
ax1.semilogy(np.arange( len(out_cg["residual_history"])), out_cg["residual_history"], "-.", color="#2ca02c", lw=2.0, label="Conjugate Gradient ($33^2$)")
ax1.semilogy(np.arange(len(out_mg["residual_history"])), out_mg["residual_history"], "o-", color="#1f77b4", lw=2.2, ms=5, label="Multigrid V(2,2) ($33^2$)")
ax1.set_xlim(0, 160)
ax1.set_xlabel("Iteration / V-Cycle Count [-]")
ax1.set_ylabel(r"Max Residual $\|f - (-\nabla_h^2 u)\|_\infty$")
ax1.set_title("Residual Decay on $33\\times 33$ Grid")
ax1.legend(fontsize=8.3, frameon=False, loc=(0.60, 0.50))
ax2.loglog(grids_mg, jac_theory, "^:", color="#7f7f7f", lw=1.8, label="Jacobi ($O(N^2)$)")
ax2.loglog(grids_mg, sor_iters, "s--", color="#ff7f0e", lw=2.0, label="Optimal SOR ($O(N)$)")
ax2.loglog(grids_mg, cg_iters, "d-.", color="#2ca02c", lw=2.0, label="Conjugate Gradient ($O(N)$)")
ax2.loglog(grids_mg, mg_cycles, "o-", color="#1f77b4", lw=2.4, ms=6, label="Multigrid V(2,2) ($O(1)$ cycles)")
ax2.set_xlabel("Grid Points per Axis $N$ [-]")
ax2.set_ylabel("Iterations or V-Cycles")
ax2.set_title("Mesh-Independent Multigrid Scaling")
ax2.legend(fontsize=8.3, frameon=False)
label_panels(fig)
plt.show()
assert max(mg_cycles) <= 12 and all(r < 0.12 for r in mg_rhos)
Demonstration 3: Mesh-Refinement Scaling Benchmark Across 17^2, 33^2, 65^2, and 129^2 Grids
===========================================================================================
Grid | DOFs | Jacobi(th) | Opt SOR | CG | MG V(2,2) | MG rho
------------------------------------------------------------------------
17x17 | 225 | 1187 | 70 | 48 | 8 | 0.0575
33x33 | 961 | 4771 | 144 | 101 | 9 | 0.0605
65x65 | 3969 | 19105 | 295 | 209 | 9 | 0.0623
129x129 | 16129 | 76441 | 604 | 423 | 9 | 0.0634

Figure 3.2. (a) Largest residual against the iteration number on the grid for Jacobi, optimal SOR, conjugate gradients and multigrid V-cycles. (b) Number of iterations or V-cycles needed against the number of grid points per axis; the Jacobi values are the estimate from its spectral radius.
What Demonstration 3 shows. Refining the mesh by a factor of 8 per axis, from 172 (225 unknowns) to 1292 ( unknowns), raises the estimated number of Jacobi sweeps from 1187 to , the SOR sweeps from 70 to 604 and the conjugate-gradient iterations from 48 to 423. Multigrid needs 8 or 9 V-cycles on every grid (panel (b)); its convergence factor stays between 0.058 and 0.063, so each V-cycle lowers the residual by more than a factor of ten whatever the grid size.
4. SOR Sensitivity Cliff Around & Dyadic Guards¶
What happens if we guess slightly too low or too high in poisson_2d_sor instead of using Young’s theoretical ? We sweep on () and verify the dyadic grid check in poisson_2d_multigrid_vcycle.
heading("Demonstration 4: SOR Relaxation-Factor Cliff Around Young's Optimum & Multigrid Guards")
omegas = [1.0, 1.4, 1.7, out_sor["omega"], 1.88, 1.95]
print(f"Theoretical Young optimum on 33x33: omega_opt = {out_sor['omega']:.5f}")
iters_om = []
for om in omegas:
res_o = elliptic_multigrid.poisson_2d_sor(f33, h33, h33, omega=om, tol=1e-9, max_iter=4000)
iters_om.append(res_o["iterations"])
tag = " <-- Gauss-Seidel" if om == 1.0 else (" <-- Young Optimum" if np.isclose(om, out_sor["omega"]) else "")
print(f"omega = {om:.5f} -> {res_o['iterations']:4d} iterations{tag}")
assert iters_om[3] == min(iters_om)
assert iters_om[0] > 15 * iters_om[3] # Gauss-Seidel (omega=1) is >15x slower than optimal SOR
# Verify dyadic grid requirement (2^k + 1) in poisson_2d_multigrid_vcycle:
caught_dyadic = False
try:
elliptic_multigrid.poisson_2d_multigrid_vcycle(np.zeros((20, 20)), L=1.0)
except ValueError:
caught_dyadic = True
assert caught_dyadic
Demonstration 4: SOR Relaxation-Factor Cliff Around Young's Optimum & Multigrid Guards
======================================================================================
Theoretical Young optimum on 33x33: omega_opt = 1.82147
omega = 1.00000 -> 2573 iterations <-- Gauss-Seidel
omega = 1.40000 -> 1114 iterations
omega = 1.70000 -> 440 iterations
omega = 1.82147 -> 156 iterations <-- Young Optimum
omega = 1.88000 -> 212 iterations
omega = 1.95000 -> 530 iterations
Inside the algorithm¶
Geometric multigrid relies on the variational property of its transfer operators: full-weighting restriction (_restrict_full_weighting) is the exact scaled transpose of bilinear prolongation (_prolong_bilinear) with respect to the discrete inner product:
Below we inspect both transfer operators and verify Equation (4.1) to rounding error ().
Check against the library¶
heading("Inside the Algorithm: Full-Weighting Restriction == Adjoint of Bilinear Prolongation")
print(show_source(elliptic_multigrid._restrict_full_weighting))
print(show_source(elliptic_multigrid._prolong_bilinear))
rng = np.random.default_rng(2026)
nf, nc = 33, 17
hf, hc = 1.0 / (nf - 1), 1.0 / (nc - 1)
r_fine = np.zeros((nf, nf))
r_fine[1:-1, 1:-1] = rng.standard_normal((nf - 2, nf - 2))
e_coarse = np.zeros((nc, nc))
e_coarse[1:-1, 1:-1] = rng.standard_normal((nc - 2, nc - 2))
r_rest = elliptic_multigrid._restrict_full_weighting(r_fine)
e_prol = elliptic_multigrid._prolong_bilinear(e_coarse)
ip_coarse = (hc ** 2) * float(np.sum(r_rest[1:-1, 1:-1] * e_coarse[1:-1, 1:-1]))
ip_fine = (hf ** 2) * float(np.sum(r_fine[1:-1, 1:-1] * e_prol[1:-1, 1:-1]))
print(f"<I_h^2h r_h, e_2h>_2h = {ip_coarse:+.14f}")
print(f"<r_h, I_2h^h e_2h>_h = {ip_fine:+.14f} | |diff| = {abs(ip_coarse - ip_fine):.2e}")
assert np.isclose(ip_coarse, ip_fine, rtol=1e-14, atol=1e-14)
Inside the Algorithm: Full-Weighting Restriction == Adjoint of Bilinear Prolongation
====================================================================================
def _restrict_full_weighting(res_fine: np.ndarray) -> np.ndarray:
"""Full-weighting restriction from (2^k + 1) x (2^k + 1) fine vertex grid to (2^{k-1} + 1) coarse grid."""
nxf, nyf = res_fine.shape
nxc, nyc = (nxf - 1) // 2 + 1, (nyf - 1) // 2 + 1
rc = np.zeros((nxc, nyc), dtype=float)
rc[1:-1, 1:-1] = (
4.0 * res_fine[2:-2:2, 2:-2:2]
+ 2.0
* (
res_fine[1:-3:2, 2:-2:2]
+ res_fine[3:-1:2, 2:-2:2]
+ res_fine[2:-2:2, 1:-3:2]
+ res_fine[2:-2:2, 3:-1:2]
)
+ (
res_fine[1:-3:2, 1:-3:2]
+ res_fine[1:-3:2, 3:-1:2]
+ res_fine[3:-1:2, 1:-3:2]
+ res_fine[3:-1:2, 3:-1:2]
)
) / 16.0
return rc
def _prolong_bilinear(err_coarse: np.ndarray) -> np.ndarray:
"""Bilinear prolongation from (2^{k-1} + 1) coarse vertex grid to (2^k + 1) fine vertex grid."""
nxc, nyc = err_coarse.shape
nxf, nyf = 2 * (nxc - 1) + 1, 2 * (nyc - 1) + 1
ef = np.zeros((nxf, nyf), dtype=float)
ef[0::2, 0::2] = err_coarse
ef[1::2, 0::2] = 0.5 * (err_coarse[:-1, :] + err_coarse[1:, :])
ef[0::2, 1::2] = 0.5 * (err_coarse[:, :-1] + err_coarse[:, 1:])
ef[1::2, 1::2] = 0.25 * (
err_coarse[:-1, :-1] + err_coarse[1:, :-1] + err_coarse[:-1, 1:] + err_coarse[1:, 1:]
)
return ef
<I_h^2h r_h, e_2h>_2h = +0.00032483723828
<r_h, I_2h^h e_2h>_h = +0.00032483723828 | |diff| = 8.67e-18
Exercises¶
Worked solutions are in 03_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. On a grid (), verify that
poisson_2d_fast_sinerecovers to when forced by , and verify the exact ratio when forced by .Find how it fails. Demonstrate Ostrowski–Reich instability of
poisson_2d_sorat on , show algebraically on random arrays that the discrete pure-Neumann Laplacian sums to zero (), and verify zero-mean gauge projection inpoisson_2d_cg(..., neumann=True).Implement it yourself. Implement
audit_smoother_frequency_selectivity(n_pts=33, n_sweeps=10)applying Red–Black Gauss–Seidel (_rbgs_smooth) to from initial error for smooth vs. oscillatory , and show that 10 sweeps damp by while leaving of untouched.
heading("Self-check for the exercises")
nv_c = 33
hc = 1.0 / (nv_c - 1)
xc = np.linspace(0.0, 1.0, nv_c)
Xc, Yc = np.meshgrid(xc, xc, indexing="ij")
p_m, q_m = 3, 5
v_pq = np.sin(p_m * np.pi * Xc) * np.sin(q_m * np.pi * Yc)
lam_disc = (4.0 / hc ** 2) * (np.sin(0.5 * p_m * np.pi * hc) ** 2 + np.sin(0.5 * q_m * np.pi * hc) ** 2)
u_rec = elliptic_multigrid.poisson_2d_fast_sine((lam_disc * v_pq)[1:-1, 1:-1], hc, hc)
assert np.allclose(u_rec, v_pq[1:-1, 1:-1], atol=1e-14)
print(f"Discrete eigenmode (3,5) recovered to {np.max(np.abs(u_rec - v_pq[1:-1, 1:-1])):.2e}")
print("All checks passed.")
Self-check for the exercises
============================
Discrete eigenmode (3,5) recovered to 1.55e-15
All checks passed.