Worked solutions to the three exercises of Lecture 8. 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 Cole-Hopf Solution & Conservative Godunov FVM Verification")
L_ch = 2.0 * np.pi
n_ch = 256
dx_ch = L_ch / n_ch
x_ch = (np.arange(n_ch) + 0.5) * dx_ch
nu_ch = 0.15
a0_ch = 1.12
# 1. Verify directly via 4th-order/spectral Fourier derivatives that cole_hopf_viscous_burgers_exact solves PDE (1.1):
t_pde = 0.40
dt_fd = 1e-6
u_c = burgers_riemann.cole_hopf_viscous_burgers_exact(x_ch, t_pde, nu=nu_ch, L=L_ch, offset_a0=a0_ch)
u_p = burgers_riemann.cole_hopf_viscous_burgers_exact(x_ch, t_pde + dt_fd, nu=nu_ch, L=L_ch, offset_a0=a0_ch)
u_m = burgers_riemann.cole_hopf_viscous_burgers_exact(x_ch, t_pde - dt_fd, nu=nu_ch, L=L_ch, offset_a0=a0_ch)
ut_num = (u_p - u_m) / (2.0 * dt_fd)
k_fft = np.fft.fftfreq(n_ch, d=dx_ch / (2.0 * np.pi))
u_hat = np.fft.fft(u_c)
ux_spec = np.real(np.fft.ifft(1j * k_fft * u_hat))
uxx_spec = np.real(np.fft.ifft(-(k_fft ** 2) * u_hat))
pde_residual = float(np.max(np.abs(ut_num + u_c * ux_spec - nu_ch * uxx_spec)))
print(f"Cole-Hopf exact PDE residual max |u_t + u*u_x - nu*u_xx| = {pde_residual:.3e}")
assert pde_residual < 1e-9
# 2. Integrate from t = 0 to t = 1.0 via solve_viscous_burgers_1d (Godunov + SSP-RK2):
u0_ch = burgers_riemann.cole_hopf_viscous_burgers_exact(x_ch, 0.0, nu=nu_ch, L=L_ch, offset_a0=a0_ch)
t_end_ch = 1.0
n_steps_ch = 1250
dt_ch = t_end_ch / n_steps_ch
sol_god = burgers_riemann.solve_viscous_burgers_1d(u0_ch, L=L_ch, nu=nu_ch, dt=dt_ch, n_steps=n_steps_ch, flux="godunov", periodic=True)
sol_rus = burgers_riemann.solve_viscous_burgers_1d(u0_ch, L=L_ch, nu=nu_ch, dt=dt_ch, n_steps=n_steps_ch, flux="rusanov", periodic=True)
u_exact_end = burgers_riemann.cole_hopf_viscous_burgers_exact(x_ch, t_end_ch, nu=nu_ch, L=L_ch, offset_a0=a0_ch)
err_god = float(np.sqrt(np.mean((sol_god["final"] - u_exact_end) ** 2)))
err_rus = float(np.sqrt(np.mean((sol_rus["final"] - u_exact_end) ** 2)))
imp_drift = float(np.max(np.abs(sol_god["impulses"] - sol_god["impulses"][0])))
print(f"Godunov L2 error = {err_god:.4e}, Rusanov L2 error = {err_rus:.4e}, Impulse drift = {imp_drift:.2e}")
assert imp_drift < 1e-14
assert err_god < 3e-3 and err_rus < 4e-3
fig, ax = plt.subplots(figsize=(7.4, 4.1))
for tv, ls in [(0.0, "--"), (0.4, "-."), (1.0, "-")]:
ax.plot(x_ch, burgers_riemann.cole_hopf_viscous_burgers_exact(x_ch, tv, nu=nu_ch, L=L_ch, offset_a0=a0_ch), ls, lw=1.8, label=f"Cole-Hopf Exact ($t={tv:.1f}$)")
ax.plot(x_ch[::6], sol_god["final"][::6], "ko", ms=4.5, label="Godunov FVM ($t=1.0$)")
ax.set_xlabel("Position $x$ [rad]")
ax.set_ylabel("Velocity $u(x, t)$ [m/s]")
ax.set_title(r"Periodic Viscous Burgers Evolution ($\nu = 0.15$, $a_0 = 1.12$)")
ax.legend(fontsize=8.5)
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Perform a grid-refinement study () for solve_viscous_burgers_1d(..., flux='godunov', periodic=True) against cole_hopf_viscous_burgers_exact (), asserting first-order convergence and exact impulse conservation.
heading("Exercise 1: Mesh Convergence of Godunov Viscous Burgers Against Exact Cole-Hopf")
L_e1 = 2.0 * np.pi
nu_e1 = 0.20
a0_e1 = 1.25
t_e1 = 0.60
errs_e1 = []
for ng in [64, 128, 256, 512]:
dxg = L_e1 / ng
xg = (np.arange(ng) + 0.5) * dxg
u0g = burgers_riemann.cole_hopf_viscous_burgers_exact(xg, 0.0, nu=nu_e1, L=L_e1, offset_a0=a0_e1)
u_ex = burgers_riemann.cole_hopf_viscous_burgers_exact(xg, t_e1, nu=nu_e1, L=L_e1, offset_a0=a0_e1)
dtg = 0.20 * (dxg ** 2) / nu_e1
n_stg = int(np.ceil(t_e1 / dtg))
dtg = t_e1 / n_stg
res_g = burgers_riemann.solve_viscous_burgers_1d(u0g, L=L_e1, nu=nu_e1, dt=dtg, n_steps=n_stg, flux="godunov", periodic=True)
l2_e = float(np.sqrt(np.mean((res_g["final"] - u_ex) ** 2)))
imp_d = float(np.max(np.abs(res_g["impulses"] - res_g["impulses"][0])))
errs_e1.append(l2_e)
print(f"N = {ng:3d} | steps = {n_stg:5d} | L2 error = {l2_e:.4e} | impulse drift = {imp_d:.2e}")
assert imp_d < 1e-13
order_finest = float(np.log2(errs_e1[-2] / errs_e1[-1]))
print(f"Observed spatial order (256 -> 512): {order_finest:.3f}")
assert 0.90 < order_finest < 1.15
Exercise 1: Mesh Convergence of Godunov Viscous Burgers Against Exact Cole-Hopf
===============================================================================
N = 64 | steps = 63 | L2 error = 3.4048e-03 | impulse drift = 9.81e-17
N = 128 | steps = 250 | L2 error = 1.7720e-03 | impulse drift = 2.96e-16
N = 256 | steps = 997 | L2 error = 9.0130e-04 | impulse drift = 5.23e-16
N = 512 | steps = 3985 | L2 error = 4.5421e-04 | impulse drift = 3.49e-16
Observed spatial order (256 -> 512): 0.989
Explanation. Although centered viscous differencing and SSP-RK2 time integration are both second-order accurate, piecewise-constant cell reconstruction in 1st-order Godunov introduces numerical viscosity that dominates truncation error as , motivating the 2nd-order MUSCL reconstruction in Exercise 3.
Exercise 2¶
Problem. Verify cole_hopf_viscous_burgers_exact input guards (, ) and demonstrate that unfixed Roe flux produces an unphysical stationary expansion shock on while _burgers_godunov_flux resolves the exact rarefaction fan.
heading("Exercise 2: Unfixed Roe Sonic Expansion Shock vs Entropy-Satisfying Godunov")
for bad_args in [(0.0, 2.0), (-0.1, 2.0), (0.1, 1.0), (0.1, 0.8)]:
caught = False
try:
burgers_riemann.cole_hopf_viscous_burgers_exact(np.array([0.5]), t=0.1, nu=bad_args[0], offset_a0=bad_args[1])
except ValueError:
caught = True
assert caught is True
# Compare unfixed Roe flux vs Godunov flux on transonic rarefaction u_L = -1, u_R = +1:
n_r = 200
L_r = 4.0
dx_r = L_r / n_r
x_r = (np.arange(n_r) + 0.5) * dx_r
u0_r = np.where(x_r < 2.0, -1.0, 1.0)
t_r = 0.8
n_st = 320
dt_r = t_r / n_st
u_roe = u0_r.copy()
for _ in range(n_st):
up = np.pad(u_roe, 1, mode="edge")
ul, ur = up[:-1], up[1:]
a_bar = 0.5 * (ul + ur)
f_roe = 0.25 * (ul ** 2 + ur ** 2) - 0.5 * np.abs(a_bar) * (ur - ul)
u_roe = u_roe - (dt_r / dx_r) * (f_roe[1:] - f_roe[:-1])
u_god = burgers_riemann.solve_viscous_burgers_1d(u0_r, L=L_r, nu=0.0, dt=dt_r, n_steps=n_st, flux="godunov", periodic=False)["final"]
xi_r = (x_r - 2.0) / t_r
u_ex_r = np.where(xi_r <= -1.0, -1.0, np.where(xi_r >= 1.0, 1.0, xi_r))
err_roe = float(np.mean(np.abs(u_roe - u_ex_r)))
err_god = float(np.mean(np.abs(u_god - u_ex_r)))
print(f"Unfixed Roe L1 error = {err_roe:.4f} (frozen step jump = {u_roe[n_r//2] - u_roe[n_r//2 - 1]:.2f})")
print(f"Godunov L1 error = {err_god:.4f} (center jump = {u_god[n_r//2] - u_god[n_r//2 - 1]:.4f})")
assert np.allclose(u_roe, u0_r, atol=1e-14)
assert err_roe > 0.18 and err_god < 0.02
Exercise 2: Unfixed Roe Sonic Expansion Shock vs Entropy-Satisfying Godunov
===========================================================================
Unfixed Roe L1 error = 0.2000 (frozen step jump = 2.00)
Godunov L1 error = 0.0185 (center jump = 0.0952)
Explanation. u_roe remains bit-for-bit frozen at the discontinuous step . At the center interface , Roe’s linearized wave speed is , so and , matching on all other faces so . Although satisfies Rankine–Hugoniot algebraically, it violates Lax’s entropy inequality (), showing why Roe solvers require a Harten–Hyman sonic entropy fix whereas Godunov satisfies all entropy inequalities automatically.
Exercise 3¶
Problem. Implement solve_muscl_viscous_burgers_1d(u_init, L, nu, dt, n_steps) using periodic minmod slope reconstruction, _burgers_godunov_flux, centered viscous diffusion, and SSP-RK2. Verify convergence on cole_hopf_viscous_burgers_exact () and assert lower error than 1st-order solve_viscous_burgers_1d at .
heading("Exercise 3: Implement It Yourself — 2nd-Order MUSCL-Godunov Viscous Burgers Solver")
def solve_muscl_viscous_burgers_1d(u_init: np.ndarray, L: float, nu: float, dt: float, n_steps: int) -> dict:
"""Integrate 1-D periodic viscous Burgers equation via 2nd-order MUSCL-minmod + Godunov + SSP-RK2."""
u = np.asarray(u_init, dtype=float).ravel().copy()
dx = float(L) / u.size
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 rhs_muscl(state: np.ndarray) -> np.ndarray:
dq_back = state - np.roll(state, 1)
dq_fwd = np.roll(state, -1) - state
slope = minmod(dq_back, dq_fwd)
ul_face = state + 0.5 * slope
ur_face = np.roll(state, -1) - 0.5 * np.roll(slope, -1)
f_half = burgers_riemann._burgers_godunov_flux(ul_face, ur_face)
conv_div = (f_half - np.roll(f_half, 1)) / dx
visc = float(nu) * (np.roll(state, -1) - 2.0 * state + np.roll(state, 1)) / (dx ** 2)
return -conv_div + visc
for _ in range(n_steps):
u1 = u + dt * rhs_muscl(u)
u = 0.5 * u + 0.5 * (u1 + dt * rhs_muscl(u1))
return {"final": u, "impulse": float(np.sum(u) * dx)}
L_m = 2.0 * np.pi
nu_m = 0.12
a0_m = 1.20
t_m = 0.50
muscl_errs, first_errs = [], []
for ng in [64, 128, 256]:
dxg = L_m / ng
xg = (np.arange(ng) + 0.5) * dxg
u0g = burgers_riemann.cole_hopf_viscous_burgers_exact(xg, 0.0, nu=nu_m, L=L_m, offset_a0=a0_m)
u_ex = burgers_riemann.cole_hopf_viscous_burgers_exact(xg, t_m, nu=nu_m, L=L_m, offset_a0=a0_m)
dtg = 0.20 * (dxg ** 2) / nu_m
n_stg = int(np.ceil(t_m / dtg))
dtg = t_m / n_stg
res_m = solve_muscl_viscous_burgers_1d(u0g, L=L_m, nu=nu_m, dt=dtg, n_steps=n_stg)
res_1 = burgers_riemann.solve_viscous_burgers_1d(u0g, L=L_m, nu=nu_m, dt=dtg, n_steps=n_stg, flux="godunov", periodic=True)
em = float(np.sqrt(np.mean((res_m["final"] - u_ex) ** 2)))
e1 = float(np.sqrt(np.mean((res_1["final"] - u_ex) ** 2)))
muscl_errs.append(em)
first_errs.append(e1)
assert abs(res_m["impulse"]) < 1e-13
print(f"N = {ng:3d} | 1st-Order Godunov L2 = {e1:.3e} | 2nd-Order MUSCL L2 = {em:.3e} | Speedup ratio = {e1/em:6.2f}x")
p_muscl = float(np.log2(muscl_errs[-2] / muscl_errs[-1]))
print(f"Observed MUSCL convergence rate (128 -> 256): {p_muscl:.3f}")
assert p_muscl > 1.85
assert muscl_errs[-1] * 8.0 < first_errs[-1]
Exercise 3: Implement It Yourself — 2nd-Order MUSCL-Godunov Viscous Burgers Solver
==================================================================================
N = 64 | 1st-Order Godunov L2 = 2.046e-03 | 2nd-Order MUSCL L2 = 4.809e-04 | Speedup ratio = 4.26x
N = 128 | 1st-Order Godunov L2 = 1.067e-03 | 2nd-Order MUSCL L2 = 1.324e-04 | Speedup ratio = 8.06x
N = 256 | 1st-Order Godunov L2 = 5.433e-04 | 2nd-Order MUSCL L2 = 3.466e-05 | Speedup ratio = 15.68x
Observed MUSCL convergence rate (128 -> 256): 1.933
Summary. Reconstructing piecewise-linear interface states , with minmod slope limiting eliminates the leading artificial viscosity of piecewise-constant Godunov, boosting spatial convergence to and cutting error by more than an order of magnitude at .