Heat Diffusion in a Rod

This notebook solves the classical 1D heat equation on a rod of unit length using numgrids.

The heat equation describes how temperature \(u(x, t)\) evolves over time due to thermal diffusion:

\[\frac{\partial u}{\partial t} = \kappa \, \frac{\partial^2 u}{\partial x^2}, \qquad x \in [0, 1]\]

where \(\kappa = 0.01\) is the thermal diffusivity.

Boundary conditions: The rod is held at zero temperature at both ends (Dirichlet):

\[u(0, t) = 0, \qquad u(1, t) = 0\]

Initial condition: A sinusoidal temperature profile:

\[u(x, 0) = \sin(\pi x)\]

This problem has the exact analytical solution

\[u(x, t) = \sin(\pi x) \, e^{-\kappa \pi^2 t},\]

which makes it an ideal test case for validating the numerical method.

Setup: Grid and Operator

We use a Chebyshev grid with 40 points on \([0, 1]\), which gives spectral accuracy in space. The right-hand side of the heat equation is the operator \(\kappa\, \partial^2/\partial x^2\), which we write down directly as an Operator.

[1]:
import numpy as np
import matplotlib.pyplot as plt
from numgrids import *

kappa = 0.01  # thermal diffusivity

grid = Grid(x=chebyshev(40, 0, 1))
x = grid.coords

rhs = kappa * grid.diff_operator(2)   # kappa * d^2/dx^2
print(grid)
print(rhs)
Grid(shape=(40,), ndims=1, axes=[
    ChebyshevAxis(num_points=40, low=0, high=1, periodic=False, name='x')
])
Operator(grid=Grid(40,), nnz=1600)

Time Integration

evolve integrates the semi-discrete system \(du/dt = \kappa L u\) in time (method of lines) using scipy.integrate.solve_ivp:

  • bcs=0 holds the temperature at both ends fixed at zero,

  • diffusion problems are stiff, so we use the implicit BDF method; because the right-hand side is an Operator, its sparse matrix is used as the Jacobian,

  • the time step is chosen adaptively to meet the tolerances – no CFL condition to worry about.

[2]:
u0 = np.sin(np.pi * x)
t_final = 50.0
times = np.linspace(0, t_final, 11)

result = evolve(grid, rhs, u0, t_span=(0, t_final), t_eval=times,
                bcs=0, method="BDF", rtol=1e-10, atol=1e-12)

print(result.message)
print("solution array:", result.u.shape, "(time, space)")
The solver successfully reached the end of the integration interval.
solution array: (11, 40) (time, space)

Plot 1: Waterfall Plot of Temperature Profiles

Each curve shows the temperature distribution \(u(x)\) at a different time. Lines are colored from hot (red) at \(t = 0\) to cold (blue) at the final time, reflecting the physical cooling of the rod.

[3]:
fig, ax = plt.subplots(figsize=(10, 6))
cmap = plt.cm.coolwarm

for i, (t, u) in enumerate(zip(result.t, result.u)):
    ax.plot(x, u, color=cmap(1.0 - i / (len(result.t) - 1)), linewidth=2, label=f"t = {t:.0f}")

ax.set_xlabel("Position x", fontsize=13)
ax.set_ylabel("Temperature u(x, t)", fontsize=13)
ax.set_title("Temperature Evolution in a Rod", fontsize=15)
ax.legend(loc="upper right", fontsize=9, ncol=2, framealpha=0.9)
ax.set_xlim(0, 1)
ax.set_ylim(-0.05, 1.05)
ax.grid(True, alpha=0.3)
fig.tight_layout()
plt.show()
../_images/examples_heat-equation-rod_6_0.png

Plot 2: Space-Time Heatmap

For a smooth heatmap we simply ask evolve for many more output times.

[4]:
dense = evolve(grid, rhs, u0, t_span=(0, t_final), t_eval=np.linspace(0, t_final, 201),
               bcs=0, method="BDF", rtol=1e-8, atol=1e-10)

fig, ax = plt.subplots(figsize=(10, 6))
X_mesh, T_mesh = np.meshgrid(x, dense.t)
pcm = ax.pcolormesh(X_mesh, T_mesh, dense.u, cmap="inferno", shading="gouraud")
ax.set_xlabel("Position x", fontsize=13)
ax.set_ylabel("Time t", fontsize=13)
ax.set_title("Space-Time Heatmap of Temperature", fontsize=15)
fig.colorbar(pcm, ax=ax, pad=0.02).set_label("Temperature u(x, t)", fontsize=12)
fig.tight_layout()
plt.show()
../_images/examples_heat-equation-rod_8_0.png

Plot 3: Numerical vs. Analytical Solution

We compare the numerical solution at the final time with the exact solution \(u(x, t) = \sin(\pi x) \, e^{-\kappa \pi^2 t}\). Spatial (spectral) and temporal (adaptive BDF) errors are both tiny.

[5]:
u_exact = np.sin(np.pi * x) * np.exp(-kappa * np.pi**2 * t_final)
u_numerical = result.final
error = np.abs(u_numerical - u_exact)

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8), height_ratios=[3, 1], sharex=True)

ax1.plot(x, u_exact, "k-", linewidth=2.5, label="Analytical")
ax1.plot(x, u_numerical, "o", color="#e74c3c", markersize=5, label="Numerical (numgrids)", zorder=5)
ax1.set_ylabel("Temperature u(x, t)", fontsize=13)
ax1.set_title(f"Numerical vs. Analytical Solution at t = {t_final:.0f}", fontsize=15)
ax1.legend(fontsize=12)
ax1.grid(True, alpha=0.3)
ax1.annotate(f"Max error: {error.max():.2e}", xy=(0.02, 0.95), xycoords="axes fraction",
             fontsize=11, verticalalignment="top",
             bbox=dict(boxstyle="round,pad=0.4", facecolor="wheat", alpha=0.8))

ax2.semilogy(x[1:-1], error[1:-1], "-", color="#2c3e50", linewidth=1.5)
ax2.set_xlabel("Position x", fontsize=13)
ax2.set_ylabel("Absolute error", fontsize=13)
ax2.grid(True, alpha=0.3)
ax2.set_xlim(0, 1)
fig.tight_layout()
plt.show()
../_images/examples_heat-equation-rod_10_0.png

Bonus: Non-Zero Boundary Temperatures

Changing the boundary conditions is a one-line change. Here the left end is kept at temperature 0 and the right end at temperature 1. The rod relaxes to the linear steady state \(u(x) = x\), which we could also compute directly by solving \(u'' = 0\) with Operator.solve.

[6]:
bcs = {"x_low": 0.0, "x_high": 1.0}
hot_end = evolve(grid, rhs, u0, t_span=(0, 200), t_eval=[0, 5, 20, 50, 200],
                 bcs=bcs, method="BDF")

steady = grid.diff_operator(2).solve(0.0, bcs=bcs)   # u'' = 0

fig, ax = plt.subplots(figsize=(10, 5))
for t, u in zip(hot_end.t, hot_end.u):
    ax.plot(x, u, linewidth=2, label=f"t = {t:.0f}")
ax.plot(x, steady, "k--", linewidth=1.5, label="steady state (solve)")
ax.set_xlabel("Position x", fontsize=13)
ax.set_ylabel("Temperature u(x, t)", fontsize=13)
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()
../_images/examples_heat-equation-rod_12_0.png

Insulated and Cooled Ends

Fixed temperatures are not the only option. The heat flux through an end is proportional to the temperature gradient there, so

  • an insulated end has \(\partial u / \partial n = 0\) (a Neumann condition), and

  • an end that releases heat to the surroundings by Newton’s law of cooling has \(-\partial u / \partial n = \mathrm{Bi}\,(u - u_\infty)\) (a Robin condition). The Biot number \(\mathrm{Bi}\) compares the heat transfer at the surface with the conduction inside the rod.

Both are one-liners in bcs: Neumann(g) means \(\partial u / \partial n = g\), and Robin(a, b, g) means \(a u + b\, \partial u / \partial n = g\). evolve enforces them at every instant.

We insulate the left end and cool the right end into surroundings at \(u_\infty = 0\). Separation of variables gives the exact solutions \(u = \cos(\mu x)\, e^{-\kappa \mu^2 t}\), where \(\mu \tan \mu = \mathrm{Bi}\). We start with the slowest of these modes and compare.

[7]:
from scipy.optimize import brentq

Bi = 1.0
mu = brentq(lambda m: m * np.tan(m) - Bi, 0.1, np.pi / 2 - 1e-9)

bcs = {"x_low": Neumann(0), "x_high": Robin(Bi, 1, 0)}
cooled = evolve(grid, rhs, np.cos(mu * x), t_span=(0, t_final), t_eval=times,
                bcs=bcs, method="BDF", rtol=1e-10, atol=1e-12)

exact = np.cos(mu * x) * np.exp(-kappa * mu**2 * cooled.t[:, None])
print(f"mu = {mu:.10f}")
print("max. error:", np.max(np.abs(cooled.u - exact)))

fig, ax = plt.subplots(figsize=(10, 5))
cmap = plt.cm.coolwarm
for i, (t, u) in enumerate(zip(cooled.t, cooled.u)):
    ax.plot(x, u, color=cmap(1.0 - i / (len(cooled.t) - 1)), linewidth=2, label=f"t = {t:.0f}")
ax.set_xlabel("Position x", fontsize=13)
ax.set_ylabel("Temperature u(x, t)", fontsize=13)
ax.set_title("Insulated at x = 0, cooled at x = 1", fontsize=14)
ax.legend(ncol=2, fontsize=9)
ax.grid(True, alpha=0.3)
plt.show()
mu = 0.8603335890
max. error: 1.6607748509755993e-10
../_images/examples_heat-equation-rod_14_1.png

The profiles stay flat at the insulated end, while heat leaves through the cooled end.

If both ends are insulated, no heat can leave the rod: the total heat \(\int u\, dx\) is conserved, and an initial hot spot spreads until the temperature is uniform.

[8]:
# a hot spot at x = 0.3 (with its mirror image, so that it starts with zero slope at x = 0)
u_spot = np.exp(-50 * (x - 0.3) ** 2) + np.exp(-50 * (x + 0.3) ** 2)
insulated = evolve(grid, rhs, u_spot, t_span=(0, 100), t_eval=[0, 2, 10, 30, 100],
                   bcs=Neumann(0), method="BDF", rtol=1e-10, atol=1e-12)

for t, u in zip(insulated.t, insulated.u):
    print(f"t = {t:5.0f}:  total heat = {grid.integrate(u):.10f}")

fig, ax = plt.subplots(figsize=(10, 5))
for t, u in zip(insulated.t, insulated.u):
    ax.plot(x, u, linewidth=2, label=f"t = {t:.0f}")
ax.axhline(grid.integrate(u_spot), color="k", ls="--", lw=1.5, label="mean temperature")
ax.set_xlabel("Position x", fontsize=13)
ax.set_ylabel("Temperature u(x, t)", fontsize=13)
ax.set_title("Both ends insulated", fontsize=14)
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()
t =     0:  total heat = 0.2506628275
t =     2:  total heat = 0.2506628275
t =    10:  total heat = 0.2506628275
t =    30:  total heat = 0.2506628275
t =   100:  total heat = 0.2506628275
../_images/examples_heat-equation-rod_16_1.png

Summary

In this notebook we solved the 1D heat equation with numgrids:

  1. A Chebyshev grid with named axis, Grid(x=chebyshev(40, 0, 1)), and the operator kappa * grid.diff_operator(2).

  2. evolve(...) integrated the problem in time with an adaptive implicit method; bcs=0 imposed the Dirichlet conditions.

  3. The numerical solution agrees with the analytical one to many digits.

  4. Different boundary temperatures only required a different bcs dictionary, and the steady state followed from Operator.solve.

  5. Insulated (Neumann) and cooled (Robin) ends are just as easy. They hold at every instant, so the numerical solution matches the exact one, and an insulated rod conserves its heat.