Worked solutions to the three exercises of Lecture 2. 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: Nuclear Fuel Slab With Volumetric Heat Generation (Dirichlet & Neumann BCs)")
L_slab = 0.10 # [m]
k_fuel = 20.0 # [W/(m*K)]
q_vol = 1.6e6 # [W/m^3]
mesh = grids_fvm.uniform_fvm_grid_1d(0.0, L_slab, 12)
# Case A: Asymmetric Dirichlet walls T(0) = 400 K, T(L) = 500 K
sol_dir = grids_fvm.fvm_diffusion_1d_steady(
mesh["x_faces"], k_cells=k_fuel, q_source=q_vol,
bc_left=("dirichlet", 400.0), bc_right=("dirichlet", 500.0),
)
xc = sol_dir["x_centers"]
T_exact_dir = 400.0 + (500.0 - 400.0) * (xc / L_slab) + (q_vol / (2.0 * k_fuel)) * xc * (L_slab - xc)
J_left_exact = -k_fuel * ((500.0 - 400.0) / L_slab + q_vol * L_slab / (2.0 * k_fuel))
J_right_exact = -k_fuel * ((500.0 - 400.0) / L_slab - q_vol * L_slab / (2.0 * k_fuel))
# Case B: Adiabatic centerline J(0) = 0 (Neumann) and cooled cladding T(L) = 450 K (Dirichlet)
sol_neu = grids_fvm.fvm_diffusion_1d_steady(
mesh["x_faces"], k_cells=k_fuel, q_source=q_vol,
bc_left=("neumann", 0.0), bc_right=("dirichlet", 450.0),
)
T_exact_neu = 450.0 + (q_vol / (2.0 * k_fuel)) * (L_slab ** 2 - xc ** 2)
half_cell_offset = q_vol * (mesh["dx"] ** 2) / (8.0 * k_fuel)
print(f"Dirichlet-Dirichlet max |T_fvm - T_exact| = {np.max(np.abs(sol_dir['phi'] - T_exact_dir)):.4f} K (= exact O(dx^2) half-cell offset q*dx^2/(8k) = {half_cell_offset:.4f} K)")
print(f"Dirichlet wall fluxes: FVM = ({sol_dir['face_fluxes'][0]:.2f}, {sol_dir['face_fluxes'][-1]:.2f}) vs Exact = ({J_left_exact:.2f}, {J_right_exact:.2f}) W/m^2")
print(f"Neumann-Dirichlet max |T_fvm - T_exact| = {np.max(np.abs(sol_neu['phi'] - T_exact_neu)):.4f} K | J_right = {sol_neu['face_fluxes'][-1]:.2f} W/m^2 (= q*L = {q_vol*L_slab:.2f})")
print(f"Max cell balance residual = {sol_dir['max_cell_balance_residual']:.2e} W/m^2")
# Verify pure linear conduction (q = 0) is exact at centroids to machine precision, and parabolic offset == q*dx^2/(8k):
sol_lin = grids_fvm.fvm_diffusion_1d_steady(mesh["x_faces"], k_fuel, 0.0, ("dirichlet", 400.0), ("dirichlet", 500.0))
assert np.allclose(sol_lin["phi"], 400.0 + 100.0 * (xc / L_slab), atol=1e-12)
assert np.allclose(sol_dir["phi"] - T_exact_dir, half_cell_offset, rtol=1e-11)
assert np.isclose(sol_dir["face_fluxes"][0], J_left_exact, rtol=1e-12)
assert np.isclose(sol_dir["face_fluxes"][-1], J_right_exact, rtol=1e-12)
assert np.allclose(sol_neu["phi"] - T_exact_neu, half_cell_offset, rtol=1e-11)
assert np.isclose(sol_neu["face_fluxes"][-1], q_vol * L_slab, rtol=1e-12)
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify the limit of a nearly perfect insulator (, ) of harmonic_interface_conductivity on equal () and unequal () cell volumes, confirming matches exact series thermal resistance.
heading("Exercise 1: Perfect-Insulator Asymptotics & Non-Uniform Volume Harmonic Weighting")
k_pair = np.array([200.0, 1.0e-8])
vols_eq = np.array([0.05, 0.05])
vols_uneq = np.array([0.02, 0.08])
kh_eq = grids_fvm.harmonic_interface_conductivity(k_pair, vols_eq)[0]
kh_uneq = grids_fvm.harmonic_interface_conductivity(k_pair, vols_uneq)[0]
ka_eq = float(np.mean(k_pair))
# Exact unequal-cell series formula (0.01 + 0.04) / (0.01/200 + 0.04/1e-8) -> 1.25 * k_1:
kh_uneq_exact = (0.01 + 0.04) / (0.01 / 200.0 + 0.04 / 1.0e-8)
print(f"Equal volumes (0.05, 0.05): k_harm = {kh_eq:.6e} (~ 2.00 * k_ins) vs k_arith = {ka_eq:.2f} W/(m*K)")
print(f"Unequal volumes (0.02, 0.08): k_harm = {kh_uneq:.6e} (~ 1.25 * k_ins) vs exact = {kh_uneq_exact:.6e}")
sol_barrier = grids_fvm.fvm_diffusion_1d_steady(
np.array([0.0, 0.02, 0.10]), k_pair, q_source=0.0, bc_left=("dirichlet", 800.0), bc_right=("dirichlet", 300.0)
)
J_exact_bar = (800.0 - 300.0) / (0.02 / 200.0 + 0.08 / 1.0e-8)
print(f"Heat flux across insulator: FVM = {sol_barrier['face_fluxes'][0]:.6e} vs Exact = {J_exact_bar:.6e} W/m^2")
assert np.isclose(kh_eq, 2.0e-8, rtol=1e-9)
assert np.isclose(kh_uneq, kh_uneq_exact, rtol=1e-14)
assert np.isclose(sol_barrier["face_fluxes"][0], J_exact_bar, rtol=1e-12)
Exercise 1: Perfect-Insulator Asymptotics & Non-Uniform Volume Harmonic Weighting
=================================================================================
Equal volumes (0.05, 0.05): k_harm = 2.000000e-08 (~ 2.00 * k_ins) vs k_arith = 100.00 W/(m*K)
Unequal volumes (0.02, 0.08): k_harm = 1.250000e-08 (~ 1.25 * k_ins) vs exact = 1.250000e-08
Heat flux across insulator: FVM = 6.249820e-05 vs Exact = 6.250000e-05 W/m^2
Explanation. When , the series resistance is controlled by the insulating layer, giving ( for equal cells, for ) so the heat flux is very small ().
Exercise 2¶
Problem. Quantify the exact heat-flux error from using full-cell distance instead of half-cell at Dirichlet boundaries on linear conduction (), and verify ValueError guards on negative conductivity and unsupported BC names.
heading("Exercise 2: Full-Cell vs Half-Cell Dirichlet Wall Conductance Bug")
N_test = 10
k_val, L_val, T_L, T_R = 10.0, 1.0, 100.0, 0.0
gm = grids_fvm.uniform_fvm_grid_1d(0.0, L_val, N_test)
dx = gm["dx"]
sol_true = grids_fvm.fvm_diffusion_1d_steady(gm["x_faces"], k_val, 0.0, ("dirichlet", T_L), ("dirichlet", T_R))
# Buggy assembly using G_wall = k / dx instead of 2*k / dx (adds dx/2 fake wall thickness on BOTH ends -> L_eff = L + dx):
cond_i = np.full(N_test - 1, k_val / dx)
diag_b = np.full(N_test, 2.0 * k_val / dx)
rhs_b = np.zeros(N_test)
g_wall_bug = k_val / dx # BUG: missing factor of 2
diag_b[0] = cond_i[0] + g_wall_bug; rhs_b[0] = g_wall_bug * T_L
diag_b[-1] = cond_i[-1] + g_wall_bug; rhs_b[-1] = g_wall_bug * T_R
phi_bug = grids_fvm.solve_tridiagonal(-cond_i, diag_b, -cond_i, rhs_b)
J_bug = -g_wall_bug * (phi_bug[0] - T_L)
J_exact_lin = k_val * (T_L - T_R) / L_val # 1000 W/m^2
J_bug_theory = k_val * (T_L - T_R) / (L_val + dx) # 1000 / 1.1 = 909.09 W/m^2
print(f"True half-cell FVM flux = {sol_true['face_fluxes'][0]:.4f} W/m^2 (exact = {J_exact_lin:.4f})")
print(f"Buggy full-cell FVM flux = {J_bug:.4f} W/m^2 (matches L_eff = L + dx = {J_bug_theory:.4f}, {100*(J_exact_lin-J_bug)/J_exact_lin:.2f}% error)")
assert np.isclose(sol_true["face_fluxes"][0], J_exact_lin, rtol=1e-13)
assert np.isclose(J_bug, J_bug_theory, rtol=1e-13)
# Verify defensive ValueError checks:
for fn, args in [
(grids_fvm.harmonic_interface_conductivity, (np.array([10.0, -1.0]), np.array([0.5, 0.5]))),
(grids_fvm.harmonic_interface_conductivity, (np.array([10.0, 5.0]), np.array([0.5]))),
(grids_fvm.fvm_diffusion_1d_steady, (gm["x_faces"], 10.0, 0.0, ("periodic_bad", 0.0), ("dirichlet", 0.0))),
]:
raised = False
try:
fn(*args)
except ValueError:
raised = True
assert raised
Exercise 2: Full-Cell vs Half-Cell Dirichlet Wall Conductance Bug
=================================================================
True half-cell FVM flux = 1000.0000 W/m^2 (exact = 1000.0000)
Buggy full-cell FVM flux = 909.0909 W/m^2 (matches L_eff = L + dx = 909.0909, 9.09% error)
Explanation. Treating the boundary-to-centroid distance as instead of inserts a phantom slab on each wall, stretching the effective domain length to and underpredicting heat flux by .
Exercise 3¶
Problem. Implement fvm_diffusion_1d_robin(x_faces, k_cells, q_source, h_left, T_inf_left, h_right, T_inf_right) using series film-plus-half-cell conductance , and verify to rounding error against the exact Biot-number analytical parabola on ().
heading("Exercise 3: Implement It Yourself — 1-D FVM Diffusion with Convective Robin Boundary Conditions")
def fvm_diffusion_1d_robin(
x_faces: np.ndarray,
k_cells: float | np.ndarray,
q_source: float | np.ndarray,
h_left: float,
T_inf_left: float,
h_right: float,
T_inf_right: float,
) -> dict:
"""Solve -d/dx(k dT/dx) = q with convective Robin cooling J_out = h*(T_wall - T_inf) at both ends."""
xf = np.asarray(x_faces, dtype=float).ravel()
vols = np.diff(xf)
xc = 0.5 * (xf[:-1] + xf[1:])
n = xc.size
kc = np.full(n, float(k_cells)) if np.ndim(k_cells) == 0 else np.asarray(k_cells, dtype=float)
qs = np.full(n, float(q_source)) if np.ndim(q_source) == 0 else np.asarray(q_source, dtype=float)
k_int = grids_fvm.harmonic_interface_conductivity(kc, vols)
cond = k_int / np.diff(xc)
diag = np.zeros(n)
diag[:-1] += cond; diag[1:] += cond
rhs = qs * vols
g_rob_l = 1.0 / (1.0 / float(h_left) + (xc[0] - xf[0]) / kc[0])
g_rob_r = 1.0 / (1.0 / float(h_right) + (xf[-1] - xc[-1]) / kc[-1])
diag[0] += g_rob_l; rhs[0] += g_rob_l * float(T_inf_left)
diag[-1] += g_rob_r; rhs[-1] += g_rob_r * float(T_inf_right)
T_sol = grids_fvm.solve_tridiagonal(-cond, diag, -cond, rhs)
J_left = -g_rob_l * (T_sol[0] - T_inf_left) # flux in +x at x_min
J_right = g_rob_r * (T_sol[-1] - T_inf_right) # flux in +x at x_max
return {"x_centers": xc, "T": T_sol, "J_left": float(J_left), "J_right": float(J_right)}
L_half, k_s, q_s, h_conv, T_amb = 0.05, 25.0, 5.0e5, 250.0, 300.0
Bi = h_conv * L_half / k_s # Biot number = 0.5
# 1. Source-free asymmetric Robin heat transfer (T_inf_L = 500 K, T_inf_R = 300 K) is exact to machine precision on ANY stretched grid:
g_str = grids_fvm.tanh_stretched_grid_1d(-L_half, L_half, 16, beta_cluster=1.8, two_sided=True)
out_lin_rob = fvm_diffusion_1d_robin(g_str["x_faces"], k_s, 0.0, h_conv, 500.0, h_conv, 300.0)
J_exact_rob_lin = (500.0 - 300.0) / (1.0 / h_conv + (2.0 * L_half) / k_s + 1.0 / h_conv)
assert np.isclose(out_lin_rob["J_right"], J_exact_rob_lin, rtol=1e-13)
# 2. Volumetric-source Biot parabola on stretched meshes N = 16, 32, 64: exact global flux balance + O(N^-2) convergence
errs_bi = []
for n_r in (16, 32, 64):
gr = grids_fvm.tanh_stretched_grid_1d(-L_half, L_half, n_r, beta_cluster=1.8, two_sided=True)
out_r = fvm_diffusion_1d_robin(gr["x_faces"], k_s, q_s, h_conv, T_amb, h_conv, T_amb)
xc_r = out_r["x_centers"]
T_exact_bi = T_amb + (q_s * (L_half ** 2) / (2.0 * k_s)) * (1.0 - (xc_r / L_half) ** 2 + 2.0 / Bi)
errs_bi.append(float(np.max(np.abs(out_r["T"] - T_exact_bi))))
assert np.isclose(out_r["J_right"] - out_r["J_left"], q_s * (2.0 * L_half), rtol=1e-13)
ord_bi = np.log2(errs_bi[-2] / errs_bi[-1])
print(f"Biot Bi = {Bi:.2f} | Stretched Robin errors (N=16,32,64): {[round(e, 4) for e in errs_bi]} K (order = {ord_bi:.3f})")
print(f"Symmetric outward wall fluxes: -J_left = {-out_r['J_left']:.2f}, +J_right = {out_r['J_right']:.2f} vs q*L_half = {q_s*L_half:.2f} W/m^2")
assert ord_bi > 1.98
Exercise 3: Implement It Yourself — 1-D FVM Diffusion with Convective Robin Boundary Conditions
===============================================================================================
Biot Bi = 0.50 | Stretched Robin errors (N=16,32,64): [0.3414, 0.0875, 0.022] K (order = 1.991)
Symmetric outward wall fluxes: -J_left = 25000.00, +J_right = 25000.00 vs q*L_half = 25000.00 W/m^2
Summary. Combining convective film resistance and half-cell conductive resistance in series reproduces Robin cooling with second-order accuracy on stretched meshes (observed order 1.99), recovering pure Neumann ( as ) and pure Dirichlet ( as ) as exact limits.