Mini Project: A Heat-Flow Simulator for a Metal Plate
In this project you build a small thermal simulator, the kind of calculation an engineer does before choosing a heat sink or placing a sensor. A thin aluminium plate, cm, has its left edge clamped to a hot block at C and its other edges held at room temperature, C. A cm heater near the right side injects heat. We want the steady temperature field, how fast the plate heats up, and how much heater power keeps the heater spot at a target temperature.
The project combines most of the course:
- finite differences in 2D (Poisson's Equation in 2D);
- sparse direct and iterative solvers (Sparse Matrices, Conjugate Gradients);
- convergence checks and Richardson extrapolation (Error and Step Size in Finite Differences);
- implicit time stepping for a stiff problem (The Heat Equation: Implicit Methods).
The model
The temperature obeys the heat equation with a source,
with thermal diffusivity m/s (aluminium) and K/s inside the heater square centred at , zero elsewhere. (For a 2 mm thick plate this is about 60 W.) The steady state solves the Poisson problem with the edge temperatures as Dirichlet conditions.
Every code block below is self-contained, so each step starts by defining the same build function.
Step 1: Build the discrete problem
The 5-point Laplacian on an grid of interior points is assembled with Kronecker products. Edge temperatures move to the right-hand side.
import numpy as np
import scipy.sparse as sp
kappa = 9.7e-5 # thermal diffusivity of aluminium, m^2/s
Lx, Ly = 0.2, 0.1 # plate size, m
def build(h, q=30.0):
"""5-point Laplacian A, right-hand side b (sources and edge temperatures), grid."""
nx, ny = int(round(Lx / h)) - 1, int(round(Ly / h)) - 1
Tx = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(nx, nx)) / h**2
Ty = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(ny, ny)) / h**2
A = (sp.kron(sp.identity(ny), Tx) + sp.kron(Ty, sp.identity(nx))).tocsc()
X, Y = np.meshgrid(np.arange(1, nx + 1) * h, np.arange(1, ny + 1) * h)
heater = (np.abs(X - 0.15) <= 0.01) & (np.abs(Y - 0.05) <= 0.01)
b = np.where(heater, q / kappa, 0.0)
b[:, 0] += 100 / h**2 # left edge at 100 C
b[:, -1] += 20 / h**2; b[0, :] += 20 / h**2; b[-1, :] += 20 / h**2 # other edges at 20 C
return A, b.ravel(), X, Y
for h in (0.01, 0.005, 0.0025):
A, b, X, Y = build(h)
sym = abs(A - A.T).max() == 0
print(f"h = {h * 1000:.1f} mm: grid {X.shape[1]} x {X.shape[0]}, unknowns {A.shape[0]:5d}, nonzeros {A.nnz:6d}, symmetric {sym}")h = 10.0 mm: grid 19 x 9, unknowns 171, nonzeros 799, symmetric True
h = 5.0 mm: grid 39 x 19, unknowns 741, nonzeros 3589, symmetric True
h = 2.5 mm: grid 79 x 39, unknowns 3081, nonzeros 15169, symmetric True
The matrix is symmetric positive definite with at most 5 nonzeros per row.
Step 2: Steady state by sparse LU and by CG
Solve the mm problem both ways and compare.
import numpy as np
import scipy.sparse as sp
kappa = 9.7e-5 # thermal diffusivity of aluminium, m^2/s
Lx, Ly = 0.2, 0.1 # plate size, m
def build(h, q=30.0):
"""5-point Laplacian A, right-hand side b (sources and edge temperatures), grid."""
nx, ny = int(round(Lx / h)) - 1, int(round(Ly / h)) - 1
Tx = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(nx, nx)) / h**2
Ty = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(ny, ny)) / h**2
A = (sp.kron(sp.identity(ny), Tx) + sp.kron(Ty, sp.identity(nx))).tocsc()
X, Y = np.meshgrid(np.arange(1, nx + 1) * h, np.arange(1, ny + 1) * h)
heater = (np.abs(X - 0.15) <= 0.01) & (np.abs(Y - 0.05) <= 0.01)
b = np.where(heater, q / kappa, 0.0)
b[:, 0] += 100 / h**2 # left edge at 100 C
b[:, -1] += 20 / h**2; b[0, :] += 20 / h**2; b[-1, :] += 20 / h**2 # other edges at 20 C
return A, b.ravel(), X, Y
from scipy.sparse.linalg import splu, cg
A, b, X, Y = build(0.0025)
u_lu = splu(A).solve(b)
count = [0]
u_cg, info = cg(A, b, rtol=1e-10, callback=lambda xk: count.__setitem__(0, count[0] + 1))
print(f"CG: {count[0]} iterations, info {info}, max difference from LU {np.max(np.abs(u_cg - u_lu)):.1e} C")
U = u_lu.reshape(X.shape)
def temp(x, y):
i, j = np.argmin(np.abs(Y[:, 0] - y)), np.argmin(np.abs(X[0] - x))
return U[i, j]
print(f"temperature at the centre (0.10, 0.05): {temp(0.10, 0.05):.3f} C")
print(f"temperature at the heater (0.15, 0.05): {temp(0.15, 0.05):.3f} C")
print(f"hottest interior point: {U.max():.2f} C at x = {X.ravel()[np.argmax(U)] * 100:.2f} cm")CG: 208 iterations, info 0, max difference from LU 9.7e-09 C
temperature at the centre (0.10, 0.05): 32.685 C
temperature at the heater (0.15, 0.05): 62.875 C
hottest interior point: 96.06 C at x = 0.25 cm
Both solvers agree far below any meaningful temperature difference. The hottest interior points are next to the C edge; the heater raises its own neighbourhood by about C above what it would otherwise be.
Step 3: Is the grid fine enough?
Refine the grid and watch the centre and heater temperatures. If the error behaves like , the changes between successive grids shrink by per halving of , and Richardson extrapolation estimates the grid-independent value.
import numpy as np
import scipy.sparse as sp
kappa = 9.7e-5 # thermal diffusivity of aluminium, m^2/s
Lx, Ly = 0.2, 0.1 # plate size, m
def build(h, q=30.0):
"""5-point Laplacian A, right-hand side b (sources and edge temperatures), grid."""
nx, ny = int(round(Lx / h)) - 1, int(round(Ly / h)) - 1
Tx = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(nx, nx)) / h**2
Ty = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(ny, ny)) / h**2
A = (sp.kron(sp.identity(ny), Tx) + sp.kron(Ty, sp.identity(nx))).tocsc()
X, Y = np.meshgrid(np.arange(1, nx + 1) * h, np.arange(1, ny + 1) * h)
heater = (np.abs(X - 0.15) <= 0.01) & (np.abs(Y - 0.05) <= 0.01)
b = np.where(heater, q / kappa, 0.0)
b[:, 0] += 100 / h**2 # left edge at 100 C
b[:, -1] += 20 / h**2; b[0, :] += 20 / h**2; b[-1, :] += 20 / h**2 # other edges at 20 C
return A, b.ravel(), X, Y
from scipy.sparse.linalg import splu
vals = []
for h in (0.01, 0.005, 0.0025, 0.00125):
A, b, X, Y = build(h)
U = splu(A).solve(b).reshape(X.shape)
i = np.argmin(np.abs(Y[:, 0] - 0.05))
vals.append((h, U[i, np.argmin(np.abs(X[0] - 0.10))], U[i, np.argmin(np.abs(X[0] - 0.15))]))
for h, c, s in vals:
print(f"h = {h * 1000:5.2f} mm: centre {c:.4f} C, heater {s:.4f} C")
dc = np.diff([v[1] for v in vals]); ds = np.diff([v[2] for v in vals])
print("centre: changes", np.round(dc, 4), "-> observed order", np.round(np.log2(dc[:-1] / dc[1:]), 2))
print("heater: changes", np.round(ds, 4), "-> observed order", np.round(np.log2(ds[:-1] / ds[1:]), 2))
print(f"Richardson (p = 1) estimate of the centre value: {vals[-1][1] + dc[-1]:.3f} C")h = 10.00 mm: centre 33.8491 C, heater 62.3795 C
h = 5.00 mm: centre 33.0579 C, heater 62.7902 C
h = 2.50 mm: centre 32.6847 C, heater 62.8755 C
h = 1.25 mm: centre 32.5040 C, heater 62.8815 C
centre: changes [-0.7912 -0.3733 -0.1807] -> observed order [1.08 1.05]
heater: changes [0.4107 0.0853 0.006 ] -> observed order [2.27 3.83]
Richardson (p = 1) estimate of the centre value: 32.323 C
The heater temperature converges quickly, but the centre value changes by only a factor of 2 per halving: first order, not the second order the 5-point stencil promises. The culprit is the boundary data. The edge temperature jumps from to C at the left corners, so the exact solution is not smooth there, and on the grid the position of the jump is only known to within about . That costs an error that spreads through the whole plate. Measuring the observed order, rather than assuming it, is what reveals this; with Richardson extrapolation gives a centre temperature of about C. Smoothing the corner data, or refining the grid locally near the corners, would restore faster convergence.
Step 4: Heating up
At the plate is at C, the left edge jumps to C and the heater switches on. Integrate in time with backward Euler, which is unconditionally stable, and record when the centre reaches 90 % of its steady temperature rise. Compare with the time-step limit of the explicit method.
import numpy as np
import scipy.sparse as sp
kappa = 9.7e-5 # thermal diffusivity of aluminium, m^2/s
Lx, Ly = 0.2, 0.1 # plate size, m
def build(h, q=30.0):
"""5-point Laplacian A, right-hand side b (sources and edge temperatures), grid."""
nx, ny = int(round(Lx / h)) - 1, int(round(Ly / h)) - 1
Tx = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(nx, nx)) / h**2
Ty = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(ny, ny)) / h**2
A = (sp.kron(sp.identity(ny), Tx) + sp.kron(Ty, sp.identity(nx))).tocsc()
X, Y = np.meshgrid(np.arange(1, nx + 1) * h, np.arange(1, ny + 1) * h)
heater = (np.abs(X - 0.15) <= 0.01) & (np.abs(Y - 0.05) <= 0.01)
b = np.where(heater, q / kappa, 0.0)
b[:, 0] += 100 / h**2 # left edge at 100 C
b[:, -1] += 20 / h**2; b[0, :] += 20 / h**2; b[-1, :] += 20 / h**2 # other edges at 20 C
return A, b.ravel(), X, Y
from scipy.sparse.linalg import splu
h = 0.0025
A, b, X, Y = build(h)
u_steady = splu(A).solve(b)
i, j = np.argmin(np.abs(Y[:, 0] - 0.05)), np.argmin(np.abs(X[0] - 0.10))
k = i * X.shape[1] + j
I = sp.identity(A.shape[0])
print(f"explicit (FTCS) stability limit: dt <= h^2 / (4 kappa) = {h**2 / (4 * kappa):.4f} s")
for dt in (10.0, 2.0, 0.5):
step = splu((I + dt * kappa * A).tocsc()) # factor once per step size
u = np.full(A.shape[0], 20.0); t = 0.0; t90 = None
while t < 300:
u = step.solve(u + dt * kappa * b); t += dt
if t90 is None and u[k] - 20 >= 0.9 * (u_steady[k] - 20):
t90 = t
print(f"backward Euler dt = {dt:4.1f} s: {int(round(300 / dt)):4d} steps, centre reaches 90 % at t = {t90:.1f} s, u(300 s) = {u[k]:.4f} C")explicit (FTCS) stability limit: dt <= h^2 / (4 kappa) = 0.0161 s
backward Euler dt = 10.0 s: 30 steps, centre reaches 90 % at t = 40.0 s, u(300 s) = 32.6847 C
backward Euler dt = 2.0 s: 150 steps, centre reaches 90 % at t = 30.0 s, u(300 s) = 32.6847 C
backward Euler dt = 0.5 s: 600 steps, centre reaches 90 % at t = 26.5 s, u(300 s) = 32.6847 C
The explicit method would need about 19,000 steps for the same 300 seconds. Backward Euler is only first order in time, so the 90 % time still changes with ; halving the step until it stops changing (or switching to Crank-Nicolson) gives a reliable answer.
Step 5: Sizing the heater
Which heater power keeps the heater spot at exactly C in steady state? The problem is linear in , so the heater temperature is : two solves determine and , and the answer follows without any iteration. (This is superposition; a root finder would also work, but it would need several solves.)
import numpy as np
import scipy.sparse as sp
kappa = 9.7e-5 # thermal diffusivity of aluminium, m^2/s
Lx, Ly = 0.2, 0.1 # plate size, m
def build(h, q=30.0):
"""5-point Laplacian A, right-hand side b (sources and edge temperatures), grid."""
nx, ny = int(round(Lx / h)) - 1, int(round(Ly / h)) - 1
Tx = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(nx, nx)) / h**2
Ty = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(ny, ny)) / h**2
A = (sp.kron(sp.identity(ny), Tx) + sp.kron(Ty, sp.identity(nx))).tocsc()
X, Y = np.meshgrid(np.arange(1, nx + 1) * h, np.arange(1, ny + 1) * h)
heater = (np.abs(X - 0.15) <= 0.01) & (np.abs(Y - 0.05) <= 0.01)
b = np.where(heater, q / kappa, 0.0)
b[:, 0] += 100 / h**2 # left edge at 100 C
b[:, -1] += 20 / h**2; b[0, :] += 20 / h**2; b[-1, :] += 20 / h**2 # other edges at 20 C
return A, b.ravel(), X, Y
from scipy.sparse.linalg import splu
h = 0.0025
A, b0, X, Y = build(h, q=0.0)
_, b1, _, _ = build(h, q=1.0)
lu = splu(A) # the same matrix for every q
i, j = np.argmin(np.abs(Y[:, 0] - 0.05)), np.argmin(np.abs(X[0] - 0.15))
T0 = lu.solve(b0).reshape(X.shape)[i, j]
w = lu.solve(b1).reshape(X.shape)[i, j] - T0
q_needed = (80 - T0) / w
check = lu.solve(build(h, q=q_needed)[1]).reshape(X.shape)[i, j]
print(f"without heater: {T0:.3f} C; each 1 K/s of q adds {w:.4f} C")
print(f"q for 80 C: {q_needed:.3f} K/s (check: {check:.6f} C)")
print(f"power for a 2 mm plate: {q_needed * 2.43e6 * 0.02 * 0.02 * 0.002:.1f} W")without heater: 20.877 C; each 1 K/s of q adds 1.3999 C
q for 80 C: 42.232 K/s (check: 80.000000 C)
power for a 2 mm plate: 82.1 W
The factor J/(mK) is aluminium's volumetric heat capacity .
Extensions
- Replace the fixed C edges by insulated (Neumann) edges with ghost points, or by a convective (Robin) condition .
- Use Crank-Nicolson in Step 4 and compare the 90 % time with backward Euler at the same .
- Precondition CG with incomplete Cholesky or use PyAMG's multigrid and measure iterations as the grid is refined.
- Make the plate out of two materials (a copper strip in aluminium): then varies in space, and the stencil must use face-averaged coefficients.
Test yourself
Why is backward Euler a good choice for Step 4?
- It is the most accurate method
- It is unconditionally stable, so the step is not limited to about 0.016 s
- It needs no linear solve
- It conserves energy exactly
In Step 5, why are two linear solves enough to find the required heater power?
- Because the matrix is small
- Because the steady temperature depends linearly on
- Because CG converges in two steps
- Because the heater is square
If halving changes the centre temperature by and the next halving by , the method's order is about…
- 1
- 2
- 4
- 8