A new incompressible Navier–Stokes code is often tested first on a square box whose left, right, and bottom walls are stationary while the top lid slides horizontally at speed : the 2-D lid-driven cavity. The geometry is simple, but the flow has singular corners at the lid, a primary vortex and counter-rotating corner eddies, of which Moffatt showed in 1964 that there is in principle an infinite sequence. In 2-D planar geometry, taking the curl of the momentum equation removes identically () and enforces automatically via a scalar streamfunction . In this lecture we derive the – formulation and Thom’s (1933) 2nd-order no-slip wall vorticity boundary condition, accelerate every elliptic step to via elliptic_multigrid.poisson_2d_fast_sine, verify navier_stokes.lid_driven_cavity_2d against Ghia, Ghia & Shin (1982) (constants.GHIA_RE100_BENCHMARK), and compare vs. vortex structures.
Learning objectives¶
Derive the 2-D vorticity–streamfunction (–) Navier–Stokes system coupled to with .
Derive and verify Thom’s (1933) 2nd-order wall vorticity formula enforcing tangential no-slip on solid walls.
Verify
navier_stokes.lid_driven_cavity_2dat point-by-point against the 17-point Ghia, Ghia & Shin (1982) centerline tables (constants.GHIA_RE100_BENCHMARK) and core strength .Contrast viscous-dominated () vs. inertia-convected () primary vortex migration and secondary bottom-corner Moffatt eddies ().
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: Vorticity–Streamfunction (–) & Thom’s Wall Formula¶
In 2-D incompressible flow (), defining the scalar streamfunction and out-of-plane vorticity via:
satisfies continuity identically. Taking eliminates () and yields the scalar advection–diffusion equation characterized solely by the cavity Reynolds number :
1.1 Where Does Vorticity Come From? Thom’s (1933) No-Slip Wall Condition.¶
Impermeable cavity walls form a closed streamline (homogeneous Dirichlet for poisson_2d_fast_sine), yet has no independent physical boundary value, no-slip tangential shear at the walls generates all vorticity in the flow. Taylor-expanding one spacing below the moving top lid (, where and ):
Setting on the stationary left, right, and bottom walls immediately gives .
heading("Demonstration 1: Fast Sine O(N log N) Streamfunction Inversion & Thom's 2nd-Order Wall Vorticity")
n_t = 65
h_t = 1.0 / (n_t - 1)
xg = np.linspace(0.0, 1.0, n_t)
Xt, Yt = np.meshgrid(xg, xg, indexing="ij")
# Manufactured smooth cavity streamfunction psi(x,y) = sin^2(pi*x)*sin^2(pi*y) (psi=0 and u=v=0 on all walls):
psi_exact = (np.sin(np.pi * Xt) ** 2) * (np.sin(np.pi * Yt) ** 2)
d2_sin2 = lambda z: 2.0 * (np.pi**2) * np.cos(2.0 * np.pi * z)
omega_exact = -(d2_sin2(Xt) * (np.sin(np.pi * Yt) ** 2) + (np.sin(np.pi * Xt) ** 2) * d2_sin2(Yt))
# 1) Verify poisson_2d_fast_sine recovers psi from discrete -lap_h(psi_exact) to machine precision, and matches continuum omega to O(h^2):
psi_dst = np.zeros_like(psi_exact)
psi_dst[1:-1, 1:-1] = elliptic_multigrid.poisson_2d_fast_sine(omega_exact[1:-1, 1:-1], dx=h_t, dy=h_t)
psi_err = float(np.max(np.abs(psi_dst - psi_exact)))
# 2) Verify Thom's top-wall vorticity formula omega_top = -2 * psi[:, -2] / h^2 vs omega_exact[:, -1]:
thom_top = -2.0 * psi_exact[:, -2] / (h_t**2)
thom_err = float(np.max(np.abs(thom_top - omega_exact[:, -1])))
print(f"DST-I streamfunction max |psi_dst - psi_exact| (65x65) : {psi_err:.4e}")
print(f"Thom top-wall vorticity max |omega_Thom - omega_exact| : {thom_err:.4e} (exact peak |omega_wall| = {2*np.pi**2:.3f})")
# Confirm O(h^2) convergence of Thom's wall formula across n_grid = 33 -> 65 -> 129:
thom_errs = []
for ng in [33, 65, 129]:
hg = 1.0 / (ng - 1)
xs = np.linspace(0.0, 1.0, ng)
psi_penult = (np.sin(np.pi * xs) ** 2) * (np.sin(np.pi * (1.0 - hg)) ** 2)
om_wall_ex = -(np.sin(np.pi * xs) ** 2) * (2.0 * (np.pi**2))
thom_errs.append(float(np.max(np.abs(-2.0 * psi_penult / (hg**2) - om_wall_ex))))
thom_order = np.log2(thom_errs[0] / thom_errs[1])
print(f"Thom wall error 33 -> 65 -> 129 : {[round(e, 6) for e in thom_errs]} (observed order = {thom_order:.3f})")
assert psi_err < 1e-3 and np.isclose(thom_order, 2.0, atol=0.05)
Demonstration 1: Fast Sine O(N log N) Streamfunction Inversion & Thom's 2nd-Order Wall Vorticity
================================================================================================
DST-I streamfunction max |psi_dst - psi_exact| (65x65) : 8.0358e-04
Thom top-wall vorticity max |omega_Thom - omega_exact| : 1.5849e-02 (exact peak |omega_wall| = 19.739)
Thom wall error 33 -> 65 -> 129 : [0.063336, 0.015849, 0.003963] (observed order = 1.999)
What Demonstration 1 shows. Every time step of lid_driven_cavity_2d solves exactly in floating-point operations via 2-D Discrete Sine Transform (poisson_2d_fast_sine), avoiding iterative SOR inner loops while Thom’s formula injects wall vorticity at accuracy.
2. Benchmark Verification Against Ghia, Ghia & Shin (1982) at ¶
In 1982, U. Ghia, K. N. Ghia, and C. T. Shin published coupled-multigrid cavity solutions (J. Comput. Phys. 48, 387–411) that are still the standard reference for this flow (constants.GHIA_RE100_BENCHMARK). We run navier_stokes.lid_driven_cavity_2d on a grid at (constants.reynolds_number(1.0, 1.0, 0.01) == 100.0) and compare every single vertical-centerline and horizontal-centerline point.
heading("Demonstration 2: Re = 100 Lid-Driven Cavity vs Ghia, Ghia & Shin (1982) Benchmark")
re_100 = constants.reynolds_number(u_m_s=1.0, L_m=1.0, nu_m2_s=0.01)
assert np.isclose(re_100, 100.0)
cav100 = navier_stokes.lid_driven_cavity_2d(n_grid=49, Re=re_100, U_lid=1.0, L=1.0, max_steps=6000, tol=1e-6)
ghia = constants.GHIA_RE100_BENCHMARK
u_at_ghia = np.interp(ghia["y_u"], cav100["y"], cav100["u_vertical_centerline"])
v_at_ghia = np.interp(ghia["x_v"], cav100["x"], cav100["v_horizontal_centerline"])
u_max_err = float(np.max(np.abs(u_at_ghia - ghia["u_centerline"])))
v_max_err = float(np.max(np.abs(v_at_ghia - ghia["v_centerline"])))
ghia_psi_min = -0.103423
print(f"49x49 Re=100 Cavity (steps={cav100['steps']}, d|omega|/dt={cav100['residual_rate']:.2e}):")
print(f" Primary vortex core psi_min : {cav100['psi_min']:.5f} vs Ghia (1982) -0.10342 (rel diff = {abs(cav100['psi_min'] - ghia_psi_min)/abs(ghia_psi_min):.2%})")
print(f" Max |u(0.5, y) - u_Ghia| : {u_max_err:.5f}")
print(f" Max |v(x, 0.5) - v_Ghia| : {v_max_err:.5f}")
assert abs(cav100["psi_min"] - ghia_psi_min) < 0.003
assert u_max_err < 0.006 and v_max_err < 0.010
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.3))
ax1.plot(cav100["u_vertical_centerline"], cav100["y"], "b-", lw=2.2, label="engcfd $u(0.5, y)$ ($49\\times 49$)")
ax1.plot(ghia["u_centerline"], ghia["y_u"], "ko", ms=5.5, fillstyle="none", mew=1.5, label="Ghia et al. (1982) $u$")
ax1.axvline(0.0, color="gray", lw=0.8, ls=":")
ax1.set_xlabel("Horizontal velocity $u(0.5, y) / U_{\\mathrm{lid}}$ [-]")
ax1.set_ylabel("Vertical coordinate $y / L$ [-]")
ax1.set_title("Vertical Centerline Velocity $u(0.5, y)$ ($\\mathrm{Re} = 100$)")
ax1.legend(fontsize=8.5)
ax2.plot(cav100["x"], cav100["v_horizontal_centerline"], "r-", lw=2.2, label="engcfd $v(x, 0.5)$ ($49\\times 49$)")
ax2.plot(ghia["x_v"], ghia["v_centerline"], "ks", ms=5.5, fillstyle="none", mew=1.5, label="Ghia et al. (1982) $v$")
ax2.axhline(0.0, color="gray", lw=0.8, ls=":")
ax2.set_xlabel("Horizontal coordinate $x / L$ [-]")
ax2.set_ylabel("Vertical velocity $v(x, 0.5) / U_{\\mathrm{lid}}$ [-]")
ax2.set_title("Horizontal Centerline Velocity $v(x, 0.5)$ ($\\mathrm{Re} = 100$)")
ax2.legend(fontsize=8.5)
label_panels(fig)
plt.show()
Demonstration 2: Re = 100 Lid-Driven Cavity vs Ghia, Ghia & Shin (1982) Benchmark
=================================================================================
49x49 Re=100 Cavity (steps=3634, d|omega|/dt=9.97e-07):
Primary vortex core psi_min : -0.10207 vs Ghia (1982) -0.10342 (rel diff = 1.31%)
Max |u(0.5, y) - u_Ghia| : 0.00335
Max |v(x, 0.5) - v_Ghia| : 0.00297

Figure 14.1. Lid-driven cavity at on a grid (lines) and the values tabulated by Ghia, Ghia and Shin (1982) (symbols). (a) Horizontal velocity along the vertical centerline. (b) Vertical velocity along the horizontal centerline.
What Demonstration 2 shows. The centerline profiles at are not symmetric: the top moving lid drags a sharp forward shear layer ( near ), which falls downward along the right wall ( at ) and returns more gently upward along the left wall ( at ), and the computed profiles differ from the 34 tabulated values of Ghia, Ghia and Shin by at most 0.004.
3. Mesh-Refinement Convergence Toward Ghia’s Continuum Limit¶
We verify monotone grid convergence of both the primary vortex circulation and the centerline discrepancy against GHIA_RE100_BENCHMARK across .
heading("Demonstration 3: Grid-Refinement Convergence at Re = 100 (21x21 -> 33x33 -> 45x45)")
ghia_ref = constants.GHIA_RE100_BENCHMARK
n_list = [21, 33, 45]
u_l2_ghia, psi_mins = [], []
print(f"{'Grid N':>8s} | {'h = 1/(N-1)':>12s} | {'psi_min':>11s} | {'|psi_min + 0.10342|':>20s} | {'Ghia u-profile L2 diff':>23s}")
print("-" * 86)
for ng in n_list:
sol = navier_stokes.lid_driven_cavity_2d(n_grid=ng, Re=100.0, max_steps=6000, tol=1e-6)
u_int = np.interp(ghia_ref["y_u"], sol["y"], sol["u_vertical_centerline"])
err_u = float(np.sqrt(np.mean((u_int - ghia_ref["u_centerline"]) ** 2)))
u_l2_ghia.append(err_u)
psi_mins.append(sol["psi_min"])
print(f"{ng:8d} | {1.0/(ng-1):12.5f} | {sol['psi_min']:11.5f} | {abs(sol['psi_min'] + 0.103423):20.5f} | {err_u:23.5f}")
assert u_l2_ghia[0] > u_l2_ghia[1] > u_l2_ghia[2]
assert abs(psi_mins[0] + 0.103423) > abs(psi_mins[1] + 0.103423) > abs(psi_mins[2] + 0.103423)
Demonstration 3: Grid-Refinement Convergence at Re = 100 (21x21 -> 33x33 -> 45x45)
==================================================================================
Grid N | h = 1/(N-1) | psi_min | |psi_min + 0.10342| | Ghia u-profile L2 diff
--------------------------------------------------------------------------------------
21 | 0.05000 | -0.09530 | 0.00812 | 0.01496
33 | 0.03125 | -0.10038 | 0.00304 | 0.00467
45 | 0.02273 | -0.10179 | 0.00163 | 0.00194
What Demonstration 3 shows. Both and the 17-point Ghia centerline error decrease from as wall boundary layers are progressively resolved.
4. vs. & Corner Moffatt Eddies¶
What happens physically when we quadruple inertia from to on a mesh?
Inviscid Core Migration: At higher , vorticity advects around closed streamlines into a core of nearly uniform vorticity whose center migrates downward and leftward from toward the center of the cavity .
Moffatt Corner Vortices (): Adverse pressure gradients along the decelerating walls separate the boundary layer before reaching the stagnant bottom corners, spinning up counter-rotating secondary eddies (, counterclockwise vs. the clockwise primary vortex) whose strength grows strongly from to .
heading("Demonstration 4: Vortex Core Migration & Secondary Corner Moffatt Eddies (Re=100 vs Re=400)")
c100 = navier_stokes.lid_driven_cavity_2d(n_grid=49, Re=100.0, max_steps=5000, tol=1e-6)
c400 = navier_stokes.lid_driven_cavity_2d(n_grid=49, Re=400.0, max_steps=8000, tol=1e-6)
idx100 = np.unravel_index(np.argmin(c100["psi"]), c100["psi"].shape)
idx400 = np.unravel_index(np.argmin(c400["psi"]), c400["psi"].shape)
core100 = (float(c100["x"][idx100[0]]), float(c100["y"][idx100[1]]))
core400 = (float(c400["x"][idx400[0]]), float(c400["y"][idx400[1]]))
moffatt_100 = float(np.max(c100["psi"]))
moffatt_400 = float(np.max(c400["psi"]))
print(f"Re = 100 : core (x, y) = ({core100[0]:.3f}, {core100[1]:.3f}), psi_min = {c100['psi_min']:.5f}, corner Moffatt psi_max = {moffatt_100:.3e}")
print(f"Re = 400 : core (x, y) = ({core400[0]:.3f}, {core400[1]:.3f}), psi_min = {c400['psi_min']:.5f}, corner Moffatt psi_max = {moffatt_400:.3e}")
dist100 = np.hypot(core100[0] - 0.5, core100[1] - 0.5)
dist400 = np.hypot(core400[0] - 0.5, core400[1] - 0.5)
assert dist400 < dist100, "Primary vortex eye must migrate closer to geometric center (0.5, 0.5) at Re=400"
assert moffatt_400 > 10.0 * moffatt_100 and moffatt_100 > 0.0
Xc, Yc = np.meshgrid(c100["x"], c100["y"], indexing="ij")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.5))
for ax_i, sol_i, re_lbl, core_xy in [(ax1, c100, "100", core100), (ax2, c400, "400", core400)]:
cf = ax_i.contourf(Xc, Yc, sol_i["psi"], levels=20, cmap="PuBu_r")
plt.colorbar(cf, ax=ax_i, label=r"Streamfunction $\psi$ [-]")
# Highlight counter-rotating Moffatt corner eddies (psi > 0) in red dashed contours:
pos_lvls = np.geomspace(2e-6, max(5e-5, float(np.max(sol_i["psi"])) * 0.9), 4)
ax_i.contour(Xc, Yc, sol_i["psi"], levels=pos_lvls, colors="tab:red", linestyles="--", linewidths=1.5)
ax_i.plot([core_xy[0]], [core_xy[1]], "yo", ms=8, mec="k", label=f"Core ({core_xy[0]:.2f}, {core_xy[1]:.2f})")
ax_i.set_xlabel("$x / L$ [-]")
ax_i.set_ylabel("$y / L$ [-]")
ax_i.set_title(rf"$\mathrm{{Re}} = {re_lbl}$ ($\psi_{{\max}} = {np.max(sol_i['psi']):.1e}$)")
ax_i.legend(loc="upper left", fontsize=8)
label_panels(fig)
plt.show()
Demonstration 4: Vortex Core Migration & Secondary Corner Moffatt Eddies (Re=100 vs Re=400)
===========================================================================================
Re = 100 : core (x, y) = (0.625, 0.750), psi_min = -0.10207, corner Moffatt psi_max = 1.622e-05
Re = 400 : core (x, y) = (0.562, 0.604), psi_min = -0.10510, corner Moffatt psi_max = 6.330e-04

Figure 14.2. Streamfunction in the cavity on a grid. (a) . (b) . The point marks the center of the primary vortex; the dashed contours show the secondary eddies in the lower corners, where .
Inside the algorithm¶
What Demonstration 4 shows. Between and the secondary eddy in the bottom right corner (, dashed contours) becomes 39 times stronger ( and ), and the core of the primary vortex moves from to . Both runs use the grid and are continued until the vorticity changes by less than 10-6 per unit time; on this grid the corner eddies are resolved by only a few cells, so their strength is approximate. Below we inspect navier_stokes.lid_driven_cavity_2d and check that central differences of give a velocity field whose discrete divergence vanishes to rounding error at the interior vertices.
Check against the library¶
heading("Inside the Algorithm: navier_stokes.lid_driven_cavity_2d & Exact Mixed-Difference Cancellation")
print(show_source(navier_stokes.lid_driven_cavity_2d))
sol_chk = navier_stokes.lid_driven_cavity_2d(n_grid=29, Re=100.0, max_steps=280, tol=1e-5)
h_c = 1.0 / 28.0
u_c, v_c = sol_chk["u"], sol_chk["v"]
# Interior discrete divergence on [2:-2, 2:-2] where u and v are both central differences of psi:
div_int = (u_c[3:-1, 2:-2] - u_c[1:-3, 2:-2]) / (2.0 * h_c) + (v_c[2:-2, 3:-1] - v_c[2:-2, 1:-3]) / (2.0 * h_c)
# Verify -lap_h(psi) == vorticity on interior [1:-1, 1:-1]:
psi_c, om_c = sol_chk["psi"], sol_chk["vorticity"]
neg_lap_psi = -(psi_c[2:, 1:-1] + psi_c[:-2, 1:-1] + psi_c[1:-1, 2:] + psi_c[1:-1, :-2] - 4.0 * psi_c[1:-1, 1:-1]) / (h_c**2)
print(f"Max interior |du/dx + dv/dy| from streamfunction : {np.max(np.abs(div_int)):.3e}")
print(f"Max interior |-lap_h(psi) - omega| (DST-I exact) : {np.max(np.abs(neg_lap_psi - om_c[1:-1, 1:-1])):.3e}")
assert np.max(np.abs(div_int)) < 1e-14
assert np.max(np.abs(neg_lap_psi - om_c[1:-1, 1:-1])) < 1e-11
Inside the Algorithm: navier_stokes.lid_driven_cavity_2d & Exact Mixed-Difference Cancellation
==============================================================================================
def lid_driven_cavity_2d(
n_grid: int = 49,
Re: float = 100.0,
U_lid: float = 1.0,
L: float = 1.0,
dt: float | None = None,
max_steps: int = 4500,
tol: float = 1e-6,
) -> dict:
"""Solve steady 2-D incompressible Navier-Stokes lid-driven cavity via DST-accelerated vorticity-streamfunction."""
if n_grid < 9 or Re <= 0.0 or U_lid <= 0.0 or L <= 0.0:
raise ValueError("Require n_grid >= 9 and Re, U_lid, L > 0.")
h = float(L) / (int(n_grid) - 1)
nu = float(U_lid) * float(L) / float(Re)
x = np.linspace(0.0, float(L), int(n_grid))
y = np.linspace(0.0, float(L), int(n_grid))
if dt is None:
dt_diff = 0.22 * (h**2) / nu
dt_conv = 0.35 * h / float(U_lid)
dt_use = min(dt_diff, dt_conv)
else:
dt_use = float(dt)
psi = np.zeros((n_grid, n_grid), dtype=float)
omega = np.zeros((n_grid, n_grid), dtype=float)
step = 0
diff_norm = 1.0
for step in range(1, max_steps + 1):
# Thom's 2nd-order no-slip wall vorticity boundary conditions (top wall y=L moves at +U_lid):
omega[0, :] = -2.0 * psi[1, :] / (h**2)
omega[-1, :] = -2.0 * psi[-2, :] / (h**2)
omega[:, 0] = -2.0 * psi[:, 1] / (h**2)
omega[:, -1] = -2.0 * (psi[:, -2] + h * float(U_lid)) / (h**2)
u_in = (psi[1:-1, 2:] - psi[1:-1, :-2]) / (2.0 * h)
v_in = -(psi[2:, 1:-1] - psi[:-2, 1:-1]) / (2.0 * h)
# Central advection and viscous Laplacian of the interior vorticity:
dom_dx = (omega[2:, 1:-1] - omega[:-2, 1:-1]) / (2.0 * h)
dom_dy = (omega[1:-1, 2:] - omega[1:-1, :-2]) / (2.0 * h)
lap_om = (
omega[2:, 1:-1]
+ omega[:-2, 1:-1]
+ omega[1:-1, 2:]
+ omega[1:-1, :-2]
- 4.0 * omega[1:-1, 1:-1]
) / (h**2)
omega_new_in = omega[1:-1, 1:-1] + dt_use * (-(u_in * dom_dx + v_in * dom_dy) + nu * lap_om)
diff_norm = float(np.max(np.abs(omega_new_in - omega[1:-1, 1:-1])) / dt_use)
omega[1:-1, 1:-1] = omega_new_in
# Exact direct DST-I solve of -lap_h(psi) = omega on interior nodes:
psi[1:-1, 1:-1] = poisson_2d_fast_sine(omega[1:-1, 1:-1], dx=h, dy=h)
if diff_norm < tol and step > 50:
break
u = np.zeros_like(psi)
v = np.zeros_like(psi)
u[1:-1, 1:-1] = (psi[1:-1, 2:] - psi[1:-1, :-2]) / (2.0 * h)
v[1:-1, 1:-1] = -(psi[2:, 1:-1] - psi[:-2, 1:-1]) / (2.0 * h)
u[:, -1] = float(U_lid)
mid = n_grid // 2
return {
"x": x,
"y": y,
"u": u,
"v": v,
"psi": psi,
"vorticity": omega,
"u_vertical_centerline": u[mid, :],
"v_horizontal_centerline": v[:, mid],
"steps": step,
"residual_rate": diff_norm,
"psi_min": float(np.min(psi)),
}
Max interior |du/dx + dv/dy| from streamfunction : 1.360e-15
Max interior |-lap_h(psi) - omega| (DST-I exact) : 9.037e-14
Exercises¶
Worked solutions are in 14_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Evaluate Thom’s bottom-wall vorticity formula across on two analytical streamfunctions satisfying : (a) symmetric () and (b) cubic-shear (). Verify observed convergence orders and from Taylor’s remainder theorem.
Find how it fails. Verify that
navier_stokes.lid_driven_cavity_2draisesValueErrorfor invalid inputs (n_grid=5,Re=0.0,U_lid=-1.0), and demonstrate onn_grid=33, Re=50() that automatic time-stepping (dt=None) converges stably while forcingdt=0.04() blows up.Implement it yourself. Implement
my_lid_cavity_step(psi, omega, h, nu, dt, U_lid)in pure NumPy usingelliptic_multigrid.poisson_2d_fast_sine, evolve 150 steps from rest onn_grid=25, Re=100at the exact autodt = min(0.22*h^2/nu, 0.35*h/U_lid), and verify< 1e-13agreement withnavier_stokes.lid_driven_cavity_2d(n_grid=25, Re=100, max_steps=150, tol=1e-12).
heading("Self-check for the exercises")
sc_errs = []
for h_sc in [1.0 / 32.0, 1.0 / 64.0]:
x_sc = np.linspace(0.0, 1.0, int(round(1.0 / h_sc)) + 1)
psi_row1 = (np.sin(np.pi * h_sc) ** 2) * np.sin(np.pi * x_sc)
om_thom_sc = -2.0 * psi_row1 / (h_sc**2)
om_exact_sc = -2.0 * (np.pi**2) * np.sin(np.pi * x_sc)
sc_errs.append(float(np.max(np.abs(om_thom_sc - om_exact_sc))))
print(f"h = {h_sc:.5f} | max |omega_Thom - omega_exact| = {sc_errs[-1]:.5e}")
assert sc_errs[-1] < 2e-2 and np.isclose(sc_errs[0] / sc_errs[1], 4.0, atol=0.02)
print("All checks passed.")
Self-check for the exercises
============================
h = 0.03125 | max |omega_Thom - omega_exact| = 6.33359e-02
h = 0.01562 | max |omega_Thom - omega_exact| = 1.58493e-02
All checks passed.