Worked solutions to the three exercises of Lecture 13. 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: Collocated Checkerboard Blindness vs Staggered MAC Detection")
cb_audit = navier_stokes.checkerboard_pressure_audit_1d(n_cells=16)
p_cb = cb_audit["p_checkerboard"]
print(f"Alternating pressure p_i = (-1)^i : {p_cb[:8]} ...")
print(f"Collocated ||(p_{{i+1}} - p_{{i-1}})/2||_inf : {cb_audit['collocated_grad_norm']:.15f} (zero for the checkerboard mode)")
print(f"Staggered || p_{{i+1}} - p_i ||_inf : {cb_audit['staggered_grad_norm']:.15f} (the full amplitude)")
assert cb_audit["collocated_grad_norm"] == 0.0
assert np.isclose(cb_audit["staggered_grad_norm"], 2.0, rtol=1e-15)
idx_cells = np.arange(16)
idx_faces = idx_cells + 0.5
grad_col = 0.5 * (np.roll(p_cb, -1) - np.roll(p_cb, 1))
grad_mac = np.roll(p_cb, -1) - p_cb
theta = np.linspace(0.0, np.pi, 200)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.1))
ax1.plot(idx_cells, p_cb, "ko-", lw=1.6, ms=6, label=r"Checkerboard $p_i = (-1)^i$")
ax1.plot(idx_cells, grad_col, "r^--", lw=2.0, ms=6, label="Collocated gradient $(p_{i+1}-p_{i-1})/2 = 0$")
ax1.plot(idx_faces, grad_mac, "bs:", lw=1.8, ms=6, label=r"MAC face gradient $p_{i+1}-p_i = \pm 2$")
ax1.set_xlabel("Cell / Face index $i$ [-]")
ax1.set_ylabel("Discrete amplitude [-]")
ax1.set_title("1-D Odd–Even Sawtooth Pressure Audit")
ax1.set_ylim(-2.3, 4.4)
ax1.legend(fontsize=8, loc="upper left")
ax2.plot(theta / np.pi, theta, "k:", lw=1.8, label=r"Exact continuum $|k|\Delta x = \theta$")
ax2.plot(theta / np.pi, np.sin(theta), "r--", lw=2.2, label=r"Collocated $|\sin\theta|$ (dies at $\theta=\pi$)")
ax2.plot(theta / np.pi, 2.0 * np.sin(0.5 * theta), "b-", lw=2.2, label=r"Staggered MAC $2|\sin(\theta/2)|$ (peaks at $\theta=\pi$)")
ax2.set_xlabel("Normalized wavenumber $\\theta / \\pi = k\\Delta x / \\pi$ [-]")
ax2.set_ylabel("Dimensionless gradient symbol $|\\hat{G}(\\theta)|\\Delta x$ [-]")
ax2.set_title("Fourier Gradient Transfer Function on $[0, \\pi]$")
ax2.legend(fontsize=8)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. On a periodic grid (), evaluate both the collocated central gradient and the staggered MAC face gradient on all four basis candidates of : , , , and . Prove numerically that while only vanishes under .
heading("Exercise 1: 4-Mode Collocated Spurious Nullspace vs 1-Mode Physical Hydrostatic Nullspace on MAC")
ii, jj = np.meshgrid(np.arange(16), np.arange(16), indexing="ij")
modes = {
"Constant p = 1": np.ones((16, 16)),
"Vertical stripes (-1)^i": (-1.0) ** ii,
"Horizontal stripes (-1)^j": (-1.0) ** jj,
"2-D Chessboard (-1)^(i+j)": (-1.0) ** (ii + jj),
}
for name, p_m in modes.items():
col_x = 0.5 * (np.roll(p_m, -1, axis=0) - np.roll(p_m, 1, axis=0))
col_y = 0.5 * (np.roll(p_m, -1, axis=1) - np.roll(p_m, 1, axis=1))
mac_x = np.roll(p_m, -1, axis=0) - p_m
mac_y = np.roll(p_m, -1, axis=1) - p_m
n_col = float(max(np.max(np.abs(col_x)), np.max(np.abs(col_y))))
n_mac = float(max(np.max(np.abs(mac_x)), np.max(np.abs(mac_y))))
print(f"{name:27s} | Collocated ||grad||_inf = {n_col:.4f} | MAC ||grad||_inf = {n_mac:.4f}")
assert n_col == 0.0
if "Constant" in name:
assert n_mac == 0.0
else:
assert np.isclose(n_mac, 2.0, rtol=1e-15)
Exercise 1: 4-Mode Collocated Spurious Nullspace vs 1-Mode Physical Hydrostatic Nullspace on MAC
================================================================================================
Constant p = 1 | Collocated ||grad||_inf = 0.0000 | MAC ||grad||_inf = 0.0000
Vertical stripes (-1)^i | Collocated ||grad||_inf = 0.0000 | MAC ||grad||_inf = 2.0000
Horizontal stripes (-1)^j | Collocated ||grad||_inf = 0.0000 | MAC ||grad||_inf = 2.0000
2-D Chessboard (-1)^(i+j) | Collocated ||grad||_inf = 0.0000 | MAC ||grad||_inf = 2.0000
Explanation. In 2-D, taking tensor products of creates three non-physical sawtooth modes invisible to and . Staggering normal velocities onto cell faces shrinks the difference stencil to , eliminating all three oscillatory modes without adding artificial fourth-order pressure dissipation.
Exercise 2¶
Problem. Verify that navier_stokes.staggered_mac_projection_2d raises ValueError when given collocated (16, 16) velocity arrays instead of staggered (17, 16) and (16, 17) arrays, and use grids_fvm.verify_discrete_gauss_divergence_2d to show that an uncompensated inlet into a closed box () creates a net volume source .
heading("Exercise 2: MAC Shape Mismatch Guard & Net-Flux Solvability check")
caught_shape = False
try:
navier_stokes.staggered_mac_projection_2d(np.zeros((16, 16)), np.zeros((16, 16)), dx=0.1, dy=0.1)
except ValueError:
caught_shape = True
assert caught_shape is True, "Collocated (16,16) shapes must raise ValueError in staggered_mac_projection_2d"
nx_b, ny_b = 20, 16
Lx_b, Ly_b = 1.0, 0.8
dx_b, dy_b = Lx_b / nx_b, Ly_b / ny_b
u_inlet = np.zeros((nx_b + 1, ny_b))
v_inlet = np.zeros((nx_b, ny_b + 1))
u_inlet[0, :] = 1.5 # Left wall injects fluid, right/top/bottom walls closed
g_audit = grids_fvm.verify_discrete_gauss_divergence_2d(u_inlet, v_inlet, dx=dx_b, dy=dy_b)
expected_net_flux = -1.5 * Ly_b # Outward normal on left wall is -e_x -> boundary integral = (0 - 1.5)*Ly = -1.2
print(f"Uncompensated inlet: sum(div_h u)*dx*dy = {g_audit['volume_integral']:+.6f} == boundary integral = {g_audit['boundary_integral']:+.6f}")
assert np.isclose(g_audit["volume_integral"], expected_net_flux, rtol=1e-14)
assert abs(g_audit["volume_integral"]) > 1.0
Exercise 2: MAC Shape Mismatch Guard & Net-Flux Solvability check
=================================================================
Uncompensated inlet: sum(div_h u)*dx*dy = -1.200000 == boundary integral = -1.200000
Explanation. You cannot pump incompressible fluid into a rigid sealed container without an equal outflow (). In open-channel CFD with inflows and outflows, outlet velocities must always be scaled to satisfy global mass conservation before solving the Neumann pressure Poisson equation.
Exercise 3¶
Problem. Implement my_staggered_mac_projection_2d(u_face, v_face, dx, dy, dt=1.0) using elliptic_multigrid.poisson_2d_cg(..., neumann=True, tol=1e-12), test it on a MAC mesh with random interior face velocities, and verify < 1e-12 agreement with navier_stokes.staggered_mac_projection_2d and max_div_after < 1e-11.
heading("Exercise 3: Implement It Yourself — 2-D Staggered MAC Helmholtz-Hodge Projector")
def my_staggered_mac_projection_2d(u_face: np.ndarray, v_face: np.ndarray, dx: float, dy: float, dt: float = 1.0) -> dict:
"""NumPy staggered MAC velocity projector using zero-mean Neumann Conjugate Gradient."""
uf = np.asarray(u_face, dtype=float).copy()
vf = np.asarray(v_face, dtype=float).copy()
nx = uf.shape[0] - 1
ny = uf.shape[1]
if vf.shape != (nx, ny + 1):
raise ValueError("Shape mismatch for MAC face arrays.")
uf[0, :] = uf[-1, :] = 0.0
vf[:, 0] = vf[:, -1] = 0.0
div_bef = (uf[1:, :] - uf[:-1, :]) / dx + (vf[:, 1:] - vf[:, :-1]) / dy
p_cell = elliptic_multigrid.poisson_2d_cg(-div_bef / dt, dx=dx, dy=dy, neumann=True, tol=1e-12)["u"]
uf[1:-1, :] -= dt * (p_cell[1:, :] - p_cell[:-1, :]) / dx
vf[:, 1:-1] -= dt * (p_cell[:, 1:] - p_cell[:, :-1]) / dy
div_aft = (uf[1:, :] - uf[:-1, :]) / dx + (vf[:, 1:] - vf[:, :-1]) / dy
return {"u_projected": uf, "v_projected": vf, "p_cell": p_cell, "max_div_after": float(np.max(np.abs(div_aft)))}
rng_e3 = np.random.default_rng(1309)
u_in = rng_e3.standard_normal((29, 22))
v_in = rng_e3.standard_normal((28, 23))
mine_mac = my_staggered_mac_projection_2d(u_in, v_in, dx=0.05, dy=0.04, dt=0.2)
ref_mac = navier_stokes.staggered_mac_projection_2d(u_in, v_in, dx=0.05, dy=0.04, dt=0.2)
err_u = float(np.max(np.abs(mine_mac["u_projected"] - ref_mac["u_projected"])))
err_p = float(np.max(np.abs(mine_mac["p_cell"] - ref_mac["p_cell"])))
print(f"Max |u_mine - u_ref| = {err_u:.3e} | Max |p_mine - p_ref| = {err_p:.3e} | max_div_after = {mine_mac['max_div_after']:.3e}")
assert err_u < 1e-12 and err_p < 1e-12 and mine_mac["max_div_after"] < 1e-11
Exercise 3: Implement It Yourself — 2-D Staggered MAC Helmholtz-Hodge Projector
===============================================================================
Max |u_mine - u_ref| = 0.000e+00 | Max |p_mine - p_ref| = 0.000e+00 | max_div_after = 4.903e-13
Summary. Harlow & Welch’s staggered MAC arrangement is the standard arrangement for incompressible flow on structured grids: it has no checkerboard pressure modes, it conserves mass discretely, and its projection does not create kinetic energy. Next, in Lecture 14, we explore an alternative 2-D strategy that eliminates pressure analytically via the curl operator (– formulation) to solve the lid-driven cavity problem and compare with the results of Ghia, Ghia and Shin.