Worked solutions to the three exercises of Lecture 12. 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 2-D Taylor-Green Vortex — Advection-Pressure Balance & Kinetic Energy Decay")
nx_g = 64
L_dom = 2.0 * np.pi
x_1d = np.linspace(0.0, L_dom, nx_g, endpoint=False)
X_tg, Y_tg = np.meshgrid(x_1d, x_1d, indexing="ij")
nu_tg = 0.10
tg0 = navier_stokes.taylor_green_vortex_exact(X_tg, Y_tg, t=0.0, nu=nu_tg)
tg_half = navier_stokes.taylor_green_vortex_exact(X_tg, Y_tg, t=0.5, nu=nu_tg)
# Analytical convective acceleration (u*du/dx + v*du/dy) vs -dp/dx at t = 0:
conv_x = tg0["u"] * (np.cos(X_tg) * np.cos(Y_tg)) + tg0["v"] * (-np.sin(X_tg) * np.sin(Y_tg))
neg_dp_dx = 0.5 * np.sin(2.0 * X_tg)
div_exact = np.cos(X_tg) * np.cos(Y_tg) - np.cos(X_tg) * np.cos(Y_tg)
ek_0 = float(0.5 * np.mean(tg0["u"] ** 2 + tg0["v"] ** 2))
ek_half = float(0.5 * np.mean(tg_half["u"] ** 2 + tg_half["v"] ** 2))
enstrophy_0 = float(0.5 * np.mean(tg0["vorticity"] ** 2))
print(f"Max |(u.grad)u_x - (-dp/dx)| at t=0 : {np.max(np.abs(conv_x - neg_dp_dx)):.3e}")
print(f"Initial kinetic energy E_k(0) : {ek_0:.8f} (exact 1/4 = 0.25000000)")
print(f"E_k(0.5) / E_k(0) : {ek_half / ek_0:.8f} vs exp(-4*nu*t) = {np.exp(-4.0*nu_tg*0.5):.8f}")
print(f"Viscous dissipation -dE_k/dt|_{{t=0}}: 2*nu*Z(0) = {2.0*nu_tg*enstrophy_0:.6f} == 4*nu*E_k(0) = {4.0*nu_tg*ek_0:.6f}")
assert np.allclose(conv_x, neg_dp_dx, atol=1e-15)
assert np.allclose(div_exact, 0.0, atol=1e-15)
assert np.isclose(ek_0, 0.25, rtol=1e-14)
assert np.isclose(ek_half, ek_0 * np.exp(-4.0 * nu_tg * 0.5), rtol=1e-14)
assert np.isclose(2.0 * nu_tg * enstrophy_0, 4.0 * nu_tg * ek_0, rtol=1e-14)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.3))
cf = ax1.contourf(X_tg, Y_tg, tg0["p"], levels=18, cmap="coolwarm")
plt.colorbar(cf, ax=ax1, label="Kinematic pressure $p(x,y,0)$ [$\\mathrm{m^2/s^2}$]")
skip = 4
ax1.quiver(X_tg[::skip, ::skip], Y_tg[::skip, ::skip], tg0["u"][::skip, ::skip], tg0["v"][::skip, ::skip], color="k")
ax1.set_xlabel("$x$ [rad]")
ax1.set_ylabel("$y$ [rad]")
ax1.set_title("Taylor–Green Cellular Vortices & Pressure Saddle ($t = 0$)")
t_vec = np.linspace(0.0, 4.0, 200)
ax2.plot(t_vec, np.exp(-2.0 * nu_tg * t_vec), lw=2.2, label=r"$|\mathbf{u}(t)| / |\mathbf{u}(0)| = e^{-2\nu t}$")
ax2.plot(t_vec, np.exp(-4.0 * nu_tg * t_vec), "--", lw=2.2, label=r"$E_k(t)/E_k(0) = p_{\max}(t)/p_{\max}(0) = e^{-4\nu t}$")
ax2.set_xlabel("Time $t$ [s]")
ax2.set_ylabel("Normalized amplitude [-]")
ax2.set_title(rf"Exact Viscous Decay Laws ($\nu = {nu_tg:.2f}$)")
ax2.legend(fontsize=8.5)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. On a periodic mesh with at , evaluate navier_stokes.taylor_green_vortex_exact and verify pointwise to that , and verify across that mean enstrophy equals .
heading("Exercise 1: Exact Pressure Poisson Source Identity & Enstrophy-Energy Relation Z(t) = 2*E_k(t)")
nx_e1 = 64
x_e1 = np.linspace(0.0, 2.0 * np.pi, nx_e1, endpoint=False)
X_e1, Y_e1 = np.meshgrid(x_e1, x_e1, indexing="ij")
nu_e1 = 0.08
for t_val in [0.0, 0.4, 1.0]:
st = navier_stokes.taylor_green_vortex_exact(X_e1, Y_e1, t=t_val, nu=nu_e1)
e2 = np.exp(-2.0 * nu_e1 * t_val)
e4 = np.exp(-4.0 * nu_e1 * t_val)
du_dx = np.cos(X_e1) * np.cos(Y_e1) * e2
du_dy = -np.sin(X_e1) * np.sin(Y_e1) * e2
dv_dx = np.sin(X_e1) * np.sin(Y_e1) * e2
dv_dy = -np.cos(X_e1) * np.cos(Y_e1) * e2
lap_p_ana = -(np.cos(2.0 * X_e1) + np.cos(2.0 * Y_e1)) * e4
ppe_rhs = 2.0 * (du_dx * dv_dy - du_dy * dv_dx)
ek_t = float(0.5 * np.mean(st["u"] ** 2 + st["v"] ** 2))
enst_t = float(0.5 * np.mean(st["vorticity"] ** 2))
print(f"t={t_val:.1f} s | max |lap(p) - PPE_rhs| = {np.max(np.abs(lap_p_ana - ppe_rhs)):.2e} | Z(t) = {enst_t:.6f} vs 2*E_k(t) = {2.0*ek_t:.6f}")
assert np.allclose(lap_p_ana, ppe_rhs, atol=1e-14)
assert np.isclose(enst_t, 2.0 * ek_t, rtol=1e-14)
Exercise 1: Exact Pressure Poisson Source Identity & Enstrophy-Energy Relation Z(t) = 2*E_k(t)
==============================================================================================
t=0.0 s | max |lap(p) - PPE_rhs| = 6.66e-16 | Z(t) = 0.500000 vs 2*E_k(t) = 0.500000
t=0.4 s | max |lap(p) - PPE_rhs| = 6.66e-16 | Z(t) = 0.439927 vs 2*E_k(t) = 0.439927
t=1.0 s | max |lap(p) - PPE_rhs| = 4.44e-16 | Z(t) = 0.363075 vs 2*E_k(t) = 0.363075
Explanation. Since , we have . Using , matches identically (note at vortex centers , confirming pressure minima inside vortex cores). Moreover, because , Parseval’s identity forces .
Exercise 2¶
Problem. Demonstrate numerically: (a) on a mesh, projecting a divergent velocity field with continuum leaves discrete divergence whereas achieves ; and (b) running taylor_green_projection_2d(nx=32, dt=0.18, n_steps=90, nu=0.25) exceeds the 2-D explicit Fourier diffusion bound and blows up.
heading("Exercise 2: Wavenumber Mismatch Divergence Leak & 2-D Explicit Viscous Fourier Blow-Up")
# Part (a): Continuum k^2 vs Modified k_eff^2 on 24x24 grid
n24 = 24
dx24 = 2.0 * np.pi / n24
x24 = np.linspace(0.0, 2.0 * np.pi, n24, endpoint=False)
X24, Y24 = np.meshgrid(x24, x24, indexing="ij")
ustar = np.sin(X24) * np.cos(Y24) + np.cos(3.0 * X24) * np.sin(2.0 * Y24)
vstar = -np.cos(X24) * np.sin(Y24) + 0.7 * np.sin(3.0 * X24) * np.cos(2.0 * Y24)
ddx24 = lambda f: (np.roll(f, -1, axis=0) - np.roll(f, 1, axis=0)) / (2.0 * dx24)
ddy24 = lambda f: (np.roll(f, -1, axis=1) - np.roll(f, 1, axis=1)) / (2.0 * dx24)
div24 = ddx24(ustar) + ddy24(vstar)
kv = 2.0 * np.pi * np.fft.fftfreq(n24, d=dx24)
KX24, KY24 = np.meshgrid(kv, kv, indexing="ij")
k2_raw = KX24**2 + KY24**2
k2_eff = (np.sin(KX24 * dx24) / dx24) ** 2 + (np.sin(KY24 * dx24) / dx24) ** 2
p_raw = np.real(np.fft.ifft2(np.where(k2_raw > 1e-12, -np.fft.fft2(div24) / np.where(k2_raw > 1e-12, k2_raw, 1.0), 0.0)))
p_eff = np.real(np.fft.ifft2(np.where(k2_eff > 1e-12, -np.fft.fft2(div24) / np.where(k2_eff > 1e-12, k2_eff, 1.0), 0.0)))
leak_raw = float(np.max(np.abs(ddx24(ustar - ddx24(p_raw)) + ddy24(vstar - ddy24(p_raw)))))
leak_eff = float(np.max(np.abs(ddx24(ustar - ddx24(p_eff)) + ddy24(vstar - ddy24(p_eff)))))
print(f"24x24 projection divergence: naive k^2 = {leak_raw:.4e} vs consistent k_eff^2 = {leak_eff:.4e}")
assert leak_raw > 1e-2 and leak_eff < 1e-14
# Part (b): 2-D explicit diffusion stability limit dt_max = dx^2 / (4*nu)
dx32 = 2.0 * np.pi / 32
nu_hi = 0.25
dt_crit_2d = (dx32**2) / (4.0 * nu_hi)
stable_run = navier_stokes.taylor_green_projection_2d(nx=32, dt=0.02, n_steps=40, nu=nu_hi)
with np.errstate(over="ignore", invalid="ignore"):
unstable_run = navier_stokes.taylor_green_projection_2d(nx=32, dt=0.18, n_steps=90, nu=nu_hi)
blew_up = bool((not np.all(np.isfinite(unstable_run["u"]))) or unstable_run["u_l2_error"] > 10.0)
print(f"2-D viscous limit dx^2/(4*nu) = {dt_crit_2d:.4f} s | dt=0.02 err={stable_run['u_l2_error']:.4e} | dt=0.18 blew_up={blew_up}")
assert stable_run["u_l2_error"] < 5e-3 and blew_up is True
Exercise 2: Wavenumber Mismatch Divergence Leak & 2-D Explicit Viscous Fourier Blow-Up
======================================================================================
24x24 projection divergence: naive k^2 = 6.3901e-01 vs consistent k_eff^2 = 4.2188e-15
2-D viscous limit dx^2/(4*nu) = 0.0386 s | dt=0.02 err=2.4024e-04 | dt=0.18 blew_up=True
Explanation. Even when pressure projection enforces at every step, explicit treatment of multiplies the 2-D checkerboard Nyquist mode by , so stability demands (twice as strict as 1-D ).
Exercise 3¶
Problem. Implement my_taylor_green_projection_2d(nx, dt, n_steps, nu) from scratch in pure NumPy, verify that u, v, and p match navier_stokes.taylor_green_projection_2d on a grid (dt=0.0025, n_steps=160, nu=0.12) to < 1e-14, and verify max_divergence < 1e-14.
heading("Exercise 3: Implement It Yourself — 2-D Chorin Fractional-Step Taylor-Green Solver")
def my_taylor_green_projection_2d(nx: int, dt: float, n_steps: int, nu: float) -> dict:
"""NumPy Chorin projection solver with exact discrete central-difference Fourier wavenumbers."""
L = 2.0 * np.pi
dx = L / int(nx)
x = np.linspace(0.0, L, int(nx), endpoint=False)
X, Y = np.meshgrid(x, x, indexing="ij")
u = np.sin(X) * np.cos(Y)
v = -np.cos(X) * np.sin(Y)
k1d = 2.0 * np.pi * np.fft.fftfreq(nx, d=dx)
kx, ky = np.meshgrid(k1d, k1d, indexing="ij")
k2_eff = (np.sin(kx * dx) / dx) ** 2 + (np.sin(ky * dx) / dx) ** 2
valid = k2_eff > 1e-12
k2_safe = np.where(valid, k2_eff, 1.0)
ddx = lambda f: (np.roll(f, -1, axis=0) - np.roll(f, 1, axis=0)) / (2.0 * dx)
ddy = lambda f: (np.roll(f, -1, axis=1) - np.roll(f, 1, axis=1)) / (2.0 * dx)
lap = lambda f: (np.roll(f, -1, axis=0) + np.roll(f, 1, axis=0) + np.roll(f, -1, axis=1) + np.roll(f, 1, axis=1) - 4.0 * f) / (dx**2)
p = np.zeros_like(u)
for _ in range(n_steps):
u_s = u + dt * (-(u * ddx(u) + v * ddy(u)) + nu * lap(u))
v_s = v + dt * (-(u * ddx(v) + v * ddy(v)) + nu * lap(v))
div_s = ddx(u_s) + ddy(v_s)
p = np.real(np.fft.ifft2(np.where(valid, -np.fft.fft2(div_s) / (dt * k2_safe), 0.0)))
u = u_s - dt * ddx(p)
v = v_s - dt * ddy(p)
return {"u": u, "v": v, "p": p, "max_divergence": float(np.max(np.abs(ddx(u) + ddy(v))))}
mine = my_taylor_green_projection_2d(nx=40, dt=0.0025, n_steps=160, nu=0.12)
ref = navier_stokes.taylor_green_projection_2d(nx=40, dt=0.0025, n_steps=160, nu=0.12)
u_diff = float(np.max(np.abs(mine["u"] - ref["u"])))
p_diff = float(np.max(np.abs(mine["p"] - ref["p"])))
print(f"Max |u_mine - u_ref| = {u_diff:.3e} | Max |p_mine - p_ref| = {p_diff:.3e} | max_div = {mine['max_divergence']:.3e}")
assert u_diff < 1e-14 and p_diff < 1e-14 and mine["max_divergence"] < 1e-14
Exercise 3: Implement It Yourself — 2-D Chorin Fractional-Step Taylor-Green Solver
==================================================================================
Max |u_mine - u_ref| = 0.000e+00 | Max |p_mine - p_ref| = 0.000e+00 | max_div = 4.441e-16
Summary. Chorin’s projection decouples momentum advection-diffusion from incompressibility by solving one scalar elliptic Poisson problem per step; matching the discrete Poisson operator to guarantees exact discrete mass conservation on periodic domains. Note, however, the zeroed Nyquist modes (sin(pi) = 0) on collocated grids: Lecture 13 shows why wall-bounded collocated grids admit a checkerboard pressure mode and how Harlow & Welch’s staggered MAC grid cures it permanently.