In compressible gas dynamics (Euler’s equations), density obeys a hyperbolic continuity PDE and pressure follows algebraically from an equation of state . Yet the moment we pass to the incompressible Navier–Stokes limit (, ), vanishes and there is no explicit evolution equation anywhere in the system. Instead, kinematic pressure acts across the entire fluid domain as an elliptic Lagrange multiplier enforcing the solenoidal constraint . In 1968, Chorin introduced the fractional-step projection method, splitting each step into an unconstrained momentum predictor followed by an orthogonal Helmholtz–Hodge projection onto divergence-free vector fields. In this lecture we derive Chorin’s projection, show why discrete Fourier wavenumbers must match the discrete central-difference stencil to reach , and verify spatial accuracy and dissipation against G. I. Taylor & A. E. Green’s (1937) exact unsteady vortex solution.
Learning objectives¶
Explain why incompressible pressure lacks a equation, acting as a Lagrange multiplier governed by the pressure Poisson equation (for ).
Verify the exact 2-D unsteady Taylor–Green decaying vortex (
navier_stokes.taylor_green_vortex_exact), including exact cancellation and viscous kinetic-energy decay .Apply Helmholtz–Hodge decomposition in
navier_stokes.taylor_green_projection_2dusing modified discrete wavenumbers to achieve machine-precision incompressibility .Confirm spatial convergence and audit viscosity sensitivity across laminar Reynolds regimes.
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. Principles and governing equations¶
For a constant-density Newtonian fluid ( by kinematic normalization, ), the 2-D incompressible Navier–Stokes equations couple momentum transport to the instantaneous kinematic divergence constraint:
Why is incompressible flow numerically stiffer to couple than explicit compressible flow? Taking the divergence of the momentum equation and enforcing eliminates , yielding the elliptic Pressure Poisson Equation (PPE):
Pressure therefore adjusts elliptically (infinite acoustic wave speed ) as the Lagrange multiplier that prevents convective self-advection from compressing fluid elements.
1.1 Exact Benchmark: The 2-D Taylor–Green Decaying Vortex¶
On the doubly periodic square , Taylor & Green (1937) discovered a closed-form unsteady solution of the full nonlinear Navier–Stokes PDE (navier_stokes.taylor_green_vortex_exact) in which nonlinear advection is purely irrotational and balances point-by-point, leaving pure viscous decay of velocity, vorticity , and domain-averaged kinetic energy :
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()
Demonstration 1: Exact 2-D Taylor-Green Vortex — Advection-Pressure Balance & Kinetic Energy Decay
==================================================================================================
Max |(u.grad)u_x - (-dp/dx)| at t=0 : 2.220e-16
Initial kinetic energy E_k(0) : 0.25000000 (exact 1/4 = 0.25000000)
E_k(0.5) / E_k(0) : 0.81873075 vs exp(-4*nu*t) = 0.81873075
Viscous dissipation -dE_k/dt|_{t=0}: 2*nu*Z(0) = 0.100000 == 4*nu*E_k(0) = 0.100000

Figure 12.1. The Taylor–Green vortex. (a) Velocity vectors and pressure at . (b) Exact decay of the velocity amplitude and of the kinetic energy for .
What Demonstration 1 shows. Every vortex core () sits at a pressure minimum (, centrifugal low-pressure eye), while stagnation points where counter-rotating streams collide sit at pressure maxima (). Because , kinematic pressure and kinetic energy both decay as , twice as fast as velocity amplitude , satisfying the exact enstrophy dissipation balance .
2. Helmholtz–Hodge Decomposition & Chorin’s Projection Method¶
The Helmholtz–Hodge theorem states that any smooth vector field on a periodic (or impermeable-wall) domain decomposes uniquely into a divergence-free (solenoidal) part and a curl-free (irrotational) gradient :
Chorin’s fractional-step algorithm (navier_stokes.taylor_green_projection_2d) advances in three stages:
Advection–Diffusion Predictor (ignoring ): .
Pressure Poisson Solve: Taking of Eq. (2.1) requires .
Orthogonal Velocity Correction: .
2.1 Why Modified Discrete Wavenumbers Are Mandatory.¶
On a periodic collocated mesh of spacing , applying central differences to a Fourier mode multiplies by where:
If you carelessly divide by the continuum symbol instead of , fails to cancel , leaving an divergence leak. Using drives down to 10-15.
heading("Demonstration 2: Chorin Fractional-Step Solver on [0, 2*pi)^2 — Machine-Zero Discrete Divergence")
nx_run = 48
dt_run = 0.002
n_steps_run = 250 # t_end = 0.50 s
sim = navier_stokes.taylor_green_projection_2d(nx=nx_run, dt=dt_run, n_steps=n_steps_run, nu=nu_tg)
t_end_run = n_steps_run * dt_run
ek_num = float(0.5 * np.mean(sim["u"] ** 2 + sim["v"] ** 2))
ek_ana = 0.25 * float(np.exp(-4.0 * nu_tg * t_end_run))
p_err_l2 = float(np.sqrt(np.mean((sim["p"] - sim["exact"]["p"]) ** 2)))
print(f"Grid {nx_run}x{nx_run}, t_end = {t_end_run:.2f} s:")
print(f" Max discrete divergence ||div_h(u)||_inf : {sim['max_divergence']:.3e} (< 1e-14)")
print(f" Velocity L2 error ||u - u_exact||_2 : {sim['u_l2_error']:.4e}")
print(f" Pressure L2 error ||p - p_exact||_2 : {p_err_l2:.4e}")
print(f" Kinetic energy E_k(0.5): Chorin = {ek_num:.7f} vs Exact = {ek_ana:.7f} (rel err = {abs(ek_num - ek_ana)/ek_ana:.2e})")
assert sim["max_divergence"] < 1e-14
assert sim["u_l2_error"] < 2e-4
assert p_err_l2 < 2e-3
assert np.isclose(ek_num, ek_ana, rtol=1e-3)
j_slice = nx_run // 4 # y = pi/2 where u_exact = 0, or j = 0 where y = 0 -> u(x, 0, t) = sin(x)*exp(-2*nu*t)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.2))
x_line = sim["X"][:, 0]
ax1.plot(x_line, sim["exact"]["u"][:, 0], "k-", lw=2.2, label="Analytical $u(x, 0, t)$")
ax1.plot(x_line[::2], sim["u"][::2, 0], "ro", ms=5, label="Chorin projection $u_h(x, 0, t)$")
ax1.plot(x_line, sim["exact"]["v"][:, j_slice], "b--", lw=2.0, label=r"Analytical $v(x, \pi/2, t)$")
ax1.plot(x_line[::2], sim["v"][::2, j_slice], "bs", ms=4.5, fillstyle="none", label=r"Chorin $v_h(x, \pi/2, t)$")
ax1.set_xlabel("Coordinate $x$ [rad]")
ax1.set_ylabel("Velocity [m/s]")
ax1.set_title(rf"Velocity Slice Parity at $t = {t_end_run:.2f}$ s ($\|\nabla_h\cdot\mathbf{{u}}\|_\infty = {sim['max_divergence']:.1e}$)")
ax1.set_ylim(-1.05, 1.80)
ax1.legend(fontsize=8, ncol=2, loc="upper center")
ax2.plot(x_line, sim["exact"]["p"][:, 0], "k-", lw=2.2, label="Analytical $p(x, 0, t)$")
ax2.plot(x_line[::2], sim["p"][::2, 0], "gd", ms=5, label="Projected Lagrange multiplier $p_h(x, 0, t)$")
ax2.set_xlabel("Coordinate $x$ [rad]")
ax2.set_ylabel("Kinematic pressure $p$ [$\\mathrm{m^2/s^2}$]")
ax2.set_title("Recovered Pressure Without Any $\\partial_t p$ PDE")
ax2.set_ylim(-0.02, 0.56)
ax2.legend(fontsize=8.5, loc="upper center")
label_panels(fig)
plt.show()
Demonstration 2: Chorin Fractional-Step Solver on [0, 2*pi)^2 — Machine-Zero Discrete Divergence
================================================================================================
Grid 48x48, t_end = 0.50 s:
Max discrete divergence ||div_h(u)||_inf : 5.551e-16 (< 1e-14)
Velocity L2 error ||u - u_exact||_2 : 5.5542e-05
Pressure L2 error ||p - p_exact||_2 : 1.9820e-03
Kinetic energy E_k(0.5): Chorin = 0.2047329 vs Exact = 0.2046827 (rel err = 2.46e-04)

Figure 12.2. Projection-method solution at s (symbols) and the analytical solution (lines). (a) Velocity components along two grid lines. (b) Pressure along .
What Demonstration 2 shows. Starting with p = 0 and no initial pressure field whatsoever, Chorin’s FFT Poisson projection reconstructs the exact doubly harmonic pressure wave purely from the divergence of the nonlinear convective predictor . Simultaneously, modified discrete wavenumbers enforce .
3. Spatial Mesh-Refinement Verification¶
Because both central differences and the 5-point discrete Laplacian have second-order truncation error , fixing a small time step (so forward-Euler temporal error is small compared with spatial discretization error) must exhibit clean second-order spatial convergence across ( error reduction per grid doubling).
heading("Demonstration 3: Spatial O(dx^2) Convergence Study Across N = 16, 32, 64")
grids_n = [16, 32, 64]
dt_conv = 5.0e-4
steps_conv = 400 # t_end = 0.20 s
dxs, u_errs, divs = [], [], []
print(f"{'Grid N':>8s} | {'dx [rad]':>10s} | {'||u - u_ex||_2':>15s} | {'Observed Order p':>17s} | {'Max |div_h u|':>14s}")
print("-" * 76)
for idx, n_val in enumerate(grids_n):
out = navier_stokes.taylor_green_projection_2d(nx=n_val, dt=dt_conv, n_steps=steps_conv, nu=nu_tg)
dx_v = 2.0 * np.pi / n_val
dxs.append(dx_v)
u_errs.append(out["u_l2_error"])
divs.append(out["max_divergence"])
order_str = " ---" if idx == 0 else f"{np.log2(u_errs[idx - 1] / u_errs[idx]):17.3f}"
print(f"{n_val:8d} | {dx_v:10.5f} | {out['u_l2_error']:15.4e} | {order_str:>17s} | {out['max_divergence']:14.3e}")
orders = np.log2(np.array(u_errs[:-1]) / np.array(u_errs[1:]))
assert np.all(orders > 1.95) and np.all(orders < 2.15)
assert max(divs) < 1e-14
dxs_arr = np.array(dxs)
fig, ax = plt.subplots(figsize=(6.8, 4.1))
ax.loglog(dxs_arr, u_errs, "o-", lw=2.2, ms=7, label=r"Chorin $\|u_h - u_{\mathrm{exact}}\|_{L_2}$")
ax.loglog(dxs_arr, u_errs[0] * (dxs_arr / dxs_arr[0]) ** 2, "k--", lw=1.8, label=r"Reference slope $O(\Delta x^2)$")
ax.set_xlabel("Grid spacing $\\Delta x = 2\\pi / N$ [rad]")
ax.set_ylabel("Velocity $L_2$ error [m/s]")
ax.set_title(rf"Second-Order Spatial Convergence ($p_1 = {orders[0]:.2f}$, $p_2 = {orders[1]:.2f}$)")
ax.legend(fontsize=9)
plt.show()
Demonstration 3: Spatial O(dx^2) Convergence Study Across N = 16, 32, 64
========================================================================
Grid N | dx [rad] | ||u - u_ex||_2 | Observed Order p | Max |div_h u|
----------------------------------------------------------------------------
16 | 0.39270 | 2.4480e-04 | --- | 2.220e-16
32 | 0.19635 | 6.0706e-05 | 2.012 | 3.331e-16
64 | 0.09817 | 1.4470e-05 | 2.069 | 6.661e-16

Figure 12.3. error of the velocity against the grid spacing, with a line of slope 2.
What Demonstration 3 shows. Doubling grid resolution from cuts the velocity error by factors of () and (), while discrete divergence remains below 10-14 on every mesh.
4. Sensitivity to the parameters¶
How does kinematic viscosity (or Reynolds number for ) control kinetic-energy dissipation in a decaying vortex array? We sweep (Re from 100 down to 4) at and verify that the logarithmic decay rate scales strictly linearly with .
heading("Demonstration 4: Viscosity Sensitivity Sweep nu in {0.01, 0.05, 0.10, 0.25} (Re = 100 down to 4)")
nus = [0.01, 0.05, 0.10, 0.25]
ek_ratios, decay_rates = [], []
print(f"{'nu [m^2/s]':>11s} | {'Re = 1/nu':>10s} | {'E_k(1)/E_k(0) num':>18s} | {'exp(-4*nu) exact':>17s} | {'Measured rate / (4*nu)':>22s}")
print("-" * 88)
for nu_v in nus:
res = navier_stokes.taylor_green_projection_2d(nx=32, dt=0.0025, n_steps=400, nu=nu_v) # t_end = 1.0 s
ek_ratio = float(0.5 * np.mean(res["u"] ** 2 + res["v"] ** 2)) / 0.25
exact_ratio = float(np.exp(-4.0 * nu_v * 1.0))
meas_rate = -float(np.log(ek_ratio)) / 1.0
ek_ratios.append(ek_ratio)
decay_rates.append(meas_rate)
print(f"{nu_v:11.2f} | {1.0/nu_v:10.1f} | {ek_ratio:18.6f} | {exact_ratio:17.6f} | {meas_rate/(4.0*nu_v):22.5f}")
assert np.isclose(ek_ratio, exact_ratio, rtol=4e-3)
fig, ax = plt.subplots(figsize=(6.8, 4.0))
nu_dense = np.linspace(0.0, 0.28, 120)
ax.plot(nu_dense, np.exp(-4.0 * nu_dense), "k-", lw=2.1, label=r"Analytical $E_k(1)/E_k(0) = e^{-4\nu}$")
ax.plot(nus, ek_ratios, "ro", ms=7, label="Chorin 2-D simulation ($N=32$)")
ax.set_xlabel("Kinematic viscosity $\\nu$ [$\\mathrm{m^2/s}$]")
ax.set_ylabel("Remaining kinetic energy fraction $E_k(1)/E_k(0)$ [-]")
ax.set_title("Viscous Enstrophy Dissipation Across $\\mathrm{Re} \\in [4, 100]$")
ax.legend(fontsize=9)
plt.show()
Demonstration 4: Viscosity Sensitivity Sweep nu in {0.01, 0.05, 0.10, 0.25} (Re = 100 down to 4)
================================================================================================
nu [m^2/s] | Re = 1/nu | E_k(1)/E_k(0) num | exp(-4*nu) exact | Measured rate / (4*nu)
----------------------------------------------------------------------------------------
0.01 | 100.0 | 0.960912 | 0.960789 | 0.99682
0.05 | 20.0 | 0.819236 | 0.818731 | 0.99692
0.10 | 10.0 | 0.671114 | 0.670320 | 0.99704
0.25 | 4.0 | 0.368832 | 0.367879 | 0.99741

Figure 12.4. Fraction of the kinetic energy that remains at against the kinematic viscosity: simulation on a grid (points) and the analytical result (line).
Inside the algorithm¶
What Demonstration 4 shows. At (), of initial kinetic energy survives at , whereas at (), viscous shear converts () of kinetic energy into heat within one eddy turnover. The source code below shows how valid_k = k2_eff > 1e-12 masks both the mean-pressure gauge mode and the Nyquist modes where .
Check against the library¶
heading("Inside the Algorithm: navier_stokes.taylor_green_projection_2d & Modified Wavenumber Check")
print(show_source(navier_stokes.taylor_green_projection_2d))
# NumPy single Helmholtz-Hodge projection audit: k_eff vs naive continuum k
n_chk = 32
dx_c = 2.0 * np.pi / n_chk
xc_c = np.linspace(0.0, 2.0 * np.pi, n_chk, endpoint=False)
Xc, Yc = np.meshgrid(xc_c, xc_c, indexing="ij")
# Construct a contaminated field u_star = u_solenoidal + grad(0.4 * sin(2X)*cos(3Y)):
u_star_c = np.sin(Xc) * np.cos(Yc) + 0.8 * np.cos(2.0 * Xc) * np.cos(3.0 * Yc)
v_star_c = -np.cos(Xc) * np.sin(Yc) - 1.2 * np.sin(2.0 * Xc) * np.sin(3.0 * Yc)
ddx_c = lambda f: (np.roll(f, -1, axis=0) - np.roll(f, 1, axis=0)) / (2.0 * dx_c)
ddy_c = lambda f: (np.roll(f, -1, axis=1) - np.roll(f, 1, axis=1)) / (2.0 * dx_c)
div_star_c = ddx_c(u_star_c) + ddy_c(v_star_c)
k1 = 2.0 * np.pi * np.fft.fftfreq(n_chk, d=dx_c)
KX, KY = np.meshgrid(k1, k1, indexing="ij")
k2_cont = np.where(KX**2 + KY**2 > 1e-12, KX**2 + KY**2, 1.0)
k2_mod = np.where((np.sin(KX * dx_c) / dx_c) ** 2 + (np.sin(KY * dx_c) / dx_c) ** 2 > 1e-12,
(np.sin(KX * dx_c) / dx_c) ** 2 + (np.sin(KY * dx_c) / dx_c) ** 2, 1.0)
mask_mod = ((np.sin(KX * dx_c) / dx_c) ** 2 + (np.sin(KY * dx_c) / dx_c) ** 2) > 1e-12
p_naive = np.real(np.fft.ifft2(np.where(KX**2 + KY**2 > 1e-12, -np.fft.fft2(div_star_c) / k2_cont, 0.0)))
p_exact_disc = np.real(np.fft.ifft2(np.where(mask_mod, -np.fft.fft2(div_star_c) / k2_mod, 0.0)))
div_naive = float(np.max(np.abs(ddx_c(u_star_c - ddx_c(p_naive)) + ddy_c(v_star_c - ddy_c(p_naive)))))
div_mod = float(np.max(np.abs(ddx_c(u_star_c - ddx_c(p_exact_disc)) + ddy_c(v_star_c - ddy_c(p_exact_disc)))))
print(f"Initial ||div_h u*||_inf = {np.max(np.abs(div_star_c)):.4f}")
print(f"Residual divergence with naive k^2 = {div_naive:.4e} (not zero) vs modified k_eff^2 = {div_mod:.4e}")
assert div_naive > 1e-2 and div_mod < 1e-14
Inside the Algorithm: navier_stokes.taylor_green_projection_2d & Modified Wavenumber Check
==========================================================================================
def taylor_green_projection_2d(
nx: int,
dt: float,
n_steps: int,
nu: float,
) -> dict:
"""Solve 2-D periodic Taylor-Green Navier-Stokes via Chorin fractional-step projection on [0, 2*pi)^2."""
L = 2.0 * np.pi
dx = L / int(nx)
x = np.linspace(0.0, L, int(nx), endpoint=False)
xx, yy = np.meshgrid(x, x, indexing="ij")
init = taylor_green_vortex_exact(xx, yy, 0.0, nu=nu)
u = init["u"].copy()
v = init["v"].copy()
k1d = 2.0 * np.pi * np.fft.fftfreq(nx, d=dx)
kx, ky = np.meshgrid(k1d, k1d, indexing="ij")
# Exact discrete central-difference modified wavenumbers (masking zero/Nyquist modes where sin(pi) == 0):
kx_eff = np.sin(kx * dx) / dx
ky_eff = np.sin(ky * dx) / dx
k2_eff = kx_eff**2 + ky_eff**2
valid_k = k2_eff > 1e-12
k2_safe = np.where(valid_k, k2_eff, 1.0)
def ddx(f: np.ndarray) -> np.ndarray:
return (np.roll(f, -1, axis=0) - np.roll(f, 1, axis=0)) / (2.0 * dx)
def ddy(f: np.ndarray) -> np.ndarray:
return (np.roll(f, -1, axis=1) - np.roll(f, 1, axis=1)) / (2.0 * dx)
def lap(f: np.ndarray) -> np.ndarray:
return (
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_star = u + dt * (-(u * ddx(u) + v * ddy(u)) + nu * lap(u))
v_star = v + dt * (-(u * ddx(v) + v * ddy(v)) + nu * lap(v))
div_star = ddx(u_star) + ddy(v_star)
p_hat = np.where(valid_k, -np.fft.fft2(div_star) / (dt * k2_safe), 0.0)
p = np.real(np.fft.ifft2(p_hat))
u = u_star - dt * ddx(p)
v = v_star - dt * ddy(p)
t_end = n_steps * dt
exact = taylor_green_vortex_exact(xx, yy, t_end, nu=nu)
div_final = ddx(u) + ddy(v)
return {
"X": xx,
"Y": yy,
"u": u,
"v": v,
"p": p,
"exact": exact,
"u_l2_error": float(np.sqrt(np.mean((u - exact["u"]) ** 2))),
"max_divergence": float(np.max(np.abs(div_final))),
}
Initial ||div_h u*||_inf = 4.9546
Residual divergence with naive k^2 = 4.5559e-01 (not zero) vs modified k_eff^2 = 4.2188e-15
Exercises¶
Worked solutions are in 12_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. On a periodic mesh with at , evaluate
navier_stokes.taylor_green_vortex_exactand verify pointwise to that , and verify across that mean enstrophy equals .Find how it fails. 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.Implement it yourself. Implement
my_taylor_green_projection_2d(nx, dt, n_steps, nu)from scratch in pure NumPy, verify thatu,v, andpmatchnavier_stokes.taylor_green_projection_2don a grid (dt=0.0025,n_steps=160,nu=0.12) to< 1e-14, and verifymax_divergence < 1e-14.
heading("Self-check for the exercises")
X_sc, Y_sc = np.meshgrid(np.linspace(0.0, 2.0 * np.pi, 64, endpoint=False),
np.linspace(0.0, 2.0 * np.pi, 64, endpoint=False), indexing="ij")
tg_sc = navier_stokes.taylor_green_vortex_exact(X_sc, Y_sc, t=0.4, nu=0.08)
e4_sc = np.exp(-4.0 * 0.08 * 0.4)
lap_p_sc = -(np.cos(2.0 * X_sc) + np.cos(2.0 * Y_sc)) * e4_sc
rhs_ppe_sc = 2.0 * ((np.cos(X_sc) * np.cos(Y_sc)) * (-np.cos(X_sc) * np.cos(Y_sc))
- (-np.sin(X_sc) * np.sin(Y_sc)) * (np.sin(X_sc) * np.sin(Y_sc))) * e4_sc
print(f"Max |lap(p) - 2*(u_x*v_y - u_y*v_x)| = {np.max(np.abs(lap_p_sc - rhs_ppe_sc)):.3e}")
assert np.allclose(lap_p_sc, rhs_ppe_sc, atol=1e-15) and np.isclose(0.5 * np.mean(tg_sc["vorticity"] ** 2), np.mean(tg_sc["u"] ** 2 + tg_sc["v"] ** 2))
print("All checks passed.")
Self-check for the exercises
============================
Max |lap(p) - 2*(u_x*v_y - u_y*v_x)| = 6.661e-16
All checks passed.