Worked solutions to the three exercises of Lecture 15. 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: 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()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Across 50 random states , verify to < 1e-14 that d2q9_equilibrium reproduces , , and , and show that the 3rd-order moment discrepancy equals identically.
heading("Exercise 1: D2Q9 Hermite Moment Conservation & Exact O(Ma^3) Galilean Defect")
rng_e1 = np.random.default_rng(1501)
rho_r = rng_e1.uniform(0.8, 1.2, size=50)
ux_r = rng_e1.uniform(-0.15, 0.15, size=50)
uy_r = rng_e1.uniform(-0.15, 0.15, size=50)
feq_r = lattice_boltzmann.d2q9_equilibrium(rho_r, ux_r, uy_r) # shape (9, 50)
cv = lattice_boltzmann.D2Q9_VELOCITIES
cs2_v = lattice_boltzmann.CS2
rho_chk = np.sum(feq_r, axis=0)
jx_chk = np.sum(cv[:, 0][:, None] * feq_r, axis=0)
jy_chk = np.sum(cv[:, 1][:, None] * feq_r, axis=0)
pxx_chk = np.sum((cv[:, 0] ** 2)[:, None] * feq_r, axis=0)
pxy_chk = np.sum((cv[:, 0] * cv[:, 1])[:, None] * feq_r, axis=0)
qxxx_d2q9 = np.sum((cv[:, 0] ** 3)[:, None] * feq_r, axis=0)
qxxx_maxwell = 3.0 * rho_r * cs2_v * ux_r + rho_r * (ux_r**3)
print(f"Max |sum(f^eq) - rho| : {np.max(np.abs(rho_chk - rho_r)):.3e}")
print(f"Max |Pi_xx^eq - (rho*cs^2+rho*ux^2)|: {np.max(np.abs(pxx_chk - (rho_r*cs2_v + rho_r*ux_r**2))):.3e}")
print(f"Max |Pi_xy^eq - rho*ux*uy| : {np.max(np.abs(pxy_chk - rho_r*ux_r*uy_r)):.3e}")
print(f"Max |(Q_xxx^MB - Q_xxx^D2Q9) - rho*ux^3| : {np.max(np.abs((qxxx_maxwell - qxxx_d2q9) - rho_r*(ux_r**3))):.3e}")
assert np.allclose(rho_chk, rho_r, atol=1e-14)
assert np.allclose(jx_chk, rho_r * ux_r, atol=1e-14) and np.allclose(jy_chk, rho_r * uy_r, atol=1e-14)
assert np.allclose(pxx_chk, rho_r * cs2_v + rho_r * (ux_r**2), atol=1e-14)
assert np.allclose(pxy_chk, rho_r * ux_r * uy_r, atol=1e-14)
assert np.allclose(qxxx_maxwell - qxxx_d2q9, rho_r * (ux_r**3), atol=1e-14)
Exercise 1: D2Q9 Hermite Moment Conservation & Exact O(Ma^3) Galilean Defect
============================================================================
Max |sum(f^eq) - rho| : 2.220e-16
Max |Pi_xx^eq - (rho*cs^2+rho*ux^2)|: 1.110e-16
Max |Pi_xy^eq - rho*ux*uy| : 1.019e-17
Max |(Q_xxx^MB - Q_xxx^D2Q9) - rho*ux^3| : 5.193e-17
Explanation. Because every component of D2Q9_VELOCITIES belongs to , the algebraic identity forces , omitting the term. That single identity explains why standard 3-speed D2Q9 LBM is strictly a low-Mach weakly compressible Navier–Stokes solver ().
Exercise 2¶
Problem. Verify ValueError guards on lbm_viscosity_from_tau(0.5), lbm_tau_from_viscosity(0.0), and simulate_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.
heading("Exercise 2: H-Theorem Guards & Raw Over-Relaxation Instability at tau = 0.36 < 0.5")
for fn, arg in [(lattice_boltzmann.lbm_viscosity_from_tau, 0.5),
(lattice_boltzmann.lbm_viscosity_from_tau, 0.42),
(lattice_boltzmann.lbm_tau_from_viscosity, 0.0)]:
caught = False
try:
fn(arg)
except ValueError:
caught = True
assert caught is True
caught_pois = False
try:
lattice_boltzmann.simulate_lbm_poiseuille_2d(nx=6, ny=12, tau=0.49, n_steps=10)
except ValueError:
caught_pois = True
assert caught_pois is True
# Raw unguarded BGK shear-wave test on 4x24 periodic lattice with wavelength-4 shear wave:
cv = lattice_boltzmann.D2Q9_VELOCITIES
y_g = np.arange(24)[None, :] * np.ones((4, 1))
u0_rip = 1e-3 * np.sin(0.5 * np.pi * y_g)
amps = {}
for tau_raw in [0.80, 0.36]:
f_r = lattice_boltzmann.d2q9_equilibrium(np.ones((4, 24)), u0_rip, np.zeros((4, 24)))
with np.errstate(over="ignore", invalid="ignore"):
for _ in range(45):
rho_s = np.sum(f_r, axis=0)
ux_s = np.sum(cv[:, 0][:, None, None] * f_r, axis=0) / rho_s
uy_s = np.sum(cv[:, 1][:, None, None] * f_r, axis=0) / rho_s
f_post = f_r - (f_r - lattice_boltzmann.d2q9_equilibrium(rho_s, ux_s, uy_s)) / tau_raw
for i in range(9):
f_r[i] = np.roll(np.roll(f_post[i], int(cv[i, 0]), axis=0), int(cv[i, 1]), axis=1)
ux_end = np.sum(cv[:, 0][:, None, None] * f_r, axis=0) / np.sum(f_r, axis=0)
amps[tau_raw] = float(np.max(np.abs(ux_end)))
print(f"Initial amplitude = 1.000e-03 | tau=0.80 final amp = {amps[0.80]:.3e} (decayed) | tau=0.36 final amp = {amps[0.36]:.3e} (grew without bound)")
assert amps[0.80] < 5e-5 and (not np.isfinite(amps[0.36]) or amps[0.36] > 1.0)
Exercise 2: H-Theorem Guards & Raw Over-Relaxation Instability at tau = 0.36 < 0.5
==================================================================================
Initial amplitude = 1.000e-03 | tau=0.80 final amp = 2.064e-09 (decayed) | tau=0.36 final amp = 9.754e+05 (grew without bound)
Explanation. For , the BGK relaxation factor overshoots local equilibrium on every collision (1 - omega = -1.778 < -1), corresponding to negative kinematic viscosity and short-wavelength shear modes that grow without bound within 45 steps.
Exercise 3¶
Problem. 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 against lattice_boltzmann.lbm_viscosity_from_tau(tau) across .
heading("Exercise 3: Implement It Yourself — Chapman-Enskog Viscosity Measurement via Shear-Wave Decay")
def my_lbm_kolmogorov_shear_decay(ny: int, tau: float, n_steps: int = 160, t1: int = 30) -> dict:
"""Evolve 2-D periodic D2Q9 Kolmogorov shear wave u_x(y,t) = U0*sin(k*y)*exp(-nu*k^2*t) and measure asymptotic nu."""
nx = 4
k_wave = 2.0 * np.pi / float(ny)
y = np.arange(ny, dtype=float)[None, :] * np.ones((nx, 1))
ux = 1.0e-3 * np.sin(k_wave * y)
uy = np.zeros_like(ux)
rho = np.ones_like(ux)
f = lattice_boltzmann.d2q9_equilibrium(rho, ux, uy)
cv = lattice_boltzmann.D2Q9_VELOCITIES
sin_basis = np.sin(np.arange(ny) * k_wave)
u_amp_t1 = 0.0
for step in range(1, n_steps + 1):
rho = np.sum(f, axis=0)
ux = np.sum(cv[:, 0][:, None, None] * f, axis=0) / rho
uy = np.sum(cv[:, 1][:, None, None] * f, axis=0) / rho
f_post = f - (f - lattice_boltzmann.d2q9_equilibrium(rho, ux, uy)) / tau
for i in range(9):
f[i] = np.roll(np.roll(f_post[i], int(cv[i, 0]), axis=0), int(cv[i, 1]), axis=1)
if step == t1:
ux_p1 = np.mean(np.sum(cv[:, 0][:, None, None] * f, axis=0) / np.sum(f, axis=0), axis=0)
u_amp_t1 = float(2.0 * np.mean(ux_p1 * sin_basis))
ux_prof = np.mean(np.sum(cv[:, 0][:, None, None] * f, axis=0) / np.sum(f, axis=0), axis=0)
u_amp_end = float(2.0 * np.mean(ux_prof * sin_basis))
nu_meas = -float(np.log(u_amp_end / u_amp_t1)) / ((k_wave**2) * (n_steps - t1))
return {"nu_measured": nu_meas, "nu_exact": lattice_boltzmann.lbm_viscosity_from_tau(tau)}
for tau_t in [0.65, 0.85, 1.10]:
out = my_lbm_kolmogorov_shear_decay(ny=36, tau=tau_t, n_steps=160, t1=30)
rel_diff = abs(out["nu_measured"] - out["nu_exact"]) / out["nu_exact"]
print(f"tau = {tau_t:.2f} | nu_measured = {out['nu_measured']:.6f} vs nu_CE = {out['nu_exact']:.6f} | rel diff = {rel_diff:.3%}")
assert rel_diff < 5.0e-3
Exercise 3: Implement It Yourself — Chapman-Enskog Viscosity Measurement via Shear-Wave Decay
=============================================================================================
tau = 0.65 | nu_measured = 0.050116 vs nu_CE = 0.050000 | rel diff = 0.231%
tau = 0.85 | nu_measured = 0.116818 vs nu_CE = 0.116667 | rel diff = 0.130%
tau = 1.10 | nu_measured = 0.199774 vs nu_CE = 0.200000 | rel diff = 0.113%
Summary. Measuring macroscopic viscous decay from pure D2Q9 streaming + BGK collision confirms Chapman & Enskog’s law directly from kinetic dynamics. Note also that solid boolean indexing handles channel walls in 2 lines of code; in Lecture 16 the same masking is used to simulate bluff-body wakes and porous-rock Darcy permeability with zero body-fitted remeshing.