In finite-volume or finite-element CFD, computing flow through a micro-CT X-ray scan of sandstone, a fibrous battery electrode, or a catalytic packed bed requires generating millions of body-fitted tetrahedral cells around tortuous pore throats. In Lattice Boltzmann CFD, turning any arbitrary pixel/voxel array into no-slip solid obstacles requires zero remeshing: you pass a 2-D boolean obstacle_mask directly to lattice_boltzmann.simulate_lbm_obstacle_flow_2d, and halfway bounce-back enforces across every fluid–solid link. At creeping pore Reynolds numbers (), microscopic viscous shear over thousands of pore walls homogenizes macroscopically into Darcy’s law . In this lecture we verify exact slit-pore analytical permeability, compare bluff-body wakes and hydraulic tortuosity around circular vs. square obstacles, show Stokes-regime Darcy linearity (and audit Forchheimer inertial + lattice-Mach compressibility limits), and map porosity–permeability scaling against the Kozeny–Carman relation.
Learning objectives¶
Verify voxel-masked
lattice_boltzmann.simulate_lbm_obstacle_flow_2dagainst the exact planar slit permeability benchmark [] where porosity .Compare velocity wakes, shear-layer vorticity , and hydraulic tortuosity past circular cylinders versus sharp-edged square obstacles.
Confirm Stokes-regime Darcy linearity ( independent of for ) and diagnose high-driving-force Forchheimer inertia and lattice-Mach compressibility ().
Predict intrinsic permeability across obstacle packing fractions and compare with the classical Kozeny–Carman scaling .
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: Voxel Bounce-Back & Darcy’s Law from Pore-Scale Stokes Flow¶
Consider incompressible flow driven by a uniform body force through a periodic Representative Elementary Volume (REV) of total area containing solid phase (obstacle_mask == True) and pore space (~obstacle_mask) of porosity . Defining the volume-averaged superficial (Darcy) velocity (averaged over total solid + fluid volume) vs. interstitial pore velocity :
The physical units of intrinsic permeability : (, or on the lattice, converting via ).
1.1 Exact Analytical Benchmark: Parallel Slit-Pore Permeability¶
Before inserting curved obstacles, test Eq. (1.1) on a 2-D slit channel of fluid aperture inside total rows (). From Poiseuille’s law, , so , yielding the exact analytical slit permeability:
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()
Demonstration 1: Exact Slit Permeability Benchmark & Zero-Remeshing Cylinder Wake
=================================================================================
Slit channel (H=10, eps=0.8333): k_LBM = 6.968191 vs disc-exact = 6.979167 (cont = 6.944444) lu^2
Cylinder-in-channel: porosity = 0.8678, k = 5.978 lu^2, peak Re_D = 0.52

Figure 16.1. Flow past a cylinder in a channel, driven by a body force. (a) Speed; the solid nodes are white. (b) Vorticity.
What Demonstration 1 shows. In the slit benchmark (H = 10), simulate_lbm_obstacle_flow_2d reproduces the continuum permeability to and matches the exact discrete midpoint parabola quadrature to . Dropping a circular obstacle into the channel (mask_cyl) requires zero mesh generation: fluid accelerates through the narrow upper/lower throats and sheds antisymmetric shear layers off the cylinder shoulders while maintaining on every solid node.
2. Bluff-Body Geometry Comparison & Hydraulic Tortuosity¶
In porous media transport, fluid streamlines cannot travel straight along ; they detour around solid grains, lengthening the average path by the hydraulic tortuosity :
We compare a smooth circular cylinder against a bluff square obstacle of matched frontal blockage height inside a periodic channel.
heading("Demonstration 2: Circular Cylinder vs Square Prism at Matched Frontal Blockage D = 7 lu")
nx_b, ny_b = 32, 21
Xb, Yb = np.meshgrid(np.arange(nx_b), np.arange(ny_b), indexing="ij")
# Construct circular vs square obstacles with identical frontal blockage height D = 7 lu (rows 7..13) + top/bottom walls:
mask_circ = ((Xb - 14.0) ** 2 + (Yb - 10.0) ** 2) <= (3.2**2)
mask_sq = (np.abs(Xb - 14.0) <= 3.0) & (np.abs(Yb - 10.0) <= 3.0) # 7 x 7 = 49 px vs circle = 37 px (bluffer corners)
for mk in (mask_circ, mask_sq):
mk[:, 0] = True
mk[:, -1] = True
sim_circ = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(mask_circ, tau=0.80, body_force_x=1.5e-5, n_steps=240)
sim_sq = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(mask_sq, tau=0.80, body_force_x=1.5e-5, n_steps=240)
tort_circ = float(np.sum(np.hypot(sim_circ["ux"], sim_circ["uy"])) / np.sum(sim_circ["ux"]))
tort_sq = float(np.sum(np.hypot(sim_sq["ux"], sim_sq["uy"])) / np.sum(sim_sq["ux"]))
print(f"Circular obstacle (D=7 lu): eps = {sim_circ['porosity']:.4f}, tortuosity T = {tort_circ:.4f}, k = {sim_circ['darcy_permeability_lu2']:.4f} lu^2")
print(f"Square obstacle (D=7 lu): eps = {sim_sq['porosity']:.4f}, tortuosity T = {tort_sq:.4f}, k = {sim_sq['darcy_permeability_lu2']:.4f} lu^2")
assert tort_circ > 1.02 and tort_sq > 1.02
# At identical frontal blockage D = 7 lu, the flat-faced 7x7 square prism obstructs more volume & exerts higher drag -> lower k
assert sim_sq["darcy_permeability_lu2"] < sim_circ["darcy_permeability_lu2"]
Demonstration 2: Circular Cylinder vs Square Prism at Matched Frontal Blockage D = 7 lu
=======================================================================================
Circular obstacle (D=7 lu): eps = 0.8497, tortuosity T = 1.0293, k = 4.9857 lu^2
Square obstacle (D=7 lu): eps = 0.8318, tortuosity T = 1.0337, k = 3.8971 lu^2
What Demonstration 2 shows. At identical frontal blockage height , the flat-faced square prism blocks corner streamlines that glide smoothly around the circular cylinder shoulders, lowering intrinsic permeability while maintaining .
3. Stokes-Regime Darcy Linearity vs. Inertial & Lattice-Mach Limits¶
Darcy’s law claims is a purely geometric material property of the pore space, independent of the applied pressure gradient . That linearity holds only when two dimensionless numbers stay small:
Pore Reynolds Number : once , quadratic convective wakes add Forchheimer inertial drag (), depressing apparent permeability .
Lattice Mach Number : in weakly compressible LBM (), spatial density variations scale as .
heading("Demonstration 3: Darcy Linearity Plateau vs High-Forcing Forchheimer & Compressibility Regime")
nx_p, ny_p = 20, 20
Xp, Yp = np.meshgrid(np.arange(nx_p), np.arange(ny_p), indexing="ij")
# Staggered 2-grain periodic porous unit cell (no channel walls, pure periodic porous medium):
r_grain = 3.4
mask_rev = (((Xp - 5.0) ** 2 + (Yp - 5.0) ** 2) <= r_grain**2) | (((Xp - 15.0) ** 2 + (Yp - 15.0) ** 2) <= r_grain**2)
forces = [5.0e-6, 5.0e-5, 8.0e-4, 4.0e-3]
nu_rev = lattice_boltzmann.lbm_viscosity_from_tau(0.80)
cs_val = np.sqrt(lattice_boltzmann.CS2)
k_apps, re_pores, machs, drhos = [], [], [], []
print(f"{'F_x [lu/ts^2]':>13s} | {'u_sup [lu/ts]':>13s} | {'Re_p':>8s} | {'Ma_max':>8s} | {'d_rho / rho0':>12s} | {'k_app [lu^2]':>12s}")
print("-" * 80)
for fx in forces:
out_r = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(mask_rev, tau=0.80, body_force_x=fx, n_steps=200)
u_max = float(np.max(np.hypot(out_r["ux"], out_r["uy"])))
re_p = constants.reynolds_number(u_m_s=out_r["superficial_velocity"], L_m=2.0 * r_grain, nu_m2_s=nu_rev)
ma_p = u_max / cs_val
drho = float(np.max(out_r["rho"]) - np.min(out_r["rho"]))
k_apps.append(out_r["darcy_permeability_lu2"])
re_pores.append(re_p)
machs.append(ma_p)
drhos.append(drho)
print(f"{fx:13.1e} | {out_r['superficial_velocity']:13.4e} | {re_p:8.3f} | {ma_p:8.4f} | {drho:12.3e} | {out_r['darcy_permeability_lu2']:12.5f}")
# Verify < 0.2% Darcy invariance in the creeping Stokes regime (10x force span) vs Forchheimer drop at high Re_p:
assert np.isclose(k_apps[0], k_apps[1], rtol=2e-3)
assert k_apps[-1] < 0.90 * k_apps[0], "Inertial Forchheimer drag must reduce apparent permeability at Re_p > 1"
assert drhos[0] < 1e-3 and drhos[-1] > 3e-2
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.0))
ax1.semilogx(forces, np.array(k_apps) / k_apps[0], "bo-", lw=2.1, ms=6.5, label=r"$k_{\mathrm{app}}(F_x) / k_{\mathrm{Stokes}}$")
ax1.axhline(1.0, color="k", ls="--", lw=1.2, label="Exact Darcy linear law")
ax1.set_xlabel("Body force $F_x$ [$\\mathrm{lu/ts^2}$]")
ax1.set_ylabel("Normalized apparent permeability $k_{\\mathrm{app}}/k_0$ [-]")
ax1.set_title("Stokes Darcy Plateau vs. Forchheimer Inertial Drop")
ax1.legend(fontsize=8.5)
ax2.loglog(machs, drhos, "rs-", lw=2.1, ms=6.5, label=r"LBM density span $\rho_{\max} - \rho_{\min}$")
ma_arr = np.array(machs)
ax2.loglog(ma_arr, drhos[1] * (ma_arr / ma_arr[1]) ** 2, "k--", lw=1.6, label=r"slope 2, $\propto \mathrm{Ma}^2$")
ax2.set_xlabel("Peak lattice Mach number $\\mathrm{Ma} = u_{\\max} / c_s$ [-]")
ax2.set_ylabel("Density fluctuation $\\Delta \\rho / \\rho_0$ [-]")
ax2.set_title("Density Variation against Mach Number")
ax2.legend(fontsize=8.5)
label_panels(fig)
plt.show()
Demonstration 3: Darcy Linearity Plateau vs High-Forcing Forchheimer & Compressibility Regime
=============================================================================================
F_x [lu/ts^2] | u_sup [lu/ts] | Re_p | Ma_max | d_rho / rho0 | k_app [lu^2]
--------------------------------------------------------------------------------
5.0e-06 | 2.0011e-04 | 0.014 | 0.0006 | 2.197e-04 | 4.00227
5.0e-05 | 2.0010e-03 | 0.136 | 0.0065 | 2.197e-03 | 4.00204
8.0e-04 | 3.1575e-02 | 2.147 | 0.1039 | 3.596e-02 | 3.94688
4.0e-03 | 1.3263e-01 | 9.019 | 0.4917 | 2.674e-01 | 3.31575

Figure 16.2. (a) Apparent permeability, relative to its value at the smallest force, against the body force: it falls when inertia becomes important. (b) Density variation against the peak lattice Mach number, with a line of slope 2; the computed variation is proportional to the Mach number.
What Demonstration 3 shows. Across a span of creeping-flow driving force ( to ), darcy_permeability_lu2 stays constant to within while . At , and : the apparent permeability is lower because of inertia, and the density varies by . In this forced flow the density variation is proportional to the force, and so to the Mach number, as panel (b) shows; it does not follow the estimate of an unforced flow.
4. Porosity–Permeability Scaling vs. Kozeny–Carman¶
How sensitive is rock or catalyst-bed permeability to grain compaction (shrinking porosity )? The classical Kozeny–Carman equation models a porous medium as tortuous hydraulic tubes of specific surface area , predicting:
We sweep obstacle radius in our staggered porous array and compare LBM permeability directly against Eq. (4.1).
heading("Demonstration 4: Porosity-Permeability Compaction Sweep vs Kozeny-Carman Scaling")
radii = [2.2, 3.2, 4.2, 5.2]
eps_list, k_list = [], []
print(f"{'Grain R [lu]':>12s} | {'Porosity eps':>13s} | {'k_LBM [lu^2]':>14s} | {'eps^3 / (1 - eps)^2':>20s}")
print("-" * 68)
for rad in radii:
mk = (((Xp - 5.0) ** 2 + (Yp - 5.0) ** 2) <= rad**2) | (((Xp - 15.0) ** 2 + (Yp - 15.0) ** 2) <= rad**2)
res_k = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(mk, tau=0.80, body_force_x=1.0e-5, n_steps=200)
eps_v = res_k["porosity"]
kc_factor = (eps_v**3) / ((1.0 - eps_v) ** 2)
eps_list.append(eps_v)
k_list.append(res_k["darcy_permeability_lu2"])
print(f"{rad:12.1f} | {eps_v:13.4f} | {res_k['darcy_permeability_lu2']:14.4f} | {kc_factor:20.3f}")
eps_arr = np.array(eps_list)
k_arr = np.array(k_list)
# Verify strict monotone drop (> 10x permeability loss under grain compaction):
assert np.all(np.diff(k_arr) < 0.0) and (k_arr[0] / k_arr[-1]) > 10.0
kc_fit = k_arr[1] * ((eps_arr**3) / ((1.0 - eps_arr) ** 2)) / ((eps_arr[1] ** 3) / ((1.0 - eps_arr[1]) ** 2))
fig, ax = plt.subplots(figsize=(7.0, 4.1))
ax.semilogy(eps_arr, k_arr, "bo-", lw=2.2, ms=7, label="2-D D2Q9 LBM staggered cylinder array")
ax.semilogy(eps_arr, kc_fit, "r--", lw=2.0, label=r"Kozeny–Carman trend $C\,\varepsilon^3 / (1 - \varepsilon)^2$")
ax.set_xlabel("Porosity $\\varepsilon = |\\Omega_f| / |\\Omega|$ [-]")
ax.set_ylabel("Intrinsic permeability $k$ [$\\mathrm{lu^2}$] (log scale)")
ax.set_title("Permeability against porosity")
ax.legend(fontsize=8.5)
plt.show()
Demonstration 4: Porosity-Permeability Compaction Sweep vs Kozeny-Carman Scaling
================================================================================
Grain R [lu] | Porosity eps | k_LBM [lu^2] | eps^3 / (1 - eps)^2
--------------------------------------------------------------------
2.2 | 0.9350 | 7.9576 | 193.468
3.2 | 0.8150 | 4.0023 | 15.817
4.2 | 0.7150 | 2.1929 | 4.500
5.2 | 0.5700 | 0.6313 | 1.002

Figure 16.3. Permeability against porosity for an array of cylinders (points) and the Kozeny–Carman form with fitted at one point (dashed line). The form does not describe the computed values.
Inside the algorithm¶
What Demonstration 4 shows. Lowering the porosity from to lowers the permeability by a factor of 12.6, from 7.96 to . The Kozeny–Carman factor falls by a factor of 193 over the same range, so it does not describe these data: it was derived for packed beds of touching grains, and a dilute array of cylinders is not one. The cylinders are also resolved by only a few lattice nodes, which adds a discretization error. Below we inspect simulate_lbm_obstacle_flow_2d and verify its exact macroscopic averaging formulas.
Check against the library¶
heading("Inside the Algorithm: lattice_boltzmann.simulate_lbm_obstacle_flow_2d")
print(show_source(lattice_boltzmann.simulate_lbm_obstacle_flow_2d))
# Verify exact consistency of returned dictionary quantities:
nu_chk = lattice_boltzmann.lbm_viscosity_from_tau(0.80)
fx_chk = 1.5e-5
assert np.isclose(sim_circ["porosity"], float(np.mean(~mask_circ)), rtol=1e-15)
assert np.isclose(sim_circ["superficial_velocity"], float(np.mean(sim_circ["ux"])), rtol=1e-15)
assert np.isclose(sim_circ["darcy_permeability_lu2"], nu_chk * sim_circ["superficial_velocity"] / fx_chk, rtol=1e-15)
print("Verified exact consistency of porosity, superficial_velocity, and darcy_permeability_lu2")
Inside the Algorithm: lattice_boltzmann.simulate_lbm_obstacle_flow_2d
=====================================================================
def simulate_lbm_obstacle_flow_2d(
obstacle_mask: np.ndarray,
tau: float = 0.80,
body_force_x: float = 1.5e-5,
n_steps: int = 800,
) -> dict:
"""Simulate 2-D periodic/porous-channel D2Q9 flow past an arbitrary boolean `obstacle_mask` and compute Darcy k."""
solid = np.asarray(obstacle_mask, dtype=bool)
if solid.ndim != 2 or np.all(solid) or tau <= 0.5:
raise ValueError("obstacle_mask must be a 2-D boolean array with at least one fluid node and tau > 0.5.")
nx, ny = solid.shape
nu = lbm_viscosity_from_tau(tau)
rho = np.ones((nx, ny), dtype=float)
ux = np.zeros((nx, ny), dtype=float)
uy = np.zeros((nx, ny), dtype=float)
f = d2q9_equilibrium(rho, ux, uy)
cx_vec = D2Q9_VELOCITIES[:, 0][:, None, None]
cy_vec = D2Q9_VELOCITIES[:, 1][:, None, None]
for _ in range(n_steps):
rho = np.sum(f, axis=0)
ux = (np.sum(cx_vec * f, axis=0) + 0.5 * body_force_x) / rho
uy = np.sum(cy_vec * f, axis=0) / rho
ux[solid] = 0.0
uy[solid] = 0.0
feq = d2q9_equilibrium(rho, ux, uy)
src = _guo_forcing_term(ux, uy, body_force_x, 0.0, tau)
f_post = f - (f - feq) / tau + src
for i in range(9):
f_post[i, solid] = f[D2Q9_OPPOSITE[i], solid]
f = _stream_periodic(f_post)
rho = np.sum(f, axis=0)
ux = (np.sum(cx_vec * f, axis=0) + 0.5 * body_force_x) / rho
uy = np.sum(cy_vec * f, axis=0) / rho
ux[solid] = 0.0
uy[solid] = 0.0
porosity = float(np.mean(~solid))
u_superficial = float(np.mean(ux))
k_darcy = (nu * u_superficial / body_force_x) if abs(body_force_x) > 0.0 else 0.0
dv_dx = np.roll(uy, -1, axis=0) - np.roll(uy, 1, axis=0)
du_dy = np.roll(ux, -1, axis=1) - np.roll(ux, 1, axis=1)
vort = 0.5 * (dv_dx - du_dy)
return {
"rho": rho,
"ux": ux,
"uy": uy,
"vorticity": vort,
"porosity": porosity,
"superficial_velocity": u_superficial,
"darcy_permeability_lu2": float(k_darcy),
}
Verified exact consistency of porosity, superficial_velocity, and darcy_permeability_lu2
Exercises¶
Worked solutions are in 16_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. 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_2dthat each permeability matches the exact discrete midpoint parabola identity to< 0.2%.Find how it fails. Verify that
simulate_lbm_obstacle_flow_2draisesValueErrorfor an all-solid mask, a 1-D mask, ortau <= 0.5, and comparebody_force_x = 1e-5vs3e-3through a constricted pore throat (20 x 16domain) to show how violating produces artificial density compression.Implement it yourself. Implement
analyze_porous_fibrous_bed(mask, tau=0.80, fx=1.2e-5, n_steps=220)returningporosity,u_interstitial,tortuosity, anddarcy_k. Compare a straight slit channel against a staggered 4-fiber bed on24 x 24, verifying for the straight slit and for the staggered fiber bed.
heading("Self-check for the exercises")
tau_m_sc = 0.5 + np.sqrt(3.0) / 4.0
m_wide = np.ones((4, 12), dtype=bool)
m_wide[:, 2:10] = False # 1 channel of width 8 -> eps = 8/12 = 2/3
m_two = np.ones((4, 12), dtype=bool)
for s0 in (1, 7):
m_two[:, s0 : s0 + 4] = False # 2 channels of width 4 -> 8 fluid rows -> eps = 2/3
k_w = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(m_wide, tau=tau_m_sc, body_force_x=1e-5, n_steps=400)["darcy_permeability_lu2"]
k_2 = lattice_boltzmann.simulate_lbm_obstacle_flow_2d(m_two, tau=tau_m_sc, body_force_x=1e-5, n_steps=180)["darcy_permeability_lu2"]
exact_ratio_disc = (8.0**2 + 0.5) / (4.0**2 + 0.5)
print(f"Same porosity eps = 2/3: 1x8-lu slit k = {k_w:.4f} vs 2x4-lu slits k = {k_2:.4f} | ratio = {k_w / k_2:.4f} (disc-exact = {exact_ratio_disc:.4f})")
assert np.isclose(k_w / k_2, exact_ratio_disc, rtol=3e-3)
print("All checks passed.")
Self-check for the exercises
============================
Same porosity eps = 2/3: 1x8-lu slit k = 3.5829 vs 2x4-lu slits k = 0.9167 | ratio = 3.9086 (disc-exact = 3.9091)
All checks passed.