Worked solutions to the three exercises of Lecture 10. 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 Sod Shock Tube — 5 Regions, Entropy Jump & Rankine-Hugoniot check")
x_sod = np.linspace(0.0, 1.0, 800)
t_sod = 0.20
gam = constants.GAMMA_AIR
ex_sod = burgers_riemann.exact_sod_shock_tube(x_sod, t=t_sod, x0=0.5, gamma=gam)
ps, us = ex_sod["p_star"], ex_sod["u_star"]
rls, rrs, sr = ex_sod["rho_star_left"], ex_sod["rho_star_right"], ex_sod["shock_speed"]
print(f"Exact Sod star values (gamma={gam}): p* = {ps:.6f}, u* = {us:.6f}")
print(f"Contact density jump: rho*_L = {rls:.6f} -> rho*_R = {rrs:.6f} | Shock speed S_R = {sr:.6f}")
# 1. Verify isentropic constancy p / rho^gamma == 1.0 everywhere left of contact x_contact = 0.5 + u* * t:
x_contact = 0.5 + us * t_sod
x_shock = 0.5 + sr * t_sod
entropy_ind = ex_sod["p"] / (ex_sod["rho"] ** gam)
left_of_contact = x_sod < (x_contact - 0.005)
shocked_gas = (x_sod > x_contact + 0.005) & (x_sod < x_shock - 0.005)
undisturbed_r = x_sod > (x_shock + 0.005)
assert np.allclose(entropy_ind[left_of_contact], 1.0, rtol=1e-12, atol=1e-12)
assert np.all(entropy_ind[shocked_gas] > entropy_ind[undisturbed_r][0] + 0.1)
# 2. Verify all 3 Rankine-Hugoniot jump equations (mass, momentum, total energy) across right shock S_R:
rho_r0, u_r0, p_r0 = 0.125, 0.0, 0.1
E_star_r = ps / (gam - 1.0) + 0.5 * rrs * (us ** 2)
E_r0 = p_r0 / (gam - 1.0)
rh_mass = abs(sr * (rrs - rho_r0) - (rrs * us - 0.0))
rh_mom = abs(sr * (rrs * us - 0.0) - ((rrs * us ** 2 + ps) - p_r0))
rh_eng = abs(sr * (E_star_r - E_r0) - (us * (E_star_r + ps) - 0.0))
print(f"Rankine-Hugoniot residuals across S_R: mass={rh_mass:.2e}, mom={rh_mom:.2e}, energy={rh_eng:.2e}")
assert rh_mass < 1e-12 and rh_mom < 1e-12 and rh_eng < 1e-12
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
ax1.plot(x_sod, ex_sod["rho"], lw=2.0, label=r"Density $\rho$")
ax1.plot(x_sod, ex_sod["p"], lw=2.0, label="Pressure $p$")
ax1.plot(x_sod, ex_sod["u"], lw=2.0, label="Velocity $u$")
ax1.axvline(x_contact, color="gray", ls=":", label="Contact $x_0 + u^* t$")
ax1.axvline(x_shock, color="#c0392b", ls="--", label="Shock $x_0 + S_R t$")
ax1.set_xlabel("Position $x$ [-]")
ax1.set_ylabel("Primitive Variables [-]")
ax1.set_title("Exact Sod Shock Tube ($t = 0.20$)")
ax1.legend(fontsize=8)
ax2.plot(x_sod, entropy_ind, lw=2.1, color="#8e44ad")
ax2.axvline(x_contact, color="gray", ls=":", label="Contact entropy jump")
ax2.axvline(x_shock, color="#c0392b", ls="--", label="Shock entropy jump")
ax2.set_xlabel("Position $x$ [-]")
ax2.set_ylabel(r"Adiabat $p / \rho^\gamma$ [-]")
ax2.set_title("Thermodynamic Entropy Indicator Across All 3 Waves")
ax2.legend(fontsize=8.5)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Sweep driver pressure in exact_sod_shock_tube (, right state , ), verifying that shock Mach number grows unboundedly while post-shock compression approaches monotonically from below.
heading("Exercise 1: Strong-Shock Compression Limit (gamma + 1)/(gamma - 1) == 6.0 for Air")
g_air = constants.GAMMA_AIR
rho_r_ref, p_r_ref = 0.125, 0.1
a_r_ref = float(np.sqrt(g_air * p_r_ref / rho_r_ref))
pL_sweep = [1.0, 10.0, 100.0, 1.0e4, 1.0e6]
ratios_comp = []
for pl_v in pL_sweep:
ex_s = burgers_riemann.exact_sod_shock_tube(
np.array([0.5]), t=0.05, gamma=g_air, left_state=(1.0, 0.0, pl_v), right_state=(rho_r_ref, 0.0, p_r_ref)
)
mach_s = ex_s["shock_speed"] / a_r_ref
comp_r = ex_s["rho_star_right"] / rho_r_ref
ratios_comp.append(comp_r)
print(f"p_L = {pl_v:9.1f} | p*/p_R = {ex_s['p_star']/p_r_ref:10.2f} | Shock Mach M_s = {mach_s:8.2f} | rho*_R / rho_R = {comp_r:8.5f}")
assert all(ratios_comp[i] < ratios_comp[i + 1] < 6.0 for i in range(len(ratios_comp) - 1))
assert ratios_comp[-1] > 5.98
Exercise 1: Strong-Shock Compression Limit (gamma + 1)/(gamma - 1) == 6.0 for Air
=================================================================================
p_L = 1.0 | p*/p_R = 3.03 | Shock Mach M_s = 1.66 | rho*_R / rho_R = 2.12459
p_L = 10.0 | p*/p_R = 21.98 | Shock Mach M_s = 4.36 | rho*_R / rho_R = 4.74931
p_L = 100.0 | p*/p_R = 210.86 | Shock Mach M_s = 13.45 | rho*_R / rho_R = 5.83860
p_L = 10000.0 | p*/p_R = 20985.82 | Shock Mach M_s = 134.12 | rho*_R / rho_R = 5.99833
p_L = 1000000.0 | p*/p_R = 2098481.44 | Shock Mach M_s = 1341.16 | rho*_R / rho_R = 5.99998
Explanation. From the Rankine–Hugoniot density relation , taking the hypersonic limit cancels between numerator and denominator, leaving for : the work done by a very strong shock raises the temperature of the gas, while the density ratio stays bounded.
Exercise 2¶
Problem. Verify exact_sod_shock_tube raises ValueError for , and show algebraically and numerically that on a stationary contact jump vs. , two-wave HLL produces spurious mass diffusion that smears the motionless interface.
heading("Exercise 2: Two-Wave HLL Smearing of a Stationary Contact Discontinuity")
caught_t = False
try:
burgers_riemann.exact_sod_shock_tube(np.array([0.5]), t=0.0)
except ValueError:
caught_t = True
assert caught_t is True
# Stationary contact: u_L = u_R = 0, p_L = p_R = 1.0, rho_L = 1.0, rho_R = 0.125:
g_c = constants.GAMMA_AIR
rhol_c, rhor_c = 1.0, 0.125
p_c = 1.0
ql_c = np.array([rhol_c, 0.0, p_c / (g_c - 1.0)])
qr_c = np.array([rhor_c, 0.0, p_c / (g_c - 1.0)])
fl_c = np.array([0.0, p_c, 0.0])
fr_c = np.array([0.0, p_c, 0.0])
sl_c = -np.sqrt(g_c * p_c / rhol_c)
sr_c = +np.sqrt(g_c * p_c / rhor_c)
f_hll_contact = (sr_c * fl_c - sl_c * fr_c + sl_c * sr_c * (qr_c - ql_c)) / (sr_c - sl_c)
exact_spurious_mass_flux = (sl_c * sr_c / (sr_c - sl_c)) * (rhor_c - rhol_c)
print(f"Exact stationary Euler flux : {fl_c}")
print(f"Two-wave HLL flux across u=0 jump : {np.round(f_hll_contact, 5)}")
print(f"Spurious HLL mass flux F_HLL[0] : {f_hll_contact[0]:+.6f} (matches formula {exact_spurious_mass_flux:+.6f})")
assert np.isclose(f_hll_contact[0], exact_spurious_mass_flux, atol=1e-15)
assert abs(f_hll_contact[0]) > 0.70
Exercise 2: Two-Wave HLL Smearing of a Stationary Contact Discontinuity
=======================================================================
Exact stationary Euler flux : [0. 1. 0.]
Two-wave HLL flux across u=0 jump : [0.76489 1. 0. ]
Spurious HLL mass flux F_HLL[0] : +0.764886 (matches formula +0.764886)
Explanation. Because two-wave HLL replaces the entire Riemann fan between and by a single averaged state , it ignores the middle contact wave completely. Consequently, HLL misinterprets a benign stationary temperature/density interface as an acoustic disturbance and gives a spurious mass flux of +0.765 per unit time across a gas at rest, which is the reason for the three-wave HLLC solver of Exercise 3.
Exercise 3¶
Problem. Implement hllc_euler_flux(ql, qr, gamma=1.4) (vectorized over cell faces (3, M)). Verify exact preservation of the stationary contact from Exercise 2 ( to 10-15), and integrate the 1st-order Sod shock tube () with HLLC to show strictly smaller l1_rho_error than 1st-order HLL.
heading("Exercise 3: Implement It Yourself — Three-Wave HLLC Contact-Resolving Euler Solver")
def hllc_euler_flux(ql: np.ndarray, qr: np.ndarray, gamma: float = constants.GAMMA_AIR) -> tuple[np.ndarray, float]:
"""Compute vectorized 3-wave HLLC Euler numerical flux for left/right conserved states (3, M)."""
rhol, rhor = ql[0], qr[0]
ul, ur = ql[1] / rhol, qr[1] / rhor
pl = (gamma - 1.0) * (ql[2] - 0.5 * rhol * (ul ** 2))
pr = (gamma - 1.0) * (qr[2] - 0.5 * rhor * (ur ** 2))
al = np.sqrt(gamma * np.maximum(pl, 1e-12) / rhol)
ar = np.sqrt(gamma * np.maximum(pr, 1e-12) / rhor)
sl = np.minimum(ul - al, ur - ar)
sr = np.maximum(ul + al, ur + ar)
s_max = float(np.max(np.maximum(np.abs(sl), np.abs(sr))))
# Toro contact wave speed S*:
num_s = pr - pl + rhol * ul * (sl - ul) - rhor * ur * (sr - ur)
den_s = rhol * (sl - ul) - rhor * (sr - ur)
s_star = num_s / np.where(np.abs(den_s) > 1e-14, den_s, 1.0)
def q_star_k(qk: np.ndarray, rk: np.ndarray, uk: np.ndarray, pk: np.ndarray, sk: np.ndarray) -> np.ndarray:
fac = rk * (sk - uk) / np.where(np.abs(sk - s_star) > 1e-14, sk - s_star, 1.0)
e_term = qk[2] / rk + (s_star - uk) * (s_star + pk / (rk * np.where(np.abs(sk - uk) > 1e-14, sk - uk, 1.0)))
return fac[None, :] * np.vstack([np.ones_like(s_star), s_star, e_term])
fl = np.vstack([ql[1], ql[1] * ul + pl, ul * (ql[2] + pl)])
fr = np.vstack([qr[1], qr[1] * ur + pr, ur * (qr[2] + pr)])
f_star_l = fl + sl[None, :] * (q_star_k(ql, rhol, ul, pl, sl) - ql)
f_star_r = fr + sr[None, :] * (q_star_k(qr, rhor, ur, pr, sr) - qr)
f_out = np.where(
sl[None, :] >= 0.0,
fl,
np.where(s_star[None, :] >= 0.0, f_star_l, np.where(sr[None, :] >= 0.0, f_star_r, fr)),
)
return f_out, s_max
# 1. Verify ZERO spurious diffusion on stationary contact (u=0, p=1, rho_L=1, rho_R=0.125):
g_e3 = constants.GAMMA_AIR
ql_stat = np.array([[1.0], [0.0], [1.0 / (g_e3 - 1.0)]])
qr_stat = np.array([[0.125], [0.0], [1.0 / (g_e3 - 1.0)]])
f_stat, _ = hllc_euler_flux(ql_stat, qr_stat, gamma=g_e3)
print(f"HLLC flux on stationary contact: {f_stat.ravel()} (exact = [0, 1, 0])")
assert np.allclose(f_stat.ravel(), np.array([0.0, 1.0, 0.0]), atol=1e-15)
# 2. Run 1st-order HLLC Sod shock tube (N=400, t_end=0.20) vs 1st-order HLL:
n_c3 = 400
dx_c3 = 1.0 / n_c3
xc_c3 = (np.arange(n_c3) + 0.5) * dx_c3
rho_hllc = np.where(xc_c3 < 0.5, 1.0, 0.125)
p_hllc = np.where(xc_c3 < 0.5, 1.0, 0.1)
q_hllc = np.vstack([rho_hllc, np.zeros_like(xc_c3), p_hllc / (g_e3 - 1.0)])
t_cur = 0.0
while t_cur < 0.20 - 1e-15:
qp = np.pad(q_hllc, ((0, 0), (1, 1)), mode="edge")
ff, smax = hllc_euler_flux(qp[:, :-1], qp[:, 1:], gamma=g_e3)
dt_step = min(0.45 * dx_c3 / smax, 0.20 - t_cur)
q_hllc = q_hllc - (dt_step / dx_c3) * (ff[:, 1:] - ff[:, :-1])
t_cur += dt_step
hll_1st = burgers_riemann.euler_1d_sod_shock_tube(n_cells=n_c3, t_end=0.20, cfl=0.45, muscl=False)
err_hllc = float(np.mean(np.abs(q_hllc[0] - hll_1st["exact"]["rho"])))
print(f"1st-Order HLL (N=400) L1(rho) = {hll_1st['l1_rho_error']:.4e}")
print(f"1st-Order HLLC (N=400) L1(rho) = {err_hllc:.4e} (sharper contact wave)")
assert err_hllc < hll_1st["l1_rho_error"]
Exercise 3: Implement It Yourself — Three-Wave HLLC Contact-Resolving Euler Solver
==================================================================================
HLLC flux on stationary contact: [0. 1. 0.] (exact = [0, 1, 0])
1st-Order HLL (N=400) L1(rho) = 7.6819e-03
1st-Order HLLC (N=400) L1(rho) = 7.2395e-03 (sharper contact wave)
Summary. Restoring the middle contact wave in HLLC eliminates stationary contact diffusion to rounding error (10-16) and sharpens the moving Sod contact discontinuity at ; on 400 cells the density error falls from to .