Suppose you store velocity and pressure together at cell centers (collocated arrangement) and discretize with standard second-order central differences . Now insert a sawtooth pressure field of arbitrarily large amplitude: because and have the same sign, everywhere. The momentum equation does not respond to odd–even checkerboard pressure modes, decoupling even-indexed and odd-indexed nodes into two non-communicating subgrids. In 1965, Harlow and Welch introduced the Marker-and-Cell (MAC) staggered grid, placing scalar at cell centers while shifting onto vertical cell faces and onto horizontal faces. In this lecture we audit 1-D and 2-D checkerboard nullspaces, show the Neumann pressure solvability condition via discrete Gauss divergence, and project divergent face velocities onto with navier_stokes.staggered_mac_projection_2d.
Learning objectives¶
Prove algebraically and numerically via
navier_stokes.checkerboard_pressure_audit_1dwhy collocated central gradients annihilate pressure modes while staggered face gradients detect them at full sensitivity.Map Harlow & Welch’s (1965) 2-D MAC variable arrangement ( on centers, on vertical faces, on horizontal faces) and verify discrete Gauss telescoping via
grids_fvm.verify_discrete_gauss_divergence_2d.Explain the Neumann pressure compatibility condition and zero-mean gauge fixing in
elliptic_multigrid.poisson_2d_cg(..., neumann=True).Project contaminated 2-D velocity fields onto using
navier_stokes.staggered_mac_projection_2dand verify discrete Helmholtz–Hodge orthogonality.
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. Physical Principles & The Odd–Even Checkerboard Crisis¶
In 1-D steady or fractional-step momentum balance, velocity responds only to the pressure gradient , never to absolute pressure itself (physically, only should lie in the nullspace ). Compare two discrete gradient operators on a grid of spacing :
Naive Collocated Central Gradient (spanning , skipping cell ):
Harlow–Welch Staggered MAC Face Gradient (spanning right across face ):
In Fourier space (, grid phase ), the collocated symbol is , which vanishes both at and at Nyquist . The staggered symbol is , whose magnitude increases monotonically all the way to its maximum at .
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()
Demonstration 1: Collocated Checkerboard Blindness vs Staggered MAC Detection
=============================================================================
Alternating pressure p_i = (-1)^i : [ 1. -1. 1. -1. 1. -1. 1. -1.] ...
Collocated ||(p_{i+1} - p_{i-1})/2||_inf : 0.000000000000000 (zero for the checkerboard mode)
Staggered || p_{i+1} - p_i ||_inf : 2.000000000000000 (the full amplitude)

Figure 13.1. (a) A checkerboard pressure field in one dimension, its collocated central gradient, which is zero everywhere, and its staggered face gradient, which is . (b) Fourier symbol of the collocated and the staggered gradient against the wavenumber, with the exact symbol.
What Demonstration 1 shows. In 2-D, a collocated central stencil has a null space of four linearly independent pressure modes, 1, , and , unless stabilized by Rhie–Chow (1983) momentum interpolation. By contrast, Harlow & Welch’s staggered MAC stencil has a 1-dimensional nullspace consisting solely of the physical hydrostatic constant .
2. 2-D MAC Topology & Neumann Pressure Solvability¶
On an Cartesian FVM mesh (dx, dy), the 2-D MAC grid stores:
Cell-centered pressure & divergence : shape
(nx, ny)Normal horizontal velocity on vertical faces : shape
(nx + 1, ny)Normal vertical velocity on horizontal faces : shape
(nx, ny + 1)
Every cell’s discrete divergence is an exact compact flux balance, and composing MAC divergence with MAC face gradients automatically generates the compact 5-point cell-centered Poisson stencil (with homogeneous Neumann boundary conditions on impermeable walls where ):
Because with pure Neumann walls satisfies , a solution exists if and only if the right-hand side has zero mean (, guaranteed automatically by impermeable walls via discrete Gauss divergence), and elliptic_multigrid.poisson_2d_cg(..., neumann=True) fixes the additive constant by projecting onto zero-mean pressure .
heading("Demonstration 2: MAC Telescoping Gauss Theorem & Zero-Mean Neumann Compatibility")
nx_m, ny_m = 24, 18
Lx_m, Ly_m = 1.2, 0.9
dx_m, dy_m = Lx_m / nx_m, Ly_m / ny_m
rng_mac = np.random.default_rng(1302)
u_f = rng_mac.standard_normal((nx_m + 1, ny_m))
v_f = rng_mac.standard_normal((nx_m, ny_m + 1))
# Impermeable box walls (u.n = 0 on all 4 boundaries):
u_f[0, :] = 0.0
u_f[-1, :] = 0.0
v_f[:, 0] = 0.0
v_f[:, -1] = 0.0
gauss_chk = grids_fvm.verify_discrete_gauss_divergence_2d(u_f, v_f, dx=dx_m, dy=dy_m)
cg_sol = elliptic_multigrid.poisson_2d_cg(-gauss_chk["div_cells"], dx=dx_m, dy=dy_m, neumann=True, tol=1e-12)
print(f"Volume integral sum(div_h u*)*dx*dy : {gauss_chk['volume_integral']:+.3e}")
print(f"Boundary flux integral : {gauss_chk['boundary_integral']:+.3e} (discrepancy = {gauss_chk['discrepancy']:.3e})")
print(f"Neumann CG converged in {cg_sol['iterations']} iterations | final residual = {cg_sol['residual_history'][-1]:.3e}")
print(f"Gauge-fixed mean cell pressure <p> : {np.mean(cg_sol['u']):+.3e}")
assert abs(gauss_chk["volume_integral"]) < 1e-14
assert gauss_chk["discrepancy"] < 1e-15
assert cg_sol["residual_history"][-1] <= 1e-12
assert abs(float(np.mean(cg_sol["u"]))) < 1e-15
Demonstration 2: MAC Telescoping Gauss Theorem & Zero-Mean Neumann Compatibility
================================================================================
Volume integral sum(div_h u*)*dx*dy : +1.776e-16
Boundary flux integral : +0.000e+00 (discrepancy = 1.776e-16)
Neumann CG converged in 141 iterations | final residual = 6.191e-13
Gauge-fixed mean cell pressure <p> : +1.028e-18
What Demonstration 2 shows. Interior face fluxes cancel pairwise across every shared cell wall, so holds to 10-15 even for random interior velocities, making the Neumann pressure Poisson equation solvable without artificial boundary pressure guesses.
3. 2-D Staggered MAC Projection & Vortex Extraction¶
We test navier_stokes.staggered_mac_projection_2d on by contaminating an exact solenoidal cellular vortex (, ) with a strong compressible potential flow where ( on all walls):
heading("Demonstration 3: 2-D MAC Projection — Stripping Compressible Contamination to Recover Exact Vortex")
nx_p, ny_p = 40, 40
dx_p = dy_p = 1.0 / nx_p
xf_u, yf_u = np.meshgrid(np.linspace(0.0, 1.0, nx_p + 1), (np.arange(ny_p) + 0.5) * dy_p, indexing="ij")
xf_v, yf_v = np.meshgrid((np.arange(nx_p) + 0.5) * dx_p, np.linspace(0.0, 1.0, ny_p + 1), indexing="ij")
xc_p, yc_p = np.meshgrid((np.arange(nx_p) + 0.5) * dx_p, (np.arange(ny_p) + 0.5) * dy_p, indexing="ij")
# Exact solenoidal vortex + irrotational contamination grad(phi) with phi = 0.25*cos(pi*x)*cos(2*pi*y):
u_sol = np.pi * np.sin(np.pi * xf_u) * np.cos(np.pi * yf_u)
v_sol = -np.pi * np.cos(np.pi * xf_v) * np.sin(np.pi * yf_v)
u_irrot = -0.25 * np.pi * np.sin(np.pi * xf_u) * np.cos(2.0 * np.pi * yf_u)
v_irrot = -0.50 * np.pi * np.cos(np.pi * xf_v) * np.sin(2.0 * np.pi * yf_v)
u_contaminated = u_sol + u_irrot
v_contaminated = v_sol + v_irrot
proj = navier_stokes.staggered_mac_projection_2d(u_contaminated, v_contaminated, dx=dx_p, dy=dy_p, dt=1.0)
phi_exact_cell = 0.25 * np.cos(np.pi * xc_p) * np.cos(2.0 * np.pi * yc_p)
u_rec_err = float(np.sqrt(np.mean((proj["u_projected"] - u_sol) ** 2)))
p_rec_err = float(np.sqrt(np.mean((proj["p_cell"] - phi_exact_cell) ** 2)))
# Discrete Helmholtz-Hodge L2 orthogonality <u_proj, grad_h(p)>_face == 0:
gp_x = (proj["p_cell"][1:, :] - proj["p_cell"][:-1, :]) / dx_p
gp_y = (proj["p_cell"][:, 1:] - proj["p_cell"][:, :-1]) / dy_p
inner_orth = float(np.sum(proj["u_projected"][1:-1, :] * gp_x) * dx_p * dy_p
+ np.sum(proj["v_projected"][:, 1:-1] * gp_y) * dx_p * dy_p)
print(f"Max |div_h u| before projection : {proj['max_div_before']:.4f}")
print(f"Max |div_h u| after projection : {proj['max_div_after']:.3e}")
print(f"Recovered solenoidal ||u_proj - u_sol||_2 : {u_rec_err:.4e}")
print(f"Recovered potential ||p_cell - phi||_2 : {p_rec_err:.4e}")
print(f"Discrete orthogonality <u_proj, grad_h p> : {inner_orth:+.3e}")
assert proj["max_div_before"] > 3.0 and proj["max_div_after"] < 1e-11
assert u_rec_err < 5e-3 and p_rec_err < 2e-3
assert abs(inner_orth) < 1e-12
# Interpolate face velocities to cell centers for visualization:
u_c_bef = 0.5 * (u_contaminated[:-1, :] + u_contaminated[1:, :])
v_c_bef = 0.5 * (v_contaminated[:, :-1] + v_contaminated[:, 1:])
u_c_aft = 0.5 * (proj["u_projected"][:-1, :] + proj["u_projected"][1:, :])
v_c_aft = 0.5 * (proj["v_projected"][:, :-1] + proj["v_projected"][:, 1:])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.3))
div_bef_map = (u_contaminated[1:, :] - u_contaminated[:-1, :]) / dx_p + (v_contaminated[:, 1:] - v_contaminated[:, :-1]) / dy_p
im1 = ax1.contourf(xc_p, yc_p, div_bef_map, levels=16, cmap="RdBu_r")
plt.colorbar(im1, ax=ax1, label=r"$\nabla_h \cdot \mathbf{u}^*$ [1/s]")
sk = 3
ax1.quiver(xc_p[::sk, ::sk], yc_p[::sk, ::sk], u_c_bef[::sk, ::sk], v_c_bef[::sk, ::sk], color="k")
ax1.set_xlabel("$x$ [m]")
ax1.set_ylabel("$y$ [m]")
ax1.set_title(rf"Before MAC Projection ($\|\nabla_h\cdot\mathbf{{u}}^*\|_\infty = {proj['max_div_before']:.2f}$)")
im2 = ax2.contourf(xc_p, yc_p, proj["p_cell"], levels=16, cmap="viridis")
plt.colorbar(im2, ax=ax2, label="Recovered $p_{\\mathrm{cell}} \\approx \\phi$ [$\\mathrm{m^2/s^2}$]")
ax2.quiver(xc_p[::sk, ::sk], yc_p[::sk, ::sk], u_c_aft[::sk, ::sk], v_c_aft[::sk, ::sk], color="w")
ax2.set_xlabel("$x$ [m]")
ax2.set_ylabel("$y$ [m]")
ax2.set_title(rf"After MAC Projection ($\|\nabla_h\cdot\mathbf{{u}}\|_\infty = {proj['max_div_after']:.1e}$)")
label_panels(fig)
plt.show()
Demonstration 3: 2-D MAC Projection — Stripping Compressible Contamination to Recover Exact Vortex
==================================================================================================
Max |div_h u| before projection : 12.2788
Max |div_h u| after projection : 7.550e-13
Recovered solenoidal ||u_proj - u_sol||_2 : 2.3934e-04
Recovered potential ||p_cell - phi||_2 : 1.0929e-04
Discrete orthogonality <u_proj, grad_h p> : -3.392e-16

Figure 13.2. Projection on a staggered grid. (a) Provisional velocity (arrows) and its discrete divergence (colors). (b) Velocity after the projection and the pressure-like potential; the titles give the largest divergence.
What Demonstration 3 shows. The projection removes the potential component (the potential is recovered to in the norm) and leaves the divergence-free vortex unchanged (to ), and satisfies discrete Helmholtz–Hodge orthogonality to 10-14.
4. Sensitivity to the parameters¶
Because with , the discrete face norm obeys an exact Pythagorean energy theorem:
Projection never creates spurious kinetic energy, which is important for stability on stretched or anisotropic meshes. We test this Pythagorean identity and Conjugate-Gradient iteration count across grid aspect ratios .
heading("Demonstration 4: Pythagorean Energy Theorem & CG Conditioning Across Mesh Aspect Ratios")
aspect_ratios = [0.5, 1.0, 2.0, 4.0]
nx_ar, ny_ar = 24, 24
rng_ar = np.random.default_rng(1304)
u0_ar = rng_ar.standard_normal((nx_ar + 1, ny_ar))
v0_ar = rng_ar.standard_normal((nx_ar, ny_ar + 1))
u0_ar[0, :] = u0_ar[-1, :] = 0.0
v0_ar[:, 0] = v0_ar[:, -1] = 0.0
print(f"{'AR = dx/dy':>10s} | {'CG iters':>9s} | {'||u*||_h^2':>12s} | {'||u_p||^2 + ||dp||^2':>21s} | {'Pythagorean diff':>16s}")
print("-" * 80)
cg_iters_list = []
for ar in aspect_ratios:
dx_a, dy_a = ar * (1.0 / nx_ar), 1.0 / ny_ar
out_p = navier_stokes.staggered_mac_projection_2d(u0_ar, v0_ar, dx=dx_a, dy=dy_a, dt=1.0)
div_b = (u0_ar[1:, :] - u0_ar[:-1, :]) / dx_a + (v0_ar[:, 1:] - v0_ar[:, :-1]) / dy_a
cg_i = elliptic_multigrid.poisson_2d_cg(-div_b, dx=dx_a, dy=dy_a, neumann=True, tol=1e-12)["iterations"]
cg_iters_list.append(cg_i)
du_x = u0_ar - out_p["u_projected"]
du_y = v0_ar - out_p["v_projected"]
e_star = float((np.sum(u0_ar**2) + np.sum(v0_ar**2)) * dx_a * dy_a)
e_proj = float((np.sum(out_p["u_projected"]**2) + np.sum(out_p["v_projected"]**2)) * dx_a * dy_a)
e_grad = float((np.sum(du_x**2) + np.sum(du_y**2)) * dx_a * dy_a)
pyth_diff = abs(e_star - (e_proj + e_grad))
print(f"{ar:10.1f} | {cg_i:9d} | {e_star:12.6f} | {e_proj + e_grad:21.6f} | {pyth_diff:16.3e}")
assert pyth_diff < 1e-11 and e_proj <= e_star
assert cg_iters_list[-1] > cg_iters_list[1]
Demonstration 4: Pythagorean Energy Theorem & CG Conditioning Across Mesh Aspect Ratios
=======================================================================================
AR = dx/dy | CG iters | ||u*||_h^2 | ||u_p||^2 + ||dp||^2 | Pythagorean diff
--------------------------------------------------------------------------------
0.5 | 192 | 0.934797 | 0.934797 | 1.110e-16
1.0 | 124 | 1.869593 | 1.869593 | 0.000e+00
2.0 | 190 | 3.739187 | 3.739187 | 4.441e-16
4.0 | 259 | 7.478373 | 7.478373 | 1.776e-15
Inside the algorithm¶
What Demonstration 4 shows. Why does the discrete Pythagorean theorem hold to 10-13 regardless of cell aspect ratio ? Because on a staggered MAC grid with impermeable walls, the negative discrete divergence and the interior face gradient are exact negative matrix transposes (), making symmetric positive semi-definite (ideal for Conjugate Gradient). High aspect ratio () increases matrix condition number , requiring more CG iterations while preserving exact orthogonality.
Check against the library¶
heading("Inside the Algorithm: MAC Discrete Adjoint Identity <-div_h(u), q>_cell == <u, grad_h(q)>_face")
print(show_source(navier_stokes.checkerboard_pressure_audit_1d))
print(show_source(navier_stokes.staggered_mac_projection_2d))
rng_adj = np.random.default_rng(1305)
nx_a, ny_a = 14, 12
dx_a, dy_a = 0.08, 0.11
u_adj = rng_adj.standard_normal((nx_a + 1, ny_a))
v_adj = rng_adj.standard_normal((nx_a, ny_a + 1))
u_adj[0, :] = u_adj[-1, :] = 0.0
v_adj[:, 0] = v_adj[:, -1] = 0.0
q_adj = rng_adj.standard_normal((nx_a, ny_a))
div_u_adj = (u_adj[1:, :] - u_adj[:-1, :]) / dx_a + (v_adj[:, 1:] - v_adj[:, :-1]) / dy_a
grad_qx = (q_adj[1:, :] - q_adj[:-1, :]) / dx_a
grad_qy = (q_adj[:, 1:] - q_adj[:, :-1]) / dy_a
lhs_cell = float(-np.sum(div_u_adj * q_adj) * dx_a * dy_a)
rhs_face = float((np.sum(u_adj[1:-1, :] * grad_qx) + np.sum(v_adj[:, 1:-1] * grad_qy)) * dx_a * dy_a)
print(f"Cell inner product <-div_h(u), q> : {lhs_cell:+.12f}")
print(f"Face inner product <u, grad_h(q)> : {rhs_face:+.12f} | difference = {abs(lhs_cell - rhs_face):.3e}")
assert np.isclose(lhs_cell, rhs_face, rtol=1e-14, atol=1e-14)
Inside the Algorithm: MAC Discrete Adjoint Identity <-div_h(u), q>_cell == <u, grad_h(q)>_face
==============================================================================================
def checkerboard_pressure_audit_1d(n_cells: int = 16) -> dict:
"""Show collocated central gradient annihilates (-1)^i checkerboard while staggered MAC gradient detects it."""
idx = np.arange(n_cells, dtype=float)
p_cb = (-1.0) ** idx
# Periodic collocated central gradient (p_{i+1} - p_{i-1}) / (2*dx):
grad_collocated = 0.5 * (np.roll(p_cb, -1) - np.roll(p_cb, 1))
# Staggered face gradient (p_{i+1} - p_i) / dx:
grad_staggered = np.roll(p_cb, -1) - p_cb
return {
"p_checkerboard": p_cb,
"collocated_grad_norm": float(np.max(np.abs(grad_collocated))),
"staggered_grad_norm": float(np.max(np.abs(grad_staggered))),
}
def staggered_mac_projection_2d(
u_face: np.ndarray,
v_face: np.ndarray,
dx: float,
dy: float,
dt: float = 1.0,
) -> dict:
"""Project arbitrary staggered MAC face velocities (u_face:(nx+1,ny), v_face:(nx,ny+1)) onto div_h(u) == 0."""
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("Require u_face (nx+1, ny) and v_face (nx, ny+1).")
# Enforce impermeable normal walls before projection:
uf[0, :] = 0.0
uf[-1, :] = 0.0
vf[:, 0] = 0.0
vf[:, -1] = 0.0
div_before = (uf[1:, :] - uf[:-1, :]) / dx + (vf[:, 1:] - vf[:, :-1]) / dy
cg = poisson_2d_cg(-div_before / dt, dx=dx, dy=dy, neumann=True, tol=1e-12)
p_cell = cg["u"]
uf[1:-1, :] -= dt * (p_cell[1:, :] - p_cell[:-1, :]) / dx
vf[:, 1:-1] -= dt * (p_cell[:, 1:] - p_cell[:, :-1]) / dy
div_after = (uf[1:, :] - uf[:-1, :]) / dx + (vf[:, 1:] - vf[:, :-1]) / dy
return {
"u_projected": uf,
"v_projected": vf,
"p_cell": p_cell,
"max_div_before": float(np.max(np.abs(div_before))),
"max_div_after": float(np.max(np.abs(div_after))),
}
Cell inner product <-div_h(u), q> : +4.113271407807
Face inner product <u, grad_h(q)> : +4.113271407807 | difference = 0.000e+00
Exercises¶
Worked solutions are in 13_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. 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 .
Find how it fails. Verify that
navier_stokes.staggered_mac_projection_2draisesValueErrorwhen given collocated(16, 16)velocity arrays instead of staggered(17, 16)and(16, 17)arrays, and usegrids_fvm.verify_discrete_gauss_divergence_2dto show that an uncompensated inlet into a closed box () creates a net volume source .Implement it yourself. Implement
my_staggered_mac_projection_2d(u_face, v_face, dx, dy, dt=1.0)usingelliptic_multigrid.poisson_2d_cg(..., neumann=True, tol=1e-12), test it on a MAC mesh with random interior face velocities, and verify< 1e-12agreement withnavier_stokes.staggered_mac_projection_2dandmax_div_after < 1e-11.
heading("Self-check for the exercises")
ii_sc, jj_sc = np.meshgrid(np.arange(16), np.arange(16), indexing="ij")
p_chess = (-1.0) ** (ii_sc + jj_sc)
gx_col = 0.5 * (np.roll(p_chess, -1, axis=0) - np.roll(p_chess, 1, axis=0))
gy_col = 0.5 * (np.roll(p_chess, -1, axis=1) - np.roll(p_chess, 1, axis=1))
gx_mac = np.roll(p_chess, -1, axis=0) - p_chess
print(f"2-D chessboard (-1)^(i+j): collocated max |grad| = {max(np.max(np.abs(gx_col)), np.max(np.abs(gy_col))):.1f}, MAC max |grad| = {np.max(np.abs(gx_mac)):.1f}")
assert np.max(np.abs(gx_col)) == 0.0 and np.max(np.abs(gy_col)) == 0.0 and np.isclose(np.max(np.abs(gx_mac)), 2.0)
print("All checks passed.")
Self-check for the exercises
============================
2-D chessboard (-1)^(i+j): collocated max |grad| = 0.0, MAC max |grad| = 2.0
All checks passed.