Why can liquid sodium flowing through a fast-reactor coolant duct be turbulent in momentum () while behaving almost like a solid thermal conductor in energy transport (), whereas room-temperature glycerol moving slowly through the same pipe () forms very thin thermal boundary layers ()? And why does halving a computational mesh spacing cut the maximum explicit convective time step by (), yet reduces the explicit diffusive time step by ()? In this opening lecture, we connect integral and differential continuum conservation laws to physical fluid properties in constants.FLUIDS_DB and establish the dimensionless groups (Re, Pe, CFL, and mesh Fourier number ) that govern every solver in engcfd.
Learning objectives¶
Formulate integral finite-volume vs. differential divergence conservation laws and verify thermophysical trends across all 10 Newtonian fluids in
constants.FLUIDS_DB.Compute momentum
reynolds_number() and scalar/thermalpeclet_number(), contrasting liquid metals (), gases (), water (), and viscous polyols ().Quantify explicit time-step ceilings across mesh refinement by comparing convective
courant_number() against diffusivefourier_mesh_number().Identify the exact cell-Péclet crossover grid size where explicit time-stepping transitions from advection-limited to diffusion-limited.
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: Integral Conservation Laws & FLUIDS_DB¶
1.1 Integral vs. Differential Conservation Laws¶
Every finite-volume CFD solver begins not with partial derivatives, but with an integral balance over a fixed control volume bounded by closed surface with outward unit normal . For any conserved intensive density (mass , momentum , or enthalpy ) subject to total flux and volumetric source :
Only when and are continuously differentiable () can Gauss’s divergence theorem convert the surface integral into a volume integral to yield the differential divergence form:
Across shock waves (Lectures 8 to 10) or discontinuous composite-material interfaces (Lecture 2), classical derivatives blow up while Equation (1.1) remains exact.
1.2 Momentum vs. Thermal Diffusivity Across Six Orders of Prandtl Number¶
In a Newtonian fluid of density , dynamic viscosity , thermal conductivity , and isobaric heat capacity , momentum and thermal energy diffuse with kinematic diffusivities and :
We audit the gas constant, the gravitational acceleration and all 10 benchmark fluids curated in constants.FLUIDS_DB.
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
Demonstration 1: Ideal-Gas Air Check & Complete 10-Fluid Prandtl check of FLUIDS_DB
===================================================================================
Ideal-gas dry air at 1 atm, 298.15 K: rho = 1.1839 kg/m^3 vs FLUIDS_DB = 1.1840 kg/m^3
Fluid | rho [kg/m^3] | nu [m^2/s] | alpha [m^2/s] | Pr [-]
------------------------------------------------------------------------------
liquid_sodium_673K | 856.000 | 3.318e-07 | 6.609e-05 | 0.0050
mercury_298K | 13534.000 | 1.128e-07 | 4.396e-06 | 0.0256
methane_298K | 0.657 | 1.686e-05 | 2.332e-05 | 0.7233
air_298K | 1.184 | 1.562e-05 | 2.139e-05 | 0.7302
steam_473K | 0.464 | 3.491e-05 | 3.645e-05 | 0.9579
co2_supercritical | 629.000 | 7.599e-08 | 3.008e-08 | 2.5261
water_298K | 997.050 | 8.926e-07 | 1.456e-07 | 6.1303
ethanol_298K | 785.000 | 1.368e-06 | 8.719e-08 | 15.6920
engine_oil_313K | 876.000 | 2.397e-04 | 8.370e-08 | 2864.1667
glycerol_298K | 1261.000 | 7.534e-04 | 9.312e-08 | 8090.0000
What Demonstration 1 shows. constants.FLUIDS_DB spans six orders of magnitude in Prandtl number ( in liquid_sodium_673K up to in glycerol_298K):
Liquid metals (): Free-electron conduction makes in liquid sodium (
6.61e-5vs.3.32e-7), so heat diffuses far faster than vorticity.Diatomic/light gases (): Kinetic theory of gases ties molecular momentum and energy mean-free-path transport together (
air_298K,methane_298K,steam_473K).Hydrogen-bonded & viscous liquids (): Heavy entangled molecules transfer momentum rapidly via intermolecular shear (), while phonon-like thermal conduction () stays modest (
water_298K,glycerol_298K).
2. Reynolds vs. Péclet Scaling in Channel & Pipe Flows¶
Non-dimensionalizing steady advection–diffusion by characteristic speed and length scale yields the Reynolds number (for momentum, ) and thermal Péclet number (for temperature, ):
We subject all 10 fluids to the identical geometric and kinematic flow ( in a pipe) using constants.reynolds_number and constants.peclet_number.
heading("Demonstration 2: Identical Pipe Flow (U = 0.20 m/s, D = 0.05 m) Across All 10 Fluids")
U_pipe = 0.20 # [m/s]
D_pipe = 0.05 # [m]
print(f"{'Fluid':20s} | {'Re [-]':>12s} | {'Pe_T [-]':>12s} | {'Pe_T / Re':>10s} | {'Flow / Thermal Regime'}")
print("-" * 88)
for name, p in ranked_fluids:
re = constants.reynolds_number(U_pipe, D_pipe, p["nu_m2_s"])
pe = constants.peclet_number(U_pipe, D_pipe, p["alpha_m2_s"])
assert np.isclose(pe, re * p["Pr"], rtol=1e-13)
mom_reg = "Turbulent" if re > 4000 else ("Transitional" if re > 2300 else ("Creeping" if re < 1 else "Laminar"))
thm_reg = "High-Pe BL" if pe > 1000 else "Moderate-Pe"
print(f"{name:20s} | {re:12.2f} | {pe:12.2f} | {pe / re:10.4f} | {mom_reg} / {thm_reg}")
re_na = constants.reynolds_number(U_pipe, D_pipe, constants.FLUIDS_DB["liquid_sodium_673K"]["nu_m2_s"])
pe_na = constants.peclet_number(U_pipe, D_pipe, constants.FLUIDS_DB["liquid_sodium_673K"]["alpha_m2_s"])
re_gly = constants.reynolds_number(U_pipe, D_pipe, constants.FLUIDS_DB["glycerol_298K"]["nu_m2_s"])
pe_gly = constants.peclet_number(U_pipe, D_pipe, constants.FLUIDS_DB["glycerol_298K"]["alpha_m2_s"])
assert re_na > 3.0e4 and pe_na < 160.0
assert re_gly < 15.0 and pe_gly > 1.0e5
Demonstration 2: Identical Pipe Flow (U = 0.20 m/s, D = 0.05 m) Across All 10 Fluids
====================================================================================
Fluid | Re [-] | Pe_T [-] | Pe_T / Re | Flow / Thermal Regime
----------------------------------------------------------------------------------------
liquid_sodium_673K | 30140.85 | 151.31 | 0.0050 | Turbulent / Moderate-Pe
mercury_298K | 88689.38 | 2274.69 | 0.0256 | Turbulent / High-Pe BL
methane_298K | 592.96 | 428.88 | 0.7233 | Laminar / Moderate-Pe
air_298K | 640.35 | 467.56 | 0.7302 | Laminar / Moderate-Pe
steam_473K | 286.42 | 274.37 | 0.9579 | Laminar / Moderate-Pe
co2_supercritical | 131589.96 | 332405.84 | 2.5261 | Turbulent / High-Pe BL
water_298K | 11202.81 | 68676.54 | 6.1303 | Turbulent / High-Pe BL
ethanol_298K | 7309.12 | 114694.61 | 15.6920 | Turbulent / High-Pe BL
engine_oil_313K | 41.71 | 119476.67 | 2864.1667 | Laminar / High-Pe BL
glycerol_298K | 13.27 | 107384.11 | 8090.0000 | Laminar / High-Pe BL
fig, ax = plt.subplots(figsize=(6.6, 4.4))
label_offset = {"methane_298K": (8, -12), "air_298K": (8, 5), "steam_473K": (-68, -3), "ethanol_298K": (-8, 7),
"engine_oil_313K": (6, 5), "glycerol_298K": (6, -11), "co2_supercritical": (-102, -4),
"water_298K": (-62, -13), "mercury_298K": (-80, -3)}
for name_f, props_f in constants.FLUIDS_DB.items():
re_f = constants.reynolds_number(0.20, 0.05, props_f["nu_m2_s"])
pe_f = constants.peclet_number(0.20, 0.05, props_f["alpha_m2_s"])
ax.loglog(re_f, pe_f, "o", color="C0")
ax.annotate(name_f, (re_f, pe_f), textcoords="offset points", xytext=label_offset.get(name_f, (6, 4)), fontsize=8)
re_line = np.array([5.0, 5.0e5])
ax.loglog(re_line, re_line, "k--", lw=1.0, label=r"$\mathrm{Pr} = 1$")
ax.set_xlim(5.0, 5.0e5); ax.set_ylim(50.0, 2.0e6)
ax.set_xlabel(r"Reynolds number $\mathrm{Re}$ [-]"); ax.set_ylabel(r"thermal Péclet number $\mathrm{Pe}_T$ [-]")
ax.legend(loc="lower right")
plt.show()
Figure 0.1. Thermal Péclet number against Reynolds number for the ten fluids of FLUIDS_DB at m/s and m. The vertical distance of a point from the dashed line is its Prandtl number.
What Demonstration 2 shows. liquid_sodium_673K and glycerol_298K behave in opposite ways at the same :
Liquid sodium: (fully turbulent hydrodynamic core with thin viscous wall sublayer), yet (broad conductive temperature profile across the duct).
Glycerol: (deeply laminar viscous flow), yet ( higher thermal Péclet than turbulent sodium, which gives very thin thermal boundary layers).
3. Explicit Time-Step Ceilings: Convective CFL vs. Diffusive Fourier Limits¶
When advancing an explicit time-marching CFD solver on grid spacing with step , two dimensionless stability numbers control whether information outruns the numerical stencil:
In spatial dimension (, ), the maximum allowable explicit time steps scale with different powers of :
Equating gives the crossover grid spacing:
Coarser grids (, ) are convection-limited; finer grids (, ) become diffusion-stiff.
heading("Demonstration 3: CFL vs Diffusive Fourier Time-Step Scaling Across Mesh Refinement")
u_adv = 0.05 # [m/s]
nu_oil = constants.FLUIDS_DB["engine_oil_313K"]["nu_m2_s"] # ~2.397e-4 m^2/s
dx_grid = np.logspace(-4, -1, 100) # 0.1 mm to 10 cm
dt_cfl = dx_grid / u_adv
dt_diff = 0.5 * (dx_grid ** 2) / nu_oil
dt_combined = 1.0 / (1.0 / dt_cfl + 1.0 / dt_diff) # exact 1-D upwind advection-diffusion ceiling C + 2r <= 1
dx_star = 2.0 * nu_oil / u_adv
dt_star = dx_star / u_adv
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.2, 4.3))
ax1.loglog(dx_grid, dt_cfl, "--", color="#1f77b4", lw=2.0, label=r"Convective limit $\Delta t_{\mathrm{CFL}} = \Delta x / |u|$")
ax1.loglog(dx_grid, dt_diff, "-.", color="#d62728", lw=2.0, label=r"Diffusive limit $\Delta t_{\mathrm{diff}} = \Delta x^2 / (2\nu)$")
ax1.loglog(dx_grid, dt_combined, "-", color="#111111", lw=2.4, label=r"Combined $\mathrm{CFL} + 2r \leq 1$")
ax1.scatter([dx_star], [dt_star], color="#2ca02c", s=70, zorder=5, label=rf"Crossover $\Delta x^* = {dx_star*1e3:.2f}\ \mathrm{{mm}}$ ($\mathrm{{Pe}}_{{\Delta x}}=2$)")
ax1.set_xlabel(r"Grid Spacing $\Delta x$ [m]")
ax1.set_ylabel(r"Max Explicit Time Step $\Delta t_{\max}$ [s]")
ax1.set_title("Engine Oil ($u=0.05$ m/s): $\\propto \\Delta x$ vs. $\\propto \\Delta x^2$ Stiffness")
ax1.legend(fontsize=8.2, frameon=False)
# Right panel: Prandtl number vs kinematic viscosity/diffusivity map across all 10 fluids
names = [k for k, _ in ranked_fluids]
prs = [p["Pr"] for _, p in ranked_fluids]
nus = [p["nu_m2_s"] for _, p in ranked_fluids]
alphas = [p["alpha_m2_s"] for _, p in ranked_fluids]
y_pos = np.arange(len(names))
ax2.scatter(nus, y_pos, color="#1f77b4", marker="o", s=55, label=r"Momentum $\nu$ [$\mathrm{m^2/s}$]")
ax2.scatter(alphas, y_pos, color="#d62728", marker="s", s=55, label=r"Thermal $\alpha$ [$\mathrm{m^2/s}$]")
for yi, nv, av in zip(y_pos, nus, alphas):
ax2.plot([min(nv, av), max(nv, av)], [yi, yi], color="gray", lw=1.2, alpha=0.6)
ax2.set_xscale("log")
ax2.set_yticks(y_pos)
ax2.set_yticklabels(names, fontsize=8.5)
ax2.set_xlabel(r"Diffusivity [$\mathrm{m^2/s}$]")
ax2.set_title(r"Momentum $\nu$ vs. Thermal $\alpha$ Across `FLUIDS_DB`")
ax2.legend(fontsize=8.5, frameon=False)
label_panels(fig)
plt.show()
cfl_at_star = constants.courant_number(u_adv, dt_star, dx_star)
r_at_star = constants.fourier_mesh_number(nu_oil, dt_star, dx_star)
pe_at_star = constants.peclet_number(u_adv, dx_star, nu_oil)
print(f"At crossover dx* = {dx_star:.6f} m: CFL = {cfl_at_star:.4f}, r = {r_at_star:.4f}, Pe_dx = {pe_at_star:.4f}")
assert np.isclose(cfl_at_star, 1.0, rtol=1e-14)
assert np.isclose(r_at_star, 0.5, rtol=1e-14)
assert np.isclose(pe_at_star, 2.0, rtol=1e-14)
Demonstration 3: CFL vs Diffusive Fourier Time-Step Scaling Across Mesh Refinement
==================================================================================

At crossover dx* = 0.009589 m: CFL = 1.0000, r = 0.5000, Pe_dx = 2.0000
Figure 0.2. (a) Largest stable explicit time step against grid spacing for engine oil moving at 0.05 m/s: the convective limit, the diffusive limit and the combined limit; the point marks the grid spacing at which the two limits are equal. (b) Kinematic viscosity and thermal diffusivity of the ten fluids of FLUIDS_DB; the length of each bar is the Prandtl number on the logarithmic axis.
What Demonstration 3 shows. marks the exact threshold (which we will meet again in Lecture 4 as the central-difference oscillation limit). Refining a viscous wall mesh from to forces a smaller explicit diffusive step (plus another more cells in 1-D, or in 3-D, inflating 3-D explicit runtime by ). That quadratic penalty explains why industrial Navier–Stokes solvers treat viscous diffusion implicitly (Crank–Nicolson / ADI).
4. Multi-Dimensional Fourier Limits, Sign Conventions & Guards¶
Two subtleties frequently trip up CFD practitioners:
Dimensionality penalty in explicit diffusion: On an isotropic -dimensional Cartesian mesh (), the center coefficient of explicit FTCS diffusion stays non-negative only when (0.5 in 1-D, 0.25 in 2-D, in 3-D).
Signed Péclet vs. Unsigned Reynolds/CFL: Flow direction matters for upwind flux biasing (
peclet_numberpreserves the sign ofu_m_s), whereasreynolds_numberandcourant_numbertake and accept vectorized velocity arrays.
heading("Demonstration 4: Signed Peclet, Vectorized Velocities & Multi-D Fourier Limits")
u_profile = np.array([-2.5, -0.5, 0.0, 0.5, 2.5]) # reversing shear-layer velocity [m/s]
nu_w = constants.FLUIDS_DB["water_298K"]["nu_m2_s"]
re_vec = constants.reynolds_number(u_profile, 0.01, nu_w)
pe_vec = constants.peclet_number(u_profile, 0.01, nu_w)
cfl_vec = constants.courant_number(u_profile, 1.0e-3, 5.0e-3)
print("Velocity u [m/s] :", u_profile)
print("Unsigned Re [-] :", np.round(re_vec, 2))
print("Signed Pe [-] :", np.round(pe_vec, 2))
print("Unsigned CFL [-] :", np.round(cfl_vec, 3))
assert np.all(re_vec >= 0.0) and np.all(cfl_vec >= 0.0)
assert np.allclose(pe_vec, -pe_vec[::-1], rtol=1e-14)
# Multi-dimensional explicit FTCS diffusion limit dt_max(d) = dx^2 / (2 * d * alpha):
dx_test = 1.0e-3
alpha_na = constants.FLUIDS_DB["liquid_sodium_673K"]["alpha_m2_s"]
for dim in (1, 2, 3):
dt_d = (dx_test ** 2) / (2.0 * dim * alpha_na)
r_d = constants.fourier_mesh_number(alpha_na, dt_d, dx_test)
print(f"{dim}-D liquid-sodium thermal FTCS limit (dx=1 mm): dt_max = {dt_d*1e3:.4f} ms (r = {r_d:.4f} <= {1/(2*dim):.4f})")
assert np.isclose(r_d, 1.0 / (2.0 * dim), rtol=1e-14)
# Verify defensive input validation on non-positive length, viscosity, or grid step:
caught_re, caught_r = False, False
try:
constants.reynolds_number(1.0, -0.05, nu_w)
except ValueError:
caught_re = True
try:
constants.fourier_mesh_number(nu_w, 0.0, 1.0e-3)
except ValueError:
caught_r = True
assert caught_re and caught_r
Demonstration 4: Signed Peclet, Vectorized Velocities & Multi-D Fourier Limits
==============================================================================
Velocity u [m/s] : [-2.5 -0.5 0. 0.5 2.5]
Unsigned Re [-] : [28007.02 5601.4 0. 5601.4 28007.02]
Signed Pe [-] : [-28007.02 -5601.4 0. 5601.4 28007.02]
Unsigned CFL [-] : [0.5 0.1 0. 0.1 0.5]
1-D liquid-sodium thermal FTCS limit (dx=1 mm): dt_max = 7.5655 ms (r = 0.5000 <= 0.5000)
2-D liquid-sodium thermal FTCS limit (dx=1 mm): dt_max = 3.7827 ms (r = 0.2500 <= 0.2500)
3-D liquid-sodium thermal FTCS limit (dx=1 mm): dt_max = 2.5218 ms (r = 0.1667 <= 0.1667)
Inside the algorithm¶
Below we inspect the exact implementation of constants.reynolds_number, constants.peclet_number, constants.courant_number, and constants.fourier_mesh_number, and verify all derived properties in constants.FLUIDS_DB from raw primitives using pure NumPy vectorization.
Check against the library¶
heading("Inside the Algorithm: NumPy check of Dimensionless Groups & FLUIDS_DB")
print(show_source(constants.reynolds_number))
print(show_source(constants.fourier_mesh_number))
keys = list(constants.FLUIDS_DB.keys())
rho_arr = np.array([constants.FLUIDS_DB[k]["rho_kg_m3"] for k in keys])
mu_arr = np.array([constants.FLUIDS_DB[k]["mu_Pa_s"] for k in keys])
k_arr = np.array([constants.FLUIDS_DB[k]["k_W_mK"] for k in keys])
cp_arr = np.array([constants.FLUIDS_DB[k]["cp_J_kgK"] for k in keys])
nu_np = mu_arr / rho_arr
alpha_np = k_arr / (rho_arr * cp_arr)
pr_np = (mu_arr * cp_arr) / k_arr
nu_db = np.array([constants.FLUIDS_DB[k]["nu_m2_s"] for k in keys])
alpha_db = np.array([constants.FLUIDS_DB[k]["alpha_m2_s"] for k in keys])
pr_db = np.array([constants.FLUIDS_DB[k]["Pr"] for k in keys])
print(f"Max |nu_np - nu_db| = {np.max(np.abs(nu_np - nu_db)):.2e} m^2/s")
print(f"Max |alpha_np - alpha_db| = {np.max(np.abs(alpha_np - alpha_db)):.2e} m^2/s")
print(f"Max |Pr_np - Pr_db| = {np.max(np.abs(pr_np - pr_db)):.2e}")
assert np.allclose(nu_np, nu_db, rtol=1e-14)
assert np.allclose(alpha_np, alpha_db, rtol=1e-14)
assert np.allclose(pr_np, pr_db, rtol=1e-14)
Inside the Algorithm: NumPy check of Dimensionless Groups & FLUIDS_DB
=====================================================================
def reynolds_number(u_m_s: float | np.ndarray, L_m: float, nu_m2_s: float) -> float | np.ndarray:
"""Compute Reynolds number Re = |u| * L / nu [-]."""
if L_m <= 0.0 or nu_m2_s <= 0.0:
raise ValueError("Characteristic length L_m and kinematic viscosity nu_m2_s must be > 0.")
re_val = np.abs(np.asarray(u_m_s, dtype=float)) * float(L_m) / float(nu_m2_s)
return float(re_val) if np.ndim(u_m_s) == 0 else re_val
def fourier_mesh_number(diffusivity_m2_s: float, dt_s: float, dx_m: float) -> float:
"""Compute diffusive mesh Fourier number r = Gamma * dt / dx^2 [-]."""
if diffusivity_m2_s < 0.0 or dt_s <= 0.0 or dx_m <= 0.0:
raise ValueError("Require diffusivity >= 0, dt_s > 0, and dx_m > 0.")
return float(diffusivity_m2_s * dt_s / (dx_m**2))
Max |nu_np - nu_db| = 0.00e+00 m^2/s
Max |alpha_np - alpha_db| = 0.00e+00 m^2/s
Max |Pr_np - Pr_db| = 9.09e-13
Exercises¶
Worked solutions are in 00_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Across all 10 fluids in
constants.FLUIDS_DBat and , verify to relative error, and programmatically identify all fluids satisfying (a) with and (b) with .Find how it fails. Quantify the error factor when dynamic viscosity is mistakenly passed instead of into
reynolds_numberforwater_298Kandmercury_298K, evaluate the unphysical center-node stencil weight when the 1-D limit is used in 3-D explicit FTCS diffusion, and verifyValueErrorguards.Implement it yourself. 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("Self-check for the exercises")
U_chk, L_chk = 0.25, 0.04
turb_low_pe, lam_high_pe = [], []
for name, p in constants.FLUIDS_DB.items():
re_c = constants.reynolds_number(U_chk, L_chk, p["nu_m2_s"])
pe_c = constants.peclet_number(U_chk, L_chk, p["alpha_m2_s"])
assert np.isclose(pe_c / re_c, (p["mu_Pa_s"] * p["cp_J_kgK"]) / p["k_W_mK"], rtol=1e-13)
if re_c > 1.0e4 and pe_c < 1.0e3:
turb_low_pe.append(name)
if re_c < 20.0 and pe_c > 5.0e4:
lam_high_pe.append(name)
print("Turbulent (Re > 1e4) yet Pe_T < 1e3 :", turb_low_pe)
print("Laminar (Re < 20) yet Pe_T > 5e4 :", lam_high_pe)
assert "liquid_sodium_673K" in turb_low_pe
assert "glycerol_298K" in lam_high_pe
print("All checks passed.")
Self-check for the exercises
============================
Turbulent (Re > 1e4) yet Pe_T < 1e3 : ['liquid_sodium_673K']
Laminar (Re < 20) yet Pe_T > 5e4 : ['glycerol_298K']
All checks passed.