Real environmental and chemical-engineering flows, such as an atmospheric pollutant plume dispersing in an oblique crosswind while undergoing photochemical decay, or a dye patch swirling inside a 2-D vortex, transport scalars simultaneously across multiple spatial dimensions and competing physical mechanisms. Applying 1-D TVD limiters naively one coordinate at a time ( then , Lie splitting) degrades temporal accuracy to whenever directional transport operators fail to commute (). In this lecture we upgrade 1-D TVD advection to second-order 2-D Strang operator splitting (––, tvd_advection.advect_2d_strang_periodic) for incompressible solid-body rotation, and solve steady 2-D finite-volume convection–diffusion–reaction plumes (convection_diffusion.fvm_convection_diffusion_2d_steady) across Péclet and Damköhler regimes.
Learning objectives¶
Derive the Baker–Campbell–Hausdorff commutator error distinguishing first-order Lie (–) splitting from second-order symmetric Strang (––) splitting.
Simulate 2-D incompressible solid-body vortex rotation via
tvd_advection.advect_2d_strang_periodic, showing exact mass conservation and boundedness.Formulate and solve steady 2-D finite-volume convection–diffusion–reaction transport (
convection_diffusion.fvm_convection_diffusion_2d_steady).Quantify Péclet () and Damköhler () plume regimes, audit central-difference M-matrix failure at , and implement a time-reversible 2-D swirling deformation benchmark.
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. Dimensional Operator Splitting & 2-D Solid-Body Rotation¶
Consider 2-D incompressible scalar advection where and (encompassing shear layers and solid-body rotation , ):
Even for linear operators, and do not commute because . By the Baker–Campbell–Hausdorff expansion:
Lie–Trotter (–) Splitting: global error .
Strang (1968) Symmetric (––) Splitting:
Because each 1-D sweep in tvd_advection.advect_2d_strang_periodic is a conservative TVD flux-difference step along a constant-velocity row or column, the composite 2-D Strang step preserves discrete total mass to rounding error and guarantees positivity and boundedness without dimensional CFL degradation.
heading("Demonstration 1: 2-D Solid-Body Vortex Rotation via Strang-Split TVD Transport")
nx_v, ny_v = 64, 64
dx_v = dy_v = 1.0 / nx_v
xc_v = (np.arange(nx_v) + 0.5) * dx_v
yc_v = (np.arange(ny_v) + 0.5) * dy_v
XC_v, YC_v = np.meshgrid(xc_v, yc_v, indexing="ij")
# Compact cosine-bell tracer centered at (0.50, 0.30), orbiting (0.50, 0.50) completely inside [0, 1]^2:
r_bell = np.hypot(XC_v - 0.50, YC_v - 0.30)
r0_bell = 0.14
q0_vort = np.where(r_bell < r0_bell, 0.5 * (1.0 + np.cos(np.pi * r_bell / r0_bell)), 0.0)
omega_rot = 2.0 * np.pi # Exact 1 revolution in T = 1.0 s
u_row_rot = -omega_rot * (yc_v - 0.50)
v_col_rot = +omega_rot * (xc_v - 0.50)
n_steps_rot = 320
dt_rot = 1.0 / n_steps_rot
rot_runs = {}
print(f"{'Limiter':12s} | {'Mass Drift':>11s} | {'Min q':>10s} | {'Peak q_max':>10s} | {'L2 Error (1 rev)':>16s}")
print("-" * 70)
for lim in ["upwind", "minmod", "van_leer", "superbee"]:
out = tvd_advection.advect_2d_strang_periodic(
q0_vort, u_row_rot, v_col_rot, dx=dx_v, dy=dy_v, dt=dt_rot, n_steps=n_steps_rot, limiter=lim
)
rot_runs[lim] = out
l2_e = float(np.sqrt(np.mean((out["final"] - q0_vort) ** 2)))
print(f"{lim:12s} | {out['mass_drift']:11.2e} | {out['min_val']:+10.2e} | {out['max_val']:10.4f} | {l2_e:16.5f}")
assert out["mass_drift"] < 1e-14
assert out["min_val"] >= -1e-13 and out["max_val"] <= 1.0 + 1e-12
assert rot_runs["superbee"]["max_val"] > rot_runs["van_leer"]["max_val"] > rot_runs["minmod"]["max_val"] > rot_runs["upwind"]["max_val"]
assert rot_runs["van_leer"]["max_val"] > 2.2 * rot_runs["upwind"]["max_val"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 4.2))
cf1 = ax1.contourf(XC_v, YC_v, rot_runs["upwind"]["final"], levels=np.linspace(0.0, 1.0, 11), cmap="viridis")
ax1.contour(XC_v, YC_v, q0_vort, levels=[0.2, 0.5, 0.8], colors="white", linestyles="--", linewidths=1.1)
fig.colorbar(cf1, ax=ax1, label="$q(x, y, T)$")
ax1.set_xlabel("$x$ [m]")
ax1.set_ylabel("$y$ [m]")
ax1.set_title(f"1st-Order Upwind ($q_{{\\max}} = {rot_runs['upwind']['max_val']:.2f}$)")
cf2 = ax2.contourf(XC_v, YC_v, rot_runs["van_leer"]["final"], levels=np.linspace(0.0, 1.0, 11), cmap="viridis")
ax2.contour(XC_v, YC_v, q0_vort, levels=[0.2, 0.5, 0.8], colors="white", linestyles="--", linewidths=1.1)
fig.colorbar(cf2, ax=ax2, label="$q(x, y, T)$")
ax2.set_xlabel("$x$ [m]")
ax2.set_ylabel("$y$ [m]")
ax2.set_title(f"Strang + van Leer TVD ($q_{{\\max}} = {rot_runs['van_leer']['max_val']:.2f}$)")
label_panels(fig)
plt.show()
Demonstration 1: 2-D Solid-Body Vortex Rotation via Strang-Split TVD Transport
==============================================================================
Limiter | Mass Drift | Min q | Peak q_max | L2 Error (1 rev)
----------------------------------------------------------------------
upwind | 0.00e+00 | +3.46e-06 | 0.2339 | 0.07519
minmod | 0.00e+00 | +5.12e-12 | 0.5822 | 0.03360
van_leer | 6.94e-18 | +5.21e-16 | 0.7486 | 0.01689
superbee | 6.94e-18 | +9.38e-17 | 0.8919 | 0.00800

Figure 7.1. A cosine bell after one full rotation on a grid. (a) First-order upwind. (b) Strang splitting with the van Leer limiter. The dashed contours show the initial condition.
What Demonstration 1 shows. After a full solid-body rotation on a mesh, first-order upwind lowers the peak of the cosine bell to (a loss of ), whereas Strang-split van_leer and superbee keep 0.75 and 0.89 of the peak and the circular shape (white dashed contours show exact reference) while holding mass conservation to and strict non-negativity .
2. Quantitative Verification of Lie vs. Strang Splitting¶
We verify Equation (1.2) directly on a pair of non-commuting linear transport–reaction operators (where mimics coupled directional advection and cross-stream shear/reaction). Because we can compute the exact matrix exponential via spectral/Taylor series to rounding error, refining isolates the pure operator-splitting error free of spatial discretization error.
heading("Demonstration 2: Baker-Campbell-Hausdorff Order Verification — Lie O(dt) vs Strang O(dt^2)")
def mat_exp_series(M: np.ndarray, terms: int = 28) -> np.ndarray:
"""Evaluate matrix exponential exp(M) to IEEE-754 machine precision via Taylor series."""
out = np.eye(M.shape[0], dtype=float)
term = np.eye(M.shape[0], dtype=float)
for k in range(1, terms + 1):
term = (term @ M) / float(k)
out = out + term
return out
# Non-commuting directional advection-reaction prototype matrices:
A_op = np.array([[-0.4, -1.5, 0.2], [1.5, -0.2, -0.6], [0.0, 0.6, -0.3]], dtype=float)
B_op = np.array([[-0.2, 0.4, -1.2], [-0.4, -0.5, 0.8], [1.2, -0.8, -0.1]], dtype=float)
comm_norm = float(np.linalg.norm(A_op @ B_op - B_op @ A_op))
assert comm_norm > 1.0
T_split = 0.8
y0_vec = np.array([1.0, -0.5, 0.75], dtype=float)
y_exact_split = mat_exp_series((A_op + B_op) * T_split) @ y0_vec
m_steps_list = [8, 16, 32, 64, 128]
err_lie, err_strang = [], []
for m_st in m_steps_list:
dt_s = T_split / m_st
eA_full = mat_exp_series(A_op * dt_s)
eA_half = mat_exp_series(0.5 * A_op * dt_s)
eB_full = mat_exp_series(B_op * dt_s)
step_lie = eB_full @ eA_full
step_strang = eA_half @ eB_full @ eA_half
y_l = np.linalg.matrix_power(step_lie, m_st) @ y0_vec
y_s = np.linalg.matrix_power(step_strang, m_st) @ y0_vec
err_lie.append(float(np.linalg.norm(y_l - y_exact_split)))
err_strang.append(float(np.linalg.norm(y_s - y_exact_split)))
order_lie = float(np.log2(err_lie[-2] / err_lie[-1]))
order_strang = float(np.log2(err_strang[-2] / err_strang[-1]))
print(f"Commutator ||[A, B]|| = {comm_norm:.4f}")
print(f"Observed global order: Lie (X-Y) = {order_lie:.4f} vs Strang (X/2-Y-X/2) = {order_strang:.4f}")
print(f"At M=128 steps: Lie error = {err_lie[-1]:.3e} vs Strang error = {err_strang[-1]:.3e}")
assert np.isclose(order_lie, 1.0, atol=0.03)
assert np.isclose(order_strang, 2.0, atol=0.03)
assert err_strang[-1] < 0.01 * err_lie[-1]
dts_arr = T_split / np.array(m_steps_list, dtype=float)
fig, ax = plt.subplots(figsize=(6.8, 4.0))
ax.loglog(dts_arr, err_lie, "o-", lw=2.0, label=f"Lie $X$-$Y$ Splitting (slope = {order_lie:.2f})")
ax.loglog(dts_arr, err_strang, "s-", lw=2.0, label=f"Strang $X/2$-$Y$-$X/2$ Splitting (slope = {order_strang:.2f})")
ax.set_xlabel(r"Splitting Time Step $\Delta t$ [s]")
ax.set_ylabel(r"Global Splitting Error $\|\mathbf{y}_M - \mathbf{y}_{\mathrm{exact}}\|_2$ [-]")
ax.set_title("Operator-Splitting Convergence Rate for Non-Commuting Transport")
ax.legend()
Demonstration 2: Baker-Campbell-Hausdorff Order Verification — Lie O(dt) vs Strang O(dt^2)
==========================================================================================
Commutator ||[A, B]|| = 3.0274
Observed global order: Lie (X-Y) = 0.9987 vs Strang (X/2-Y-X/2) = 2.0000
At M=128 steps: Lie error = 3.993e-03 vs Strang error = 2.908e-06

Figure 7.2. Error of Lie splitting and of Strang splitting against the time step for two operators that do not commute; the fitted slopes are 1 and 2.
What Demonstration 2 shows. Symmetric Strang splitting achieves an observed order of 2.00, and at its error is about 1400 times smaller than that of Lie splitting, at virtually identical cost (since consecutive interior half-steps share the same cost structure as a single – cycle).
3. Steady 2-D Plume Convection–Diffusion–Reaction (fvm_convection_diffusion_2d_steady)¶
Now consider steady transport of a dissolved chemical species or thermal plume on with crosswind , diffusivity , first-order reaction rate constant , and volumetric source :
Integrating over a finite-volume cell with Patankar’s generalized Péclet conductance yields a positive-coefficient 5-point linear system:
Adding linear decay directly strengthens diagonal dominance of , accelerating Red–Black SOR convergence while attenuating the downstream plume. Two dimensionless groups govern Equation (3.1):
heading("Demonstration 3: Steady 2-D Chemical Plume in an Oblique Crosswind (Da_I Sweep)")
nx_p, ny_p = 48, 48
Lx_p, Ly_p = 1.0, 1.0
u_p, v_p = 1.20, 0.60
Gamma_p = 0.025
speed_p = float(np.hypot(u_p, v_p))
pe_global = constants.peclet_number(speed_p, Lx_p, Gamma_p)
dx_p, dy_p = Lx_p / nx_p, Ly_p / ny_p
xc_p = (np.arange(nx_p) + 0.5) * dx_p
yc_p = (np.arange(ny_p) + 0.5) * dy_p
XC_p, YC_p = np.meshgrid(xc_p, yc_p, indexing="ij")
S_stack = 30.0 * np.exp(-((XC_p - 0.20) ** 2 + (YC_p - 0.20) ** 2) / (2.0 * 0.055**2))
k_rates = [0.0, 2.5, 10.0]
plume_sols = {}
print(f"Global Peclet Pe = {pe_global:.2f}")
print(f"{'k [1/s]':>8s} | {'Da_I':>8s} | {'SOR Iters':>10s} | {'Final Resid':>12s} | {'Peak phi':>10s} | {'Mean phi':>10s}")
print("-" * 72)
for kv in k_rates:
da_i = kv * Lx_p / speed_p
sol = convection_diffusion.fvm_convection_diffusion_2d_steady(
nx=nx_p, ny=ny_p, Lx=Lx_p, Ly=Ly_p, u_vel=u_p, v_vel=v_p, Gamma=Gamma_p,
source=S_stack, k_react=kv, scheme="power_law", tol=1e-10
)
plume_sols[kv] = sol
print(
f"{kv:8.2f} | {da_i:8.3f} | {sol['iterations']:10d} | {sol['residual_history'][-1]:12.2e} | "
f"{np.max(sol['phi']):10.4f} | {np.mean(sol['phi']):10.5f}"
)
assert sol["residual_history"][-1] < 1e-10
assert np.min(sol["phi"]) >= -1e-12
# Discrete comparison principle: higher decay rate k strictly lowers concentration everywhere
assert np.all(plume_sols[10.0]["phi"] <= plume_sols[2.5]["phi"] + 1e-12)
assert np.all(plume_sols[2.5]["phi"] <= plume_sols[0.0]["phi"] + 1e-12)
assert plume_sols[10.0]["iterations"] < plume_sols[0.0]["iterations"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 4.2))
vmax_p = float(np.max(plume_sols[0.0]["phi"]))
cf_a = ax1.contourf(XC_p, YC_p, plume_sols[0.0]["phi"], levels=np.linspace(0.0, vmax_p, 14), cmap="inferno")
fig.colorbar(cf_a, ax=ax1, label=r"$\phi(x, y)$")
ax1.set_xlabel("$x$ [m]")
ax1.set_ylabel("$y$ [m]")
ax1.set_title("Conservative Plume ($k = 0$, $\\mathrm{Da}_{\\mathrm{I}} = 0$)")
cf_b = ax2.contourf(XC_p, YC_p, plume_sols[10.0]["phi"], levels=np.linspace(0.0, vmax_p, 14), cmap="inferno")
fig.colorbar(cf_b, ax=ax2, label=r"$\phi(x, y)$")
ax2.set_xlabel("$x$ [m]")
ax2.set_ylabel("$y$ [m]")
ax2.set_title("Reactive Plume ($k = 10\\ \\mathrm{s}^{-1}$, $\\mathrm{Da}_{\\mathrm{I}} = 7.45$)")
label_panels(fig)
plt.show()
Demonstration 3: Steady 2-D Chemical Plume in an Oblique Crosswind (Da_I Sweep)
===============================================================================
Global Peclet Pe = 53.67
k [1/s] | Da_I | SOR Iters | Final Resid | Peak phi | Mean phi
------------------------------------------------------------------------
0.00 | 0.000 | 120 | 2.03e-13 | 1.9701 | 0.37120
2.50 | 1.863 | 100 | 4.89e-13 | 1.6560 | 0.17885
10.00 | 7.454 | 60 | 8.88e-12 | 1.1576 | 0.05643

Figure 7.3. Steady plume from a source in a uniform diagonal flow, computed with the power-law scheme. (a) Without reaction. (b) With a first-order reaction; the titles give the rate constant and the Damköhler number.
What Demonstration 3 shows. At and , the non-reactive plume stretches diagonally along the wind vector right up to the outflow walls, whereas at () chemical reaction consumes the species within a reaction penetration length , and reduces Red–Black SOR iterations because boosts diagonal dominance.
4. Péclet Thermal Boundary Layers¶
What happens when hot fluid enters from the left wall (, other walls held cold at ) with zero source/reaction () as diffusivity drops across two orders of magnitude ()? We compare Patankar’s power_law against exponential and upwind schemes across boundary-layer thinning .
heading("Demonstration 4: Peclet Sensitivity of 2-D Outflow Boundary-Layer Thickness")
nx_b, ny_b = 40, 40
bcs_hot_left = {"left": 1.0, "right": 0.0, "bottom": 0.0, "top": 0.0}
mid_j = ny_b // 2
for gamma_val in [0.20, 0.04, 0.008]:
pe_x = constants.peclet_number(1.0, 1.0, gamma_val)
pe_cell_x = pe_x / nx_b
s_pl = convection_diffusion.fvm_convection_diffusion_2d_steady(
nx_b, ny_b, 1.0, 1.0, u_vel=1.0, v_vel=0.0, Gamma=gamma_val, bc_walls=bcs_hot_left, scheme="power_law"
)
s_ex = convection_diffusion.fvm_convection_diffusion_2d_steady(
nx_b, ny_b, 1.0, 1.0, u_vel=1.0, v_vel=0.0, Gamma=gamma_val, bc_walls=bcs_hot_left, scheme="exponential"
)
diff_pl_ex = float(np.max(np.abs(s_pl["phi"] - s_ex["phi"])))
phi_mid = float(s_pl["phi"][nx_b // 2, mid_j])
print(f"Pe = {pe_x:6.1f} (Pe_cell = {pe_cell_x:5.3f}) | phi(0.5, 0.5) = {phi_mid:8.5f} | max |PowerLaw - Exp| = {diff_pl_ex:.3e}")
assert 0.0 <= np.min(s_pl["phi"]) and np.max(s_pl["phi"]) <= 1.0 + 1e-12
assert diff_pl_ex < 0.015
Demonstration 4: Peclet Sensitivity of 2-D Outflow Boundary-Layer Thickness
===========================================================================
Pe = 5.0 (Pe_cell = 0.125) | phi(0.5, 0.5) = 0.56374 | max |PowerLaw - Exp| = 2.071e-05
Pe = 25.0 (Pe_cell = 0.625) | phi(0.5, 0.5) = 0.96289 | max |PowerLaw - Exp| = 1.054e-03
Pe = 125.0 (Pe_cell = 3.125) | phi(0.5, 0.5) = 1.00000 | max |PowerLaw - Exp| = 5.263e-03
Inside the algorithm¶
Demonstration 4 shows that the fifth-power approximation (power_law) tracks the exact analytical conductance (exponential) within at the three Péclet numbers tested, without evaluating exponentials.
Below we inspect convection_diffusion.fvm_convection_diffusion_2d_steady and verify exact global integral species conservation:
Check against the library¶
heading("Inside the Algorithm: Global Species Conservation check of fvm_convection_diffusion_2d_steady")
print(show_source(convection_diffusion.fvm_convection_diffusion_2d_steady))
# Verify exact global integral conservation (boundary outflux + reaction sink == source generation):
nx_c, ny_c = 32, 32
Lx_c, Ly_c = 1.0, 1.0
dx_c, dy_c = Lx_c / nx_c, Ly_c / ny_c
u_c, v_c, G_c, k_c = 0.8, -0.4, 0.05, 3.5
bcs_c = {"left": 0.5, "right": 0.1, "bottom": 0.0, "top": 0.25}
S_c = 2.0
sol_c = convection_diffusion.fvm_convection_diffusion_2d_steady(
nx_c, ny_c, Lx_c, Ly_c, u_c, v_c, G_c, source=S_c, k_react=k_c, bc_walls=bcs_c, scheme="power_law", tol=1e-12
)
phi_c = sol_c["phi"]
# Reconstruct exact boundary half-cell conductances used in the FVM balance:
fx_c, fy_c = u_c * dy_c, v_c * dx_c
dxc, dyc = G_c * dy_c / dx_c, G_c * dx_c / dy_c
ax_b = convection_diffusion._peclet_weighting_A(0.5 * abs(fx_c / dxc), "power_law")
ay_b = convection_diffusion._peclet_weighting_A(0.5 * abs(fy_c / dyc), "power_law")
aw_b = 2.0 * dxc * ax_b + max(fx_c, 0.0)
ae_b = 2.0 * dxc * ax_b + max(-fx_c, 0.0)
as_b = 2.0 * dyc * ay_b + max(fy_c, 0.0)
an_b = 2.0 * dyc * ay_b + max(-fy_c, 0.0)
# Exact combined convective + diffusive inward boundary transfer across all 4 walls:
inward_bnd = (
np.sum(aw_b * bcs_c["left"] - (aw_b - fx_c) * phi_c[0, :])
+ np.sum(ae_b * bcs_c["right"] - (ae_b + fx_c) * phi_c[-1, :])
+ np.sum(as_b * bcs_c["bottom"] - (as_b - fy_c) * phi_c[:, 0])
+ np.sum(an_b * bcs_c["top"] - (an_b + fy_c) * phi_c[:, -1])
)
source_tot = S_c * Lx_c * Ly_c
react_sink = float(np.sum(k_c * phi_c * dx_c * dy_c))
global_imbalance = abs(float(inward_bnd) + source_tot - react_sink)
print(f"Net inward wall flux = {inward_bnd:+.6f}, Source = {source_tot:+.6f}, Reaction sink = {react_sink:+.6f}")
print(f"Global species conservation residual = {global_imbalance:.3e}")
assert global_imbalance < 1e-9
Inside the Algorithm: Global Species Conservation check of fvm_convection_diffusion_2d_steady
=============================================================================================
def fvm_convection_diffusion_2d_steady(
nx: int,
ny: int,
Lx: float,
Ly: float,
u_vel: float,
v_vel: float,
Gamma: float,
source: float | np.ndarray = 0.0,
k_react: float = 0.0,
bc_walls: dict | None = None,
scheme: str = "power_law",
tol: float = 1e-10,
max_iter: int = 5000,
) -> dict:
"""Solve 2-D steady FVM convection-diffusion-reaction u*phi_x + v*phi_y = Gamma*lap(phi) - k*phi + S."""
if nx < 3 or ny < 3 or Lx <= 0.0 or Ly <= 0.0 or Gamma <= 0.0 or k_react < 0.0:
raise ValueError("Require nx, ny >= 3, Lx, Ly, Gamma > 0, and k_react >= 0.")
dx = float(Lx) / int(nx)
dy = float(Ly) / int(ny)
xc = (np.arange(nx, dtype=float) + 0.5) * dx
yc = (np.arange(ny, dtype=float) + 0.5) * dy
bcs = {"left": 0.0, "right": 0.0, "bottom": 0.0, "top": 0.0}
if bc_walls is not None:
bcs.update(bc_walls)
fx = float(u_vel) * dy
fy = float(v_vel) * dx
dx_cond = float(Gamma) * dy / dx
dy_cond = float(Gamma) * dx / dy
ax_wt = _peclet_weighting_A(abs(fx / dx_cond), scheme)
ay_wt = _peclet_weighting_A(abs(fy / dy_cond), scheme)
aw = dx_cond * ax_wt + max(fx, 0.0)
ae = dx_cond * ax_wt + max(-fx, 0.0)
as_s = dy_cond * ay_wt + max(fy, 0.0)
an = dy_cond * ay_wt + max(-fy, 0.0)
# Boundary half-cell conductances:
ax_b = _peclet_weighting_A(0.5 * abs(fx / dx_cond), scheme)
ay_b = _peclet_weighting_A(0.5 * abs(fy / dy_cond), scheme)
aw_b = 2.0 * dx_cond * ax_b + max(fx, 0.0)
ae_b = 2.0 * dx_cond * ax_b + max(-fx, 0.0)
as_b = 2.0 * dy_cond * ay_b + max(fy, 0.0)
an_b = 2.0 * dy_cond * ay_b + max(-fy, 0.0)
src = np.full((nx, ny), float(source), dtype=float) if np.ndim(source) == 0 else np.asarray(source, dtype=float)
vol = dx * dy
aw_mat = np.full((nx, ny), aw, dtype=float)
ae_mat = np.full((nx, ny), ae, dtype=float)
as_mat = np.full((nx, ny), as_s, dtype=float)
an_mat = np.full((nx, ny), an, dtype=float)
aw_mat[0, :] = 0.0
ae_mat[-1, :] = 0.0
as_mat[:, 0] = 0.0
an_mat[:, -1] = 0.0
ap_mat = aw_mat + ae_mat + as_mat + an_mat + float(k_react) * vol
b_rhs = src * vol
ap_mat[0, :] += aw_b
b_rhs[0, :] += aw_b * float(bcs["left"])
ap_mat[-1, :] += ae_b
b_rhs[-1, :] += ae_b * float(bcs["right"])
ap_mat[:, 0] += as_b
b_rhs[:, 0] += as_b * float(bcs["bottom"])
ap_mat[:, -1] += an_b
b_rhs[:, -1] += an_b * float(bcs["top"])
phi = np.zeros((nx, ny), dtype=float)
ii, jj = np.meshgrid(np.arange(nx), np.arange(ny), indexing="ij")
red = (ii + jj) % 2 == 0
black = ~red
omega = 1.35
res_hist = []
for it in range(1, max_iter + 1):
for mask in (red, black):
nb_sum = np.zeros_like(phi)
nb_sum[1:, :] += aw_mat[1:, :] * phi[:-1, :]
nb_sum[:-1, :] += ae_mat[:-1, :] * phi[1:, :]
nb_sum[:, 1:] += as_mat[:, 1:] * phi[:, :-1]
nb_sum[:, :-1] += an_mat[:, :-1] * phi[:, 1:]
phi_gs = (nb_sum + b_rhs) / ap_mat
phi[mask] = (1.0 - omega) * phi[mask] + omega * phi_gs[mask]
if it % 20 == 0 or it == 1:
nb_all = np.zeros_like(phi)
nb_all[1:, :] += aw_mat[1:, :] * phi[:-1, :]
nb_all[:-1, :] += ae_mat[:-1, :] * phi[1:, :]
nb_all[:, 1:] += as_mat[:, 1:] * phi[:, :-1]
nb_all[:, :-1] += an_mat[:, :-1] * phi[:, 1:]
res = float(np.max(np.abs(ap_mat * phi - nb_all - b_rhs)))
res_hist.append(res)
if res < tol:
break
return {
"xc": xc,
"yc": yc,
"phi": phi,
"iterations": it,
"residual_history": np.array(res_hist, dtype=float),
}
Net inward wall flux = -0.417372, Source = +2.000000, Reaction sink = +1.582628
Global species conservation residual = 1.532e-11
Exercises¶
Worked solutions are in 07_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify
fvm_convection_diffusion_2d_steady(, , , homogeneous Dirichlet walls on ) against the exact eigenfunction across , asserting error convergence.Find how it fails. Demonstrate cell-Péclet breakdown of
scheme='central'at : show direct-solve unphysical undershoots infvm_convection_diffusion_1d(bounded_no_overshoot == False) and iterative SOR divergence infvm_convection_diffusion_2d_steady(..., max_iter=80), whilepower_lawandexponentialconverge monotonically in .Implement it yourself. Implement
advect_2d_swirl_reversible(q_init, dx, dy, T, n_steps, limiter)using midpoint-evaluated Strang splitting for and on . Verify strong filament deformation at and compare unmixing error acrossupwind,van_leer, andsuperbee.
heading("Self-check for the exercises")
q_chk = np.zeros((16, 16))
q_chk[6:10, 6:10] = 1.0
res_chk = tvd_advection.advect_2d_strang_periodic(
q_chk, np.ones(16), -0.5 * np.ones(16), dx=1.0 / 16, dy=1.0 / 16, dt=0.02, n_steps=20, limiter="van_leer"
)
assert res_chk["mass_drift"] < 1e-14 and res_chk["min_val"] >= -1e-13 and res_chk["max_val"] <= 1.0 + 1e-12
print("2-D Strang mass conservation, positivity, and steady plume checks passed")
print("All checks passed.")
Self-check for the exercises
============================
2-D Strang mass conservation, positivity, and steady plume checks passed
All checks passed.