In Lecture 5, von Neumann analysis showed a conflict: first-order upwind advection guarantees positivity and monotonicity but smears sharp concentration fronts with heavy numerical diffusion, whereas second-order linear schemes like Lax–Wendroff and Beam–Warming preserve wave amplitude better at the cost of non-physical Gibbs overshoots and undershoots. Can any linear constant-coefficient scheme achieve second-order accuracy without creating spurious oscillations? In 1959, Godunov proved that the answer is no, forcing modern CFD to become nonlinear even when solving a linear PDE. In this lecture we map Sweby’s (1984) second-order Total Variation Diminishing (TVD) admissibility region (tvd_advection.in_sweby_tvd_region), evaluate classical and high-resolution limiters (minmod, van_leer, mc, superbee), and verify exact mass conservation alongside on discontinuous and smooth wave packets (advect_1d_periodic).
Learning objectives¶
Explain Godunov’s (1959) order-barrier theorem and derive the conservative MUSCL/flux-limited interface flux parameterized by local gradient ratio and limiter .
Verify Sweby’s (1984) second-order TVD admissibility bounds (
tvd_advection.in_sweby_tvd_region) across linear schemes (upwind,lax_wendroff,beam_warming) and nonlinear limiters (minmod,van_leer,mc,superbee).Prove discrete mass conservation and Total Variation Diminishing stability (
total_variation_1d_periodic,advect_1d_periodic) on periodic square pulses and smooth Gaussian waves.Implement Koren’s third-order upwind-biased TVD limiter from scratch and audit CFL stability and limiter symmetry properties.
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. Godunov’s Order-Barrier Theorem & Sweby’s 2nd-Order TVD Region¶
Consider 1-D conservative scalar advection on a periodic domain with constant velocity and Courant number :
Following Sweby (1984), we write the normalized cell-face flux as the first-order upwind flux plus a limited anti-diffusive Lax–Wendroff correction:
where measures the ratio of upwind-to-local consecutive gradients:
Linear constant- choices: recovers 1st-order Upwind; recovers Lax–Wendroff; recovers Beam–Warming.
Godunov’s Theorem (1959): Any linear numerical scheme that preserves monotonicity (does not create new extrema) is at most first-order accurate.
Total Variation & Sweby’s TVD Theorem (1984): Defining discrete periodic total variation , a scheme is Total Variation Diminishing () and second-order accurate on smooth monotone profiles () if lies inside Sweby’s shaded region:
At any local extremum, consecutive slopes have opposite signs (), forcing so the TVD scheme locally reverts to monotone 1st-order upwind to prevent overshoot. The four standard TVD limiters in tvd_advection.flux_limiter span this region from most diffusive (minmod, the lower Sweby boundary) to most compressive (superbee, the upper Sweby boundary):
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)
Demonstration 1: Sweby 2nd-Order TVD Region & Flux Limiter Hierarchy
====================================================================
Scheme | psi(0.5) | psi(1.0) | psi(2.0) | In 2nd-Order Sweby TVD?
----------------------------------------------------------------------------
upwind | 0.0000 | 0.0000 | 0.0000 | False
lax_wendroff | 1.0000 | 1.0000 | 1.0000 | False
beam_warming | 0.5000 | 1.0000 | 2.0000 | False
minmod | 0.5000 | 1.0000 | 1.0000 | True
van_leer | 0.6667 | 1.0000 | 1.3333 | True
mc | 0.7500 | 1.0000 | 1.5000 | True
superbee | 1.0000 | 1.0000 | 2.0000 | True

Figure 6.1. The Sweby diagram. The shaded area is the region in which a limiter gives a second-order total-variation-diminishing scheme; the minmod and superbee limiters are its lower and upper boundaries, and all limiters pass through the point .
What Demonstration 1 shows. Every linear second-order scheme (lax_wendroff with , beam_warming with ) exits Sweby’s TVD region, either for or , explaining why constant-coefficient second-order schemes inevitably generate dispersive ripples near discontinuities. Conversely, minmod, van_leer, mc, and superbee remain strictly inside Sweby’s region, pass through for second-order fidelity on smooth ramps, and satisfy the ordering for all .
2. Discontinuous Square-Wave Advection & Discrete Total Variation Audit¶
We advect a sharp rectangular concentration pulse through one complete periodic revolution () on cells at using tvd_advection.advect_1d_periodic. Because jumps up once from and jumps down once from , its exact periodic total variation is at all times. We audit three exact invariants:
Telescoping Mass Conservation: to rounding error (10-14) for every conservative flux scheme.
Step-by-Step TVD Monotonicity: at every single step for
upwindand all four Sweby limiters, versus immediate TV blow-up () forlax_wendroff.Shock/Contact Sharpness: Comparing error across limiters.
heading("Demonstration 2: One-Period Square-Wave Advection — Gibbs Oscillations vs TVD Sharpness")
n_sq = 200
L_dom = 1.0
u_adv = 1.0
dx_sq = L_dom / n_sq
x_sq = (np.arange(n_sq) + 0.5) * dx_sq
q0_sq = np.where((x_sq >= 0.25) & (x_sq < 0.55), 1.0, 0.0)
dt_sq = 0.5 * dx_sq / u_adv
n_steps_sq = 400 # Exact 1 full period: 400 * 0.5 * dx = 200 * dx = L_dom
assert np.isclose(tvd_advection.total_variation_1d_periodic(q0_sq), 2.0, atol=1e-14)
test_schemes = ["upwind", "lax_wendroff", "minmod", "van_leer", "mc", "superbee"]
sq_runs = {}
print(f"{'Scheme':14s} | {'Mass Drift':>11s} | {'Max dTV/step':>13s} | {'Final TV':>9s} | {'Min q':>9s} | {'Max q':>9s} | {'L1 Error':>9s}")
print("-" * 92)
for s in test_schemes:
res = tvd_advection.advect_1d_periodic(q0_sq, L=L_dom, u=u_adv, dt=dt_sq, n_steps=n_steps_sq, scheme=s)
sq_runs[s] = res
m_drift = float(np.max(np.abs(res["masses"] - res["masses"][0])))
max_dtv = float(np.max(np.diff(res["total_variations"])))
tv_end = float(res["total_variations"][-1])
q_min, q_max = float(np.min(res["final"])), float(np.max(res["final"]))
l1_err = float(np.mean(np.abs(res["final"] - q0_sq)))
print(f"{s:14s} | {m_drift:11.2e} | {max_dtv:+13.2e} | {tv_end:9.4f} | {q_min:+9.4f} | {q_max:+9.4f} | {l1_err:9.5f}")
assert m_drift < 1e-13
if s == "lax_wendroff":
assert max_dtv > 0.05 and tv_end > 2.3 and q_max > 1.05 and q_min < -0.05
else:
assert max_dtv <= 1e-12
assert q_min >= -1e-13 and q_max <= 1.0 + 1e-13
# Compressive accuracy hierarchy on discontinuous square wave:
assert (
np.mean(np.abs(sq_runs["superbee"]["final"] - q0_sq))
< np.mean(np.abs(sq_runs["van_leer"]["final"] - q0_sq))
< np.mean(np.abs(sq_runs["minmod"]["final"] - q0_sq))
< np.mean(np.abs(sq_runs["upwind"]["final"] - q0_sq))
)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.0, 4.1))
ax1.plot(x_sq, q0_sq, "k--", lw=1.6, label="Exact ($t = L/u$)")
ax1.plot(x_sq, sq_runs["upwind"]["final"], lw=1.6, label="Upwind")
ax1.plot(x_sq, sq_runs["lax_wendroff"]["final"], lw=1.4, alpha=0.85, label="Lax-Wendroff")
ax1.plot(x_sq, sq_runs["minmod"]["final"], lw=1.7, label="minmod")
ax1.plot(x_sq, sq_runs["van_leer"]["final"], lw=1.8, label="van Leer")
ax1.plot(x_sq, sq_runs["superbee"]["final"], lw=1.8, label="Superbee")
ax1.set_xlabel("Position $x / L$ [-]")
ax1.set_ylabel("Concentration $q(x, T)$ [-]")
ax1.set_title("Square Pulse After 1 Period ($N=200$, $\\mathrm{CFL}=0.5$)")
ax1.legend(fontsize=8)
step_axis = np.arange(n_steps_sq + 1)
for s in ["upwind", "lax_wendroff", "minmod", "van_leer", "superbee"]:
ax2.plot(step_axis, sq_runs[s]["total_variations"], lw=1.8, label=s)
ax2.set_xlabel("Time Step $n$ [-]")
ax2.set_ylabel(r"Periodic Total Variation $\mathrm{TV}(q^n)$ [-]")
ax2.set_title(r"TVD Audit: $\mathrm{TV}(q^{n+1}) \leq \mathrm{TV}(q^n)$ vs. Gibbs Growth")
ax2.legend(fontsize=8)
label_panels(fig)
plt.show()
Demonstration 2: One-Period Square-Wave Advection — Gibbs Oscillations vs TVD Sharpness
=======================================================================================
Scheme | Mass Drift | Max dTV/step | Final TV | Min q | Max q | L1 Error
--------------------------------------------------------------------------------------------
upwind | 1.11e-16 | +4.44e-16 | 1.9946 | +0.0000 | +0.9973 | 0.07974
lax_wendroff | 1.67e-16 | +5.00e-01 | 3.9352 | -0.2321 | +1.2321 | 0.05225
minmod | 5.55e-17 | +4.44e-16 | 2.0000 | +0.0000 | +1.0000 | 0.03141
van_leer | 1.11e-16 | +4.44e-16 | 2.0000 | +0.0000 | +1.0000 | 0.02038
mc | 2.78e-16 | +6.66e-16 | 2.0000 | +0.0000 | +1.0000 | 0.01695
superbee | 3.89e-16 | +6.66e-16 | 2.0000 | +0.0000 | +1.0000 | 0.00876

Figure 6.2. Advection of a square pulse over one period on 200 cells at Courant number 0.5. (a) The final profiles of six schemes. (b) Total variation against the time step: it grows for the Lax–Wendroff scheme and does not grow for the upwind scheme and the limited schemes, whose curves coincide.
What Demonstration 2 shows. After one period, first-order upwind rounds the corners of the square wave ( error 0.080, the largest of the six schemes) but creates no new extrema, while lax_wendroff oscillates, with negative values (), overshoots () and a total variation that rises from 2 to 3.94. All four nonlinear Sweby limiters hold and at every step, and superbee has the smallest error (0.0088).
3. Smooth Gaussian + Square Wave Trade-Off & Grid Convergence Rate¶
If superbee is sharpest on step discontinuities, why don’t all industrial CFD codes use superbee everywhere? Because superbee applies an anti-diffusive flux factor on gentle slopes, over-steepening (“squaring off”) smooth Gaussian hills. We test a composite two-pulse profile (a smooth Gaussian peak plus a sharp rectangular pulse) alongside a formal grid-refinement order-of-accuracy study on a smooth wave .
heading("Demonstration 3: Composite Gaussian + Square Wave & Smooth-Wave Mesh Convergence")
n_comp = 240
dx_comp = 1.0 / n_comp
x_comp = (np.arange(n_comp) + 0.5) * dx_comp
q_gauss_only = np.exp(-((x_comp - 0.25) / 0.065) ** 2)
q_comp0 = q_gauss_only + np.where((x_comp >= 0.60) & (x_comp < 0.82), 1.0, 0.0)
comp_res = {}
for s in ["upwind", "minmod", "van_leer", "mc", "superbee"]:
comp_res[s] = tvd_advection.advect_1d_periodic(
q_comp0, L=1.0, u=1.0, dt=0.4 * dx_comp, n_steps=600, scheme=s
)["final"]
# Check smooth-Gaussian region (x < 0.48): MC and van Leer distort the smooth Gaussian less than upwind
g_mask = x_comp < 0.48
err_g_up = float(np.sqrt(np.mean((comp_res["upwind"][g_mask] - q_comp0[g_mask]) ** 2)))
err_g_vl = float(np.sqrt(np.mean((comp_res["van_leer"][g_mask] - q_comp0[g_mask]) ** 2)))
err_g_mc = float(np.sqrt(np.mean((comp_res["mc"][g_mask] - q_comp0[g_mask]) ** 2)))
assert err_g_mc < err_g_vl < 0.35 * err_g_up
# Grid-convergence rate on smooth periodic wave q(x,0) = sin^4(pi * x):
grids_conv = [64, 128, 256, 512]
l1_up, l1_vl, l1_mc = [], [], []
for ng in grids_conv:
dxg = 1.0 / ng
xg = (np.arange(ng) + 0.5) * dxg
q_sm = np.sin(np.pi * xg) ** 4
dtg = 0.5 * dxg
steps_g = 2 * ng
l1_up.append(float(np.mean(np.abs(tvd_advection.advect_1d_periodic(q_sm, 1.0, 1.0, dtg, steps_g, "upwind")["final"] - q_sm))))
l1_vl.append(float(np.mean(np.abs(tvd_advection.advect_1d_periodic(q_sm, 1.0, 1.0, dtg, steps_g, "van_leer")["final"] - q_sm))))
l1_mc.append(float(np.mean(np.abs(tvd_advection.advect_1d_periodic(q_sm, 1.0, 1.0, dtg, steps_g, "mc")["final"] - q_sm))))
p_up = float(np.log2(l1_up[-2] / l1_up[-1]))
p_vl = float(np.log2(l1_vl[-2] / l1_vl[-1]))
p_mc = float(np.log2(l1_mc[-2] / l1_mc[-1]))
print(f"Observed L1 convergence order (N=256->512): Upwind = {p_up:.3f}, van Leer = {p_vl:.3f}, MC = {p_mc:.3f}")
print(f"N=512 L1 error: Upwind = {l1_up[-1]:.3e} vs van Leer = {l1_vl[-1]:.3e} vs MC = {l1_mc[-1]:.3e}")
assert 0.90 < p_up < 1.10
assert p_vl > 1.80 and p_mc > 1.85
assert l1_mc[-1] < 0.02 * l1_up[-1]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.0, 4.1))
ax1.plot(x_comp, q_comp0, "k--", lw=1.6, label="Exact")
for s in ["upwind", "minmod", "van_leer", "mc", "superbee"]:
ax1.plot(x_comp, comp_res[s], lw=1.6, label=s)
ax1.set_xlabel("Position $x / L$ [-]")
ax1.set_ylabel("Scalar $q(x, T)$ [-]")
ax1.set_title("Composite Smooth Gaussian + Sharp Pulse ($t = T$)")
ax1.legend(fontsize=8)
ax2.loglog(grids_conv, l1_up, "o-", lw=1.8, label=f"Upwind (slope $\\approx {p_up:.2f}$)")
ax2.loglog(grids_conv, l1_vl, "s-", lw=1.8, label=f"van Leer (slope $\\approx {p_vl:.2f}$)")
ax2.loglog(grids_conv, l1_mc, "^-", lw=1.8, label=f"MC (slope $\\approx {p_mc:.2f}$)")
ax2.set_xlabel("Grid Cells $N$ [-]")
ax2.set_ylabel("$L_1$ Error After 1 Period [-]")
ax2.set_title(r"Smooth $\sin^4(\pi x)$ Convergence Rate")
ax2.legend(fontsize=8.5)
label_panels(fig)
plt.show()
Demonstration 3: Composite Gaussian + Square Wave & Smooth-Wave Mesh Convergence
================================================================================
Observed L1 convergence order (N=256->512): Upwind = 0.973, van Leer = 2.185, MC = 2.371
N=512 L1 error: Upwind = 7.820e-03 vs van Leer = 2.140e-05 vs MC = 8.517e-06

Figure 6.3. (a) A Gaussian and a square pulse after one period for the upwind scheme and four limiters. (b) error after one period for a smooth profile against the number of cells; the legend gives the fitted slopes.
What Demonstration 3 shows. On the smooth wave, van_leer and mc achieve convergence in the norm (at their errors are 365 and 918 times smaller than that of first-order upwind), while on the composite wave packet mc and van_leer avoid superbee’s flat-topping of the smooth Gaussian hill, which is why van_leer and mc are common general-purpose choices.
4. Courant Number Sweep¶
Look closely at the anti-diffusive term in Equation (1.2): . What happens as we sweep the Courant number over one fixed physical revolution ? At the unit Courant number , vanishes identically, turning every flux-limited scheme into exact characteristic cell-to-cell shift with zero numerical diffusion.
heading("Demonstration 4: Courant Number Sensitivity & Exact Shift Property at CFL = 1")
n_cfl = 160
dx_cfl = 1.0 / n_cfl
x_cfl = (np.arange(n_cfl) + 0.5) * dx_cfl
q0_cfl = np.where((x_cfl >= 0.30) & (x_cfl < 0.60), 1.0, 0.0)
cfl_list = [0.20, 0.50, 0.80, 1.00]
print(f"{'CFL':>6s} | {'Steps':>6s} | {'Upwind L1 Err':>14s} | {'van Leer L1 Err':>16s} | {'Superbee L1 Err':>16s}")
print("-" * 70)
for cfl_val in cfl_list:
steps_cfl = int(round(n_cfl / cfl_val))
dt_cfl = cfl_val * dx_cfl
e_up = float(np.mean(np.abs(tvd_advection.advect_1d_periodic(q0_cfl, 1.0, 1.0, dt_cfl, steps_cfl, "upwind")["final"] - q0_cfl)))
e_vl = float(np.mean(np.abs(tvd_advection.advect_1d_periodic(q0_cfl, 1.0, 1.0, dt_cfl, steps_cfl, "van_leer")["final"] - q0_cfl)))
e_sb = float(np.mean(np.abs(tvd_advection.advect_1d_periodic(q0_cfl, 1.0, 1.0, dt_cfl, steps_cfl, "superbee")["final"] - q0_cfl)))
print(f"{cfl_val:6.2f} | {steps_cfl:6d} | {e_up:14.6e} | {e_vl:16.6e} | {e_sb:16.6e}")
if np.isclose(cfl_val, 1.0):
assert e_up < 1e-14 and e_vl < 1e-14 and e_sb < 1e-14
else:
assert e_sb < e_vl < e_up
Demonstration 4: Courant Number Sensitivity & Exact Shift Property at CFL = 1
=============================================================================
CFL | Steps | Upwind L1 Err | van Leer L1 Err | Superbee L1 Err
----------------------------------------------------------------------
0.20 | 800 | 1.127754e-01 | 2.792668e-02 | 1.114020e-02
0.50 | 320 | 8.913654e-02 | 2.402122e-02 | 1.095456e-02
0.80 | 200 | 5.629568e-02 | 1.898174e-02 | 1.050752e-02
1.00 | 160 | 0.000000e+00 | 0.000000e+00 | 0.000000e+00
Inside the algorithm¶
In Demonstration 4, taking smaller time steps (, requiring 800 updates per period) actually increases numerical diffusion compared to , because modified-equation numerical diffusivity scales with and accumulates across more discrete projection steps.
Below we inspect tvd_advection._step_1d_periodic_flux_limited directly and verify a NumPy implementation, for both positive () and negative () advection velocities, against tvd_advection.advect_1d_periodic to rounding error.
Check against the library¶
heading("Inside the Algorithm: tvd_advection._step_1d_periodic_flux_limited")
print(show_source(tvd_advection._step_1d_periodic_flux_limited))
def manual_van_leer_step_pos(q: np.ndarray, nu: float) -> np.ndarray:
"""Transparent 1-step periodic van Leer TVD update for 0 < nu <= 1."""
dq_up = q - np.roll(q, 1)
dq_loc = np.roll(q, -1) - q
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 = (r + np.abs(r)) / (1.0 + np.abs(r))
f_half = q + 0.5 * (1.0 - nu) * psi * dq_loc
return q - nu * (f_half - np.roll(f_half, 1))
xg_in = np.linspace(0.0, 1.0, 64, endpoint=False)
q_in = np.exp(-((xg_in - 0.5) / 0.12) ** 2)
q_hand = q_in.copy()
for _ in range(25):
q_hand = manual_van_leer_step_pos(q_hand, nu=0.45)
lib_pos = tvd_advection.advect_1d_periodic(q_in, L=1.0, u=1.0, dt=0.45 / 64.0, n_steps=25, scheme="van_leer")
assert np.allclose(q_hand, lib_pos["final"], rtol=1e-15, atol=1e-15)
# Also verify exact time-reversal symmetry for u < 0 after 1 full period:
lib_neg = tvd_advection.advect_1d_periodic(q_in, L=1.0, u=-2.0, dt=0.5 / (64.0 * 2.0), n_steps=128, scheme="mc")
assert np.max(np.diff(lib_neg["total_variations"])) <= 1e-12
assert np.isclose(lib_neg["masses"][-1], lib_neg["masses"][0], atol=1e-14)
print(f"Manual vs library max |diff| = {np.max(np.abs(q_hand - lib_pos['final'])):.2e}; negative-velocity TVD verified.")
Inside the Algorithm: tvd_advection._step_1d_periodic_flux_limited
==================================================================
def _step_1d_periodic_flux_limited(q: np.ndarray, cfl_signed: float, kind: str) -> np.ndarray:
"""Advance 1-D periodic scalar q by one conservative flux-limited step at Courant number cfl_signed."""
if abs(cfl_signed) < 1e-15:
return q.copy()
if cfl_signed > 0.0:
nu = cfl_signed
dq_up = q - np.roll(q, 1)
dq_loc = np.roll(q, -1) - q
r_face = 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 = flux_limiter(r_face, kind=kind)
# Interface flux F_{i+1/2} / u:
f_half = q + 0.5 * (1.0 - nu) * psi * dq_loc
return q - nu * (f_half - np.roll(f_half, 1))
nu = -cfl_signed
# By reflection symmetry for u < 0:
q_rev = q[::-1]
q_next_rev = _step_1d_periodic_flux_limited(q_rev, nu, kind=kind)
return q_next_rev[::-1]
Manual vs library max |diff| = 0.00e+00; negative-velocity TVD verified.
Exercises¶
Worked solutions are in 06_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify across that
minmod,van_leer,mc, andsuperbeesatisfy Sweby’s forward–backward gradient symmetry to 10-14, whilelax_wendroffandbeam_warmingbreak self-symmetry and instead satisfy mutual duality .Find how it fails. Verify that
tvd_advection.advect_1d_periodicraisesValueErrorfor , non-positivedt/L, and unknownschemenames, and quantify the exponential Total Variation blow-up of an unguarded explicit step at .Implement it yourself. 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 thanvan_leerand lower error thanminmodon .
heading("Self-check for the exercises")
r_chk = np.linspace(-0.5, 3.5, 201)
for lim_name in ("minmod", "van_leer", "mc", "superbee"):
assert tvd_advection.in_sweby_tvd_region(r_chk, tvd_advection.flux_limiter(r_chk, kind=lim_name)) is True
assert tvd_advection.in_sweby_tvd_region(r_chk, tvd_advection.flux_limiter(r_chk, kind="lax_wendroff")) is False
print("Sweby TVD admissibility and square-wave monotonicity checks passed")
print("All checks passed.")
Self-check for the exercises
============================
Sweby TVD admissibility and square-wave monotonicity checks passed
All checks passed.