Worked solutions to the three exercises of Lecture 6. 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: Sweby 2nd-Order TVD Region & Flux Limiter Hierarchy")
r_grid = np.linspace(-1.0, 4.0, 501)
schemes_all = ["upwind", "lax_wendroff", "beam_warming", "minmod", "van_leer", "mc", "superbee"]
psi_map = {s: tvd_advection.flux_limiter(r_grid, kind=s) for s in schemes_all}
print(f"{'Scheme':15s} | {'psi(0.5)':>9s} | {'psi(1.0)':>9s} | {'psi(2.0)':>9s} | {'In 2nd-Order Sweby TVD?':>24s}")
print("-" * 76)
for s in schemes_all:
in_tvd = tvd_advection.in_sweby_tvd_region(r_grid, psi_map[s])
p05 = tvd_advection.flux_limiter(0.5, kind=s)
p10 = tvd_advection.flux_limiter(1.0, kind=s)
p20 = tvd_advection.flux_limiter(2.0, kind=s)
print(f"{s:15s} | {p05:9.4f} | {p10:9.4f} | {p20:9.4f} | {str(in_tvd):>24s}")
if s in ("minmod", "van_leer", "mc", "superbee"):
assert in_tvd is True
assert np.isclose(p10, 1.0, atol=1e-14)
else:
assert in_tvd is False
# Exact pointwise Compressive Ordering across all r in R: minmod <= van_leer <= mc <= superbee
assert np.all(psi_map["minmod"] <= psi_map["van_leer"] + 1e-14)
assert np.all(psi_map["van_leer"] <= psi_map["mc"] + 1e-14)
assert np.all(psi_map["mc"] <= psi_map["superbee"] + 1e-14)
fig, ax = plt.subplots(figsize=(7.4, 4.3))
r_pos = np.linspace(0.0, 4.0, 400)
lo_sweby = np.minimum(r_pos, 1.0)
hi_sweby = np.minimum(2.0 * r_pos, 2.0)
ax.fill_between(r_pos, lo_sweby, hi_sweby, color="#d4e6f1", alpha=0.75, label="Sweby 2nd-Order TVD Region")
ax.plot(r_grid, psi_map["lax_wendroff"], "--", color="gray", lw=1.3, label="Lax-Wendroff ($\\psi=1$)")
ax.plot(r_grid, psi_map["beam_warming"], ":", color="dimgray", lw=1.3, label="Beam-Warming ($\\psi=r$)")
ax.plot(r_grid, psi_map["minmod"], lw=2.0, color="#1f77b4", label="minmod (lower bound)")
ax.plot(r_grid, psi_map["van_leer"], lw=2.0, color="#2ca02c", label="van Leer (smooth)")
ax.plot(r_grid, psi_map["mc"], lw=2.0, color="#9467bd", label="MC (monotonized central)")
ax.plot(r_grid, psi_map["superbee"], lw=2.0, color="#d62728", label="Superbee (upper bound)")
ax.scatter([1.0], [1.0], s=60, color="black", zorder=5, label="2nd-order anchor $(1, 1)$")
ax.set_xlim(-0.5, 3.8)
ax.set_ylim(-0.3, 2.4)
ax.set_xlabel(r"Consecutive Gradient Ratio $r = (q_i - q_{i-1}) / (q_{i+1} - q_i)$ [-]")
ax.set_ylabel(r"Flux Limiter $\psi(r)$ [-]")
ax.set_title("Sweby TVD Admissibility Diagram & Classical vs. Nonlinear Limiters")
ax.legend(loc="upper left", fontsize=8)
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify across that minmod, van_leer, mc, and superbee satisfy Sweby’s forward–backward gradient symmetry to 10-14, while lax_wendroff and beam_warming break self-symmetry and instead satisfy mutual duality .
heading("Exercise 1: Sweby Gradient-Ratio Symmetry psi(r) == r * psi(1/r)")
r_pos_ex = np.logspace(-1.3, 1.3, 81)
sym_schemes = ["minmod", "van_leer", "mc", "superbee"]
for s in sym_schemes:
lhs = tvd_advection.flux_limiter(r_pos_ex, kind=s)
rhs = r_pos_ex * tvd_advection.flux_limiter(1.0 / r_pos_ex, kind=s)
max_asym = float(np.max(np.abs(lhs - rhs)))
print(f"{s:12s} | max |psi(r) - r*psi(1/r)| = {max_asym:.3e}")
assert np.allclose(lhs, rhs, rtol=1e-14, atol=1e-14)
lw_lhs = tvd_advection.flux_limiter(r_pos_ex, kind="lax_wendroff")
lw_self_rhs = r_pos_ex * tvd_advection.flux_limiter(1.0 / r_pos_ex, kind="lax_wendroff")
bw_lhs = tvd_advection.flux_limiter(r_pos_ex, kind="beam_warming")
assert not np.allclose(lw_lhs, lw_self_rhs)
assert np.allclose(bw_lhs, lw_self_rhs, rtol=1e-14, atol=1e-14)
print("Confirmed: all 4 TVD limiters are self-symmetric, while Lax-Wendroff and Beam-Warming are exact duals")
Exercise 1: Sweby Gradient-Ratio Symmetry psi(r) == r * psi(1/r)
================================================================
minmod | max |psi(r) - r*psi(1/r)| = 1.110e-16
van_leer | max |psi(r) - r*psi(1/r)| = 4.441e-16
mc | max |psi(r) - r*psi(1/r)| = 2.220e-16
superbee | max |psi(r) - r*psi(1/r)| = 2.220e-16
Confirmed: all 4 TVD limiters are self-symmetric, while Lax-Wendroff and Beam-Warming are exact duals
Explanation. Rewriting the anti-diffusive correction shows that swapping the roles of the downwind difference and upwind difference replaces by . Self-symmetry ensures that leading and trailing edges of a symmetric pulse are compressed identically without skewing its center of mass.
Exercise 2¶
Problem. Verify that tvd_advection.advect_1d_periodic raises ValueError for , non-positive dt/L, and unknown scheme names, and quantify the exponential Total Variation blow-up of an unguarded explicit step at .
heading("Exercise 2: CFL > 1 Instability & Input Guards")
q_test = np.where((np.arange(64) >= 16) & (np.arange(64) < 32), 1.0, 0.0)
bad_calls = [
("CFL = 1.25 > 1", lambda: tvd_advection.advect_1d_periodic(q_test, L=1.0, u=1.0, dt=1.25 / 64.0, n_steps=10)),
("Negative CFL = -1.2", lambda: tvd_advection.advect_1d_periodic(q_test, L=1.0, u=-1.0, dt=1.20 / 64.0, n_steps=10)),
("Non-positive dt", lambda: tvd_advection.advect_1d_periodic(q_test, L=1.0, u=1.0, dt=0.0, n_steps=10)),
("Unknown limiter", lambda: tvd_advection.flux_limiter(1.0, kind="nonexistent_limiter")),
]
for desc, fn in bad_calls:
caught = False
try:
fn()
except ValueError:
caught = True
assert caught is True
print(f"Guard verified ({desc}): raised ValueError as expected.")
# Unguarded explicit step at nu = 1.25: domain of dependence exceeds 1 cell width
q_unguarded = q_test.astype(float).copy()
tv0 = tvd_advection.total_variation_1d_periodic(q_unguarded)
nu_bad = 1.25
for _ in range(30):
dq_loc = np.roll(q_unguarded, -1) - q_unguarded
dq_up = q_unguarded - np.roll(q_unguarded, 1)
r = np.where(np.abs(dq_loc) > 1e-14, dq_up / np.where(np.abs(dq_loc) > 1e-14, dq_loc, 1.0), 0.0)
psi = tvd_advection.flux_limiter(r, kind="van_leer")
f_h = q_unguarded + 0.5 * (1.0 - nu_bad) * psi * dq_loc
q_unguarded = q_unguarded - nu_bad * (f_h - np.roll(f_h, 1))
tv_bad = tvd_advection.total_variation_1d_periodic(q_unguarded)
print(f"Unguarded nu = 1.25 after 30 steps: TV exploded from {tv0:.2f} to {tv_bad:.3e}")
assert tv_bad > 100.0 * tv0
Exercise 2: CFL > 1 Instability & Input Guards
==============================================
Guard verified (CFL = 1.25 > 1): raised ValueError as expected.
Guard verified (Negative CFL = -1.2): raised ValueError as expected.
Guard verified (Non-positive dt): raised ValueError as expected.
Guard verified (Unknown limiter): raised ValueError as expected.
Unguarded nu = 1.25 after 30 steps: TV exploded from 2.00 to 3.835e+05
Explanation. For , the exact characteristic foot originates upstream of , outside the stencil . By the Courant–Friedrichs–Lewy theorem, Harten’s incremental weights violate when (since flips the anti-diffusive term’s sign and produces negative convex-combination weights), and the solution oscillates and diverges.
Exercise 3¶
Problem. Implement Koren’s third-order upwind-biased TVD limiter (matching for ) inside a 3-stage Shu–Osher SSP-RK3 solver advect_1d_koren_rk3(q_init, L, u, dt, n_steps). Verify Sweby admissibility, , , square-wave TVD monotonicity, and strictly lower error than van_leer and lower error than minmod on .
heading("Exercise 3: Implement It Yourself — Koren 3rd-Order TVD Limiter + Shu-Osher SSP-RK3")
def koren_limiter(r: np.ndarray) -> np.ndarray:
"""Evaluate Koren 3rd-order upwind-biased Sweby TVD limiter for r = dq_up / dq_loc."""
r_arr = np.asarray(r, dtype=float)
return np.maximum(0.0, np.minimum(np.minimum(2.0 * r_arr, (2.0 + r_arr) / 3.0), 2.0))
def advect_1d_koren_rk3(q_init: np.ndarray, L: float, u: float, dt: float, n_steps: int) -> dict:
"""Integrate 1-D periodic advection u > 0 via semi-discrete Koren reconstruction + 3rd-order SSP-RK3."""
q = np.asarray(q_init, dtype=float).ravel().copy()
dx = float(L) / q.size
nu = float(u) * float(dt) / dx
assert 0.0 < nu <= 0.5 # Semi-discrete TVD Euler bound with max(psi) = 2 is nu <= 0.5
def rhs_koren(state: np.ndarray) -> np.ndarray:
dq_up = state - np.roll(state, 1)
dq_loc = np.roll(state, -1) - state
r = np.where(np.abs(dq_loc) > 1e-14, dq_up / np.where(np.abs(dq_loc) > 1e-14, dq_loc, 1.0), 0.0)
f_half = float(u) * (state + 0.5 * koren_limiter(r) * dq_loc)
return -(f_half - np.roll(f_half, 1)) / dx
tvs = [tvd_advection.total_variation_1d_periodic(q)]
for _ in range(n_steps):
q1 = q + dt * rhs_koren(q)
q2 = 0.75 * q + 0.25 * (q1 + dt * rhs_koren(q1))
q = (1.0 / 3.0) * q + (2.0 / 3.0) * (q2 + dt * rhs_koren(q2))
tvs.append(tvd_advection.total_variation_1d_periodic(q))
return {"final": q, "total_variations": np.array(tvs), "mass_drift": abs(float(np.sum(q - q_init) * dx))}
r_t = np.linspace(-1.0, 4.0, 501)
assert tvd_advection.in_sweby_tvd_region(r_t, koren_limiter(r_t)) is True
assert np.isclose(koren_limiter(np.array([1.0]))[0], 1.0, atol=1e-15)
eps_d = 1e-6
slope_at_1 = (koren_limiter(np.array([1.0 + eps_d]))[0] - koren_limiter(np.array([1.0 - eps_d]))[0]) / (2.0 * eps_d)
assert np.isclose(slope_at_1, 1.0 / 3.0, atol=1e-10)
# 1. Discontinuous square-wave TVD verification:
n_ex = 160
dx_ex = 1.0 / n_ex
x_ex = (np.arange(n_ex) + 0.5) * dx_ex
q_sq_ex = np.where((x_ex >= 0.25) & (x_ex < 0.55), 1.0, 0.0)
kor_sq = advect_1d_koren_rk3(q_sq_ex, L=1.0, u=1.0, dt=0.40 * dx_ex, n_steps=int(round(n_ex / 0.40)))
assert np.max(np.diff(kor_sq["total_variations"])) <= 1e-12
assert kor_sq["mass_drift"] < 1e-14
# 2. Smooth sin^4(pi*x) accuracy comparison at CFL = 0.40:
q_sm_ex = np.sin(np.pi * x_ex) ** 4
dt_sm = 0.40 * dx_ex
steps_sm = int(round(n_ex / 0.40))
kor_sm = advect_1d_koren_rk3(q_sm_ex, L=1.0, u=1.0, dt=dt_sm, n_steps=steps_sm)["final"]
vl_sm = tvd_advection.advect_1d_periodic(q_sm_ex, L=1.0, u=1.0, dt=dt_sm, n_steps=steps_sm, scheme="van_leer")["final"]
mm_sm = tvd_advection.advect_1d_periodic(q_sm_ex, L=1.0, u=1.0, dt=dt_sm, n_steps=steps_sm, scheme="minmod")["final"]
l2_kor = float(np.sqrt(np.mean((kor_sm - q_sm_ex) ** 2)))
l2_vl = float(np.sqrt(np.mean((vl_sm - q_sm_ex) ** 2)))
l2_mm = float(np.sqrt(np.mean((mm_sm - q_sm_ex) ** 2)))
print(f"Smooth sin^4(pi*x) L2 error (N=160, CFL=0.4): Koren-RK3 = {l2_kor:.3e} < van Leer = {l2_vl:.3e} < minmod = {l2_mm:.3e}")
assert 1.5 * l2_kor < l2_vl and 4.0 * l2_kor < l2_mm
Exercise 3: Implement It Yourself — Koren 3rd-Order TVD Limiter + Shu-Osher SSP-RK3
===================================================================================
Smooth sin^4(pi*x) L2 error (N=160, CFL=0.4): Koren-RK3 = 5.504e-04 < van Leer = 9.865e-04 < minmod = 2.685e-03
Summary. Watch out for gradient-ratio conventions in the CFD literature. In Sweby’s convention, exact 3rd-order quadratic finite-volume reconstruction corresponds to (, whereas defining gives ). Paired with Shu–Osher 3-stage SSP-RK3, Koren’s limiter gives a smaller error than van Leer and minmod on smooth waves while enforcing strict TVD monotonicity on shocks.