Worked solutions to the three exercises of Lecture 0. 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: Ideal-Gas Air Check & Complete 10-Fluid Prandtl check of FLUIDS_DB")
rho_air_ideal = constants.P_ATM / (constants.R_AIR * constants.T_STD)
rho_air_db = constants.FLUIDS_DB["air_298K"]["rho_kg_m3"]
print(f"Ideal-gas dry air at 1 atm, 298.15 K: rho = {rho_air_ideal:.4f} kg/m^3 vs FLUIDS_DB = {rho_air_db:.4f} kg/m^3")
ranked_fluids = sorted(constants.FLUIDS_DB.items(), key=lambda kv: kv[1]["Pr"])
print(f"\n{'Fluid':20s} | {'rho [kg/m^3]':>12s} | {'nu [m^2/s]':>11s} | {'alpha [m^2/s]':>13s} | {'Pr [-]':>10s}")
print("-" * 78)
for name, p in ranked_fluids:
print(f"{name:20s} | {p['rho_kg_m3']:12.3f} | {p['nu_m2_s']:11.3e} | {p['alpha_m2_s']:13.3e} | {p['Pr']:10.4f}")
assert len(constants.FLUIDS_DB) == 10
assert np.isclose(rho_air_ideal, rho_air_db, rtol=1e-3)
assert constants.FLUIDS_DB["liquid_sodium_673K"]["Pr"] < 0.01
assert 0.70 < constants.FLUIDS_DB["air_298K"]["Pr"] < 0.75
assert 5.5 < constants.FLUIDS_DB["water_298K"]["Pr"] < 6.5
assert constants.FLUIDS_DB["glycerol_298K"]["Pr"] > 5000.0
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Across all 10 fluids in constants.FLUIDS_DB at and , verify to relative error, and programmatically identify all fluids satisfying (a) with and (b) with .
heading("Exercise 1: Prandtl-Peclet Closure & Regime Inversion Across 10 Fluids")
U_ex1, L_ex1 = 0.25, 0.04
turb_low_pe, lam_high_pe = [], []
max_rel_err = 0.0
for name, p in sorted(constants.FLUIDS_DB.items(), key=lambda kv: kv[1]["Pr"]):
re_val = constants.reynolds_number(U_ex1, L_ex1, p["nu_m2_s"])
pe_val = constants.peclet_number(U_ex1, L_ex1, p["alpha_m2_s"])
pr_raw = (p["mu_Pa_s"] * p["cp_J_kgK"]) / p["k_W_mK"]
rel_err = abs((pe_val / re_val) - pr_raw) / pr_raw
max_rel_err = max(max_rel_err, rel_err)
if re_val > 1.0e4 and pe_val < 1.0e3:
turb_low_pe.append(name)
if re_val < 20.0 and pe_val > 5.0e4:
lam_high_pe.append(name)
print(f"{name:20s} | Re = {re_val:11.3f} | Pe_T = {pe_val:11.3f} | rel_err = {rel_err:.2e}")
print("\nRegime (a) [Re > 1e4 & Pe_T < 1e3]:", turb_low_pe)
print("Regime (b) [Re < 20 & Pe_T > 5e4]:", lam_high_pe)
assert max_rel_err < 1.0e-13
assert turb_low_pe == ["liquid_sodium_673K"]
assert lam_high_pe == ["glycerol_298K"]
Exercise 1: Prandtl-Peclet Closure & Regime Inversion Across 10 Fluids
======================================================================
liquid_sodium_673K | Re = 30140.845 | Pe_T = 151.310 | rel_err = 0.00e+00
mercury_298K | Re = 88689.384 | Pe_T = 2274.690 | rel_err = 1.35e-16
methane_298K | Re = 592.960 | Pe_T = 428.880 | rel_err = 1.53e-16
air_298K | Re = 640.346 | Pe_T = 467.564 | rel_err = 0.00e+00
steam_473K | Re = 286.420 | Pe_T = 274.371 | rel_err = 1.16e-16
co2_supercritical | Re = 131589.958 | Pe_T = 332405.839 | rel_err = 0.00e+00
water_298K | Re = 11202.809 | Pe_T = 68676.541 | rel_err = 1.45e-16
ethanol_298K | Re = 7309.125 | Pe_T = 114694.611 | rel_err = 1.13e-16
engine_oil_313K | Re = 41.714 | Pe_T = 119476.667 | rel_err = 0.00e+00
glycerol_298K | Re = 13.274 | Pe_T = 107384.105 | rel_err = 1.12e-16
Regime (a) [Re > 1e4 & Pe_T < 1e3]: ['liquid_sodium_673K']
Regime (b) [Re < 20 & Pe_T > 5e4]: ['glycerol_298K']
Explanation. Because cancels in , the ratio of thermal-to-momentum Péclet numbers is a pure material property (). Only liquid_sodium_673K (, ) combines high- turbulence with , while the very viscous glycerol_298K () has a very large thermal Péclet number () inside slow laminar flow ().
Exercise 2¶
Problem. Quantify the error factor when dynamic viscosity is mistakenly passed instead of into reynolds_number for water_298K and mercury_298K, evaluate the unphysical center-node stencil weight when the 1-D limit is used in 3-D explicit FTCS diffusion, and verify ValueError guards.
heading("Exercise 2: mu-vs-nu Unit Bug & 3-D Explicit Diffusion Blowup")
for fname in ("water_298K", "mercury_298K"):
p = constants.FLUIDS_DB[fname]
re_true = constants.reynolds_number(1.0, 0.05, p["nu_m2_s"])
re_bug = constants.reynolds_number(1.0, 0.05, p["mu_Pa_s"])
ratio = re_true / re_bug
print(f"{fname:14s} | True Re = {re_true:10.1f} | Buggy Re(mu) = {re_bug:7.2f} | Underpredicted by {ratio:,.2f}x (= rho)")
assert np.isclose(ratio, p["rho_kg_m3"], rtol=1e-13)
# 3-D explicit FTCS update u_P^{n+1} = (1 - 6*r)*u_P^n + r*(sum of 6 face neighbors):
r_1d_limit = 0.5
center_weight_3d = 1.0 - 6.0 * r_1d_limit
amp_nyquist_3d = abs(1.0 - 12.0 * r_1d_limit) # 3-D checkerboard mode (-1)^(i+j+k)
print(f"\nUsing 1-D limit r = {r_1d_limit} in 3-D: center weight = {center_weight_3d:.1f}, checkerboard |G| = {amp_nyquist_3d:.1f} (> 1 => explodes 5^n)")
assert np.isclose(center_weight_3d, -2.0, rtol=1e-14)
assert np.isclose(amp_nyquist_3d, 5.0, rtol=1e-14)
for fn, bad in [
(constants.reynolds_number, (1.0, 0.0, 1e-6)),
(constants.peclet_number, (1.0, 0.1, -1e-5)),
(constants.courant_number, (1.0, -1e-3, 1e-2)),
(constants.fourier_mesh_number, (-1e-6, 1e-3, 1e-2)),
]:
raised = False
try:
fn(*bad)
except ValueError:
raised = True
assert raised
Exercise 2: mu-vs-nu Unit Bug & 3-D Explicit Diffusion Blowup
=============================================================
water_298K | True Re = 56014.0 | Buggy Re(mu) = 56.18 | Underpredicted by 997.05x (= rho)
mercury_298K | True Re = 443446.9 | Buggy Re(mu) = 32.77 | Underpredicted by 13,534.00x (= rho)
Using 1-D limit r = 0.5 in 3-D: center weight = -2.0, checkerboard |G| = 5.0 (> 1 => explodes 5^n)
Explanation. Passing in place of omits density , underpredicting by in water and in mercury (which classifies a turbulent mercury pipe as laminar ). In 3-D explicit FTCS diffusion, applying makes the center weight and amplifies the checkerboard mode by every time step.
Exercise 3¶
Problem. Implement explicit_advection_diffusion_dt_max(u_m_s, diffusivity_m2_s, dx_m, ndim=1, safety=0.9) enforcing , and verify exact identity closure plus asymptotic log-slopes of 1.0 (advection regime) and 2.0 (diffusion regime).
heading("Exercise 3: Implement It Yourself — Multi-D Positivity-Preserving Explicit Step Selector")
def explicit_advection_diffusion_dt_max(
u_m_s: float,
diffusivity_m2_s: float,
dx_m: float,
ndim: int = 1,
safety: float = 0.9,
) -> dict:
"""Compute maximum explicit step dt satisfying |u|*dt/dx + 2*ndim*Gamma*dt/dx^2 = safety."""
if dx_m <= 0.0 or diffusivity_m2_s < 0.0 or ndim < 1 or not (0.0 < safety <= 1.0):
raise ValueError("Require dx_m > 0, diffusivity >= 0, ndim >= 1, and 0 < safety <= 1.")
rate_conv = abs(float(u_m_s)) / float(dx_m)
rate_diff = 2.0 * int(ndim) * float(diffusivity_m2_s) / (float(dx_m) ** 2)
if rate_conv + rate_diff == 0.0:
raise ValueError("At least one of |u_m_s| or diffusivity_m2_s must be positive.")
dt_max = float(safety) / (rate_conv + rate_diff)
cfl = constants.courant_number(u_m_s, dt_max, dx_m)
r_num = constants.fourier_mesh_number(diffusivity_m2_s, dt_max, dx_m)
return {"dt_max_s": dt_max, "cfl": cfl, "r_fourier": r_num, "combined_budget": cfl + 2.0 * ndim * r_num}
u_test, gamma_test = 1.0, 1.0e-4 # dx* = 2e-4 m in 1-D
dx_coarse = np.array([0.1, 0.2])
dx_fine = np.array([1.0e-6, 2.0e-6])
res_c = [explicit_advection_diffusion_dt_max(u_test, gamma_test, dx, ndim=3, safety=0.9) for dx in dx_coarse]
res_f = [explicit_advection_diffusion_dt_max(u_test, gamma_test, dx, ndim=3, safety=0.9) for dx in dx_fine]
slope_coarse = np.log(res_c[1]["dt_max_s"] / res_c[0]["dt_max_s"]) / np.log(dx_coarse[1] / dx_coarse[0])
slope_fine = np.log(res_f[1]["dt_max_s"] / res_f[0]["dt_max_s"]) / np.log(dx_fine[1] / dx_fine[0])
print(f"Coarse-grid log-slope (Pe_dx >> 1): {slope_coarse:.5f} (exact asymptotic = 1.0)")
print(f"Fine-grid log-slope (Pe_dx << 1): {slope_fine:.5f} (exact asymptotic = 2.0)")
for r in res_c + res_f:
assert np.isclose(r["combined_budget"], 0.9, rtol=1e-14)
assert np.isclose(slope_coarse, 1.0, atol=0.01)
assert np.isclose(slope_fine, 2.0, atol=0.01)
Exercise 3: Implement It Yourself — Multi-D Positivity-Preserving Explicit Step Selector
========================================================================================
Coarse-grid log-slope (Pe_dx >> 1): 1.00431 (exact asymptotic = 1.0)
Fine-grid log-slope (Pe_dx << 1): 1.99760 (exact asymptotic = 2.0)
Summary. Combining convective and -dimensional diffusive inverse time scales additively () guarantees discrete maximum-principle positivity across every grid resolution without ad-hoc min(dt_cfl, dt_diff) corner instabilities at .