Worked solutions to the three exercises of Lecture 3. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
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))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
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)
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. On a grid (), verify that poisson_2d_fast_sine recovers to when forced by , and verify the exact ratio when forced by .
heading("Exercise 1: Exact Discrete Eigenfunction vs Continuous PDE Eigenvalue on 33x33")
nv = 33
h = 1.0 / (nv - 1)
xv = np.linspace(0.0, 1.0, nv)
X, Y = np.meshgrid(xv, xv, indexing="ij")
p_mode, q_mode = 3, 5
v_mode = np.sin(p_mode * np.pi * X) * np.sin(q_mode * np.pi * Y)
lam_h = (4.0 / (h ** 2)) * (np.sin(0.5 * p_mode * np.pi * h) ** 2 + np.sin(0.5 * q_mode * np.pi * h) ** 2)
lam_pde = float((p_mode ** 2 + q_mode ** 2) * (np.pi ** 2))
u_from_disc = elliptic_multigrid.poisson_2d_fast_sine((lam_h * v_mode)[1:-1, 1:-1], h, h)
u_from_pde = elliptic_multigrid.poisson_2d_fast_sine((lam_pde * v_mode)[1:-1, 1:-1], h, h)
err_disc = float(np.max(np.abs(u_from_disc - v_mode[1:-1, 1:-1])))
ratio_num = float(np.max(u_from_pde) / np.max(v_mode[1:-1, 1:-1]))
ratio_exact = lam_pde / lam_h
print(f"lam_PDE = {lam_pde:.6f} vs lam_h = {lam_h:.6f} (O(h^2) relative shift = {ratio_exact - 1.0:.5f})")
print(f"Max error with discrete eigenvalue forcing = {err_disc:.2e}")
print(f"Amplitude ratio with PDE forcing = {ratio_num:.12f} vs lam_PDE/lam_h = {ratio_exact:.12f}")
assert err_disc < 1.0e-14
assert np.isclose(ratio_num, ratio_exact, rtol=1e-14)
Exercise 1: Exact Discrete Eigenfunction vs Continuous PDE Eigenvalue on 33x33
==============================================================================
lam_PDE = 335.566550 vs lam_h = 330.011443 (O(h^2) relative shift = 0.01683)
Max error with discrete eigenvalue forcing = 1.55e-15
Amplitude ratio with PDE forcing = 1.016833072668 vs lam_PDE/lam_h = 1.016833072668
Explanation. Since , the discrete 5-point Laplacian slightly underestimates curvature (), causing second-order centered differences to slightly overpredict mode amplitude by on .
Exercise 2¶
Problem. Demonstrate Ostrowski–Reich instability of poisson_2d_sor at on , show algebraically on random arrays that the discrete pure-Neumann Laplacian sums to zero (), and verify zero-mean gauge projection in poisson_2d_cg(..., neumann=True).
heading("Exercise 2: SOR Over-Relaxation Blowup (omega = 2.04) & Neumann Nullspace Solvability")
n17 = 17
h17 = 1.0 / (n17 - 1)
xv17 = np.linspace(0.0, 1.0, n17)
X17, Y17 = np.meshgrid(xv17, xv17, indexing="ij")
f17 = np.sin(np.pi * X17) * np.sin(np.pi * Y17)
sor_blowup = elliptic_multigrid.poisson_2d_sor(f17, h17, h17, omega=2.04, tol=1e-10, max_iter=60)
r_start = sor_blowup["residual_history"][0]
r_end = sor_blowup["residual_history"][-1]
print(f"SOR at omega = 2.04 (> 2.0): residual grew from {r_start:.3e} to {r_end:.3e} in 60 sweeps (amplification = {r_end/r_start:.1f}x)")
assert r_end > 20.0 * r_start
# Prove discrete Neumann operator range is strictly zero-mean for ANY field u:
rng = np.random.default_rng(99)
u_rand = rng.standard_normal((16, 16))
up = np.pad(u_rand, 1, mode="edge")
lap_neu = (2.0 * u_rand - up[:-2, 1:-1] - up[2:, 1:-1]) / (h17 ** 2) + (2.0 * u_rand - up[1:-1, :-2] - up[1:-1, 2:]) / (h17 ** 2)
sum_lap = float(np.sum(lap_neu))
print(f"Sum of discrete Neumann (-lap_h u) over all cells = {sum_lap:+.2e} (exact telescoping zero)")
assert abs(sum_lap) < 1.0e-11
# Solve biased RHS f_biased = cos(2*pi*x)*cos(2*pi*y) + 5.0 via poisson_2d_cg(..., neumann=True):
g16 = grids_fvm.uniform_fvm_grid_2d(1.0, 1.0, 16, 16)
f_biased = np.cos(2.0 * np.pi * g16["XC"]) * np.cos(2.0 * np.pi * g16["YC"]) + 5.0
cg_n = elliptic_multigrid.poisson_2d_cg(f_biased, g16["dx"], g16["dy"], neumann=True, tol=1e-12)
print(f"Biased pure-Neumann CG: {cg_n['iterations']} iters, mean(u) = {np.mean(cg_n['u']):+.2e}, final res = {cg_n['residual_history'][-1]:.2e}")
assert abs(np.mean(cg_n["u"])) < 1.0e-14 and cg_n["residual_history"][-1] < 1.0e-12
Exercise 2: SOR Over-Relaxation Blowup (omega = 2.04) & Neumann Nullspace Solvability
=====================================================================================
SOR at omega = 2.04 (> 2.0): residual grew from 4.964e+00 to 1.068e+02 in 60 sweeps (amplification = 21.5x)
Sum of discrete Neumann (-lap_h u) over all cells = +2.27e-12 (exact telescoping zero)
Biased pure-Neumann CG: 1 iters, mean(u) = +3.39e-21, final res = 1.31e-14
Explanation. Every eigenvalue of the Red–Black SOR iteration matrix has when ; once , for every coupled pair and the iteration diverges (the residual grows by a factor of 21.5 in 60 sweeps). For pure Neumann BCs (such as incompressible walls ), identically, so any net mass source violates mass conservation unless projected out.
Exercise 3¶
Problem. 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("Exercise 3: Implement It Yourself — Smoother Wavenumber Selectivity check")
def audit_smoother_frequency_selectivity(n_pts: int = 33, n_sweeps: int = 10) -> dict:
"""Measure Red-Black Gauss-Seidel error-damping ratios on low (k=1) vs mid-high (k=16) modes."""
h = 1.0 / (n_pts - 1)
xv = np.linspace(0.0, 1.0, n_pts)
X, Y = np.meshgrid(xv, xv, indexing="ij")
f_zero = np.zeros((n_pts, n_pts))
results = {}
for k_mode, label in [(1, "low_k1"), (16, "high_k16")]:
e = np.sin(k_mode * np.pi * X) * np.sin(k_mode * np.pi * Y)
e[0, :] = e[-1, :] = e[:, 0] = e[:, -1] = 0.0
norm0 = float(np.max(np.abs(e)))
hist = [norm0]
for _ in range(n_sweeps):
elliptic_multigrid._rbgs_smooth(e, f_zero, h, n_sweeps=1)
hist.append(float(np.max(np.abs(e))))
results[label] = {"history": np.array(hist), "final_ratio": hist[-1] / norm0}
return results
sel = audit_smoother_frequency_selectivity(n_pts=33, n_sweeps=10)
rho_gs_k1_theory = (np.cos(np.pi / 32.0) ** 2) ** 10 # Gauss-Seidel damps (1,1) as cos^(2*sweeps)(pi*h)
print(f"Smooth mode (1,1) remaining after 10 RBGS sweeps: {100*sel['low_k1']['final_ratio']:.2f}% (theory ~ {100*rho_gs_k1_theory:.2f}%)")
print(f"High-k mode (16,16) remaining after 10 RBGS sweeps: {sel['high_k16']['final_ratio']:.3e} (damped by {1.0/sel['high_k16']['final_ratio']:.1e}x)")
assert sel["low_k1"]["final_ratio"] > 0.90
assert sel["high_k16"]["final_ratio"] < 1.0e-5
Exercise 3: Implement It Yourself — Smoother Wavenumber Selectivity check
=========================================================================
Smooth mode (1,1) remaining after 10 RBGS sweeps: 91.24% (theory ~ 90.80%)
High-k mode (16,16) remaining after 10 RBGS sweeps: 1.393e-21 (damped by 7.2e+20x)
Summary. Gauss–Seidel is a poor stand-alone solver ( of the mode survives 10 sweeps) yet an effective smoother (it damps the mode by in 10 sweeps). Multigrid exploits this exact dichotomy by letting coarse grids handle smooth modes on their natural length scale.