In high-speed aerodynamics, supersonic nozzles, and detonation tubes, density, velocity, and thermodynamic internal energy evolve as an inseparable hyperbolic conservation system: the compressible Euler equations. In 1978, Sod proposed a test problem, the rupture of a diaphragm separating high-pressure driver gas from low-pressure driven gas , which produces all three wave families of gas dynamics: a left-running isentropic rarefaction fan, a middle entropy-carrying contact discontinuity, and a right-running supersonic shock wave. In this lecture we compute the exact solution of the Riemann problem by Newton iteration on the pressure (burgers_riemann.exact_sod_shock_tube), compare 1st-order HLL vs. 2nd-order MUSCL–minmod shock-capturing (euler_1d_sod_shock_tube), and implement a three-wave HLLC contact-resolving Riemann flux.
Learning objectives¶
Formulate the 1-D compressible Euler conservation vector , ideal-gas equation of state , and characteristic wave speeds .
Compute the exact solution of the Sod shock-tube problem (
burgers_riemann.exact_sod_shock_tube), checking isentropic invariance across the rarefaction, pressure/velocity continuity across the contact wave, and Rankine–Hugoniot shock jumps.Compare 1st-order HLL (
muscl=False) against 2nd-order MUSCL–minmod + SSP-RK2 (muscl=True) ineuler_1d_sod_shock_tube, verifying integral conservation of mass, momentum, and total energy.Diagnose HLL smearing of stationary contact discontinuities and implement the three-wave HLLC Riemann solver from scratch.
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. 1-D Compressible Euler Equations and the exact solution of the Sod problem¶
Neglecting viscosity and heat conduction, compressible conservation of mass, momentum, and total energy per unit volume reads:
where ( for diatomic air, constants.GAMMA_AIR) and is the isentropic speed of sound. The flux Jacobian possesses three real eigenvalues:
In Sod’s (1978) shock tube (, diaphragm at , and ):
(Left Rarefaction): Expands isentropically () down to star pressure and density .
(Contact Discontinuity at ): Pressure and velocity are continuous, while density jumps from down to hotter, higher-entropy .
(Right Shock at speed ): Irreversibly compresses driven gas across Rankine–Hugoniot jump relations, increasing entropy indicator .
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()
Demonstration 1: Exact Sod Shock Tube — 5 Regions, Entropy Jump & Rankine-Hugoniot check
========================================================================================
Exact Sod star values (gamma=1.4): p* = 0.303130, u* = 0.927453
Contact density jump: rho*_L = 0.426319 -> rho*_R = 0.265574 | Shock speed S_R = 1.752156
Rankine-Hugoniot residuals across S_R: mass=2.78e-17, mom=1.11e-16, energy=2.22e-16

Figure 10.1. Exact solution of the Sod problem at . (a) Density, pressure and velocity; the vertical lines mark the contact discontinuity and the shock. (b) The quantity , which is constant along the rarefaction and changes at the contact discontinuity and at the shock.
What Demonstration 1 shows. Panel (b) shows . It stays at 1.000 across the whole rarefaction, because the expansion is smooth and reversible. It jumps to 1.940 at the contact discontinuity (), which separates the expanded driver gas from the gas that the shock has passed, and falls to at the shock (), the value of the undisturbed gas on the right. The shock therefore raises from 1.838 to 1.940: the entropy increases across it.
2. 1st-Order HLL vs. 2nd-Order MUSCL–minmod (euler_1d_sod_shock_tube)¶
We now solve the Sod shock tube numerically on cells via burgers_riemann.euler_1d_sod_shock_tube comparing muscl=False (1st-order piecewise-constant HLL) against muscl=True (2nd-order minmod slope reconstruction + HLL + SSP-RK2), and verify exact integral conservation of total mass, momentum impulse , and total energy.
heading("Demonstration 2: 1st-Order HLL vs 2nd-Order MUSCL-minmod on Sod Shock Tube (N = 400)")
sod_hll1 = burgers_riemann.euler_1d_sod_shock_tube(n_cells=400, t_end=0.20, cfl=0.45, muscl=False)
sod_muscl = burgers_riemann.euler_1d_sod_shock_tube(n_cells=400, t_end=0.20, cfl=0.45, muscl=True)
dx_s = 1.0 / 400.0
# Exact integral conservation before waves hit x=0 or x=1 (u_wall = 0 at both ends for t = 0.20):
mass_exact = 0.5 * (1.0 + 0.125)
mom_exact = (1.0 - 0.1) * 0.20 # Net pressure force (p_L - p_R) * t_end
eng_exact = 0.5 * (1.0 / (gam - 1.0) + 0.1 / (gam - 1.0))
for tag, run in [("1st-Order HLL", sod_hll1), ("2nd-Order MUSCL", sod_muscl)]:
m_num = float(np.sum(run["rho"]) * dx_s)
mom_num = float(np.sum(run["rho"] * run["u"]) * dx_s)
E_arr = run["p"] / (gam - 1.0) + 0.5 * run["rho"] * (run["u"] ** 2)
eng_num = float(np.sum(E_arr) * dx_s)
print(
f"{tag:16s} | steps={run['steps']:3d} | L1(rho)={run['l1_rho_error']:.4e} | "
f"dMass={abs(m_num-mass_exact):.2e} | dMom={abs(mom_num-mom_exact):.2e} | dEng={abs(eng_num-eng_exact):.2e}"
)
assert np.isclose(m_num, mass_exact, atol=1e-12)
assert np.isclose(mom_num, mom_exact, atol=1e-12)
assert np.isclose(eng_num, eng_exact, atol=1e-12)
assert np.all(run["rho"] > 0.0) and np.all(run["p"] > 0.0)
assert sod_muscl["l1_rho_error"] < 0.50 * sod_hll1["l1_rho_error"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
xc_400 = sod_muscl["xc"]
ax1.plot(xc_400, sod_muscl["exact"]["rho"], "k--", lw=1.7, label="Exact solution")
ax1.plot(xc_400, sod_hll1["rho"], lw=1.6, alpha=0.85, label="1st-Order HLL")
ax1.plot(xc_400, sod_muscl["rho"], lw=1.8, color="#d62728", label="2nd-Order MUSCL-minmod")
ax1.set_xlabel("Position $x$ [-]")
ax1.set_ylabel(r"Density $\rho(x, 0.2)$ [-]")
ax1.set_title("Sod Density Profile: Contact & Shock Sharpening")
ax1.legend(fontsize=8.5)
ax2.plot(xc_400, sod_muscl["exact"]["u"], "k--", lw=1.7, label="Exact solution")
ax2.plot(xc_400, sod_hll1["u"], lw=1.6, alpha=0.85, label="1st-Order HLL")
ax2.plot(xc_400, sod_muscl["u"], lw=1.8, color="#1f77b4", label="2nd-Order MUSCL-minmod")
ax2.set_xlabel("Position $x$ [-]")
ax2.set_ylabel("Velocity $u(x, 0.2)$ [-]")
ax2.set_title("Sod Velocity Profile (Zero Gibbs Overshoot)")
ax2.legend(fontsize=8.5)
label_panels(fig)
plt.show()
Demonstration 2: 1st-Order HLL vs 2nd-Order MUSCL-minmod on Sod Shock Tube (N = 400)
====================================================================================
1st-Order HLL | steps=386 | L1(rho)=7.6819e-03 | dMass=0.00e+00 | dMom=5.55e-17 | dEng=0.00e+00
2nd-Order MUSCL | steps=388 | L1(rho)=2.6174e-03 | dMass=0.00e+00 | dMom=2.78e-17 | dEng=0.00e+00

Figure 10.2. The Sod problem on 400 cells with the first-order HLL scheme and with MUSCL reconstruction (minmod limiter), compared with the exact solution. (a) Density. (b) Velocity.
What Demonstration 2 shows. MUSCL-minmod cuts l1_rho_error by more than compared to 1st-order HLL, strongly sharpening the rarefaction head/tail corners, the contact discontinuity at , and the right shock at while maintaining zero non-physical oscillations and exact integral conservation of mass, momentum, and total energy to 10-14.
3. Mesh Convergence Rate: Contact Discontinuities vs. Self-Steepening Shocks¶
We sweep grid resolution for both muscl=False and muscl=True. Why do linear contact discontinuities converge more slowly in than compressive shocks? Because characteristics run parallel to a contact ( on both sides), so numerical diffusion grows as without nonlinear characteristic convergence to re-steepen it.
heading("Demonstration 3: Mesh Refinement Sweep (N = 100..800) — 1st-Order HLL vs 2nd-Order MUSCL")
grids_eu = [100, 200, 400, 800]
err_hll_list, err_muscl_list = [], []
for ng in grids_eu:
r1 = burgers_riemann.euler_1d_sod_shock_tube(n_cells=ng, t_end=0.20, cfl=0.45, muscl=False)
r2 = burgers_riemann.euler_1d_sod_shock_tube(n_cells=ng, t_end=0.20, cfl=0.45, muscl=True)
err_hll_list.append(r1["l1_rho_error"])
err_muscl_list.append(r2["l1_rho_error"])
print(f"N = {ng:3d} | 1st-Order HLL L1(rho) = {r1['l1_rho_error']:.4e} | 2nd-Order MUSCL L1(rho) = {r2['l1_rho_error']:.4e}")
p_hll = float(np.log2(err_hll_list[-2] / err_hll_list[-1]))
p_mus = float(np.log2(err_muscl_list[-2] / err_muscl_list[-1]))
print(f"Observed Sod L1(rho) rates (400->800): 1st-Order HLL = {p_hll:.3f} vs MUSCL = {p_mus:.3f}")
assert p_mus > p_hll and err_muscl_list[-1] < 0.45 * err_hll_list[-1]
fig, ax = plt.subplots(figsize=(6.8, 4.0))
ax.loglog(grids_eu, err_hll_list, "o-", lw=2.0, label=f"1st-Order HLL (rate = {p_hll:.2f})")
ax.loglog(grids_eu, err_muscl_list, "s-", lw=2.0, label=f"2nd-Order MUSCL-minmod (rate = {p_mus:.2f})")
ax.set_xlabel("Grid Cells $N$ [-]")
ax.set_ylabel(r"$L_1$ Density Error $\frac{1}{N}\sum |\rho_i - \rho_{\mathrm{exact}}|$ [-]")
ax.set_title("Sod Shock-Tube Convergence: 1st-Order vs. MUSCL")
ax.legend()
Demonstration 3: Mesh Refinement Sweep (N = 100..800) — 1st-Order HLL vs 2nd-Order MUSCL
========================================================================================
N = 100 | 1st-Order HLL L1(rho) = 1.9082e-02 | 2nd-Order MUSCL L1(rho) = 8.7145e-03
N = 200 | 1st-Order HLL L1(rho) = 1.2128e-02 | 2nd-Order MUSCL L1(rho) = 4.6812e-03
N = 400 | 1st-Order HLL L1(rho) = 7.6819e-03 | 2nd-Order MUSCL L1(rho) = 2.6174e-03
N = 800 | 1st-Order HLL L1(rho) = 4.8512e-03 | 2nd-Order MUSCL L1(rho) = 1.4926e-03
Observed Sod L1(rho) rates (400->800): 1st-Order HLL = 0.663 vs MUSCL = 0.810

Figure 10.3. error of the density against the number of cells for the two schemes. Both orders are below 1 because the solution is discontinuous; the legend gives the fitted rates.
What Demonstration 3 shows. MUSCL on cells already outperforms 1st-order HLL on cells, and on cells reduces the density error by a factor of 3.3, mainly because the reconstruction keeps the contact discontinuity and the corners of the rarefaction sharper.
4. Specific-Heat Ratio Sweep¶
How does molecular degrees-of-freedom thermodynamics ( for monatomic Argon/Helium, for diatomic Air/, for hot polyatomic combustion products) alter shock speed , star pressure , and shock compression ?
heading("Demonstration 4: Specific-Heat Ratio Sensitivity (Monatomic vs Air vs Polyatomic Gas)")
gammas_test = [("Polyatomic (gamma=1.20)", 1.20), ("Diatomic Air (gamma=1.40)", 1.40), ("Monatomic Ar (gamma=5/3)", 5.0 / 3.0)]
print(f"{'Gas Type':25s} | {'p*':>8s} | {'u*':>8s} | {'Shock S_R':>10s} | {'rho*_R / rho_R':>15s} | {'Max Limit (g+1)/(g-1)':>21s}")
print("-" * 98)
prev_sr = 0.0
for label, gv in gammas_test:
ex_g = burgers_riemann.exact_sod_shock_tube(np.array([0.5]), t=0.20, gamma=gv)
comp_ratio = ex_g["rho_star_right"] / 0.125
max_comp = (gv + 1.0) / (gv - 1.0)
print(f"{label:25s} | {ex_g['p_star']:8.5f} | {ex_g['u_star']:8.5f} | {ex_g['shock_speed']:10.5f} | {comp_ratio:15.4f} | {max_comp:21.2f}")
assert 1.0 < comp_ratio < max_comp
assert ex_g["shock_speed"] > prev_sr
prev_sr = ex_g["shock_speed"]
Demonstration 4: Specific-Heat Ratio Sensitivity (Monatomic vs Air vs Polyatomic Gas)
=====================================================================================
Gas Type | p* | u* | Shock S_R | rho*_R / rho_R | Max Limit (g+1)/(g-1)
--------------------------------------------------------------------------------------------------
Polyatomic (gamma=1.20) | 0.31274 | 1.01132 | 1.68290 | 2.5059 | 11.00
Diatomic Air (gamma=1.40) | 0.30313 | 0.92745 | 1.75216 | 2.1246 | 6.00
Monatomic Ar (gamma=5/3) | 0.29395 | 0.84119 | 1.84447 | 1.8384 | 4.00
Inside the algorithm¶
Higher means fewer internal rotational/vibrational modes to absorb energy, stiffening acoustic speed so the shock propagates faster ( for ) while limiting maximum density compression below ().
Below we inspect burgers_riemann.exact_sod_shock_tube and trace the Newton–Raphson iteration on , and check its quadratic convergence.
Check against the library¶
heading("Inside the Algorithm: Toro Newton-Raphson Star-Pressure Solver in exact_sod_shock_tube")
print(show_source(burgers_riemann.exact_sod_shock_tube))
# Trace quadratic Newton convergence of |dp_k| on Sod's pressure function:
rho_l, u_l, p_l = 1.0, 0.0, 1.0
rho_r, u_r, p_r = 0.125, 0.0, 0.1
g_in = constants.GAMMA_AIR
a_l, a_r = np.sqrt(g_in * p_l / rho_l), np.sqrt(g_in * p_r / rho_r)
p_iter = 0.5 * (p_l + p_r)
dp_hist = []
for k in range(1, 7):
# Left rarefaction (p < p_l) + Right shock (p > p_r) for Sod:
fl = (2.0 * a_l / (g_in - 1.0)) * ((p_iter / p_l) ** ((g_in - 1.0) / (2.0 * g_in)) - 1.0)
dfl = (1.0 / (rho_l * a_l)) * ((p_iter / p_l) ** (-(g_in + 1.0) / (2.0 * g_in)))
ar_c = 2.0 / ((g_in + 1.0) * rho_r)
br_c = ((g_in - 1.0) / (g_in + 1.0)) * p_r
qrt = np.sqrt(ar_c / (p_iter + br_c))
fr = (p_iter - p_r) * qrt
dfr = qrt * (1.0 - 0.5 * (p_iter - p_r) / (p_iter + br_c))
dp = -(fl + fr + (u_r - u_l)) / (dfl + dfr)
p_iter += dp
dp_hist.append(abs(dp))
print(f"Newton iter {k}: p* = {p_iter:.15f}, |dp| = {abs(dp):.3e}")
lib_p_star = burgers_riemann.exact_sod_shock_tube(np.array([0.5]), t=0.20, gamma=g_in)["p_star"]
assert dp_hist[-1] < 1e-15 and np.isclose(p_iter, lib_p_star, rtol=1e-15, atol=1e-15)
Inside the Algorithm: Toro Newton-Raphson Star-Pressure Solver in exact_sod_shock_tube
======================================================================================
def exact_sod_shock_tube(
x: np.ndarray,
t: float,
x0: float = 0.5,
gamma: float = GAMMA_AIR,
left_state: tuple[float, float, float] = (1.0, 0.0, 1.0),
right_state: tuple[float, float, float] = (0.125, 0.0, 0.1),
) -> dict:
"""Exact Toro (2009) Riemann solution for the 1-D compressible Euler Sod shock tube."""
if t <= 0.0:
raise ValueError("Time t must be strictly positive.")
rho_l, u_l, p_l = map(float, left_state)
rho_r, u_r, p_r = map(float, right_state)
a_l = float(np.sqrt(gamma * p_l / rho_l))
a_r = float(np.sqrt(gamma * p_r / rho_r))
def wave_f(p: float, rho_k: float, p_k: float, a_k: float) -> tuple[float, float]:
if p > p_k:
ak = 2.0 / ((gamma + 1.0) * rho_k)
bk = ((gamma - 1.0) / (gamma + 1.0)) * p_k
qrt = float(np.sqrt(ak / (p + bk)))
f_val = (p - p_k) * qrt
df_val = qrt * (1.0 - 0.5 * (p - p_k) / (p + bk))
return f_val, df_val
pr = p / p_k
f_val = (2.0 * a_k / (gamma - 1.0)) * (pr ** ((gamma - 1.0) / (2.0 * gamma)) - 1.0)
df_val = (1.0 / (rho_k * a_k)) * (pr ** (-(gamma + 1.0) / (2.0 * gamma)))
return float(f_val), float(df_val)
p_star = 0.5 * (p_l + p_r)
for _ in range(40):
fl, dfl = wave_f(p_star, rho_l, p_l, a_l)
fr, dfr = wave_f(p_star, rho_r, p_r, a_r)
dp = -(fl + fr + (u_r - u_l)) / (dfl + dfr)
p_star = max(1e-12, p_star + dp)
if abs(dp) < 1e-13 * p_star:
break
fl, _ = wave_f(p_star, rho_l, p_l, a_l)
fr, _ = wave_f(p_star, rho_r, p_r, a_r)
u_star = 0.5 * (u_l + u_r + fr - fl)
# Left rarefaction & right shock structure (standard Sod p_r < p_star < p_l):
rho_star_l = rho_l * ((p_star / p_l) ** (1.0 / gamma))
a_star_l = a_l * ((p_star / p_l) ** ((gamma - 1.0) / (2.0 * gamma)))
gm_gp = (gamma - 1.0) / (gamma + 1.0)
pr_ratio = p_star / p_r
rho_star_r = rho_r * ((pr_ratio + gm_gp) / (gm_gp * pr_ratio + 1.0))
s_shock_r = u_r + a_r * float(np.sqrt(((gamma + 1.0) / (2.0 * gamma)) * pr_ratio + (gamma - 1.0) / (2.0 * gamma)))
xi = (np.asarray(x, dtype=float) - float(x0)) / float(t)
rho = np.empty_like(xi)
u = np.empty_like(xi)
p = np.empty_like(xi)
sh_l = u_l - a_l
st_l = u_star - a_star_l
m1 = xi <= sh_l
m2 = (xi > sh_l) & (xi < st_l)
m3 = (xi >= st_l) & (xi < u_star)
m4 = (xi >= u_star) & (xi < s_shock_r)
m5 = xi >= s_shock_r
rho[m1], u[m1], p[m1] = rho_l, u_l, p_l
u_fan = (2.0 / (gamma + 1.0)) * (a_l + 0.5 * (gamma - 1.0) * u_l + xi[m2])
a_fan = (2.0 / (gamma + 1.0)) * (a_l + 0.5 * (gamma - 1.0) * (u_l - xi[m2]))
rho[m2] = rho_l * ((a_fan / a_l) ** (2.0 / (gamma - 1.0)))
u[m2] = u_fan
p[m2] = p_l * ((a_fan / a_l) ** (2.0 * gamma / (gamma - 1.0)))
rho[m3], u[m3], p[m3] = rho_star_l, u_star, p_star
rho[m4], u[m4], p[m4] = rho_star_r, u_star, p_star
rho[m5], u[m5], p[m5] = rho_r, u_r, p_r
energy = p / (gamma - 1.0) + 0.5 * rho * (u**2)
return {
"x": np.asarray(x, dtype=float),
"rho": rho,
"u": u,
"p": p,
"energy": energy,
"p_star": float(p_star),
"u_star": float(u_star),
"rho_star_left": float(rho_star_l),
"rho_star_right": float(rho_star_r),
"shock_speed": float(s_shock_r),
}
Newton iter 1: p* = 0.245538897712679, |dp| = 3.045e-01
Newton iter 2: p* = 0.298411084566338, |dp| = 5.287e-02
Newton iter 3: p* = 0.303101195525898, |dp| = 4.690e-03
Newton iter 4: p* = 0.303130176965532, |dp| = 2.898e-05
Newton iter 5: p* = 0.303130178050647, |dp| = 1.085e-09
Newton iter 6: p* = 0.303130178050647, |dp| = 2.031e-17
Exercises¶
Worked solutions are in 10_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. 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.Find how it fails. Verify
exact_sod_shock_tuberaisesValueErrorfor , and show algebraically and numerically that on a stationary contact jump vs. , two-wave HLL produces spurious mass diffusion that smears the motionless interface.Implement it yourself. 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 smallerl1_rho_errorthan 1st-order HLL.
heading("Self-check for the exercises")
sod_chk = burgers_riemann.euler_1d_sod_shock_tube(n_cells=120, t_end=0.20, cfl=0.45, muscl=True)
assert sod_chk["l1_rho_error"] < 0.02 and np.all(sod_chk["p"] > 0.0)
print(f"MUSCL Sod check (N=120): steps = {sod_chk['steps']}, L1(rho) = {sod_chk['l1_rho_error']:.4e}")
print("All checks passed.")
Self-check for the exercises
============================
MUSCL Sod check (N=120): steps = 115, L1(rho) = 7.3040e-03
All checks passed.