Worked solutions to the three exercises of Lecture 17. 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("Stage 1: Fluid Screening (FLUIDS_DB) & Planar Microchannel Hydraulic Baseline")
H_ch = 4.0e-4 # 400 um channel height [m]
L_ch = 8.0e-3 # 8 mm reactor length [m]
U_mean = 0.05 # 5 cm/s mean velocity [m/s]
D_mol = 2.0e-9 # Aqueous solute diffusivity [m^2/s]
print(f"{'Fluid':>20s} | {'Pr [-]':>8s} | {'Re_H [-]':>10s} | {'Pe_thermal':>11s} | {'dP/dx [kPa/m]':>14s}")
print("-" * 76)
for fname in ["water_298K", "ethanol_298K", "air_298K", "liquid_sodium_673K"]:
fp = constants.FLUIDS_DB[fname]
re_h = constants.reynolds_number(U_mean, H_ch, fp["nu_m2_s"])
pe_th = constants.peclet_number(U_mean, H_ch, fp["alpha_m2_s"])
dp_dx_mag = 12.0 * fp["mu_Pa_s"] * U_mean / (H_ch**2)
print(f"{fname:>20s} | {fp['Pr']:8.4f} | {re_h:10.3f} | {pe_th:11.3f} | {dp_dx_mag*1e-3:14.3f}")
assert np.isclose(pe_th, re_h * fp["Pr"], rtol=1e-12)
water = constants.FLUIDS_DB["water_298K"]
re_water = constants.reynolds_number(U_mean, H_ch, water["nu_m2_s"])
pe_mass = constants.peclet_number(U_mean, H_ch, D_mol)
dp_dx_water = -12.0 * water["mu_Pa_s"] * U_mean / (H_ch**2) # negative for +x flow
y_prof = np.linspace(0.0, H_ch, 101)
hyd_base = navier_stokes.poiseuille_couette_exact(y=y_prof, H=H_ch, mu=water["mu_Pa_s"], dP_dx=dp_dx_water)
print(f"\nAqueous microreactor: Re_H = {re_water:.2f} (strictly laminar), Mass Peclet Pe_m = {pe_mass:.1f} (diffusion-limited)")
print(f"Poiseuille u_mean = {hyd_base['u_mean']:.5f} m/s, u_max = {np.max(hyd_base['u']):.5f} m/s (exact 1.5*U_m = {1.5*U_mean:.5f})")
print(f"Baseline pressure drop Delta_P = {-dp_dx_water * L_ch:.3f} Pa, wall shear tau_w = {hyd_base['tau_bottom']:.4f} Pa")
assert np.isclose(hyd_base["u_mean"], U_mean, rtol=1e-14)
assert np.isclose(float(np.max(hyd_base["u"])), 1.5 * U_mean, rtol=1e-4)
assert re_water < 30.0 and pe_mass > 5000.0
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify cross-module analytical consistency across three engcfd solvers: (a) fvm_convection_diffusion_1d(..., scheme='exponential') vs 'power_law' at (n_cells=20), (b) simulate_lbm_poiseuille_2d at vs poiseuille_couette_exact, and (c) poisson_2d_multigrid_vcycle vs poisson_2d_fast_sine on a chip cooling Poisson problem.
heading("Exercise 1: Cross-Module Verification Across FVM, LBM, Navier-Stokes & Multigrid/DST Solvers")
# (a) Exponential vs Power-Law 1-D Convection-Diffusion at Pe = 40:
cd_exp = convection_diffusion.fvm_convection_diffusion_1d(n_cells=20, L=1.0, u=1.0, Gamma=0.025, scheme="exponential")
cd_pow = convection_diffusion.fvm_convection_diffusion_1d(n_cells=20, L=1.0, u=1.0, Gamma=0.025, scheme="power_law")
assert cd_exp["max_error"] < 1e-14 and cd_pow["max_error"] < 5e-3 and cd_pow["bounded_no_overshoot"] is True
# (b) D2Q9 LBM at tau_magic vs Analytical Navier-Stokes Poiseuille:
tau_mg = 0.5 + np.sqrt(3.0) / 4.0
fx_v = 1.2e-5
lbm_p = lattice_boltzmann.simulate_lbm_poiseuille_2d(nx=2, ny=8, tau=tau_mg, body_force_x=fx_v, n_steps=450)
ns_p = navier_stokes.poiseuille_couette_exact(y=lbm_p["y_fluid"] - 0.5, H=lbm_p["channel_height"], mu=lbm_p["nu_lb"], dP_dx=-fx_v)
u_mean_lbm = float(np.mean(lbm_p["u_lbm"]))
print(f"1-D Exp FVM err = {cd_exp['max_error']:.2e} | LBM vs NS max rel err = {lbm_p['max_rel_error']:.2e}")
assert np.allclose(lbm_p["u_lbm"], ns_p["u"], rtol=1e-7)
# (c) 2-D Geometric Multigrid V-Cycle vs Exact Fast Sine Solver on 33x33 chip thermal Poisson:
ng_mg = 33
h_mg = 1.0 / (ng_mg - 1)
X_mg, Y_mg = np.meshgrid(np.linspace(0.0, 1.0, ng_mg), np.linspace(0.0, 1.0, ng_mg), indexing="ij")
rhs_chip = np.sin(np.pi * X_mg) * np.sin(2.0 * np.pi * Y_mg)
mg_sol = elliptic_multigrid.poisson_2d_multigrid_vcycle(rhs_chip, L=1.0, n_cycles=12, tol=1e-11)
dst_int = elliptic_multigrid.poisson_2d_fast_sine(rhs_chip[1:-1, 1:-1], dx=h_mg, dy=h_mg)
mg_dst_diff = float(np.max(np.abs(mg_sol["u"][1:-1, 1:-1] - dst_int)))
print(f"Multigrid ({mg_sol['cycles']} V-cycles) vs Fast Sine max |u_MG - u_DST| = {mg_dst_diff:.3e}")
assert mg_dst_diff < 1e-10 and u_mean_lbm > 0.0
Exercise 1: Cross-Module Verification Across FVM, LBM, Navier-Stokes & Multigrid/DST Solvers
============================================================================================
1-D Exp FVM err = 5.55e-17 | LBM vs NS max rel err = 1.50e-08
Multigrid (9 V-cycles) vs Fast Sine max |u_MG - u_DST| = 5.438e-14
Explanation. Three independent numerical paradigms in engcfd, the exponential finite-volume flux, mesoscale D2Q9 kinetic theory at , and Geometric Multigrid vs. Fast Sine transforms, each converge to their analytical or discrete-exact counterparts to significant digits.
Exercise 2¶
Problem. Demonstrate numerically two high-consequence reactor modeling errors: (a) on a 2-cell composite wall (x_faces = [0, 1e-4, 2e-4], k = [1.5, 150.0], left flux J_in = 15,000 W/m^2, right T = 300 K), compare exact harmonic FVM (fvm_diffusion_1d_steady) against naive arithmetic face conductivity to show a error in predicted catalyst temperature rise ; and (b) show that scheme='central' in fvm_convection_diffusion_1d (n_cells=10, L=1.0, u=1.0, Gamma=0.02, ) produces negative concentrations (bounded_no_overshoot == False) while scheme='power_law' preserves .
heading("Exercise 2: Arithmetic Conductivity Error & Central-Difference Peclet Instability")
# Part (a): 2-layer washcoat (k1=1.5) / silicon (k2=150.0) under inward heat flux J_left = 15,000 W/m^2
xf_2 = np.array([0.0, 1.0e-4, 2.0e-4])
k_2 = np.array([1.5, 150.0])
J_in = 15000.0
T_sink = 300.0
harm_sol = grids_fvm.fvm_diffusion_1d_steady(xf_2, k_cells=k_2, q_source=0.0, bc_left=("neumann", J_in), bc_right=("dirichlet", T_sink))
# Exact T at cell 0 center (x = 0.5e-4): T_sink + J_in * (1.0e-4 / 150.0 + 0.5e-4 / 1.5)
dT_c0_exact = J_in * (1.0e-4 / 150.0 + 0.5e-4 / 1.5)
dT_c0_harm = float(harm_sol["phi"][0] - T_sink)
# Naive arithmetic face conductivity k_arith = 0.5*(1.5 + 150.0) = 75.75 across dx_int = 1.0e-4:
k_arith = 0.5 * (k_2[0] + k_2[1])
# Series temperature rise with erroneous arithmetic interface conductance:
T_c1_arith = T_sink + J_in * (0.5e-4 / k_2[1])
dT_c0_arith = (T_c1_arith - T_sink) + J_in * (1.0e-4 / k_arith)
rel_err_arith = abs(dT_c0_arith - dT_c0_exact) / dT_c0_exact
print(f"Catalyst center dT: Exact = {dT_c0_exact:.4f} K | Harmonic FVM = {dT_c0_harm:.4f} K | Arithmetic mean = {dT_c0_arith:.4f} K (err = {rel_err_arith:.1%})")
assert np.isclose(dT_c0_harm, dT_c0_exact, rtol=1e-14)
assert rel_err_arith > 0.90 # Naive arithmetic misses > 90% of the temperature rise
# Part (b): High cell Peclet Pe_dx = 5.0 > 2 oscillatory failure of central differencing:
cd_cen = convection_diffusion.fvm_convection_diffusion_1d(n_cells=10, L=1.0, u=1.0, Gamma=0.02, phi_0=0.0, phi_L=1.0, scheme="central")
cd_plw = convection_diffusion.fvm_convection_diffusion_1d(n_cells=10, L=1.0, u=1.0, Gamma=0.02, phi_0=0.0, phi_L=1.0, scheme="power_law")
print(f"Pe_cell = {cd_cen['cell_peclet']:.1f}: Central min(C) = {np.min(cd_cen['phi']):+.4f} (bounded={cd_cen['bounded_no_overshoot']}) | Power-law min(C) = {np.min(cd_plw['phi']):+.4e} (bounded={cd_plw['bounded_no_overshoot']})")
assert cd_cen["bounded_no_overshoot"] is False and float(np.min(cd_cen["phi"])) < -0.1
assert cd_plw["bounded_no_overshoot"] is True and float(np.min(cd_plw["phi"])) >= 0.0
Exercise 2: Arithmetic Conductivity Error & Central-Difference Peclet Instability
=================================================================================
Catalyst center dT: Exact = 0.5100 K | Harmonic FVM = 0.5100 K | Arithmetic mean = 0.0248 K (err = 95.1%)
Pe_cell = 5.0: Central min(C) = -0.1111 (bounded=False) | Power-law min(C) = +1.0893e-21 (bounded=True)
Explanation. Arithmetic averaging treats the washcoat/silicon interface as if the two materials acted in parallel () rather than in series (), and underpredicts the temperature rise in the catalyst by . Similarly, central differencing at makes the downstream neighbor coefficient , destroying diagonal dominance and creating sawtooth negative concentrations.
Exercise 3¶
Problem. Implement design_conjugate_microreactor(baffle_heights, da_rxn=0.35, q_full_conv=1.2e8) combining simulate_lbm_obstacle_flow_2d, fvm_convection_diffusion_2d_steady, and fvm_diffusion_1d_steady over baffle_heights = [0, 2, 4, 5, 7] on a 32 x 16 channel. Select the optimal baffle height maximizing conversion subject to and peak wall temperature rise , and verify all constraints programmatically.
heading("Exercise 3: Implement It Yourself — Constrained Multi-Physics Microreactor Optimizer")
def design_conjugate_microreactor(
baffle_heights: list[int],
da_rxn: float = 0.35,
q_full_conv: float = 1.2e8,
) -> dict:
"""Evaluate coupled LBM hydraulics + 2-D FVM conversion + 1-D conjugate wall cooling across baffle heights."""
grid_w = grids_fvm.uniform_fvm_grid_1d(0.0, 5.0e-4, n_cells=20)
k_w = np.where(grid_w["x_centers"] < 1.5e-4, 1.6, 148.0)
records = []
k_open = None
for hb in baffle_heights:
mk = np.zeros((32, 16), dtype=bool)
mk[:, 0] = mk[:, -1] = True
if hb > 0:
mk[6:9, 1 : 1 + hb] = True
mk[15:18, 15 - hb : 15] = True
mk[24:27, 1 : 1 + hb] = True
lb = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(mk, tau=0.80, body_force_x=1.5e-5, n_steps=160)
if k_open is None:
k_open = lb["darcy_permeability_lu2"]
dp_pen = k_open / lb["darcy_permeability_lu2"]
mix = float(np.mean(np.abs(lb["uy"])) / lb["superficial_velocity"])
cdr = convection_diffusion.fvm_convection_diffusion_2d_steady(
nx=32, ny=16, Lx=1.0, Ly=0.25, u_vel=1.0, v_vel=0.45 * mix,
Gamma=0.008 + 0.075 * mix, k_react=da_rxn,
bc_walls={"left": 1.0, "right": 0.0, "bottom": 0.0, "top": 0.0}, scheme="power_law", tol=1e-9,
)
conv = 1.0 - float(np.mean(cdr["phi"][-4, :]))
q_arr = np.where(grid_w["x_centers"] < 1.5e-4, conv * q_full_conv, 0.0)
th = grids_fvm.fvm_diffusion_1d_steady(
grid_w["x_faces"], k_cells=k_w, q_source=q_arr,
bc_left=("neumann", 0.0), bc_right=("dirichlet", 300.0),
)
dt_max = float(np.max(th["phi"]) - 300.0)
records.append({"hb": hb, "conversion": conv, "dp_penalty": dp_pen, "dT_max_K": dt_max})
feasible = [r for r in records if r["dp_penalty"] <= 4.0 and r["dT_max_K"] <= 1.5]
best = max(feasible, key=lambda r: r["conversion"])
return {"records": records, "optimal": best}
opt_res = design_conjugate_microreactor([0, 2, 4, 5, 7])
for rec in opt_res["records"]:
print(f"h_b = {rec['hb']} lu | X = {rec['conversion']:.4f} | dP/dP_0 = {rec['dp_penalty']:5.2f}x | dT_max = {rec['dT_max_K']:.4f} K")
best_cfg = opt_res["optimal"]
print(f"\nSelected optimal design: h_b = {best_cfg['hb']} lu (X = {best_cfg['conversion']:.4f}, dP/dP_0 = {best_cfg['dp_penalty']:.2f}x <= 4.0x, dT_max = {best_cfg['dT_max_K']:.3f} K <= 1.5 K)")
assert best_cfg["hb"] in (4, 5)
assert best_cfg["conversion"] > opt_res["records"][0]["conversion"] + 0.15
assert best_cfg["dp_penalty"] <= 4.0 and best_cfg["dT_max_K"] <= 1.5
Exercise 3: Implement It Yourself — Constrained Multi-Physics Microreactor Optimizer
====================================================================================
h_b = 0 lu | X = 0.8025 | dP/dP_0 = 1.00x | dT_max = 0.7113 K
h_b = 2 lu | X = 0.9260 | dP/dP_0 = 1.23x | dT_max = 0.8208 K
h_b = 4 lu | X = 0.9783 | dP/dP_0 = 1.94x | dT_max = 0.8671 K
h_b = 5 lu | X = 0.9883 | dP/dP_0 = 2.63x | dT_max = 0.8760 K
h_b = 7 lu | X = 0.9962 | dP/dP_0 = 5.38x | dT_max = 0.8830 K
Selected optimal design: h_b = 5 lu (X = 0.9883, dP/dP_0 = 2.63x <= 4.0x, dT_max = 0.876 K <= 1.5 K)
Summary of Exercise 3 and of the course. The 18 lectures have built the following methods in NumPy: finite-volume conservation & harmonic conductance, Peclet & Sweby TVD shock-capturing schemes, Fast Sine & Geometric Multigrid elliptic solvers, exact Riemann solvers for Burgers/Shallow-Water/Euler shocks, Chorin & staggered MAC Navier–Stokes projection, Ghia-verified vorticity–streamfunction cavities, and mesoscale D2Q9 Lattice Boltzmann porous-media and conjugate microreactor engineering.