TExcelTAD
Home › Numerical Methods › Mini Project: A Heat-Flow Simulator for a Metal Plate

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, 20×1020 \times 10 cm, has its left edge clamped to a hot block at 100 ∘100\,^{\circ}C and its other edges held at room temperature, 20 ∘20\,^{\circ}C. A 2×22 \times 2 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:

The model

The temperature u(x,y,t)u(x, y, t) obeys the heat equation with a source,

ut=κ Δu+q(x,y),u_t = \kappa\,\Delta u + q(x, y),

with thermal diffusivity κ=9.7×10−5\kappa = 9.7 \times 10^{-5} m2^2/s (aluminium) and q=30q = 30 K/s inside the heater square centred at (0.15,0.05)(0.15, 0.05), zero elsewhere. (For a 2 mm thick plate this is about 60 W.) The steady state solves the Poisson problem −Δu=q/κ-\Delta u = q/\kappa 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 nx×nyn_x \times n_y grid of interior points is assembled with Kronecker products. Edge temperatures move to the right-hand side.

python · try it yourself
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 h=2.5h = 2.5 mm problem both ways and compare.

python · try it yourself
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 100 ∘100\,^{\circ}C edge; the heater raises its own neighbourhood by about 40 ∘40\,^{\circ}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 ChpCh^p, the changes between successive grids shrink by 2p2^p per halving of hh, and Richardson extrapolation uh+uh−u2h2p−1u_h + \frac{u_h - u_{2h}}{2^p - 1} estimates the grid-independent value.

python · try it yourself
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 100100 to 20 ∘20\,^{\circ}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 hh. That costs an O(h)O(h) error that spreads through the whole plate. Measuring the observed order, rather than assuming it, is what reveals this; with p=1p = 1 Richardson extrapolation gives a centre temperature of about 32.3 ∘32.3\,^{\circ}C. Smoothing the corner data, or refining the grid locally near the corners, would restore faster convergence.

Step 4: Heating up

At t=0t = 0 the plate is at 20 ∘20\,^{\circ}C, the left edge jumps to 100 ∘100\,^{\circ}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.

python · try it yourself
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 Δt\Delta t; 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 80 ∘80\,^{\circ}C in steady state? The problem is linear in qq, so the heater temperature is T(q)=T0+q wT(q) = T_0 + q\,w: two solves determine T0T_0 and ww, and the answer follows without any iteration. (This is superposition; a root finder would also work, but it would need several solves.)

python · try it yourself
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 2.43×1062.43 \times 10^6 J/(m3^3K) is aluminium's volumetric heat capacity ρc\rho c.

Extensions

  • Replace the fixed 20 ∘20\,^{\circ}C edges by insulated (Neumann) edges with ghost points, or by a convective (Robin) condition −k ∂nu=hc(u−20)-k\,\partial_nu = h_c(u - 20).
  • Use Crank-Nicolson in Step 4 and compare the 90 % time with backward Euler at the same Δt\Delta t.
  • 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): κ\kappa then varies in space, and the stencil must use face-averaged coefficients.

Test yourself

Why is backward Euler a good choice for Step 4?

  1. It is the most accurate method
  2. It is unconditionally stable, so the step is not limited to about 0.016 s
  3. It needs no linear solve
  4. It conserves energy exactly

In Step 5, why are two linear solves enough to find the required heater power?

  1. Because the matrix is small
  2. Because the steady temperature depends linearly on qq
  3. Because CG converges in two steps
  4. Because the heater is square

If halving hh changes the centre temperature by 0.10.1 and the next halving by 0.0250.025, the method's order is about…

  1. 1
  2. 2
  3. 4
  4. 8