Lectures 12–14 followed the classical continuum CFD paradigm: discretize the macroscopic Navier–Stokes PDEs directly and pay an elliptic global Poisson tax at every step. The Lattice Boltzmann Method (LBM) flips CFD upside down by stepping one level deeper to mesoscale kinetic theory: instead of tracking and , we evolve nine discrete particle velocity populations on a Cartesian lattice via two embarrassingly local operations, algebraic BGK collision at each node and exact shift-streaming to nearest/diagonal neighbors. Through Sydney Chapman and David Enskog’s multiscale expansion, the macroscopic incompressible Navier–Stokes equations emerge automatically with kinematic viscosity . In this lecture we verify D2Q9 Gauss–Hermite quadrature isotropy, moment conservation of lattice_boltzmann.d2q9_equilibrium, Boltzmann’s H-theorem stability barrier (), Guo’s exact 2nd-order body forcing, halfway bounce-back walls, and the “magic” relaxation time in lattice_boltzmann.simulate_lbm_poiseuille_2d.
Learning objectives¶
Verify 2nd- and 4th-order Gauss–Hermite quadrature isotropy of
D2Q9_VELOCITIESandD2Q9_WEIGHTS() and exact mass/momentum/stress moment recovery oflattice_boltzmann.d2q9_equilibrium.Relate dimensionless relaxation time to kinematic viscosity via
lbm_viscosity_from_tauandlbm_tau_from_viscosity, and explain why violates Boltzmann’s H-theorem (, over-relaxation blow-up).Combine Guo–Zheng–Shi (2002) body forcing () with halfway bounce-back no-slip walls () in
simulate_lbm_poiseuille_2d.Demonstrate that setting cancels second-order BGK bounce-back slip error, matching analytical Poiseuille flow to .
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: Mesoscale Kinetic Theory & The D2Q9 Lattice¶
Rather than tracking individual molecules (Molecular Dynamics) or continuum averages (Navier–Stokes), Ludwig Boltzmann’s kinetic equation with the Bhatnagar–Gross–Krook (BGK, 1954) single-relaxation-time collision operator evolves the single-particle distribution along discrete 2-D lattice velocities (lattice_boltzmann.D2Q9_VELOCITIES, lattice units ):
To recover isotropic Galilean hydrodynamics (so viscous stress does not depend on whether a channel aligns with the grid axes or at ), the quadrature weights , , (D2Q9_WEIGHTS) are exact 3-point Gauss–Hermite tensor-product weights with lattice sound speed ():
Expanding the continuous Maxwell–Boltzmann distribution to in Hermite polynomials yields lattice_boltzmann.d2q9_equilibrium, which conserves density , momentum , and the Euler inviscid momentum-flux tensor (with isothermal ideal-gas pressure ):
heading("Demonstration 1: D2Q9 Gauss-Hermite Isotropy Tensors & Equilibrium Moment Conservation")
c_v = lattice_boltzmann.D2Q9_VELOCITIES
w_v = lattice_boltzmann.D2Q9_WEIGHTS
cs2 = lattice_boltzmann.CS2
# Verify 0th, 1st, 2nd, and 4th order lattice isotropy tensors:
m0 = float(np.sum(w_v))
m1 = np.sum(w_v[:, None] * c_v, axis=0)
m2 = np.einsum("i,ia,ib->ab", w_v, c_v, c_v)
m4 = np.einsum("i,ia,ib,ig,it->abgt", w_v, c_v, c_v, c_v, c_v)
delta = np.eye(2)
m4_iso = (cs2**2) * (
np.einsum("ab,gt->abgt", delta, delta)
+ np.einsum("ag,bt->abgt", delta, delta)
+ np.einsum("at,bg->abgt", delta, delta)
)
# Verify exact hydrodynamic moments of d2q9_equilibrium at a test state (rho=1.15, ux=0.08, uy=-0.05):
rho_t, ux_t, uy_t = 1.15, 0.08, -0.05
feq_t = lattice_boltzmann.d2q9_equilibrium(rho_t, ux_t, uy_t)
mom_rho = float(np.sum(feq_t))
mom_j = np.sum(c_v * feq_t[:, None], axis=0)
mom_pi = np.einsum("ia,ib,i->ab", c_v, c_v, feq_t)
u_vec = np.array([ux_t, uy_t])
pi_euler = rho_t * cs2 * delta + rho_t * np.outer(u_vec, u_vec)
print(f"Sum w_i = {m0:.15f} | 2nd-order isotropy error = {np.max(np.abs(m2 - cs2*delta)):.3e}")
print(f"4th-order Gauss-Hermite tensor isotropy error = {np.max(np.abs(m4 - m4_iso)):.3e}")
print(f"Equilibrium mass error : {abs(mom_rho - rho_t):.3e}")
print(f"Equilibrium momentum error : {np.max(np.abs(mom_j - rho_t * u_vec)):.3e}")
print(f"Equilibrium Euler stress |Pi^eq - (rho*cs^2*I + rho*u*u)| : {np.max(np.abs(mom_pi - pi_euler)):.3e}")
assert np.isclose(m0, 1.0, rtol=1e-15) and np.allclose(m1, 0.0, atol=1e-16)
assert np.allclose(m2, cs2 * delta, atol=1e-15) and np.allclose(m4, m4_iso, atol=1e-15)
assert np.isclose(mom_rho, rho_t, rtol=1e-15)
assert np.allclose(mom_j, rho_t * u_vec, atol=1e-15)
assert np.allclose(mom_pi, pi_euler, atol=1e-15)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.1))
for i in range(9):
cx_i, cy_i = c_v[i]
ax1.quiver(0, 0, cx_i, cy_i, angles="xy", scale_units="xy", scale=1, color="tab:blue" if i in (1, 2, 3, 4) else "tab:orange")
ax1.text(cx_i * 1.12 + (0.06 if i == 0 else -0.05), cy_i * 1.12 + 0.04, f"$f_{i}$ ($w={w_v[i]:.2f}$)", fontsize=8)
ax1.set_xlim(-1.85, 1.85)
ax1.set_ylim(-1.85, 1.85)
ax1.set_aspect("equal")
ax1.set_xlabel("$c_{ix}$ [lu/ts]")
ax1.set_ylabel("$c_{iy}$ [lu/ts]")
ax1.set_title("D2Q9 Discrete Velocity Stencil ($c_s^2 = 1/3$)")
u_scan = np.linspace(-0.25, 0.25, 150)
feq_scan = lattice_boltzmann.d2q9_equilibrium(np.ones_like(u_scan), u_scan, np.zeros_like(u_scan))
ax2.plot(u_scan, feq_scan[0], "k-", lw=2.0, label=r"Rest $f_0^{\mathrm{eq}}$ ($w_0 = 4/9$)")
ax2.plot(u_scan, feq_scan[1], "b-", lw=2.0, label=r"Forward $+x$ $f_1^{\mathrm{eq}}$ ($w_1 = 1/9$)")
ax2.plot(u_scan, feq_scan[3], "r--", lw=2.0, label=r"Backward $-x$ $f_3^{\mathrm{eq}}$ ($w_3 = 1/9$)")
ax2.plot(u_scan, feq_scan[5], "g-.", lw=1.8, label=r"Diagonal $(+1,+1)$ $f_5^{\mathrm{eq}}$ ($w_5 = 1/36$)")
ax2.set_xlabel("Horizontal lattice velocity $u_x$ [lu/ts]")
ax2.set_ylabel("Equilibrium population $f_i^{\\mathrm{eq}}$ [-]")
ax2.set_title("2nd-Order Hermite Equilibrium Populations")
ax2.legend(fontsize=8)
label_panels(fig)
plt.show()
Demonstration 1: D2Q9 Gauss-Hermite Isotropy Tensors & Equilibrium Moment Conservation
======================================================================================
Sum w_i = 1.000000000000000 | 2nd-order isotropy error = 5.551e-17
4th-order Gauss-Hermite tensor isotropy error = 5.551e-17
Equilibrium mass error : 0.000e+00
Equilibrium momentum error : 2.776e-17
Equilibrium Euler stress |Pi^eq - (rho*cs^2*I + rho*u*u)| : 5.551e-17

Figure 15.1. (a) The nine velocities of the D2Q9 lattice with their weights. (b) Equilibrium populations of four directions against the horizontal velocity.
What Demonstration 1 shows. In panel (b), stays positive for moderate lattice Mach numbers , and biasing when carries net momentum while reproducing the exact 2-D Euler stress tensor to 10-16.
2. Chapman–Enskog Multiscale Viscosity & Boltzmann’s H-Theorem ()¶
Expanding and in Knudsen number , Chapman–Enskog theory shows that non-equilibrium stress produces exact Newtonian viscous stress with kinematic viscosity (lattice_boltzmann.lbm_viscosity_from_tau):
Where does the shift come from? Taylor-expanding the discrete streaming difference to second order generates , an intrinsic discrete numerical viscosity that subtracts from . Consequently, corresponds to (infinite Reynolds number), while yields unphysical negative viscosity (over-relaxation factor ), violating Boltzmann’s H-theorem and blowing up high-wavenumber modes.
heading("Demonstration 2: Chapman-Enskog Viscosity Mapping & H-Theorem Stability Barrier (tau > 0.5)")
taus = np.array([0.52, 0.60, 0.80, 1.00, 1.40])
nus_lb = np.array([lattice_boltzmann.lbm_viscosity_from_tau(float(t)) for t in taus])
taus_back = np.array([lattice_boltzmann.lbm_tau_from_viscosity(float(n)) for n in nus_lb])
print(f"{'tau [-]':>9s} | {'omega = 1/tau':>14s} | {'nu_lb [lu^2/ts]':>16s} | {'Inverted tau':>13s}")
print("-" * 62)
for tv, nv, tb in zip(taus, nus_lb, taus_back):
print(f"{tv:9.3f} | {1.0/tv:14.4f} | {nv:16.6f} | {tb:13.6f}")
assert np.allclose(taus, taus_back, rtol=1e-14)
assert np.allclose(nus_lb, (taus - 0.5) / 3.0, rtol=1e-15)
# Conversion to SI units (dx = 1e-4 m, dt = 2e-3 s for water, nu = 8.926e-7 m^2/s):
nu_water = constants.FLUIDS_DB["water_298K"]["nu_m2_s"]
dx_si, dt_si = 1.0e-4, 2.0e-3
tau_water = lattice_boltzmann.lbm_tau_from_viscosity(nu_water, dx_lb=dx_si, dt_lb=dt_si)
nu_water_rec = lattice_boltzmann.lbm_viscosity_from_tau(tau_water, dx_lb=dx_si, dt_lb=dt_si)
print(f"\nWater at 298 K (dx = 100 um, dt = 2 ms): nu = {nu_water:.3e} m^2/s -> tau = {tau_water:.5f} -> recovered nu = {nu_water_rec:.3e}")
assert np.isclose(nu_water, nu_water_rec, rtol=1e-14)
# Verify H-theorem ValueError guard at tau <= 0.5:
for bad_tau in [0.50, 0.45]:
caught = False
try:
lattice_boltzmann.lbm_viscosity_from_tau(bad_tau)
except ValueError:
caught = True
assert caught is True
Demonstration 2: Chapman-Enskog Viscosity Mapping & H-Theorem Stability Barrier (tau > 0.5)
===========================================================================================
tau [-] | omega = 1/tau | nu_lb [lu^2/ts] | Inverted tau
--------------------------------------------------------------
0.520 | 1.9231 | 0.006667 | 0.520000
0.600 | 1.6667 | 0.033333 | 0.600000
0.800 | 1.2500 | 0.100000 | 0.800000
1.000 | 1.0000 | 0.166667 | 1.000000
1.400 | 0.7143 | 0.300000 | 1.400000
Water at 298 K (dx = 100 um, dt = 2 ms): nu = 8.926e-07 m^2/s -> tau = 1.03558 -> recovered nu = 8.926e-07
What Demonstration 2 shows. Equation (2.1) converts between lattice and SI units: with and , water () has the relaxation time . A time step a thousand times smaller would give , too close to the stability limit to be usable; in the lattice Boltzmann method the time step is chosen from the viscosity and the grid spacing, not from a Courant number alone.
3. Guo Body Forcing & Halfway Bounce-Back Poiseuille Verification¶
To drive planar channel flow along between solid rows and (lattice_boltzmann.simulate_lbm_poiseuille_2d):
Halfway Bounce-Back Walls: Reflecting outgoing populations back along
D2Q9_OPPOSITE([0, 3, 4, 1, 2, 7, 8, 5, 6]) places the effective zero-velocity walls half a lattice spacing inside the fluid at and , giving channel aperture and wall-normal coordinate for fluid rows .Guo–Zheng–Shi (2002) Exact 2nd-Order Forcing: Discrete body forcing requires both the source term and the half-step momentum shift to eliminate spurious discrete forcing artifacts and match
navier_stokes.poiseuille_couette_exact.
heading("Demonstration 3: 2-D LBM Poiseuille Channel vs Continuum Navier-Stokes Parabola")
fx_p = 1.0e-5
pois = lattice_boltzmann.simulate_lbm_poiseuille_2d(nx=4, ny=10, tau=0.85, body_force_x=fx_p, n_steps=650)
eta_f = pois["y_fluid"] - 0.5
ns_ref = navier_stokes.poiseuille_couette_exact(y=eta_f, H=pois["channel_height"], mu=pois["nu_lb"], dP_dx=-fx_p, U_top=0.0)
print(f"Fluid rows j = 1..8 -> Halfway bounce-back aperture H = {pois['channel_height']:.1f} lu, nu_lb = {pois['nu_lb']:.6f}")
print(f"Max relative error ||u_LBM - u_exact||_inf / u_max : {pois['max_rel_error']:.4e} ({pois['max_rel_error']*100:.3f}%)")
print(f"Cross-module check vs poiseuille_couette_exact : {np.max(np.abs(pois['u_exact'] - ns_ref['u'])):.3e}")
assert pois["max_rel_error"] < 1e-2
assert np.allclose(pois["u_exact"], ns_ref["u"], rtol=1e-15, atol=1e-15)
y_fine = np.linspace(0.0, pois["channel_height"], 200)
u_fine = navier_stokes.poiseuille_couette_exact(y=y_fine, H=pois["channel_height"], mu=pois["nu_lb"], dP_dx=-fx_p)["u"]
fig, ax = plt.subplots(figsize=(7.0, 4.1))
ax.plot(y_fine, u_fine * 1e3, "k-", lw=2.2, label=r"Analytical Poiseuille $\frac{F_x}{2\nu}\eta(H-\eta)$")
ax.plot(eta_f, pois["u_lbm"] * 1e3, "ro", ms=5.5, label=r"D2Q9 BGK + Guo + Bounce-Back ($\tau = 0.85$)")
ax.axvline(0.0, color="gray", ls="--", lw=1.0, label="Halfway bounce-back walls ($\\eta = 0, H$)")
ax.axvline(pois["channel_height"], color="gray", ls="--", lw=1.0)
ax.set_xlabel("Distance from bottom bounce-back wall $\\eta = y - 0.5$ [lu]")
ax.set_ylabel("Axial velocity $u_x \\times 10^3$ [lu/ts]")
ax.set_title(rf"Mesoscale LBM Reproduces Continuum Poiseuille Flow (Rel. Err = {pois['max_rel_error']*100:.2f}%)")
ax.legend(fontsize=8.5)
plt.show()
Demonstration 3: 2-D LBM Poiseuille Channel vs Continuum Navier-Stokes Parabola
===============================================================================
Fluid rows j = 1..8 -> Halfway bounce-back aperture H = 8.0 lu, nu_lb = 0.116667
Max relative error ||u_LBM - u_exact||_inf / u_max : 5.5103e-03 (0.551%)
Cross-module check vs poiseuille_couette_exact : 0.000e+00

Figure 15.2. Poiseuille flow between bounce-back walls driven by a body force: lattice Boltzmann result at the eight fluid nodes (points) and the analytical parabola (line).
What Demonstration 3 shows. Without solving a single Poisson equation or discretizing , local D2Q9 collisions + halfway bounce-back reproduce the continuum Navier–Stokes parabola to on just 8 fluid nodes (H = 8) at . Why is the error and not at the level of rounding error, when a parabola has constant and zero ?
4. The TRT/BGK “Magic” Relaxation Time ¶
Ginzburg & d’Humières (2003) proved via exact Milne kinetic boundary-layer analysis that single-relaxation-time BGK halfway bounce-back shifts the apparent no-slip wall position by a viscosity-dependent slip error proportional to:
We sweep on ny = 8 (H = 6) and watch the relative Poiseuille error collapse by six orders of magnitude right at .
heading("Demonstration 4: Sweeping Relaxation Time tau — Error against the Relaxation Time")
tau_magic = 0.5 + np.sqrt(3.0) / 4.0
tau_sweep = [0.72, 0.84, tau_magic, 1.12]
rel_errs = []
print(f"{'tau [-]':>10s} | {'|(tau-0.5)^2 - 3/16|':>21s} | {'Max Poiseuille Rel. Error':>26s}")
print("-" * 66)
for tv in tau_sweep:
r_p = lattice_boltzmann.simulate_lbm_poiseuille_2d(nx=2, ny=8, tau=tv, body_force_x=1.0e-5, n_steps=450)
lam_slip = abs((tv - 0.5) ** 2 - 3.0 / 16.0)
rel_errs.append(r_p["max_rel_error"])
print(f"{tv:10.6f} | {lam_slip:21.4e} | {r_p['max_rel_error']:26.4e}")
err_at_magic = rel_errs[2]
assert err_at_magic < 1e-7
assert min(rel_errs[:2] + rel_errs[3:]) > 5e-3
fig, ax = plt.subplots(figsize=(7.0, 4.1))
ax.semilogy(tau_sweep, rel_errs, "bo-", lw=2.0, ms=6.5, label="D2Q9 BGK Poiseuille max relative error")
ax.axvline(tau_magic, color="tab:red", ls="--", lw=1.8, label=rf"$\tau_{{\mathrm{{magic}}}} = \frac{{1}}{{2}} + \frac{{\sqrt{{3}}}}{{4}} \approx {tau_magic:.5f}$")
ax.set_xlabel("Dimensionless BGK relaxation time $\\tau$ [-]")
ax.set_ylabel("Max relative velocity error (log scale) [-]")
ax.set_title("Exact Cancellation of Bounce-Back Wall Slip at $\\tau_{\\mathrm{magic}}$")
ax.legend(fontsize=8.5)
plt.show()
Demonstration 4: Sweeping Relaxation Time tau — Error against the Relaxation Time
=================================================================================
tau [-] | |(tau-0.5)^2 - 3/16| | Max Poiseuille Rel. Error
------------------------------------------------------------------
0.720000 | 1.3910e-01 | 2.1293e-02
0.840000 | 7.1900e-02 | 1.0957e-02
0.933013 | 2.7756e-17 | 1.5037e-08
1.120000 | 1.9690e-01 | 3.0004e-02

Figure 15.3. Largest relative error of the lattice Boltzmann Poiseuille profile against the relaxation time. The vertical line marks , at which the bounce-back wall lies exactly halfway between the nodes.
Inside the algorithm¶
What Demonstration 4 shows. Away from , BGK wall-location error is on a coarse channel, whereas at , the error falls to . (Two-Relaxation-Time, TRT, LBM schemes exploit this exact identity at any viscosity by fixing the antisymmetric relaxation rate to keep constant.) Below we inspect d2q9_equilibrium and simulate_lbm_poiseuille_2d, and verify D2Q9_OPPOSITE involution (opp[opp[i]] == i).
Check against the library¶
heading("Inside the Algorithm: lattice_boltzmann.d2q9_equilibrium & simulate_lbm_poiseuille_2d")
print(show_source(lattice_boltzmann.d2q9_equilibrium))
print(show_source(lattice_boltzmann.simulate_lbm_poiseuille_2d))
opp = lattice_boltzmann.D2Q9_OPPOSITE
c_vecs = lattice_boltzmann.D2Q9_VELOCITIES
# Verify bounce-back opposite-direction involution opp[opp[i]] == i and c_i + c_{opp[i]} == (0, 0):
assert np.array_equal(opp[opp], np.arange(9))
assert np.array_equal(c_vecs + c_vecs[opp], np.zeros_like(c_vecs))
# Verify why Guo's +0.5*F_x velocity shift is essential at tau_magic:
res_magic = lattice_boltzmann.simulate_lbm_poiseuille_2d(nx=2, ny=7, tau=0.5 + np.sqrt(3.0) / 4.0, body_force_x=2e-5, n_steps=340)
unshifted_err = float(np.max(np.abs((res_magic["u_lbm"] - 0.5 * 2e-5) - res_magic["u_exact"])) / np.max(res_magic["u_exact"]))
print(f"At tau_magic: Guo-shifted error = {res_magic['max_rel_error']:.3e} vs unshifted momentum sum error = {unshifted_err:.3e}")
assert res_magic["max_rel_error"] < 1e-6 and unshifted_err > 1e-2
Inside the Algorithm: lattice_boltzmann.d2q9_equilibrium & simulate_lbm_poiseuille_2d
=====================================================================================
def d2q9_equilibrium(
rho: float | np.ndarray,
ux: float | np.ndarray,
uy: float | np.ndarray,
) -> np.ndarray:
"""Evaluate 2nd-order Hermite Maxwell-Boltzmann equilibrium distributions f_i^eq (shape (9, ...))."""
rho_a = np.asarray(rho, dtype=float)
ux_a = np.asarray(ux, dtype=float)
uy_a = np.asarray(uy, dtype=float)
u2 = ux_a**2 + uy_a**2
feq = np.empty((9,) + rho_a.shape, dtype=float)
for i in range(9):
cx, cy = D2Q9_VELOCITIES[i]
cu = cx * ux_a + cy * uy_a
feq[i] = D2Q9_WEIGHTS[i] * rho_a * (1.0 + 3.0 * cu + 4.5 * (cu**2) - 1.5 * u2)
return feq
def simulate_lbm_poiseuille_2d(
nx: int = 8,
ny: int = 26,
tau: float = 0.85,
body_force_x: float = 1.0e-5,
n_steps: int = 2500,
) -> dict:
"""Simulate 2-D body-force-driven Poiseuille channel flow via D2Q9 BGK + Guo forcing + halfway bounce-back."""
if ny < 5 or nx < 2 or tau <= 0.5:
raise ValueError("Require nx >= 2, ny >= 5, and tau > 0.5.")
nu = lbm_viscosity_from_tau(tau)
solid = np.zeros((nx, ny), dtype=bool)
solid[:, 0] = True
solid[:, -1] = True
fluid = ~solid
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)
for _ in range(n_steps):
rho = np.sum(f, axis=0)
cx_vec = D2Q9_VELOCITIES[:, 0][:, None, None]
cy_vec = D2Q9_VELOCITIES[:, 1][:, None, None]
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
# Halfway bounce-back: solid nodes reflect incoming post-collision populations back into fluid:
for i in range(9):
f_post[i, solid] = f[D2Q9_OPPOSITE[i], solid]
f = _stream_periodic(f_post)
# Final macroscopic velocity on fluid rows j = 1 .. ny-2 (walls at y_bot = 0.5, y_top = ny - 1.5, H = ny - 2):
rho = np.sum(f, axis=0)
ux = (np.sum(D2Q9_VELOCITIES[:, 0][:, None, None] * f, axis=0) + 0.5 * body_force_x) / rho
ux[solid] = 0.0
y_fluid = np.arange(1, ny - 1, dtype=float)
h_chan = float(ny - 2)
eta = y_fluid - 0.5
u_exact = (body_force_x / (2.0 * nu)) * eta * (h_chan - eta)
u_num = np.mean(ux[:, fluid[0, :]], axis=0)
rel_err = float(np.max(np.abs(u_num - u_exact)) / np.max(np.abs(u_exact)))
return {
"y_fluid": y_fluid,
"u_lbm": u_num,
"u_exact": u_exact,
"nu_lb": nu,
"channel_height": h_chan,
"max_rel_error": rel_err,
}
At tau_magic: Guo-shifted error = 2.670e-09 vs unshifted momentum sum error = 2.309e-02
Exercises¶
Worked solutions are in 15_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Across 50 random states , verify to
< 1e-14thatd2q9_equilibriumreproduces , , and , and show that the 3rd-order moment discrepancy equals identically.Find how it fails. Verify
ValueErrorguards onlbm_viscosity_from_tau(0.5),lbm_tau_from_viscosity(0.0), andsimulate_lbm_poiseuille_2d(tau=0.49), and run an unguarded periodic BGK shear-wave test comparing vs. over 45 steps to demonstrate H-theorem over-relaxation blow-up.Implement it yourself. Implement
my_lbm_kolmogorov_shear_decay(ny, tau, n_steps)evolving a periodic shear wave on a D2Q9 lattice (ny=36,n_steps=160), extract asymptotic between and , and verify< 0.5%relative error againstlattice_boltzmann.lbm_viscosity_from_tau(tau)across .
heading("Self-check for the exercises")
cx_sc = lattice_boltzmann.D2Q9_VELOCITIES[:, 0]
feq_sc = lattice_boltzmann.d2q9_equilibrium(1.1, 0.12, -0.04)
m3_d2q9 = float(np.sum((cx_sc**3) * feq_sc))
m3_maxwell = 3.0 * 1.1 * lattice_boltzmann.CS2 * 0.12 + 1.1 * (0.12**3)
cubic_defect = m3_maxwell - m3_d2q9
print(f"D2Q9 sum(c_x^3 f^eq) = {m3_d2q9:.8f} == rho*u_x = {1.1*0.12:.8f} | Exact cubic Mach defect rho*u_x^3 = {cubic_defect:.8f}")
assert np.isclose(m3_d2q9, 1.1 * 0.12, rtol=1e-15) and np.isclose(cubic_defect, 1.1 * (0.12**3), rtol=1e-14)
print("All checks passed.")
Self-check for the exercises
============================
D2Q9 sum(c_x^3 f^eq) = 0.13200000 == rho*u_x = 0.13200000 | Exact cubic Mach defect rho*u_x^3 = 0.00190080
All checks passed.