Worked solutions to the three exercises of Lecture 7. 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: 2-D Solid-Body Vortex Rotation via Strang-Split TVD Transport")
nx_v, ny_v = 64, 64
dx_v = dy_v = 1.0 / nx_v
xc_v = (np.arange(nx_v) + 0.5) * dx_v
yc_v = (np.arange(ny_v) + 0.5) * dy_v
XC_v, YC_v = np.meshgrid(xc_v, yc_v, indexing="ij")
# Compact cosine-bell tracer centered at (0.50, 0.30), orbiting (0.50, 0.50) completely inside [0, 1]^2:
r_bell = np.hypot(XC_v - 0.50, YC_v - 0.30)
r0_bell = 0.14
q0_vort = np.where(r_bell < r0_bell, 0.5 * (1.0 + np.cos(np.pi * r_bell / r0_bell)), 0.0)
omega_rot = 2.0 * np.pi # Exact 1 revolution in T = 1.0 s
u_row_rot = -omega_rot * (yc_v - 0.50)
v_col_rot = +omega_rot * (xc_v - 0.50)
n_steps_rot = 320
dt_rot = 1.0 / n_steps_rot
rot_runs = {}
print(f"{'Limiter':12s} | {'Mass Drift':>11s} | {'Min q':>10s} | {'Peak q_max':>10s} | {'L2 Error (1 rev)':>16s}")
print("-" * 70)
for lim in ["upwind", "minmod", "van_leer", "superbee"]:
out = tvd_advection.advect_2d_strang_periodic(
q0_vort, u_row_rot, v_col_rot, dx=dx_v, dy=dy_v, dt=dt_rot, n_steps=n_steps_rot, limiter=lim
)
rot_runs[lim] = out
l2_e = float(np.sqrt(np.mean((out["final"] - q0_vort) ** 2)))
print(f"{lim:12s} | {out['mass_drift']:11.2e} | {out['min_val']:+10.2e} | {out['max_val']:10.4f} | {l2_e:16.5f}")
assert out["mass_drift"] < 1e-14
assert out["min_val"] >= -1e-13 and out["max_val"] <= 1.0 + 1e-12
assert rot_runs["superbee"]["max_val"] > rot_runs["van_leer"]["max_val"] > rot_runs["minmod"]["max_val"] > rot_runs["upwind"]["max_val"]
assert rot_runs["van_leer"]["max_val"] > 2.2 * rot_runs["upwind"]["max_val"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 4.2))
cf1 = ax1.contourf(XC_v, YC_v, rot_runs["upwind"]["final"], levels=np.linspace(0.0, 1.0, 11), cmap="viridis")
ax1.contour(XC_v, YC_v, q0_vort, levels=[0.2, 0.5, 0.8], colors="white", linestyles="--", linewidths=1.1)
fig.colorbar(cf1, ax=ax1, label="$q(x, y, T)$")
ax1.set_xlabel("$x$ [m]")
ax1.set_ylabel("$y$ [m]")
ax1.set_title(f"1st-Order Upwind ($q_{{\\max}} = {rot_runs['upwind']['max_val']:.2f}$)")
cf2 = ax2.contourf(XC_v, YC_v, rot_runs["van_leer"]["final"], levels=np.linspace(0.0, 1.0, 11), cmap="viridis")
ax2.contour(XC_v, YC_v, q0_vort, levels=[0.2, 0.5, 0.8], colors="white", linestyles="--", linewidths=1.1)
fig.colorbar(cf2, ax=ax2, label="$q(x, y, T)$")
ax2.set_xlabel("$x$ [m]")
ax2.set_ylabel("$y$ [m]")
ax2.set_title(f"Strang + van Leer TVD ($q_{{\\max}} = {rot_runs['van_leer']['max_val']:.2f}$)")
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify fvm_convection_diffusion_2d_steady (, , , homogeneous Dirichlet walls on ) against the exact eigenfunction across , asserting error convergence.
heading("Exercise 1: Exact 2-D Reaction-Diffusion Eigenmode & O(h^2) Mesh Convergence")
Gamma_ex1 = 0.08
k_ex1 = 2.5
denom_exact = 2.0 * (np.pi ** 2) * Gamma_ex1 + k_ex1
errs_ex1 = []
for n_g in [16, 32, 64]:
dx_g = 1.0 / n_g
xc_g = (np.arange(n_g) + 0.5) * dx_g
XC_g, YC_g = np.meshgrid(xc_g, xc_g, indexing="ij")
S_mode = np.sin(np.pi * XC_g) * np.sin(np.pi * YC_g)
phi_ex = S_mode / denom_exact
out_g = convection_diffusion.fvm_convection_diffusion_2d_steady(
n_g, n_g, 1.0, 1.0, u_vel=0.0, v_vel=0.0, Gamma=Gamma_ex1, source=S_mode, k_react=k_ex1, tol=1e-12, max_iter=8000
)
max_e = float(np.max(np.abs(out_g["phi"] - phi_ex)))
errs_ex1.append(max_e)
print(f"Grid {n_g:2d}x{n_g:2d} | SOR iters = {out_g['iterations']:4d} | max |phi - phi_exact| = {max_e:.4e}")
p_rate1 = float(np.log2(errs_ex1[0] / errs_ex1[1]))
p_rate2 = float(np.log2(errs_ex1[1] / errs_ex1[2]))
print(f"Observed convergence orders: {p_rate1:.3f} (16->32), {p_rate2:.3f} (32->64)")
assert 1.90 < p_rate1 < 2.10 and 1.95 < p_rate2 < 2.05
Exercise 1: Exact 2-D Reaction-Diffusion Eigenmode & O(h^2) Mesh Convergence
============================================================================
Grid 16x16 | SOR iters = 120 | max |phi - phi_exact| = 3.0196e-04
Grid 32x32 | SOR iters = 420 | max |phi - phi_exact| = 7.6041e-05
Grid 64x64 | SOR iters = 1580 | max |phi - phi_exact| = 1.9045e-05
Observed convergence orders: 1.990 (16->32), 1.997 (32->64)
Explanation. Applying to multiplies the eigenmode by the positive Helmholtz eigenvalue . Our FVM enforces Dirichlet walls via linear half-cell extrapolation (), which matches the interior 5-point central Laplacian to across the entire domain.
Exercise 2¶
Problem. Demonstrate cell-Péclet breakdown of scheme='central' at : show direct-solve unphysical undershoots in fvm_convection_diffusion_1d (bounded_no_overshoot == False) and iterative SOR divergence in fvm_convection_diffusion_2d_steady(..., max_iter=80), while power_law and exponential converge monotonically in .
heading("Exercise 2: Central Differencing Breakdown at Cell Peclet = 5 > 2")
# 1. 1-D Direct Thomas Solve: finite solution, but violates maximum principle with oscillatory undershoots
c1d = convection_diffusion.fvm_convection_diffusion_1d(n_cells=10, L=1.0, u=1.0, Gamma=0.02, phi_0=0.0, phi_L=1.0, scheme="central")
p1d = convection_diffusion.fvm_convection_diffusion_1d(n_cells=10, L=1.0, u=1.0, Gamma=0.02, phi_0=0.0, phi_L=1.0, scheme="power_law")
print(f"1-D Pe_cell = {c1d['cell_peclet']:.1f} | Central min(phi) = {np.min(c1d['phi']):+.4f} (bounded={c1d['bounded_no_overshoot']}) | PowerLaw min(phi) = {np.min(p1d['phi']):+.4f}")
assert np.isclose(c1d["cell_peclet"], 5.0)
assert c1d["bounded_no_overshoot"] is False and np.min(c1d["phi"]) < -0.10
assert p1d["bounded_no_overshoot"] is True
# 2. 2-D Red-Black SOR: loss of diagonal dominance |a_P| < |a_W| + |a_E| amplifies residuals exponentially
bcs_step = {"left": 0.0, "right": 1.0, "bottom": 0.0, "top": 0.0}
c2d = convection_diffusion.fvm_convection_diffusion_2d_steady(
20, 20, 1.0, 1.0, u_vel=1.0, v_vel=0.0, Gamma=0.01, bc_walls=bcs_step, scheme="central", max_iter=80
)
p2d = convection_diffusion.fvm_convection_diffusion_2d_steady(
20, 20, 1.0, 1.0, u_vel=1.0, v_vel=0.0, Gamma=0.01, bc_walls=bcs_step, scheme="power_law", tol=1e-10
)
print(f"2-D Central SOR residual: iter 1 = {c2d['residual_history'][0]:.2e} -> iter 80 = {c2d['residual_history'][-1]:.2e} (diverged)")
print(f"2-D Power-Law SOR residual: iter {p2d['iterations']} = {p2d['residual_history'][-1]:.2e}, range = [{np.min(p2d['phi']):.4f}, {np.max(p2d['phi']):.4f}]")
assert c2d["residual_history"][-1] > 1e6 * c2d["residual_history"][0]
assert p2d["residual_history"][-1] < 1e-10 and np.min(p2d["phi"]) >= -1e-12 and np.max(p2d["phi"]) <= 1.0 + 1e-12
Exercise 2: Central Differencing Breakdown at Cell Peclet = 5 > 2
=================================================================
1-D Pe_cell = 5.0 | Central min(phi) = -0.1111 (bounded=False) | PowerLaw min(phi) = +0.0000
2-D Central SOR residual: iter 1 = 4.49e-03 -> iter 80 = 4.75e+36 (diverged)
2-D Power-Law SOR residual: iter 20 = 9.45e-13, range = [-0.0000, 0.0867]
Explanation. In central differencing, turns negative for . Consequently, while , so . Violating Scarborough’s diagonal-dominance condition destroys the M-matrix property, producing alternating-sign spatial oscillations in direct solvers and unstable spectral radius in iterative solvers.
Exercise 3¶
Problem. Implement advect_2d_swirl_reversible(q_init, dx, dy, T, n_steps, limiter) using midpoint-evaluated Strang splitting for and on . Verify strong filament deformation at and compare unmixing error across upwind, van_leer, and superbee.
heading("Exercise 3: Implement It Yourself — 2-D Time-Reversible Swirling Shear Deformation")
def advect_2d_swirl_reversible(
q_init: np.ndarray, dx: float, dy: float, T: float, n_steps: int, limiter: str = "van_leer"
) -> dict:
"""Integrate 2-D time-reversing periodic shear deformation via midpoint Strang TVD splitting."""
q = np.asarray(q_init, dtype=float).copy()
nx, ny = q.shape
xc = (np.arange(nx) + 0.5) * dx
yc = (np.arange(ny) + 0.5) * dy
u_base = np.sin(2.0 * np.pi * yc)
v_base = np.sin(2.0 * np.pi * xc)
dt = float(T) / int(n_steps)
mass0 = float(np.sum(q) * dx * dy)
q_mid = None
for step in range(n_steps):
t_mid = (step + 0.5) * dt
g_fac = float(np.cos(np.pi * t_mid / T))
for j in range(ny):
q[:, j] = tvd_advection._step_1d_periodic_flux_limited(q[:, j], 0.5 * g_fac * u_base[j] * dt / dx, limiter)
for i in range(nx):
q[i, :] = tvd_advection._step_1d_periodic_flux_limited(q[i, :], g_fac * v_base[i] * dt / dy, limiter)
for j in range(ny):
q[:, j] = tvd_advection._step_1d_periodic_flux_limited(q[:, j], 0.5 * g_fac * u_base[j] * dt / dx, limiter)
if step + 1 == n_steps // 2:
q_mid = q.copy()
return {"mid": q_mid, "final": q, "mass_drift": abs(float(np.sum(q) * dx * dy) - mass0)}
n_sw = 64
dx_sw = 1.0 / n_sw
xc_sw = (np.arange(n_sw) + 0.5) * dx_sw
XC_sw, YC_sw = np.meshgrid(xc_sw, xc_sw, indexing="ij")
r_sw = np.hypot(XC_sw - 0.50, YC_sw - 0.28)
q0_sw = np.where(r_sw < 0.16, 0.5 * (1.0 + np.cos(np.pi * r_sw / 0.16)), 0.0)
sw_up = advect_2d_swirl_reversible(q0_sw, dx_sw, dx_sw, T=1.2, n_steps=160, limiter="upwind")
sw_vl = advect_2d_swirl_reversible(q0_sw, dx_sw, dx_sw, T=1.2, n_steps=160, limiter="van_leer")
sw_sb = advect_2d_swirl_reversible(q0_sw, dx_sw, dx_sw, T=1.2, n_steps=160, limiter="superbee")
deform_mid = float(np.sqrt(np.mean((sw_vl["mid"] - q0_sw) ** 2)))
err_up_sw = float(np.sqrt(np.mean((sw_up["final"] - q0_sw) ** 2)))
err_vl_sw = float(np.sqrt(np.mean((sw_vl["final"] - q0_sw) ** 2)))
err_sb_sw = float(np.sqrt(np.mean((sw_sb["final"] - q0_sw) ** 2)))
print(f"Mid-cycle filament deformation ||q(T/2) - q(0)||_2 = {deform_mid:.4f}")
print(f"Full-cycle recovery L2 error: Upwind = {err_up_sw:.4f} vs van Leer = {err_vl_sw:.4f} vs Superbee = {err_sb_sw:.4f}")
assert deform_mid > 0.12
assert sw_up["mass_drift"] < 1e-14 and sw_vl["mass_drift"] < 1e-14 and sw_sb["mass_drift"] < 1e-14
assert err_sb_sw < err_vl_sw < 0.35 * err_up_sw
Exercise 3: Implement It Yourself — 2-D Time-Reversible Swirling Shear Deformation
==================================================================================
Mid-cycle filament deformation ||q(T/2) - q(0)||_2 = 0.1622
Full-cycle recovery L2 error: Upwind = 0.0738 vs van Leer = 0.0207 vs Superbee = 0.0109
Summary. LeVeque’s time-reversible swirling flow is a benchmark for front-tracking and VOF/level-set interface transport: even after severe shear stretching at , midpoint-evaluated Strang TVD splitting recovers the original circular patch with smaller error than upwind while conserving tracer mass to .