Worked solutions to the three exercises of Lecture 16. 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: Exact Slit Permeability Benchmark & Zero-Remeshing Cylinder Wake")
# 1) Exact slit-pore permeability verification at tau_magic:
nx_s, ny_s = 4, 12
mask_slit = np.zeros((nx_s, ny_s), dtype=bool)
mask_slit[:, 0] = True
mask_slit[:, -1] = True
tau_mg = 0.5 + np.sqrt(3.0) / 4.0
slit_sim = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(mask_slit, tau=tau_mg, body_force_x=1.0e-5, n_steps=450)
H_slit = float(ny_s - 2)
k_slit_cont = slit_sim["porosity"] * (H_slit**2) / 12.0
# Exact midpoint Riemann sum of parabola eta*(H - eta)/(2*nu) across H discrete lattice rows adds +1/2 to H^2:
k_slit_disc = slit_sim["porosity"] * (H_slit**2 + 0.5) / 12.0
print(f"Slit channel (H={H_slit:.0f}, eps={slit_sim['porosity']:.4f}): k_LBM = {slit_sim['darcy_permeability_lu2']:.6f} vs disc-exact = {k_slit_disc:.6f} (cont = {k_slit_cont:.6f}) lu^2")
assert np.isclose(slit_sim["darcy_permeability_lu2"], k_slit_disc, rtol=3e-3)
assert np.isclose(slit_sim["darcy_permeability_lu2"], k_slit_cont, rtol=6e-3)
# 2) Circular cylinder inside a walled microchannel (nx=44, ny=22):
nx_c, ny_c = 44, 22
Xg, Yg = np.meshgrid(np.arange(nx_c), np.arange(ny_c), indexing="ij")
mask_cyl = (Xg - 13.0) ** 2 + (Yg - 10.5) ** 2 <= (3.6**2)
mask_cyl[:, 0] = True
mask_cyl[:, -1] = True
cyl_sim = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(mask_cyl, tau=0.72, body_force_x=2.5e-5, n_steps=260)
spd_cyl = np.hypot(cyl_sim["ux"], cyl_sim["uy"])
re_cyl = constants.reynolds_number(u_m_s=float(np.max(spd_cyl)), L_m=7.2, nu_m2_s=lattice_boltzmann.lbm_viscosity_from_tau(0.72))
print(f"Cylinder-in-channel: porosity = {cyl_sim['porosity']:.4f}, k = {cyl_sim['darcy_permeability_lu2']:.3f} lu^2, peak Re_D = {re_cyl:.2f}")
assert np.all(spd_cyl[mask_cyl] == 0.0) and cyl_sim["darcy_permeability_lu2"] < slit_sim["darcy_permeability_lu2"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.2, 3.8))
spd_plot = np.where(mask_cyl, np.nan, spd_cyl * 1e2)
im1 = ax1.imshow(spd_plot.T, origin="lower", cmap="plasma", aspect="auto")
plt.colorbar(im1, ax=ax1, label=r"Speed $|\mathbf{u}| \times 10^2$ [lu/ts]")
ax1.set_xlabel("$x$ [lu]")
ax1.set_ylabel("$y$ [lu]")
ax1.set_title("Voxel-Masked Cylinder Speed Field (Solid = White)")
vort_plot = np.where(mask_cyl, np.nan, cyl_sim["vorticity"] * 1e3)
im2 = ax2.imshow(vort_plot.T, origin="lower", cmap="RdBu_r", aspect="auto", vmin=-6, vmax=6)
plt.colorbar(im2, ax=ax2, label=r"Vorticity $\omega \times 10^3$ [1/ts]")
ax2.set_xlabel("$x$ [lu]")
ax2.set_ylabel("$y$ [lu]")
ax2.set_title("Antisymmetric Boundary-Layer & Cylinder-Shoulder Vorticity")
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. On a lattice at , construct masks for identical parallel slit pores of aperture so all three masks share identical porosity . Verify via simulate_lbm_obstacle_flow_2d that each permeability matches the exact discrete midpoint parabola identity to < 0.2%.
heading("Exercise 1: Pore-Aperture Scaling k_disc = eps * (h_p^2 + 1/2) / 12 at Identical Porosity eps = 2/3")
tau_ex1 = 0.5 + np.sqrt(3.0) / 4.0
configs = [
(1, 8, [(2, 10)], 400),
(2, 4, [(1, 5), (7, 11)], 180),
(4, 2, [(1, 3), (4, 6), (7, 9), (10, 12)], 120),
]
k_measured = []
for n_pores, h_p, spans, steps in configs:
mask_p = np.ones((4, 12), dtype=bool)
for j0, j1 in spans:
mask_p[:, j0:j1] = False
res_p = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(mask_p, tau=tau_ex1, body_force_x=1.0e-5, n_steps=steps)
k_disc_ex = (2.0 / 3.0) * (h_p**2 + 0.5) / 12.0
k_cont_ex = (2.0 / 3.0) * (h_p**2) / 12.0
k_measured.append(res_p["darcy_permeability_lu2"])
print(f"M={n_pores} pores (h_p={h_p:2d} lu, eps={res_p['porosity']:.4f}) | k_LBM = {res_p['darcy_permeability_lu2']:7.4f} | disc-exact = {k_disc_ex:7.4f} (cont = {k_cont_ex:7.4f})")
assert np.isclose(res_p["porosity"], 2.0 / 3.0, rtol=1e-15)
assert np.isclose(res_p["darcy_permeability_lu2"], k_disc_ex, rtol=2e-3)
assert k_measured[0] > 3.8 * k_measured[1] and k_measured[0] > 14.0 * k_measured[2]
Exercise 1: Pore-Aperture Scaling k_disc = eps * (h_p^2 + 1/2) / 12 at Identical Porosity eps = 2/3
===================================================================================================
M=1 pores (h_p= 8 lu, eps=0.6667) | k_LBM = 3.5829 | disc-exact = 3.5833 (cont = 3.5556)
M=2 pores (h_p= 4 lu, eps=0.6667) | k_LBM = 0.9167 | disc-exact = 0.9167 (cont = 0.8889)
M=4 pores (h_p= 2 lu, eps=0.6667) | k_LBM = 0.2500 | disc-exact = 0.2500 (cont = 0.2222)
Explanation. Porosity alone never uniquely determines permeability. Splitting one fracture into four micro-pores preserves void fraction identically, yet quadruples the wetted no-slip wall surface area and reduces permeability by (where the reflects exact midpoint summation ).
Exercise 2¶
Problem. Verify that simulate_lbm_obstacle_flow_2d raises ValueError for an all-solid mask, a 1-D mask, or tau <= 0.5, and compare body_force_x = 1e-5 vs 3e-3 through a constricted pore throat (20 x 16 domain) to show how violating produces artificial density compression.
heading("Exercise 2: Obstacle Mask Validation Guards & High-Mach Orifice Compressibility check")
for bad_mask, bad_tau in [
(np.ones((12, 12), dtype=bool), 0.8),
(np.zeros(12, dtype=bool), 0.8),
(np.zeros((12, 12), dtype=bool), 0.5),
]:
caught = False
try:
lattice_boltzmann.simulate_lbm_obstacle_flow_2d(bad_mask, tau=bad_tau, n_steps=10)
except ValueError:
caught = True
assert caught is True
# Constricted orifice mask on 20x16 grid:
mk_orif = np.zeros((20, 16), dtype=bool)
mk_orif[:, 0] = mk_orif[:, -1] = True
mk_orif[8:12, :5] = True
mk_orif[8:12, 11:] = True
low_f = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(mk_orif, tau=0.80, body_force_x=1.0e-5, n_steps=200)
hi_f = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(mk_orif, tau=0.80, body_force_x=3.0e-3, n_steps=200)
cs = np.sqrt(lattice_boltzmann.CS2)
ma_low = float(np.max(np.hypot(low_f["ux"], low_f["uy"])) / cs)
ma_hi = float(np.max(np.hypot(hi_f["ux"], hi_f["uy"])) / cs)
drho_low = float(np.max(low_f["rho"]) - np.min(low_f["rho"]))
drho_hi = float(np.max(hi_f["rho"]) - np.min(hi_f["rho"]))
print(f"Low forcing (F=1e-5): Ma_max = {ma_low:.4f}, delta_rho/rho0 = {drho_low:.4e}")
print(f"High forcing (F=3e-3): Ma_max = {ma_hi:.4f}, delta_rho/rho0 = {drho_hi:.4f} (> 6% compressibility artifact)")
assert ma_low < 0.02 and drho_low < 1e-3
assert ma_hi > 0.30 and drho_hi > 0.06
Exercise 2: Obstacle Mask Validation Guards & High-Mach Orifice Compressibility check
=====================================================================================
Low forcing (F=1e-5): Ma_max = 0.0018, delta_rho/rho0 = 5.3823e-04
High forcing (F=3e-3): Ma_max = 0.5138, delta_rho/rho0 = 0.1876 (> 6% compressibility artifact)
Explanation. Because isothermal LBM links pressure to density via , driving a large pressure drop across a tight orifice creates a density variation , which reaches at the larger force. Keeping () holds compressibility error below –.
Exercise 3¶
Problem. Implement analyze_porous_fibrous_bed(mask, tau=0.80, fx=1.2e-5, n_steps=220) returning porosity, u_interstitial, tortuosity, and darcy_k. Compare a straight slit channel against a staggered 4-fiber bed on 24 x 24, verifying for the straight slit and for the staggered fiber bed.
heading("Exercise 3: Implement It Yourself — Tortuosity & Interstitial Velocity Analyzer for Fibrous Media")
def analyze_porous_fibrous_bed(mask: np.ndarray, tau: float = 0.80, fx: float = 1.2e-5, n_steps: int = 220) -> dict:
"""Run D2Q9 porous-media simulation and extract interstitial velocity, hydraulic tortuosity, and Darcy k."""
sim = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(mask, tau=tau, body_force_x=fx, n_steps=n_steps)
eps = sim["porosity"]
u_int = sim["superficial_velocity"] / eps
spd_sum = float(np.sum(np.hypot(sim["ux"], sim["uy"])))
ux_sum = float(np.sum(sim["ux"]))
tort = spd_sum / ux_sum
return {
"porosity": eps,
"u_interstitial": u_int,
"tortuosity": tort,
"darcy_k": sim["darcy_permeability_lu2"],
}
# 1) Straight slit channel (uy == 0 everywhere -> exact tortuosity T == 1.0):
mk_straight = np.zeros((8, 12), dtype=bool)
mk_straight[:, 0] = mk_straight[:, -1] = True
st_res = analyze_porous_fibrous_bed(mk_straight, n_steps=220)
# 2) Staggered 4-fiber bed on 24x24 periodic domain:
Xf, Yf = np.meshgrid(np.arange(24), np.arange(24), indexing="ij")
centers = [(6.0, 6.0), (6.0, 18.0), (18.0, 12.0), (18.0, 0.0)]
mk_fibers = np.zeros((24, 24), dtype=bool)
for cx, cy in centers:
dx_p = np.minimum(np.abs(Xf - cx), 24.0 - np.abs(Xf - cx))
dy_p = np.minimum(np.abs(Yf - cy), 24.0 - np.abs(Yf - cy))
mk_fibers |= (dx_p**2 + dy_p**2) <= (3.6**2)
fib_res = analyze_porous_fibrous_bed(mk_fibers, n_steps=220)
print(f"Straight slit : eps={st_res['porosity']:.3f}, T={st_res['tortuosity']:.8f}, k={st_res['darcy_k']:.4f} lu^2")
print(f"Staggered fibers: eps={fib_res['porosity']:.3f}, T={fib_res['tortuosity']:.6f}, k={fib_res['darcy_k']:.4f} lu^2")
assert np.isclose(st_res["tortuosity"], 1.0, atol=1e-12)
assert fib_res["tortuosity"] > 1.05 and fib_res["u_interstitial"] > 0.0
Exercise 3: Implement It Yourself — Tortuosity & Interstitial Velocity Analyzer for Fibrous Media
=================================================================================================
Straight slit : eps=0.833, T=1.00000000, k=6.1604 lu^2
Staggered fibers: eps=0.743, T=1.092615, k=1.5546 lu^2
Summary. Digital rock physics and electrode microstructure design rely on this exact workflow: voxelize 2-D/3-D tomography into boolean masks, run low-Mach Stokes LBM, and extract directly without generating unstructured meshes. Lecture 17 combines these tools with the finite-volume and multigrid solvers of the earlier lectures in a closing project.