Skip to content

Transient heat with finite differences

FDM heat_2d_fdm.py

A square plate starts as a rough patchwork of hot and cold spots and is held at zero on its edges. Heat flows from hot to cold, the fine features die first, and the plate smooths into a single bump that slowly sinks.

The temperature as a lit 3-D surface over the unit square, coloured on a diverging scale (hot red, cold blue, zero pale yellow). It starts as a rough landscape of peaks and dips; within a few hundredths of a time unit the small features flatten, and by t = 0.8 one smooth hill remains.

Height and colour are both the temperature, on one fixed scale.

The problem

The heat equation on the unit square, \(u=0\) on the boundary:

\[u_t = \nu\,\Delta u,\qquad u(x,y,0)=\sum_{m,n=1}^{8} a_{mn}\sin(m\pi x)\sin(n\pi y)\]

with random amplitudes \(a_{mn}\). Each mode decays on its own, so the exact solution is the same sum with every amplitude multiplied by \(e^{-\nu\pi^2(m^2+n^2)t}\).

The jNO code

A problem is transient exactly when it carries an initial condition, and the initial condition is a constraint like any other (u(xi, yi) - u0 on the "initial" region). The time window comes from the domain, and ui.t is the time derivative:

d = jno.shape.rect(0, 0, 1, 1, size=0.02).domain(time=(0.0, T, steps))
x, y, t = d.variable("interior", split=True)
xb, yb, _ = d.variable("boundary", split=True)
xi, yi, _ = d.variable("initial", split=True)  # the t = 0 slice

u = d.unknown()
ui = u.bind(x=x, y=y, t=t)
u0 = sum(a * jno.np.sin(m * np.pi * xi) * jno.np.sin(n * np.pi * yi) for a, (m, n) in zip(amp, modes))

traj = np.asarray(jno.fdm([ui.t - nu * (ui.xx + ui.yy), u(xb, yb) - 0.0, u(xi, yi) - u0]).solve())  # (steps, nodes)

jno.fdm collocates the equation at the mesh nodes and marches by the method of lines, with the same time stepper as jno.fem; it returns the whole trajectory.

Result

On a mesh of size \(0.02\) (3016 nodes, 400 steps), against the sum of decayed modes:

time rel. \(L^2\) error
\(t=0.02\), fine modes still present \(2.4\times10^{-3}\)
\(t=0.8\) \(8.7\times10^{-4}\)

Full script

The whole script, as it runs in the tests
"""Transient heat equation, u_t = ν Δu on the unit square with u = 0 on the boundary, by finite differences.

The initial temperature is a rough patchwork of hot and cold spots: a sum of 64 sine modes with random
amplitudes. Each mode decays on its own, sin(mπx) sin(nπy) at the rate νπ²(m² + n²), so the exact solution
is the same sum with every amplitude multiplied by its exponential: the fine modes die first and the field
smooths into a single bump. A problem is transient when its term list carries an initial condition
``u(xi, yi) - u0``; ``jno.fdm`` then marches the semi-discrete system (method of lines) over the domain's
time window and returns the trajectory.
"""

import jax

jax.config.update("jax_enable_x64", True)

import numpy as np

import jno

run = jno.setup(__file__)
nu, T, steps = 0.02, 0.8, 400
modes = [(m, n) for m in range(1, 9) for n in range(1, 9)]
amp = 0.6 * np.random.default_rng(3).normal(size=len(modes)) / np.hypot(*np.array(modes).T) ** 0.5  # finer modes smaller
amp[0] = 3.0  # the slowest mode, (1, 1), is the bump that survives

d = jno.shape.rect(0, 0, 1, 1, size=0.02).domain(time=(0.0, T, steps))
x, y, t = d.variable("interior", split=True)
xb, yb, _ = d.variable("boundary", split=True)
xi, yi, _ = d.variable("initial", split=True)  # the t = 0 slice

u = d.unknown()
ui = u.bind(x=x, y=y, t=t)
u0 = sum(a * jno.np.sin(m * np.pi * xi) * jno.np.sin(n * np.pi * yi) for a, (m, n) in zip(amp, modes))

traj = np.asarray(jno.fdm([ui.t - nu * (ui.xx + ui.yy), u(xb, yb) - 0.0, u(xi, yi) - u0]).solve())  # (steps, nodes)


def exact(px, py, time):
    """The same sum of modes, each decayed by exp(-ν π² (m² + n²) t)."""
    return sum(
        a * np.exp(-nu * np.pi**2 * (m * m + n * n) * time) * np.sin(m * np.pi * px) * np.sin(n * np.pi * py)
        for a, (m, n) in zip(amp, modes)
    )


p = np.asarray(d.mesh_connectivity["points"])[:, :2]
times = np.linspace(0.0, T, steps)
for k in (steps // 40, steps - 1):  # early, while the fine modes still matter, and at the end
    ref = exact(p[:, 0], p[:, 1], times[k])
    rel_l2 = float(np.linalg.norm(traj[k] - ref) / np.linalg.norm(ref))
    print(f"Transient heat via jno.fdm: t = {times[k]:.2f}  rel_L2 = {rel_l2:.3e}")
    assert rel_l2 < 2e-2, f"relative L2 error too large at t = {times[k]:.2f}: {rel_l2:.3e}"