Worked solutions to the three exercises of Lecture 14. 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 O(N log N) Streamfunction Inversion & Thom's 2nd-Order Wall Vorticity")
n_t = 65
h_t = 1.0 / (n_t - 1)
xg = np.linspace(0.0, 1.0, n_t)
Xt, Yt = np.meshgrid(xg, xg, indexing="ij")
# Manufactured smooth cavity streamfunction psi(x,y) = sin^2(pi*x)*sin^2(pi*y) (psi=0 and u=v=0 on all walls):
psi_exact = (np.sin(np.pi * Xt) ** 2) * (np.sin(np.pi * Yt) ** 2)
d2_sin2 = lambda z: 2.0 * (np.pi**2) * np.cos(2.0 * np.pi * z)
omega_exact = -(d2_sin2(Xt) * (np.sin(np.pi * Yt) ** 2) + (np.sin(np.pi * Xt) ** 2) * d2_sin2(Yt))
# 1) Verify poisson_2d_fast_sine recovers psi from discrete -lap_h(psi_exact) to machine precision, and matches continuum omega to O(h^2):
psi_dst = np.zeros_like(psi_exact)
psi_dst[1:-1, 1:-1] = elliptic_multigrid.poisson_2d_fast_sine(omega_exact[1:-1, 1:-1], dx=h_t, dy=h_t)
psi_err = float(np.max(np.abs(psi_dst - psi_exact)))
# 2) Verify Thom's top-wall vorticity formula omega_top = -2 * psi[:, -2] / h^2 vs omega_exact[:, -1]:
thom_top = -2.0 * psi_exact[:, -2] / (h_t**2)
thom_err = float(np.max(np.abs(thom_top - omega_exact[:, -1])))
print(f"DST-I streamfunction max |psi_dst - psi_exact| (65x65) : {psi_err:.4e}")
print(f"Thom top-wall vorticity max |omega_Thom - omega_exact| : {thom_err:.4e} (exact peak |omega_wall| = {2*np.pi**2:.3f})")
# Confirm O(h^2) convergence of Thom's wall formula across n_grid = 33 -> 65 -> 129:
thom_errs = []
for ng in [33, 65, 129]:
hg = 1.0 / (ng - 1)
xs = np.linspace(0.0, 1.0, ng)
psi_penult = (np.sin(np.pi * xs) ** 2) * (np.sin(np.pi * (1.0 - hg)) ** 2)
om_wall_ex = -(np.sin(np.pi * xs) ** 2) * (2.0 * (np.pi**2))
thom_errs.append(float(np.max(np.abs(-2.0 * psi_penult / (hg**2) - om_wall_ex))))
thom_order = np.log2(thom_errs[0] / thom_errs[1])
print(f"Thom wall error 33 -> 65 -> 129 : {[round(e, 6) for e in thom_errs]} (observed order = {thom_order:.3f})")
assert psi_err < 1e-3 and np.isclose(thom_order, 2.0, atol=0.05)
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Evaluate Thom’s bottom-wall vorticity formula across on two analytical streamfunctions satisfying : (a) symmetric () and (b) cubic-shear (). Verify observed convergence orders and from Taylor’s remainder theorem.
heading("Exercise 1: Taylor Remainder Analysis of Thom's Wall Vorticity Formula")
errs_A, errs_B = [], []
for ng in [17, 33, 65, 129]:
h = 1.0 / (ng - 1)
x = np.linspace(0.0, 1.0, ng)
psiA_1 = (np.sin(np.pi * h) ** 2) * np.sin(np.pi * x)
omA_ex = -2.0 * (np.pi**2) * np.sin(np.pi * x)
errs_A.append(float(np.max(np.abs(-2.0 * psiA_1 / (h**2) - omA_ex))))
psiB_1 = (h**2) * (1.0 - h) * np.sin(np.pi * x)
omB_ex = -2.0 * np.sin(np.pi * x)
errs_B.append(float(np.max(np.abs(-2.0 * psiB_1 / (h**2) - omB_ex))))
orders_A = np.log2(np.array(errs_A[:-1]) / np.array(errs_A[1:]))
orders_B = np.log2(np.array(errs_B[:-1]) / np.array(errs_B[1:]))
print(f"Symmetric psi_A orders : {np.round(orders_A, 4)} (O(h^2) when d^3 psi/dy^3|_wall == 0)")
print(f"Cubic psi_B orders : {np.round(orders_B, 4)} (exact leading error = 2*h*sin(pi*x) -> O(h^1))")
assert np.allclose(orders_A, 2.0, atol=0.03)
assert np.allclose(orders_B, 1.0, atol=0.01)
Exercise 1: Taylor Remainder Analysis of Thom's Wall Vorticity Formula
======================================================================
Symmetric psi_A orders : [1.9944 1.9986 1.9997] (O(h^2) when d^3 psi/dy^3|_wall == 0)
Cubic psi_B orders : [1. 1. 1.] (exact leading error = 2*h*sin(pi*x) -> O(h^1))
Explanation. Expanding shows that : Thom’s formula is truncation-exact for pure linear wall shear (), first-order in the presence of normal vorticity gradient , and second-order whenever tangential pressure gradient vanishes.
Exercise 2¶
Problem. Verify that navier_stokes.lid_driven_cavity_2d raises ValueError for invalid inputs (n_grid=5, Re=0.0, U_lid=-1.0), and demonstrate on n_grid=33, Re=50 () that automatic time-stepping (dt=None) converges stably while forcing dt=0.04 () blows up.
heading("Exercise 2: Input Guards & Explicit Wall-Coupled Viscous Time-Step Blow-Up")
for kw in [{"n_grid": 5}, {"Re": 0.0}, {"Re": -10.0}, {"U_lid": -1.0}, {"L": 0.0}]:
caught = False
try:
navier_stokes.lid_driven_cavity_2d(**kw)
except ValueError:
caught = True
assert caught is True, f"Expected ValueError for {kw}"
auto_sol = navier_stokes.lid_driven_cavity_2d(n_grid=33, Re=50.0, dt=None, max_steps=400)
with np.errstate(over="ignore", invalid="ignore"):
bad_sol = navier_stokes.lid_driven_cavity_2d(n_grid=33, Re=50.0, dt=0.04, max_steps=80)
stable_ok = bool(np.all(np.isfinite(auto_sol["psi"])) and abs(auto_sol["psi_min"]) < 0.2)
blew_up = bool((not np.all(np.isfinite(bad_sol["psi"]))) or np.max(np.abs(bad_sol["vorticity"])) > 1e8)
print(f"dt=None (auto ~ 0.0107): psi_min = {auto_sol['psi_min']:.5f}, stable = {stable_ok}")
print(f"dt=0.04 (> h^2/(4*nu)=0.0122): vorticity blew up = {blew_up}")
assert stable_ok is True and blew_up is True
Exercise 2: Input Guards & Explicit Wall-Coupled Viscous Time-Step Blow-Up
==========================================================================
dt=None (auto ~ 0.0107): psi_min = -0.09946, stable = True
dt=0.04 (> h^2/(4*nu)=0.0122): vorticity blew up = True
Explanation. The automatic time step of lid_driven_cavity_2d is dt_diff = 0.22 * h^2 / nu, slightly stricter than the periodic bound, because Thom’s explicit wall vorticity boundary condition couples to and tightens the boundary spectral radius.
Exercise 3¶
Problem. Implement my_lid_cavity_step(psi, omega, h, nu, dt, U_lid) in pure NumPy using elliptic_multigrid.poisson_2d_fast_sine, evolve 150 steps from rest on n_grid=25, Re=100 at the exact auto dt = min(0.22*h^2/nu, 0.35*h/U_lid), and verify < 1e-13 agreement with navier_stokes.lid_driven_cavity_2d(n_grid=25, Re=100, max_steps=150, tol=1e-12).
heading("Exercise 3: Implement It Yourself — DST-Accelerated Vorticity-Streamfunction Cavity Stepper")
def my_lid_cavity_step(psi: np.ndarray, omega: np.ndarray, h: float, nu: float, dt: float, U_lid: float) -> tuple[np.ndarray, np.ndarray]:
"""Advance 2-D lid-driven cavity (psi, omega) by one explicit Thom + DST-I time step."""
om = omega.copy()
ps = psi.copy()
om[0, :] = -2.0 * ps[1, :] / (h**2)
om[-1, :] = -2.0 * ps[-2, :] / (h**2)
om[:, 0] = -2.0 * ps[:, 1] / (h**2)
om[:, -1] = -2.0 * (ps[:, -2] + h * U_lid) / (h**2)
u_in = (ps[1:-1, 2:] - ps[1:-1, :-2]) / (2.0 * h)
v_in = -(ps[2:, 1:-1] - ps[:-2, 1:-1]) / (2.0 * h)
dom_x = (om[2:, 1:-1] - om[:-2, 1:-1]) / (2.0 * h)
dom_y = (om[1:-1, 2:] - om[1:-1, :-2]) / (2.0 * h)
lap_o = (om[2:, 1:-1] + om[:-2, 1:-1] + om[1:-1, 2:] + om[1:-1, :-2] - 4.0 * om[1:-1, 1:-1]) / (h**2)
om[1:-1, 1:-1] = om[1:-1, 1:-1] + dt * (-(u_in * dom_x + v_in * dom_y) + nu * lap_o)
ps[1:-1, 1:-1] = elliptic_multigrid.poisson_2d_fast_sine(om[1:-1, 1:-1], dx=h, dy=h)
return ps, om
ng_e3 = 25
h_e3 = 1.0 / (ng_e3 - 1)
nu_e3 = 1.0 / 100.0
dt_e3 = min(0.22 * (h_e3**2) / nu_e3, 0.35 * h_e3 / 1.0)
psi_m = np.zeros((ng_e3, ng_e3))
om_m = np.zeros((ng_e3, ng_e3))
for _ in range(150):
psi_m, om_m = my_lid_cavity_step(psi_m, om_m, h=h_e3, nu=nu_e3, dt=dt_e3, U_lid=1.0)
ref_cav = navier_stokes.lid_driven_cavity_2d(n_grid=ng_e3, Re=100.0, dt=dt_e3, max_steps=150, tol=1e-12)
psi_diff = float(np.max(np.abs(psi_m - ref_cav["psi"])))
om_diff = float(np.max(np.abs(om_m - ref_cav["vorticity"])))
print(f"After 150 steps: max |psi_mine - psi_ref| = {psi_diff:.3e} | max |omega_mine - omega_ref| = {om_diff:.3e}")
assert psi_diff < 1e-13 and om_diff < 1e-12
Exercise 3: Implement It Yourself — DST-Accelerated Vorticity-Streamfunction Cavity Stepper
===========================================================================================
After 150 steps: max |psi_mine - psi_ref| = 0.000e+00 | max |omega_mine - omega_ref| = 0.000e+00
Summary. Combining – curl elimination with Fast Sine Poisson solves gives a compact two-dimensional Navier–Stokes solver without a pressure equation. Lecture 15 introduces the lattice Boltzmann method, which needs no global elliptic solve at all.