Suppose a copper heat spreader () is bonded to a porous ceramic thermal barrier coating (). If your finite-volume solver interpolates the interface thermal conductivity at the shared face using the arithmetic mean , it treats the insulating face as more conductive than it truly is, and on a coarse grid overpredicts the heat flux by more than . In this lecture, we derive Patankar’s exact series-resistance harmonic_interface_conductivity, solve steady 1-D heat/mass diffusion in operations with solve_tridiagonal and fvm_diffusion_1d_steady, and verify machine-precision cell-by-cell conservation across composite walls and volumetric heat sources.
Learning objectives¶
Discretize conservative 1-D steady diffusion with Dirichlet and Neumann boundary conditions using
fvm_diffusion_1d_steady.Solve tridiagonal FVM systems in work and zero fill-in via the NumPy Thomas algorithm
solve_tridiagonal.Derive Patankar’s
harmonic_interface_conductivityfrom series thermal resistance and show why arithmetic face averaging fails across conductivity jumps.Verify exact global and cell-by-cell flux conservation (
max_cell_balance_residual) on uniform, stretched, and composite meshes.
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. Conservative 1-D FVM Diffusion & Half-Cell Boundary Conductance¶
1.1 Control-Volume Integration of Fourier / Fick Diffusion¶
Integrating over cell of width with conductive flux gives the exact discrete conservation balance:
Approximating interior face fluxes between centroids and via diffusive conductance yields a symmetric positive-definite tridiagonal system:
Dirichlet wall at (): the distance from the boundary face to the first centroid is the half-cell , giving wall conductance and inward flux .
Neumann wall: specifies boundary conductive flux directly ( inward at , or outward at ).
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)
Demonstration 1: Nuclear Fuel Slab With Volumetric Heat Generation (Dirichlet & Neumann BCs)
============================================================================================
Dirichlet-Dirichlet max |T_fvm - T_exact| = 0.6944 K (= exact O(dx^2) half-cell offset q*dx^2/(8k) = 0.6944 K)
Dirichlet wall fluxes: FVM = (-100000.00, 60000.00) vs Exact = (-100000.00, 60000.00) W/m^2
Neumann-Dirichlet max |T_fvm - T_exact| = 0.6944 K | J_right = 160000.00 W/m^2 (= q*L = 160000.00)
Max cell balance residual = 5.88e-10 W/m^2
ratio_line = np.logspace(-3, 3, 121)
k_harm_line = np.array([grids_fvm.harmonic_interface_conductivity(np.array([1.0, rr]), np.array([0.5, 0.5]))[0] for rr in ratio_line])
k_arith_line = 0.5 * (1.0 + ratio_line)
fig, ax = plt.subplots(figsize=(6.4, 4.2))
ax.loglog(ratio_line, k_arith_line, "--", label="arithmetic mean")
ax.loglog(ratio_line, k_harm_line, "-", label="harmonic mean")
ax.axhline(2.0, color="0.5", ls=":", lw=1.0)
ax.set_xlabel(r"conductivity ratio $k_2/k_1$ [-]"); ax.set_ylabel(r"interface conductivity $k_{1/2}/k_1$ [-]")
ax.legend(loc="upper left")
plt.show()
Figure 2.1. Interface conductivity between two cells of equal size against the ratio of their conductivities. The harmonic mean never exceeds twice the smaller conductivity (dotted line); the arithmetic mean grows with the larger one.
What Demonstration 1 shows. Two exact FVM properties on cells:
Machine-precision wall fluxes & linear profiles: Both Dirichlet wall heat fluxes (
-100,000and+60,000) and the adiabatic-cladding outward flux () are exact to 10-12 regardless of .Exact boundary-secant shift on quadratics: Interior centered slopes are exact on quadratics, while the half-cell boundary secant over shifts interior centroids by the exact analytical constant .
2. Patankar’s Harmonic Interface Conductivity Across Composite Walls¶
Now consider an interior face separating cell (conductivity , half-width ) from cell (conductivity , half-width ). Continuity of steady conductive heat flux across the interface demands that the two half-cells act as thermal resistors in series:
On a uniform mesh (), Equation (2.1) simplifies to the harmonic mean . We test a composite wall ( for , for , , ) against a naive arithmetic-mean face solver.
heading("Demonstration 2: 100:1 Composite Thermal Barrier — Harmonic vs Arithmetic Face Conductivity")
L_tot, T_hot, T_cold = 1.0, 1000.0, 300.0
k_metal, k_ceramic = 100.0, 1.0
R_exact = 0.5 / k_metal + 0.5 / k_ceramic
J_exact = (T_hot - T_cold) / R_exact # 700 / 0.505 = 1386.138614 W/m^2
T_int_exact = T_hot - J_exact * (0.5 / k_metal)
def solve_arithmetic_bug(x_faces: np.ndarray, k_cells: np.ndarray, T_L: float, T_R: float) -> dict:
"""Deliberately buggy FVM solver using arithmetic face mean 0.5*(k_i + k_{i+1})."""
xc = 0.5 * (x_faces[:-1] + x_faces[1:])
k_arith = 0.5 * (k_cells[:-1] + k_cells[1:])
cond = k_arith / np.diff(xc)
n = xc.size
diag = np.zeros(n)
diag[:-1] += cond; diag[1:] += cond
rhs = np.zeros(n)
gl = k_cells[0] / (xc[0] - x_faces[0]); gr = k_cells[-1] / (x_faces[-1] - xc[-1])
diag[0] += gl; rhs[0] += gl * T_L
diag[-1] += gr; rhs[-1] += gr * T_R
phi = grids_fvm.solve_tridiagonal(-cond, diag, -cond, rhs)
j_flux = -(gl * (phi[0] - T_L))
return {"xc": xc, "phi": phi, "J": float(j_flux), "k_interface": float(k_arith[n // 2 - 1])}
g_comp = grids_fvm.uniform_fvm_grid_1d(0.0, L_tot, 4)
k_arr = np.where(g_comp["x_centers"] < 0.5, k_metal, k_ceramic)
k_harm_vec = grids_fvm.harmonic_interface_conductivity(k_arr, g_comp["volumes"])
sol_harm = grids_fvm.fvm_diffusion_1d_steady(
g_comp["x_faces"], k_arr, q_source=0.0, bc_left=("dirichlet", T_hot), bc_right=("dirichlet", T_cold)
)
sol_arith = solve_arithmetic_bug(g_comp["x_faces"], k_arr, T_hot, T_cold)
J_harm = float(sol_harm["face_fluxes"][0])
err_harm_pct = 100.0 * abs(J_harm - J_exact) / J_exact
err_arith_pct = 100.0 * abs(sol_arith["J"] - J_exact) / J_exact
print(f"Interface face x=0.5 conductivity: Harmonic = {k_harm_vec[1]:.4f} W/(m*K) vs Arithmetic = {sol_arith['k_interface']:.4f} W/(m*K)")
print(f"Exact composite heat flux J = {J_exact:.4f} W/m^2 (Interface T = {T_int_exact:.2f} K)")
print(f"Harmonic FVM (N=4) J = {J_harm:.4f} W/m^2 (rel error = {err_harm_pct:.2e}%)")
print(f"Arithmetic FVM (N=4) J = {sol_arith['J']:.4f} W/m^2 (rel error = {err_arith_pct:.2f}%, too high)")
assert np.isclose(J_harm, J_exact, rtol=1e-12)
assert err_arith_pct > 30.0
Demonstration 2: 100:1 Composite Thermal Barrier — Harmonic vs Arithmetic Face Conductivity
===========================================================================================
Interface face x=0.5 conductivity: Harmonic = 1.9802 W/(m*K) vs Arithmetic = 50.5000 W/(m*K)
Exact composite heat flux J = 1386.1386 W/m^2 (Interface T = 993.07 K)
Harmonic FVM (N=4) J = 1386.1386 W/m^2 (rel error = 6.50e-12%)
Arithmetic FVM (N=4) J = 1824.3396 W/m^2 (rel error = 31.61%, too high)
What Demonstration 2 shows. On an coarse mesh, arithmetic averaging sets , short-circuiting the first ceramic half-cell and overpredicting heat transfer by ( vs. exact ). Patankar’s harmonic_interface_conductivity gives and reproduces the exact heat flux to rounding error on 4 cells.
3. Visualizing the Composite Kink & Mesh-Refinement Convergence¶
We plot the exact piecewise-linear temperature profile (gentle drop across the conductive metal vs. steep drop across the ceramic barrier) alongside harmonic vs. arithmetic FVM predictions across .
heading("Demonstration 3: Composite Wall Temperature Profile & Flux Convergence Study")
x_ex = np.array([0.0, 0.5, 1.0])
T_ex = np.array([T_hot, T_int_exact, T_cold])
ns_grid = [4, 8, 16, 32, 64, 128]
errs_harm, errs_arith = [], []
for n_c in ns_grid:
gm = grids_fvm.uniform_fvm_grid_1d(0.0, L_tot, n_c)
kc = np.where(gm["x_centers"] < 0.5, k_metal, k_ceramic)
sh = grids_fvm.fvm_diffusion_1d_steady(gm["x_faces"], kc, 0.0, ("dirichlet", T_hot), ("dirichlet", T_cold))
sa = solve_arithmetic_bug(gm["x_faces"], kc, T_hot, T_cold)
errs_harm.append(max(1.0e-16, abs(sh["face_fluxes"][0] - J_exact) / J_exact))
errs_arith.append(abs(sa["J"] - J_exact) / J_exact)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.2, 4.2))
ax1.plot(x_ex, T_ex, "-", color="#111111", lw=2.2, label="Exact piecewise-linear $T(x)$")
ax1.plot(sol_harm["x_centers"], sol_harm["phi"], "o", color="#1f77b4", ms=7, label="Harmonic FVM ($N=4$, exact)")
ax1.plot(sol_arith["xc"], sol_arith["phi"], "s--", color="#d62728", ms=6, label="Arithmetic mean ($N=4$)")
ax1.axvline(0.5, color="gray", ls=":", lw=1.2)
ax1.set_xlabel("Position $x$ [m]")
ax1.set_ylabel("Temperature $T(x)$ [K]")
ax1.set_title("100:1 Composite Barrier ($k_1=100, k_2=1$ W/mK)")
ax1.legend(fontsize=8.5, frameon=False)
ax2.loglog(ns_grid, errs_arith, "s-", color="#d62728", lw=2.0, label="Arithmetic face average ($O(N^{-1})$)")
ax2.loglog(ns_grid, errs_harm, "o-", color="#1f77b4", lw=2.0, label="Harmonic face average (exact to rounding)")
ax2.set_xlabel("Number of Cells $N$ [-]")
ax2.set_ylabel("Relative Heat-Flux Error $|J_h - J_{\\mathrm{exact}}| / J_{\\mathrm{exact}}$")
ax2.set_title("Composite Heat-Flux Convergence")
ax2.legend(fontsize=8.5, frameon=False)
label_panels(fig)
plt.show()
slope_arith = np.log2(errs_arith[-2] / errs_arith[-1])
print(f"Arithmetic mean asymptotic convergence order = {slope_arith:.3f} (degraded to 1st order O(dx)); N=128 still has {100*errs_arith[-1]:.2f}% error.")
assert all(eh < 1.0e-12 for eh in errs_harm)
assert 0.90 < slope_arith < 1.05
Demonstration 3: Composite Wall Temperature Profile & Flux Convergence Study
============================================================================

Arithmetic mean asymptotic convergence order = 1.011 (degraded to 1st order O(dx)); N=128 still has 0.76% error.
Figure 2.2. (a) Temperature across a two-layer wall with a conductivity ratio of 100, computed with four cells: the harmonic mean at the interface reproduces the exact profile and the arithmetic mean does not. (b) Relative error of the heat flux against the number of cells for the two interface rules.
What Demonstration 3 shows. Not only is arithmetic face averaging inaccurate on coarse meshes, its convergence rate degrades to first order across material discontinuities (an error of remains at ), whereas harmonic_interface_conductivity is exact to rounding error on every mesh whose face aligns with the material interface.
4. Non-Uniform Stretched Meshes & Spatially Varying ¶
Does fvm_diffusion_1d_steady remain second-order accurate and strictly conservative when both the mesh spacing is strongly stretched (tanh_stretched_grid_1d) and thermal conductivity varies smoothly in space? We test against the manufactured analytical solution on , where .
heading("Demonstration 4: Second-Order Convergence on Stretched Meshes with Exponentially Varying k(x)")
gamma_k = 1.5
errs_stretched = []
ns_st = [16, 32, 64, 128]
for n_c in ns_st:
gs = grids_fvm.tanh_stretched_grid_1d(0.0, 1.0, n_c, beta_cluster=2.0, two_sided=True)
xc = gs["x_centers"]
kc = np.exp(gamma_k * xc)
qs = np.exp(gamma_k * xc) * np.pi * (np.pi * np.sin(np.pi * xc) - gamma_k * np.cos(np.pi * xc))
sol = grids_fvm.fvm_diffusion_1d_steady(gs["x_faces"], kc, qs, ("dirichlet", 0.0), ("dirichlet", 0.0))
err_inf = float(np.max(np.abs(sol["phi"] - np.sin(np.pi * xc))))
errs_stretched.append(err_inf)
# Global integral balance: J_right - J_left == sum(qs * dV)
net_flux = float(sol["face_fluxes"][-1] - sol["face_fluxes"][0])
tot_src = float(np.sum(qs * gs["volumes"]))
assert np.isclose(net_flux, tot_src, rtol=1e-12)
assert sol["max_cell_balance_residual"] < 1.0e-11
orders_st = [np.log2(errs_stretched[i] / errs_stretched[i + 1]) for i in range(len(ns_st) - 1)]
for n_c, e_v in zip(ns_st, errs_stretched):
print(f"Stretched N = {n_c:3d} (beta=2.0) | max |phi - sin(pi*x)| = {e_v:.4e}")
print("Observed convergence orders on stretched mesh:", [round(float(p), 3) for p in orders_st])
assert all(p > 1.95 for p in orders_st)
Demonstration 4: Second-Order Convergence on Stretched Meshes with Exponentially Varying k(x)
=============================================================================================
Stretched N = 16 (beta=2.0) | max |phi - sin(pi*x)| = 2.5138e-02
Stretched N = 32 (beta=2.0) | max |phi - sin(pi*x)| = 6.2578e-03
Stretched N = 64 (beta=2.0) | max |phi - sin(pi*x)| = 1.5756e-03
Stretched N = 128 (beta=2.0) | max |phi - sin(pi*x)| = 3.9433e-04
Observed convergence orders on stretched mesh: [2.006, 1.99, 1.998]
Inside the algorithm¶
Instead of calling np.linalg.solve on an dense array ( flops and RAM), grids_fvm.solve_tridiagonal executes Thomas forward elimination and back-substitution in time and memory. Below we inspect solve_tridiagonal and harmonic_interface_conductivity, and benchmark solve_tridiagonal against dense np.linalg.solve.
Check against the library¶
heading("Inside the Algorithm: O(N) Thomas Algorithm vs Dense np.linalg.solve")
print(show_source(grids_fvm.solve_tridiagonal))
print(show_source(grids_fvm.harmonic_interface_conductivity))
rng = np.random.default_rng(123)
n_sys = 200
lower = -rng.uniform(0.5, 2.0, size=n_sys - 1)
upper = -rng.uniform(0.5, 2.0, size=n_sys - 1)
diag = rng.uniform(4.5, 6.0, size=n_sys) # strictly diagonally dominant M-matrix
rhs = rng.normal(size=n_sys)
A_dense = np.diag(diag) + np.diag(lower, k=-1) + np.diag(upper, k=1)
x_thomas = grids_fvm.solve_tridiagonal(lower, diag, upper, rhs)
x_dense = np.linalg.solve(A_dense, rhs)
max_diff = float(np.max(np.abs(x_thomas - x_dense)))
print(f"200x200 tridiagonal solve: max |x_thomas - x_dense| = {max_diff:.2e}")
assert np.allclose(x_thomas, x_dense, rtol=1e-13, atol=1e-13)
Inside the Algorithm: O(N) Thomas Algorithm vs Dense np.linalg.solve
====================================================================
def solve_tridiagonal(lower: np.ndarray, diag: np.ndarray, upper: np.ndarray, rhs: np.ndarray) -> np.ndarray:
"""Pure-NumPy O(N) Thomas algorithm for an N x N tridiagonal linear system."""
n = diag.size
cp = np.zeros(n - 1, dtype=float)
dp = np.zeros(n, dtype=float)
cp[0] = upper[0] / diag[0]
dp[0] = rhs[0] / diag[0]
for i in range(1, n):
denom = diag[i] - lower[i - 1] * cp[i - 1]
if i < n - 1:
cp[i] = upper[i] / denom
dp[i] = (rhs[i] - lower[i - 1] * dp[i - 1]) / denom
sol = np.zeros(n, dtype=float)
sol[-1] = dp[-1]
for i in range(n - 2, -1, -1):
sol[i] = dp[i] - cp[i] * sol[i + 1]
return sol
def harmonic_interface_conductivity(
k_cells: np.ndarray,
volumes: np.ndarray,
) -> np.ndarray:
"""Compute exact series-resistance harmonic face conductivities k_{i+1/2} across interior FVM faces."""
kc = np.asarray(k_cells, dtype=float).ravel()
vols = np.asarray(volumes, dtype=float).ravel()
if kc.size != vols.size or kc.size < 2 or np.any(kc <= 0.0):
raise ValueError("k_cells and volumes must match in size >= 2 with k_cells > 0.")
dl = 0.5 * vols[:-1]
dr = 0.5 * vols[1:]
return (dl + dr) / (dl / kc[:-1] + dr / kc[1:])
200x200 tridiagonal solve: max |x_thomas - x_dense| = 1.67e-16
Exercises¶
Worked solutions are in 02_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify the limit of a nearly perfect insulator (, ) of
harmonic_interface_conductivityon equal () and unequal () cell volumes, confirming matches exact series thermal resistance.Find how it fails. Quantify the exact heat-flux error from using full-cell distance instead of half-cell at Dirichlet boundaries on linear conduction (), and verify
ValueErrorguards on negative conductivity and unsupported BC names.Implement it yourself. 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("Self-check for the exercises")
k_ins = grids_fvm.harmonic_interface_conductivity(np.array([200.0, 1.0e-8]), np.array([0.05, 0.05]))[0]
assert np.isclose(k_ins, 2.0e-8, rtol=1e-9)
sol_ins = grids_fvm.fvm_diffusion_1d_steady(
np.array([0.0, 0.05, 0.10]), np.array([200.0, 1.0e-8]), 0.0, ("dirichlet", 500.0), ("dirichlet", 0.0)
)
assert sol_ins["face_fluxes"][0] < 3.0e-4
print(f"Insulator limit verified: k_harm = {k_ins:.3e} W/(m*K), J = {sol_ins['face_fluxes'][0]:.3e} W/m^2.")
print("All checks passed.")
Self-check for the exercises
============================
Insulator limit verified: k_harm = 2.000e-08 W/(m*K), J = 1.000e-04 W/m^2.
All checks passed.