Worked solutions to the three exercises of Lecture 4. 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: Overflow-Safe Analytical Outflow/Inflow Boundary Layers Across Pe")
xg = np.linspace(0.0, 1.0, 400)
pe_list = [-40.0, 1.0e-9, 5.0, 25.0, 200.0, 800.0]
for pe in pe_list:
phi_ex = convection_diffusion.exact_steady_convection_diffusion_1d(xg, L=1.0, u=pe, Gamma=1.0, phi_0=0.0, phi_L=1.0)
assert np.all(np.isfinite(phi_ex))
assert np.isclose(phi_ex[0], 0.0, atol=1e-14) and np.isclose(phi_ex[-1], 1.0, atol=1e-14)
x_90 = float(xg[np.searchsorted(phi_ex, 0.90)]) if pe > 0 else float(xg[np.searchsorted(phi_ex, 0.10)])
print(f"Pe = {pe:8.1e} | phi(0.5) = {phi_ex[200]:.6e} | 90% transition x = {x_90:.4f}")
# Verify Pe -> 0 linear limit:
phi_zero = convection_diffusion.exact_steady_convection_diffusion_1d(xg, L=1.0, u=1.0e-10, Gamma=1.0, phi_0=2.0, phi_L=5.0)
assert np.allclose(phi_zero, 2.0 + 3.0 * xg, atol=1e-9)
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify nodal machine-precision exactness () of scheme="exponential" on cells across , and verify reflection symmetry across all five schemes.
heading("Exercise 1: Scharfetter-Gummel Nodal Exactness & Flow-Reversal Symmetry")
for pe_val in (-80.0, -10.0, -1.0, 0.0, 1.0, 10.0, 80.0):
out_e = convection_diffusion.fvm_convection_diffusion_1d(8, 1.0, pe_val, 1.0, 0.0, 1.0, scheme="exponential")
print(f"Exponential scheme (N=8, Pe={pe_val:+6.1f}) | max centroid error = {out_e['max_error']:.2e}")
assert out_e["max_error"] < 1.0e-13
for sc in ("central", "upwind", "hybrid", "power_law", "exponential"):
fwd = convection_diffusion.fvm_convection_diffusion_1d(12, 1.0, 36.0, 1.0, phi_0=0.0, phi_L=1.0, scheme=sc)
rev = convection_diffusion.fvm_convection_diffusion_1d(12, 1.0, -36.0, 1.0, phi_0=1.0, phi_L=0.0, scheme=sc)
sym_err = float(np.max(np.abs(rev["phi"] - fwd["phi"][::-1])))
print(f"Flow-reversal symmetry ({sc:11s}): max |phi_rev(x) - phi_fwd(L-x)| = {sym_err:.2e}")
assert sym_err < 1.0e-13
Exercise 1: Scharfetter-Gummel Nodal Exactness & Flow-Reversal Symmetry
=======================================================================
Exponential scheme (N=8, Pe= -80.0) | max centroid error = 1.11e-16
Exponential scheme (N=8, Pe= -10.0) | max centroid error = 6.66e-16
Exponential scheme (N=8, Pe= -1.0) | max centroid error = 9.99e-16
Exponential scheme (N=8, Pe= +0.0) | max centroid error = 1.67e-16
Exponential scheme (N=8, Pe= +1.0) | max centroid error = 3.33e-16
Exponential scheme (N=8, Pe= +10.0) | max centroid error = 1.11e-16
Exponential scheme (N=8, Pe= +80.0) | max centroid error = 8.67e-19
Flow-reversal symmetry (central ): max |phi_rev(x) - phi_fwd(L-x)| = 3.47e-18
Flow-reversal symmetry (upwind ): max |phi_rev(x) - phi_fwd(L-x)| = 1.39e-17
Flow-reversal symmetry (hybrid ): max |phi_rev(x) - phi_fwd(L-x)| = 0.00e+00
Flow-reversal symmetry (power_law ): max |phi_rev(x) - phi_fwd(L-x)| = 2.78e-17
Flow-reversal symmetry (exponential): max |phi_rev(x) - phi_fwd(L-x)| = 1.73e-18
Explanation. Between any two grid nodes, the homogeneous 1-D flux is constant; integrating that two-point ODE analytically yields the exact Scharfetter–Gummel interface flux, making "exponential" exact at all centroids on any 1-D grid when sources vanish.
Exercise 2¶
Problem. Verify the oscillation threshold of scheme="central" across on cells, and check numerically that "upwind" at () matches the exact analytical profile at over more closely than at true .
heading("Exercise 2: Central-Difference Wiggle Threshold & Upwind Modified-Diffusivity Proof")
N_c = 12
for pe_dx in (1.5, 1.99, 2.5, 5.0, 8.0):
u_c = pe_dx * N_c # L=1, Gamma=1 => Pe_dx = u / N
res_c = convection_diffusion.fvm_convection_diffusion_1d(N_c, 1.0, u_c, 1.0, scheme="central")
print(f"Central Pe_dx = {pe_dx:4.2f} | min(phi) = {np.min(res_c['phi']):+10.6f} | bounded = {res_c['bounded_no_overshoot']}")
if pe_dx <= 2.0:
assert res_c["bounded_no_overshoot"] is True
else:
assert res_c["bounded_no_overshoot"] is False and np.min(res_c["phi"]) < -1.0e-3
# Upwind artificial viscosity audit: u=1, L=1, N=200 (dx=0.005) -> Gamma_num = u*dx/2 = 0.0025
u_up, L_up, N_up, Gamma_phys = 1.0, 1.0, 200, 0.02
Gamma_eff = Gamma_phys + 0.5 * u_up * (L_up / N_up) # 0.02 + 0.0025 = 0.0225
res_up = convection_diffusion.fvm_convection_diffusion_1d(N_up, L_up, u_up, Gamma_phys, scheme="upwind")
phi_ex_eff = convection_diffusion.exact_steady_convection_diffusion_1d(res_up["x_centers"], L_up, u_up, Gamma_eff)
err_vs_true_gamma = res_up["max_error"]
err_vs_eff_gamma = float(np.max(np.abs(res_up["phi"] - phi_ex_eff)))
print(f"\nUpwind (Gamma=0.02, Gamma_num=0.0025): error vs true Gamma=0.02 PDE = {err_vs_true_gamma:.4e} | error vs inflated Gamma_eff=0.0225 PDE = {err_vs_eff_gamma:.4e}")
assert err_vs_true_gamma > 6.0 * err_vs_eff_gamma
Exercise 2: Central-Difference Wiggle Threshold & Upwind Modified-Diffusivity Proof
===================================================================================
Central Pe_dx = 1.50 | min(phi) = +0.000000 | bounded = True
Central Pe_dx = 1.99 | min(phi) = +0.000000 | bounded = True
Central Pe_dx = 2.50 | min(phi) = -0.025641 | bounded = False
Central Pe_dx = 5.00 | min(phi) = -0.111110 | bounded = False
Central Pe_dx = 8.00 | min(phi) = -0.332796 | bounded = False
Upwind (Gamma=0.02, Gamma_num=0.0025): error vs true Gamma=0.02 PDE = 3.9436e-02 | error vs inflated Gamma_eff=0.0225 PDE = 5.9504e-03
Explanation. Even on cells (), first-order "upwind" in effect solves the inflated diffusivity ( artificial diffusion), matching the analytical curve closer than the true PDE.
Exercise 3¶
Problem. Implement fvm_convection_diffusion_reaction_1d(n_cells, L, u, Gamma, k_react, source, phi_0, phi_L, scheme="power_law") solving , and verify against the exact analytical characteristic-root solution for .
heading("Exercise 3: Implement It Yourself — 1-D Axial-Dispersion Convection-Diffusion-Reaction Solver")
def fvm_convection_diffusion_reaction_1d(
n_cells: int,
L: float,
u: float,
Gamma: float,
k_react: float = 0.0,
source: float = 0.0,
phi_0: float = 0.0,
phi_L: float = 0.0,
scheme: str = "power_law",
) -> dict:
"""Solve steady 1-D u*phi_x = Gamma*phi_xx - k_react*phi + source on n_cells uniform control volumes."""
dx = float(L) / int(n_cells)
xc = (np.arange(n_cells, dtype=float) + 0.5) * dx
f_c = float(u)
d_i = float(Gamma) / dx
pe_c = f_c / d_i
a_w = d_i * convection_diffusion._peclet_weighting_A(abs(pe_c), scheme) + max(f_c, 0.0)
a_e = d_i * convection_diffusion._peclet_weighting_A(abs(pe_c), scheme) + max(-f_c, 0.0)
d_b = 2.0 * d_i
a_wb = d_b * convection_diffusion._peclet_weighting_A(0.5 * abs(pe_c), scheme) + max(f_c, 0.0)
a_eb = d_b * convection_diffusion._peclet_weighting_A(0.5 * abs(pe_c), scheme) + max(-f_c, 0.0)
diag = np.full(n_cells, a_w + a_e + float(k_react) * dx)
rhs = np.full(n_cells, float(source) * dx)
diag[0] = a_e + a_wb + float(k_react) * dx; rhs[0] += a_wb * float(phi_0)
diag[-1] = a_w + a_eb + float(k_react) * dx; rhs[-1] += a_eb * float(phi_L)
phi = grids_fvm.solve_tridiagonal(np.full(n_cells - 1, -a_w), diag, np.full(n_cells - 1, -a_e), rhs)
return {"x_centers": xc, "phi": phi}
L_r, u_r, G_r, kr_r, S_r, p0_r, pL_r = 1.0, 2.0, 0.2, 3.0, 1.5, 1.0, 0.2
out_cdr = fvm_convection_diffusion_reaction_1d(100, L_r, u_r, G_r, kr_r, S_r, p0_r, pL_r, scheme="power_law")
# Exact ODE Gamma*phi'' - u*phi' - k_r*phi = -S => particular phi_p = S/k_r + C1*exp(r1*x) + C2*exp(r2*x):
phi_p = S_r / kr_r
disc = np.sqrt(u_r ** 2 + 4.0 * G_r * kr_r)
r1, r2 = (u_r + disc) / (2.0 * G_r), (u_r - disc) / (2.0 * G_r)
M_bc = np.array([[1.0, 1.0], [np.exp(r1 * L_r), np.exp(r2 * L_r)]])
c1, c2 = np.linalg.solve(M_bc, np.array([p0_r - phi_p, pL_r - phi_p]))
xc_cdr = out_cdr["x_centers"]
phi_exact_cdr = phi_p + c1 * np.exp(r1 * xc_cdr) + c2 * np.exp(r2 * xc_cdr)
max_cdr_err = float(np.max(np.abs(out_cdr["phi"] - phi_exact_cdr)))
print(f"1-D Axial-Dispersion CDR max |phi_fvm - phi_exact| (N=100) = {max_cdr_err:.3e}")
assert max_cdr_err < 2.0e-4
Exercise 3: Implement It Yourself — 1-D Axial-Dispersion Convection-Diffusion-Reaction Solver
=============================================================================================
1-D Axial-Dispersion CDR max |phi_fvm - phi_exact| (N=100) = 9.303e-05
Summary. Adding linear reaction increases the main diagonal (k_react >= 0), strengthening diagonal dominance and preserving M-matrix positivity across tubular catalytic reactors.