Worked solutions to the three exercises of Lecture 9. 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: Exact Wet-Bed Dam Break & Rankine-Hugoniot Bore Verification")
L_sw = 10.0
x_dam = 5.0
hL_sw, hR_sw = 2.0, 0.5
t_sw = 0.60
g_val = constants.G_STD
x_sw = np.linspace(0.0, L_sw, 500)
exact_db = burgers_riemann.exact_dam_break_dry_or_wet(x_sw, t=t_sw, h_left=hL_sw, h_right=hR_sw, x_dam=x_dam, g=g_val)
hs, us, S_bore = exact_db["h_star"], exact_db["u_star"], exact_db["shock_speed"]
# Verify Riemann invariant across rarefaction AND both Rankine-Hugoniot equations across bore:
inv_left = 2.0 * np.sqrt(g_val * hL_sw)
inv_star = us + 2.0 * np.sqrt(g_val * hs)
rh_mass_res = abs(S_bore * (hs - hR_sw) - hs * us)
rh_mom_res = abs(S_bore * (hs * us) - (hs * (us ** 2) + 0.5 * g_val * (hs ** 2 - hR_sw ** 2)))
print(f"Reservoir h_L = {hL_sw:.2f} m, Tailwater h_R = {hR_sw:.2f} m")
print(f"Star state: h* = {hs:.5f} m, u* = {us:.5f} m/s, Bore speed S = {S_bore:.5f} m/s")
print(f"Rarefaction invariant drift = {abs(inv_left - inv_star):.2e}")
print(f"Rankine-Hugoniot residuals = mass: {rh_mass_res:.2e}, momentum: {rh_mom_res:.2e}")
assert hR_sw < hs < hL_sw and us > 0.0 and S_bore > np.sqrt(g_val * hR_sw)
assert np.isclose(inv_left, inv_star, atol=1e-12)
assert rh_mass_res < 1e-12 and rh_mom_res < 1e-11
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
ax1.plot(x_sw, exact_db["h"], lw=2.2, color="#1f4e79")
ax1.axvline(x_dam - np.sqrt(g_val * hL_sw) * t_sw, ls=":", color="gray", label="Rarefaction head")
ax1.axvline(x_dam + S_bore * t_sw, ls="--", color="#c0392b", label="Hydraulic bore $x_{\\mathrm{dam}} + S t$")
ax1.set_xlabel("Position $x$ [m]")
ax1.set_ylabel("Water Depth $h(x, t)$ [m]")
ax1.set_title(f"Stoker Exact Depth Profile ($t = {t_sw:.2f}$ s)")
ax1.legend(fontsize=8.5)
fr_exact = np.abs(exact_db["u"]) / np.sqrt(g_val * exact_db["h"])
ax2.plot(x_sw, exact_db["u"], lw=2.0, color="#2ca02c", label="Velocity $u(x, t)$ [m/s]")
ax2.plot(x_sw, fr_exact, lw=1.8, ls="--", color="#d62728", label="Froude $\\mathrm{Fr} = |u|/\\sqrt{gh}$ [-]")
ax2.set_xlabel("Position $x$ [m]")
ax2.set_ylabel("$u$ [m/s] or $\\mathrm{Fr}$ [-]")
ax2.set_title("Particle Velocity & Local Froude Number")
ax2.legend(fontsize=8.5)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Find the critical tailwater ratio where using exact_dam_break_dry_or_wet, and check numerically across that depth and Froude number at lock onto and .
heading("Exercise 1: Critical Tailwater Ratio (Fr* == 1) & Sonic Choking at the Dam Site")
lo_r, hi_r = 0.05, 0.40
for _ in range(60):
mid_r = 0.5 * (lo_r + hi_r)
st = burgers_riemann.exact_dam_break_dry_or_wet(np.array([5.0]), t=0.5, h_left=1.0, h_right=mid_r, x_dam=5.0)
fr_m = st["u_star"] / float(np.sqrt(constants.G_STD * st["h_star"]))
if fr_m > 1.0:
lo_r = mid_r
else:
hi_r = mid_r
r_crit = 0.5 * (lo_r + hi_r)
print(f"Critical tailwater ratio (h_R / h_L)_crit = {r_crit:.6f}")
assert np.isclose(r_crit, 0.13827, atol=2e-5)
# Verify sonic hydraulic choking h(x_dam, t) == (4/9)*h_L and Fr(x_dam, t) == 1 whenever h_R/h_L < r_crit:
hL_choke = 2.7
for ratio_sup in [0.01, 0.05, 0.10]:
dam_pt = burgers_riemann.exact_dam_break_dry_or_wet(
np.array([5.0]), t=0.4, h_left=hL_choke, h_right=ratio_sup * hL_choke, x_dam=5.0
)
h_dam = float(dam_pt["h"][0])
u_dam = float(dam_pt["u"][0])
fr_dam = u_dam / float(np.sqrt(constants.G_STD * h_dam))
print(f"h_R/h_L = {ratio_sup:4.2f} < r_crit | h(x_dam) = {h_dam:.5f} vs (4/9)*h_L = {4.0*hL_choke/9.0:.5f} | Fr(x_dam) = {fr_dam:.5f}")
assert np.isclose(h_dam, (4.0 / 9.0) * hL_choke, rtol=1e-13, atol=1e-13)
assert np.isclose(fr_dam, 1.0, rtol=1e-13, atol=1e-13)
Exercise 1: Critical Tailwater Ratio (Fr* == 1) & Sonic Choking at the Dam Site
===============================================================================
Critical tailwater ratio (h_R / h_L)_crit = 0.138270
h_R/h_L = 0.01 < r_crit | h(x_dam) = 1.20000 vs (4/9)*h_L = 1.20000 | Fr(x_dam) = 1.00000
h_R/h_L = 0.05 < r_crit | h(x_dam) = 1.20000 vs (4/9)*h_L = 1.20000 | Fr(x_dam) = 1.00000
h_R/h_L = 0.10 < r_crit | h(x_dam) = 1.20000 vs (4/9)*h_L = 1.20000 | Fr(x_dam) = 1.00000
Explanation. Inside the centered rarefaction fan, and . At the dam location , and . Whenever , the rarefaction tail lies downstream of , so downstream tailwater depth can no longer signal upstream past the critical section at ; this is the shallow-water analogue of a choked nozzle.
Exercise 2¶
Problem. Verify exact_dam_break_dry_or_wet raises ValueError for invalid inputs (, , ), and show that centered forward-Euler fluxes without HLL wave-speed viscosity produce severe TV blow-up / non-physical depths on the dam break.
heading("Exercise 2: input guards & Unconditional FTCS Shallow-Water Instability")
for h_l_b, h_r_b, t_b in [(1.0, 1.0, 0.2), (0.5, 1.0, 0.2), (2.0, 0.0, 0.2), (2.0, 0.5, 0.0)]:
caught = False
try:
burgers_riemann.exact_dam_break_dry_or_wet(np.array([0.5]), t=t_b, h_left=h_l_b, h_right=h_r_b)
except ValueError:
caught = True
assert caught is True
# Centered forward-Euler flux F_{i+1/2} = 0.5*(F_L + F_R) with zero Riemann upwinding:
n_ftcs = 160
dx_f = 10.0 / n_ftcs
xc_f = (np.arange(n_ftcs) + 0.5) * dx_f
h_f = np.where(xc_f < 5.0, 2.0, 0.5)
hu_f = np.zeros_like(xc_f)
dt_f = 0.002
tv0_h = float(np.sum(np.abs(np.diff(h_f))))
crashed_or_oscillatory = False
for _ in range(80):
hp = np.pad(h_f, 1, mode="edge")
hup = np.pad(hu_f, 1, mode="edge")
hl, hr = hp[:-1], hp[1:]
hul, hur = hup[:-1], hup[1:]
if np.any(hl <= 0.0) or np.any(hr <= 0.0) or not np.all(np.isfinite(hl)):
crashed_or_oscillatory = True
break
f1 = 0.5 * (hul + hur)
f2 = 0.5 * (hul ** 2 / hl + 0.5 * constants.G_STD * hl ** 2 + hur ** 2 / hr + 0.5 * constants.G_STD * hr ** 2)
h_f = h_f - (dt_f / dx_f) * (f1[1:] - f1[:-1])
hu_f = hu_f - (dt_f / dx_f) * (f2[1:] - f2[:-1])
tv_end_h = float(np.sum(np.abs(np.diff(h_f)))) if np.all(np.isfinite(h_f)) else float("inf")
if tv_end_h > 3.0 * tv0_h or np.min(h_f) <= 0.0:
crashed_or_oscillatory = True
print(f"Centered FTCS after <=80 steps: initial TV(h) = {tv0_h:.2f} -> TV(h) = {tv_end_h:.2f}, min(h) = {np.min(h_f):.3f}")
assert crashed_or_oscillatory is True
Exercise 2: input guards & Unconditional FTCS Shallow-Water Instability
=======================================================================
Centered FTCS after <=80 steps: initial TV(h) = 1.50 -> TV(h) = 4.73, min(h) = -0.059
Explanation. For any hyperbolic system with real eigenvalues , forward-Euler centered differencing has amplification eigenvalues , giving for all . HLL’s term (with , so ) supplies the exact upwind signal-cone numerical viscosity required to keep and .
Exercise 3¶
Problem. Implement shallow_water_1d_muscl_hll(h_init, hu_init, L, dt, n_steps, g) using minmod piecewise-linear interface reconstruction, HLL Riemann fluxes, and SSP-RK2 time stepping. Benchmark at against 1st-order shallow_water_1d_hll on the Stoker dam break (), asserting exact volume conservation and lower depth and velocity errors.
heading("Exercise 3: Implement It Yourself — 2nd-Order MUSCL-HLL Shallow-Water Solver")
def shallow_water_1d_muscl_hll(
h_init: np.ndarray, hu_init: np.ndarray, L: float, dt: float, n_steps: int, g: float = constants.G_STD
) -> dict:
"""Solve 1-D shallow-water equations via 2nd-order MUSCL-minmod + HLL + SSP-RK2."""
q = np.vstack([np.asarray(h_init, dtype=float).ravel(), np.asarray(hu_init, dtype=float).ravel()])
dx = float(L) / q.shape[1]
def minmod(a: np.ndarray, b: np.ndarray) -> np.ndarray:
return 0.5 * (np.sign(a) + np.sign(b)) * np.minimum(np.abs(a), np.abs(b))
def sw_rhs(state: np.ndarray) -> np.ndarray:
qp = np.pad(state, ((0, 0), (2, 2)), mode="edge")
slope = minmod(qp[:, 1:-1] - qp[:, :-2], qp[:, 2:] - qp[:, 1:-1])
ql = qp[:, 1:-2] + 0.5 * slope[:, :-1]
qr = qp[:, 2:-1] - 0.5 * slope[:, 1:]
hl, hr = ql[0], qr[0]
hul, hur = ql[1], qr[1]
ul, ur = hul / hl, hur / hr
cl, cr = np.sqrt(g * hl), np.sqrt(g * hr)
sl = np.minimum(ul - cl, ur - cr)
sr = np.maximum(ul + cl, ur + cr)
fl = np.vstack([hul, hul * ul + 0.5 * g * (hl ** 2)])
fr = np.vstack([hur, hur * ur + 0.5 * g * (hr ** 2)])
denom = np.where(sr - sl > 1e-14, sr - sl, 1.0)
f_hll = (sr[None, :] * fl - sl[None, :] * fr + (sl * sr)[None, :] * (qr - ql)) / denom[None, :]
f_face = np.where(sl[None, :] >= 0.0, fl, np.where(sr[None, :] <= 0.0, fr, f_hll))
return -(f_face[:, 1:] - f_face[:, :-1]) / dx
for _ in range(n_steps):
q1 = q + dt * sw_rhs(q)
q = 0.5 * q + 0.5 * (q1 + dt * sw_rhs(q1))
return {"h": q[0], "hu": q[1], "u": q[1] / q[0]}
n_m9 = 200
dx_m9 = 10.0 / n_m9
xc_m9 = (np.arange(n_m9) + 0.5) * dx_m9
h0_m9 = np.where(xc_m9 < 5.0, 2.0, 0.5)
hu0_m9 = np.zeros_like(xc_m9)
t_m9 = 0.60
n_st_m9 = 180
dt_m9 = t_m9 / n_st_m9
sol_1st = burgers_riemann.shallow_water_1d_hll(h0_m9, hu0_m9, L=10.0, dt=dt_m9, n_steps=n_st_m9)
sol_2nd = shallow_water_1d_muscl_hll(h0_m9, hu0_m9, L=10.0, dt=dt_m9, n_steps=n_st_m9)
ref_m9 = burgers_riemann.exact_dam_break_dry_or_wet(xc_m9, t=t_m9, h_left=2.0, h_right=0.5, x_dam=5.0)
e1_h = float(np.mean(np.abs(sol_1st["h"] - ref_m9["h"])))
e2_h = float(np.mean(np.abs(sol_2nd["h"] - ref_m9["h"])))
e1_u = float(np.mean(np.abs(sol_1st["u"] - ref_m9["u"])))
e2_u = float(np.mean(np.abs(sol_2nd["u"] - ref_m9["u"])))
vol_drift = abs(float(np.sum(sol_2nd["h"] - h0_m9) * dx_m9))
print(f"1st-Order HLL (N=200): L1(h) = {e1_h:.4e} m | L1(u) = {e1_u:.4e} m/s")
print(f"2nd-Order MUSCL (N=200): L1(h) = {e2_h:.4e} m | L1(u) = {e2_u:.4e} m/s | Vol drift = {vol_drift:.2e}")
assert vol_drift < 1e-12 and np.all(sol_2nd["h"] > 0.0)
assert e2_h < 0.65 * e1_h and e2_u < 0.65 * e1_u
Exercise 3: Implement It Yourself — 2nd-Order MUSCL-HLL Shallow-Water Solver
============================================================================
1st-Order HLL (N=200): L1(h) = 1.5246e-02 m | L1(u) = 4.4340e-02 m/s
2nd-Order MUSCL (N=200): L1(h) = 5.3892e-03 m | L1(u) = 1.6619e-02 m/s | Vol drift = 3.55e-16
Summary. Upgrading shallow_water_1d_hll with minmod MUSCL reconstruction and SSP-RK2 cuts dam-break depth and velocity errors by at , sharpening both the rarefaction corners and the advancing hydraulic bore without introducing spurious ripples.