Worked solutions to the three exercises of Lecture 11. 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: Combined Couette-Poiseuille Regimes, Backflow Onset & Wall-Shear Balance")
H_ch = 0.010 # 10 mm gap [m]
mu_oil = constants.FLUIDS_DB["engine_oil_313K"]["mu_Pa_s"]
U_lid_ch = 1.2 # [m/s]
y_ch = np.linspace(0.0, H_ch, 201)
pi_values = [-3.0, -1.5, -1.0, 0.0, 1.0, 2.5]
print(f"{'Pi [-]':>7s} | {'dP/dx [Pa/m]':>13s} | {'u_mean [m/s]':>13s} | {'tau_bot [Pa]':>13s} | {'tau_top [Pa]':>13s} | {'Force Resid':>12s}")
print("-" * 86)
fig, ax = plt.subplots(figsize=(7.2, 4.2))
for pi_v in pi_values:
dp_dx = -pi_v * (2.0 * mu_oil * U_lid_ch) / (H_ch ** 2)
pc = navier_stokes.poiseuille_couette_exact(y_ch, H=H_ch, mu=mu_oil, dP_dx=dp_dx, U_top=U_lid_ch)
force_res = abs((pc["tau_bottom"] - pc["tau_top"]) - (-H_ch * dp_dx))
print(f"{pi_v:7.2f} | {dp_dx:13.2f} | {pc['u_mean']:13.5f} | {pc['tau_bottom']:13.4f} | {pc['tau_top']:13.4f} | {force_res:12.2e}")
assert force_res < 1e-11
if np.isclose(pi_v, -3.0):
assert np.isclose(pc["flow_rate_per_width"], 0.0, atol=1e-14)
assert np.min(pc["u"]) < -0.15 * U_lid_ch
if np.isclose(pi_v, -1.0):
assert np.isclose(pc["tau_bottom"], 0.0, atol=1e-12)
assert np.min(pc["u"]) >= -1e-15
if pi_v < -1.0:
assert np.min(pc["u"]) < 0.0 and pc["tau_bottom"] < 0.0
ax.plot(pc["u"] / U_lid_ch, y_ch / H_ch, lw=2.0, label=f"$\\Pi = {pi_v:+.1f}$")
# Pure Poiseuille identity u_max == (3/2) * u_mean and Darcy friction factor f_D * Re_{D_h} == 96:
pois_only = navier_stokes.poiseuille_couette_exact(y_ch, H=H_ch, mu=mu_oil, dP_dx=-2400.0, U_top=0.0)
assert np.isclose(np.max(pois_only["u"]), 1.5 * pois_only["u_mean"], rtol=1e-14, atol=1e-14)
rho_oil = constants.FLUIDS_DB["engine_oil_313K"]["rho_kg_m3"]
Dh = 2.0 * H_ch
Re_Dh = rho_oil * pois_only["u_mean"] * Dh / mu_oil
f_darcy = 2400.0 * Dh / (0.5 * rho_oil * (pois_only["u_mean"] ** 2))
assert np.isclose(f_darcy * Re_Dh, 96.0, rtol=1e-13, atol=1e-13)
ax.axvline(0.0, color="black", ls=":", lw=1.2)
ax.set_xlabel(r"Normalized Velocity $u(y) / U_{\mathrm{top}}$ [-]")
ax.set_ylabel("Normalized Channel Height $y / H$ [-]")
ax.set_title("Planar Couette-Poiseuille Velocity Profiles Across $\\Pi$")
ax.legend(fontsize=8.5)
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Compute the exact mid-plane startup timescale across all 10 fluids in constants.FLUIDS_DB for , and verify via impulsive_couette_exact that to across every fluid.
heading("Exercise 1: Viscous Startup Timescale check Across All 10 Benchmark Fluids in FLUIDS_DB")
H_gap = 0.01 # 1 cm gap [m]
factor_t = float(np.log(400.0 / np.pi) / (np.pi ** 2))
rows_f = []
for name, props in constants.FLUIDS_DB.items():
nu_f = props["nu_m2_s"]
t_star = factor_t * (H_gap ** 2) / nu_f
u_mid = float(navier_stokes.impulsive_couette_exact(np.array([0.5 * H_gap]), t=t_star, H=H_gap, nu=nu_f, U_wall=1.0)[0])
rel_def = (0.5 - u_mid) / 0.5
rows_f.append((t_star, name, nu_f, rel_def))
rows_f.sort()
print(f"{'Fluid':22s} | {'nu [m^2/s]':>12s} | {'t_99% [s]':>13s} | {'Rel Mid-Plane Deficit':>22s}")
print("-" * 78)
for t_s, name, nu_f, r_def in rows_f:
print(f"{name:22s} | {nu_f:12.3e} | {t_s:13.5f} | {r_def:22.8f}")
assert np.isclose(r_def, 0.01, rtol=1e-6, atol=1e-7)
# Viscous glycerol reaches steady Couette > 6000x faster than low-viscosity mercury
assert rows_f[-1][0] / rows_f[0][0] > 6000.0
Exercise 1: Viscous Startup Timescale check Across All 10 Benchmark Fluids in FLUIDS_DB
=======================================================================================
Fluid | nu [m^2/s] | t_99% [s] | Rel Mid-Plane Deficit
------------------------------------------------------------------------------
glycerol_298K | 7.534e-04 | 0.06518 | 0.01000000
engine_oil_313K | 2.397e-04 | 0.20485 | 0.01000000
steam_473K | 3.491e-05 | 1.40654 | 0.01000000
methane_298K | 1.686e-05 | 2.91189 | 0.01000000
air_298K | 1.562e-05 | 3.14459 | 0.01000000
ethanol_298K | 1.368e-06 | 35.89342 | 0.01000000
water_298K | 8.926e-07 | 55.01441 | 0.01000000
liquid_sodium_673K | 3.318e-07 | 148.01473 | 0.01000000
mercury_298K | 1.128e-07 | 435.53307 | 0.01000000
co2_supercritical | 7.599e-08 | 646.20788 | 0.01000000
Explanation. A common beginner misconception is that ‘thick, syrupy’ glycerol takes longer to reach steady Couette flow than water or mercury. Equation (3.1) shows the exact opposite. Kinematic viscosity is the diffusivity of momentum: glycerol () diffuses wall momentum across a gap in , whereas dense, low-viscosity liquid mercury () requires over (). Also at , the next odd mode has decayed to , making the single-mode formula exact to 16 digits.
Exercise 2¶
Problem. Verify poiseuille_couette_exact and impulsive_couette_exact raise ValueError on non-positive , and demonstrate via constants.von_neumann_advection_diffusion_amp and time marching that explicit FTCS at suffers Nyquist blow-up while Crank–Nicolson remains bounded.
heading("Exercise 2: Parabolic FTCS Blow-Up (r = 0.65 > 0.5) & Physical Guards")
bad_ns_calls = [
lambda: navier_stokes.poiseuille_couette_exact(np.array([0.5]), H=0.0, mu=1.0, dP_dx=-1.0),
lambda: navier_stokes.poiseuille_couette_exact(np.array([0.5]), H=1.0, mu=-0.1, dP_dx=-1.0),
lambda: navier_stokes.impulsive_couette_exact(np.array([0.5]), t=0.0, H=1.0, nu=0.1),
lambda: navier_stokes.impulsive_couette_exact(np.array([0.5]), t=0.1, H=1.0, nu=0.0),
]
for fn in bad_ns_calls:
caught = False
try:
fn()
except ValueError:
caught = True
assert caught is True
# Check von Neumann Nyquist amplification at theta = pi for r_diff = 0.65:
vn = constants.von_neumann_advection_diffusion_amp(np.pi, cfl=0.0, r_diff=0.65, scheme="ftcs")
print(f"FTCS von Neumann at theta=pi, r=0.65: G(pi) = {vn['G'].real:+.2f}, |G(pi)| = {vn['magnitude']:.2f}, stable = {vn['stable']}")
assert vn["stable"] is False and np.isclose(vn["magnitude"], 1.60, atol=1e-14)
# Run 35 steps of explicit FTCS vs Crank-Nicolson at r = 0.65:
n_pts = 41
H_b = 1.0
nu_b = 0.1
dy_b = H_b / (n_pts - 1)
r_b = 0.65
dt_b = r_b * (dy_b ** 2) / nu_b
u_ftcs = np.zeros(n_pts)
u_ftcs[0] = 1.0
u_cn = u_ftcs.copy()
m_i = n_pts - 2
lo_b = np.full(m_i - 1, -0.5 * r_b)
up_b = np.full(m_i - 1, -0.5 * r_b)
dg_b = np.full(m_i, 1.0 + r_b)
for _ in range(40):
u_ftcs[1:-1] = u_ftcs[1:-1] + r_b * (u_ftcs[:-2] - 2.0 * u_ftcs[1:-1] + u_ftcs[2:])
rhs_b = (1.0 - r_b) * u_cn[1:-1] + 0.5 * r_b * (u_cn[:-2] + u_cn[2:])
rhs_b[0] += 0.5 * r_b * 1.0
u_cn[1:-1] = grids_fvm.solve_tridiagonal(lo_b, dg_b, up_b, rhs_b)
print(f"After 40 steps at r=0.65: max |u_FTCS| = {np.max(np.abs(u_ftcs)):.3e} vs max |u_CN| = {np.max(np.abs(u_cn)):.4f}")
assert np.max(np.abs(u_ftcs)) > 1.0e5
assert 0.0 <= np.min(u_cn) and np.max(u_cn) <= 1.0 + 1e-12
Exercise 2: Parabolic FTCS Blow-Up (r = 0.65 > 0.5) & Physical Guards
=====================================================================
FTCS von Neumann at theta=pi, r=0.65: G(pi) = -1.60, |G(pi)| = 1.60, stable = False
After 40 steps at r=0.65: max |u_FTCS| = 5.399e+05 vs max |u_CN| = 1.0000
Explanation. At the grid Nyquist mode (), explicit FTCS gives at , so the sawtooth mode grows by a factor of 1.6 per step and the solution reaches after 40 steps. Crank–Nicolson replaces with the Cayley rational transform , which satisfies for every .
Exercise 3¶
Problem. Implement both exact_startup_poiseuille(y, t, H, mu, rho, dP_dx) (odd-harmonic Fourier sine series) and startup_poiseuille_cn(n_nodes, H, mu, rho, dP_dx, dt, n_steps) (Crank–Nicolson with grids_fvm.solve_tridiagonal) for startup pressure-driven channel flow from rest. Verify agreement to across and convergence onto poiseuille_couette_exact as .
heading("Exercise 3: Implement It Yourself — Startup Planar Poiseuille Flow (Exact Series vs Crank-Nicolson)")
def exact_startup_poiseuille(
y: np.ndarray, t: float, H: float, mu: float, rho: float, dP_dx: float, n_odd: int = 80
) -> np.ndarray:
"""Analytical Navier-Stokes transient velocity u(y, t) for startup planar Poiseuille flow from rest."""
yg = np.asarray(y, dtype=float)
G = -float(dP_dx)
nu = float(mu) / float(rho)
u_inf = (G / (2.0 * mu)) * yg * (H - yg)
series = np.zeros_like(yg)
for m in range(n_odd):
n = 2 * m + 1
kn = n * np.pi / H
series += (np.sin(kn * yg) / (n ** 3)) * np.exp(-nu * (kn ** 2) * t)
return u_inf - (4.0 * G * (H ** 2) / (mu * (np.pi ** 3))) * series
def startup_poiseuille_cn(
n_nodes: int, H: float, mu: float, rho: float, dP_dx: float, dt: float, n_steps: int
) -> tuple[np.ndarray, np.ndarray]:
"""Crank-Nicolson solver for rho*u_t = -dP/dx + mu*u_yy with u(0,t)=u(H,t)=0 and u(y,0)=0."""
y = np.linspace(0.0, H, n_nodes)
dy = y[1] - y[0]
nu = float(mu) / float(rho)
r = nu * dt / (dy ** 2)
src_dt = (-float(dP_dx) / float(rho)) * dt
u = np.zeros(n_nodes, dtype=float)
m_i = n_nodes - 2
lo = np.full(m_i - 1, -0.5 * r)
up = np.full(m_i - 1, -0.5 * r)
dg = np.full(m_i, 1.0 + r)
for _ in range(n_steps):
rhs = (1.0 - r) * u[1:-1] + 0.5 * r * (u[:-2] + u[2:]) + src_dt
u[1:-1] = grids_fvm.solve_tridiagonal(lo, dg, up, rhs)
return y, u
H_p, mu_p, rho_p, dpdx_p = 1.0, 0.1, 1.0, -1.6
nu_p = mu_p / rho_p
for fo_test in [0.03, 0.12, 0.80]:
t_end_p = fo_test * (H_p ** 2) / nu_p
n_st_p = 250
yg_p, u_cn_p = startup_poiseuille_cn(121, H_p, mu_p, rho_p, dpdx_p, dt=t_end_p / n_st_p, n_steps=n_st_p)
u_ex_p = exact_startup_poiseuille(yg_p, t=t_end_p, H=H_p, mu=mu_p, rho=rho_p, dP_dx=dpdx_p)
err_p = float(np.max(np.abs(u_cn_p - u_ex_p)))
print(f"Fo = {fo_test:4.2f} (t = {t_end_p:5.2f} s) | u_center = {u_cn_p[60]:.5f} m/s | max |CN - Exact| = {err_p:.3e}")
assert err_p < 5e-5
# At Fo = 0.80, verify steady-state approach to poiseuille_couette_exact (exp(-pi^2 * 0.8) ~ 3.7e-4):
u_steady_lib = navier_stokes.poiseuille_couette_exact(yg_p, H=H_p, mu=mu_p, dP_dx=dpdx_p, U_top=0.0)["u"]
assert float(np.max(np.abs(u_cn_p - u_steady_lib))) < 1e-3
Exercise 3: Implement It Yourself — Startup Planar Poiseuille Flow (Exact Series vs Crank-Nicolson)
===================================================================================================
Fo = 0.03 (t = 0.30 s) | u_center = 0.47018 m/s | max |CN - Exact| = 2.337e-05
Fo = 0.12 (t = 1.20 s) | u_center = 1.36846 m/s | max |CN - Exact| = 4.131e-05
Fo = 0.80 (t = 8.00 s) | u_center = 1.99923 m/s | max |CN - Exact| = 1.578e-07
Summary. Because a uniform pressure gradient is symmetric about the channel mid-plane , all even sine harmonics () vanish by symmetry. At early times (), fluid in the inviscid core accelerates uniformly as with thin Stokes wall boundary layers, before merging smoothly into the parabolic Hagen–Poiseuille profile as .