import numpy as np
import scipy.sparse as sparse
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
import sympy as symPartial differential equations¶
A partial differential equation (PDE) relates an unknown function of several variables to its partial derivatives. The partial derivative differentiates with respect to while the other variables are held fixed, and we often write it with a subscript, ; likewise and . For a function of one space variable and time, the standard examples are
| equation | name | describes |
|---|---|---|
| diffusion (heat) equation | heat spreading along a bar, a chemical spreading in a tube | |
| wave equation | a vibrating string, sound | |
| advection equation | a profile carried along by a flow of speed |
with a diffusion coefficient and a wave speed . The steady states of the diffusion equation, where , satisfy the Laplace or Poisson equation Boundary Value Problems.
A PDE alone has infinitely many solutions. To single one out on an interval we need an initial condition (for the wave equation, which is second order in time, also the initial velocity ) and a boundary condition at each end. The three standard choices are:
Dirichlet: the value is given, e.g. . This models a bar whose end is held at a fixed temperature, or a tube whose open end sits in a large bath that fixes the concentration there.
Neumann: the derivative is given, e.g. . The flux of heat or of a chemical is , so means that nothing flows through the end, as at an insulated end of a bar or a closed end of a tube.
Periodic: and , so the two ends are joined into a ring.
Analytical solutions¶
Separation of variables¶
The diffusion equation can be solved by separation of variables. We look for solutions of the form , a function of space times a function of time. Substituting this into the PDE and dividing by gives
The left side does not depend on and the right side does not depend on , so both sides are equal to the same constant, which we call . This leaves two ODEs,
SymPy can carry out both steps: pde_separate substitutes the product into the PDE
and returns the two sides, and dsolve (see Boundary Value Problems)
solves the ODEs.
x = sym.symbols('x', real=True)
t, D, L, b = sym.symbols('t D L b', positive=True)
u, X, T = sym.Function('u'), sym.Function('X'), sym.Function('T')
heat = sym.Eq(u(x, t).diff(t), D * u(x, t).diff(x, 2))
space_side, time_side = sym.pde_separate(heat, u(x, t), [X(x), T(t)])
sym.Eq(space_side, time_side)X_sol = sym.dsolve(sym.Eq(space_side, -b**2), X(x))
T_sol = sym.dsolve(sym.Eq(time_side, -b**2), T(t))
display(X_sol, T_sol)Multiplying the two, with the constant in absorbed into and , gives the solutions
checkpdesol substitutes a candidate solution into the PDE and simplifies what is
left over; it returns (True, 0) when the residual is zero.
u_sep = sym.exp(-b**2 * D * t) * X_sol.rhs
sym.checkpdesol(heat, sym.Eq(u(x, t), u_sep))Boundary conditions¶
The boundary conditions decide which frequencies are allowed. With both ends held at zero, forces , and then with forces to be a multiple of . The allowed solutions are
The problem with is the eigenvalue problem for with zero boundary values, and the sines are its eigenfunctions; sampled on a grid, they appeared as the eigenvectors of the second-difference matrix in Boundary Value Problems.
The PDE is linear, so the general solution is the Fourier sine series
At the series has to reproduce the initial condition, . To find the coefficients we use the fact that the sines are orthogonal on , which SymPy confirms for positive integers and :
m, n = sym.symbols('m n', integer=True, positive=True)
sym.integrate(sym.sin(m * sym.pi * x / L) * sym.sin(n * sym.pi * x / L), (x, 0, L))Multiplying by and integrating over therefore picks out a single coefficient,
Other boundary conditions select other modes. With insulated ends, forces and again , so the modes are cosines, and now is allowed as well, which gives the constant mode. With periodic boundaries must repeat with period , so is a multiple of , and both sines and cosines survive.
Example: a block of heat¶
Suppose the middle half of a bar starts at temperature 1 and the rest at 0, with both ends held at 0: on and elsewhere. The integral for only runs over the block, and SymPy evaluates it for a general .
B = sym.simplify(2 / L * sym.integrate(sym.sin(n * sym.pi * x / L), (x, L / 4, 3 * L / 4)))
B[B.subs(n, k) for k in range(1, 9)]The coefficients with even vanish, since the block is symmetric about
and the even sines are antisymmetric about it; the others decay only like ,
because jumps. To evaluate the series numerically we set and
, turn one term into a NumPy function with lambdify (see
Symbolic Computing), and add up the first nterms
terms.
term = B * sym.exp(-D * (n * sym.pi / L)**2 * t) * sym.sin(n * sym.pi * x / L)
series_term = sym.lambdify((n, x, t), term.subs({D: 0.1, L: 1}), 'numpy')
def block_series(xs, t, nterms):
"""
first nterms terms of the sine series for the block of heat (L = 1, D = 0.1),
at the points xs and time t
"""
return sum(series_term(k, xs, t) for k in range(1, nterms + 1))
xs = np.linspace(0, 1, 1001)
block = ((xs > 0.25) & (xs < 0.75)).astype(float)
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
ax[0].plot(xs, block, 'k--', lw=1, label='$u_0$')
for nterms in [5, 25, 125]:
ax[0].plot(xs, block_series(xs, 0, nterms), label=f'{nterms} terms')
ax[0].set_title('partial sums at $t = 0$')
ax[1].plot(xs, block, 'k--', lw=1, label='$t = 0$')
for tt in [0.001, 0.01, 0.05, 0.2, 1.0]:
ax[1].plot(xs, block_series(xs, tt, 125), label=f'$t = {tt}$')
ax[1].set_title('the solution (125 terms)')
for axis in ax:
axis.set_xlabel('$x$'); axis.set_ylabel('$u$'); axis.legend(fontsize=8)
plt.show()At the partial sums converge slowly, since decays only like , and near each jump they overshoot by about 9% however many terms we keep. This is also called the Gibbs phenomenon. For the factor damps the high frequencies, so the corners are rounded off almost at once and the solution is smooth even though is not. The same factor makes the series converge quickly.
Waves: d’Alembert’s solution¶
For the wave equation on the whole line, every function of is a solution: is the profile moving to the right at speed without changing its shape. Likewise, moves to the left.
c = sym.symbols('c', positive=True)
f, g = sym.Function('f'), sym.Function('g')
wave = sym.Eq(u(x, t).diff(t, 2), c**2 * u(x, t).diff(x, 2))
sym.checkpdesol(wave, sym.Eq(u(x, t), f(x - c * t) + g(x + c * t)))In fact every solution has this form, and choosing and to match the initial position and the initial velocity gives d’Alembert’s formula
u0, v0 = sym.Function('u_0'), sym.Function('v_0')
s = sym.symbols('s', real=True)
dalembert = ((u0(x - c * t) + u0(x + c * t)) / 2
+ sym.Integral(v0(s), (s, x - c * t, x + c * t)) / (2 * c))
(sym.checkpdesol(wave, sym.Eq(u(x, t), dalembert)),
dalembert.subs(t, 0).doit(),
sym.simplify(dalembert.diff(t).subs(t, 0)))A bump released at rest () splits into two copies of half the height, which move apart at speed .
bump = lambda x: np.exp(-100 * x**2)
xw = np.linspace(-1.5, 1.5, 601)
plt.figure(figsize=(8, 3))
for tt in [0, 0.25, 0.5, 1.0]:
plt.plot(xw, (bump(xw - tt) + bump(xw + tt)) / 2, label=f'$t = {tt}$')
plt.xlabel('$x$'); plt.ylabel('$u$'); plt.legend()
plt.title("d'Alembert's solution, $c = 1$, released at rest")
plt.show()The wave equation keeps the shape of its initial data, corners and jumps included, and carries it at the finite speed ; the value depends only on the initial data in . The diffusion equation instead smooths its initial data at once and, as the heat kernel showed, is felt everywhere immediately.
On with fixed ends, separation of variables gives standing waves such as , the oscillating solutions found from the eigenvectors in Boundary Value Problems.
First-order equations: pdsolve¶
SymPy’s PDE solver pdsolve handles first-order linear equations. For the advection
equation it returns an arbitrary function of :
advection = sym.Eq(u(x, t).diff(t) + c * u(x, t).diff(x), 0)
sym.pdsolve(advection)The solution is constant along each line (a “characteristic”), so the initial profile moves to the right at speed , like the right-moving half of d’Alembert’s solution. Spectral Methods uses this equation to test numerical schemes, because after one trip around a periodic domain the exact solution is the initial condition again.
With a decay term, , the solution by hand is , but SymPy writes it differently:
a = sym.symbols('a', positive=True)
F = sym.Function('F')
decay = sym.Eq(u(x, t).diff(t) + c * u(x, t).diff(x), -a * u(x, t))
display(sym.pdsolve(decay))
sym.checkpdesol(decay, sym.Eq(u(x, t), F(x - c * t) * sym.exp(-a * t)))Both are correct. With we have , so
SymPy’s exponential equals , and the factor that
depends only on can be absorbed into the arbitrary function . Symbolic
results often come back in an unfamiliar but equivalent form, and checkpdesol is a
more reliable way to compare them than reading the formulas.
For second-order equations pdsolve gives up:
Discretizing space¶
From here on we solve the diffusion equation
numerically. Put down equally spaced points with spacing , and let approximate . The standard second-order approximation to the second derivative is the second difference
which you can get by adding the Taylor expansions of . We build this similar to Boundary Value Problems, with a more detailed treatment of the boundary conditoin.
def laplacian_1d(n, dx, bc="dirichlet"):
"""
second-difference matrix on n equally spaced points with spacing dx
bc controls what is assumed to sit just outside the domain:
'dirichlet' - a ghost value of 0 (the ends are held at zero)
'neumann' - a copy of the neighbour (no flux through the ends)
'periodic' - the value at the far end (the domain is a ring)
"""
A = sparse.diags([1.0, -2.0, 1.0], [-1, 0, 1], shape=(n, n), format="lil")
if bc == "neumann":
A[0, 0] = A[-1, -1] = -1 # ghost equals the neighbour
elif bc == "periodic":
A[0, -1] = A[-1, 0] = 1 # wrap around
elif bc != "dirichlet":
raise ValueError(f"unknown boundary condition {bc!r}")
return A.tocsr() / dx**2
print('Dirchilet:\n', laplacian_1d(5, 1.0).toarray())
print('Nuemann:\n', laplacian_1d(5, 1.0, bc='neumann').toarray())
print('Periodic:\n', laplacian_1d(5, 1.0, bc='periodic').toarray())
We can check our matrix by applying it to known examples. The second difference should turn into , so applying the matrix to a sampled sine should scale it by roughly .
L, n = 1.0, 200
dx = L / (n + 1)
x = np.linspace(dx, L - dx, n) # n interior points, ends held at 0
k = np.pi / L # sin(kx) vanishes at x = 0 and x = L
u = np.sin(k * x)
Au = laplacian_1d(n, dx) @ u
print(f"Difference: {np.max(np.abs(Au + k**2 * u)):.4f}")
From PDE to ODE¶
With space discretized, is a vector and the PDE reads
an ODE system with one equation per grid point. We solve it using solve_ivp.
Discretizing space while leaving time continuous is called the method of lines.
D, T = 0.1, 0.5
A = laplacian_1d(n, dx)
u0 = np.exp(-200 * (x - 0.3)**2) + 0.6 * np.exp(-400 * (x - 0.7)**2)
sol = solve_ivp(lambda t, u: D * (A @ u), (0, T), u0,
t_eval=np.linspace(0, T, 6))
plt.figure(figsize=(8, 4))
for j, t in enumerate(sol.t):
plt.plot(x, sol.y[:, j], label=f'$t = {t:.2f}$')
plt.xlabel('$x$'); plt.ylabel('$u$'); plt.legend()
plt.title('diffusion, ends held at zero')
plt.show()Two bumps spread, merge, and drain away through the ends. That is roughly fifteen lines of code for a PDE solve, which is the appeal of the method.
What the boundary conditions do¶
The three bc options differ only in what they assume sits just outside the
domain, but they produce qualitatively different physics. A good way to see it
is to track the total mass, .
def grid_for(bc, n=120):
"""
n points on [0, L] and their spacing, placed so that laplacian_1d(n, dx, bc)
imposes the boundary condition at x = 0 and x = L
"""
if bc == "dirichlet":
# interior nodes: the zero ghosts are the end points x = 0 and x = L
dx = L / (n + 1)
return dx * np.arange(1, n + 1), dx
# cell centres: x = 0 and x = L lie halfway between the end points and their ghosts
dx = L / n
return dx * (np.arange(n) + 0.5), dx
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
for ax, bc in zip(axes, ["dirichlet", "neumann", "periodic"]):
xp, dxp = grid_for(bc)
u0p = np.exp(-200 * (xp - 0.3)**2)
Ab = laplacian_1d(len(xp), dxp, bc=bc)
s = solve_ivp(lambda t, u: D * (Ab @ u), (0, 2.0), u0p,
t_eval=np.linspace(0, 2.0, 5))
for j, t in enumerate(s.t):
ax.plot(xp, s.y[:, j], label=f'$t={t:.1f}$')
mass0 = u0p.sum() * dxp
massT = s.y[:, -1].sum() * dxp
ax.set_title(f'{bc}\nmass {mass0:.4f} -> {massT:.4f}')
ax.set_xlabel('$x$'); ax.set_ylim(-0.02, 1.05)
axes[0].set_ylabel('$u$'); axes[0].legend(fontsize=8)
plt.tight_layout()
plt.show()Dirichlet leaks -- the ends are held at zero, so material leaves. Neumann and periodic conserve the total to several digits, because nothing can escape.
That conservation is not a coincidence, and it is the single most useful test you can write for this kind of solver. For Neumann and periodic boundaries the column sums of are zero, so , so exactly, in exact arithmetic, for any initial condition. A test that asserts conservation to near machine precision will pass for a correct implementation and fail for almost any indexing slip.
for bc in ["neumann", "periodic"]:
col_sums = np.abs(np.asarray(laplacian_1d(50, 0.02, bc=bc).sum(axis=0))).max()
print(f"{bc:10} max |column sum| = {col_sums:.2e}")
print(f"{'dirichlet':10} max |column sum| = "
f"{np.abs(np.asarray(laplacian_1d(50, 0.02).sum(axis=0))).max():.2e}"
" <- leaks at the ends, as it should")Stability¶
solve_ivp picked its own time steps above. Suppose instead we step forward by
hand with the simplest possible scheme, forward Euler:
Each step multiplies by . Writing in the eigenbasis of , the component belonging to eigenvalue is multiplied by every step, so it stays bounded only if
The eigenvalues of the second-difference matrix run from near 0 down to about . The eigenvectors are the sines of the exact solution, sampled on the grid, and for small the eigenvalues are close to , so is the decay rate of that mode. Plugging in gives
Halving forces you to quarter . Refining the mesh gets expensive fast.
n2 = 40
dx2 = L / (n2 + 1)
x2 = np.linspace(dx2, L - dx2, n2)
A2 = laplacian_1d(n2, dx2)
dt_max = dx2**2 / (2 * D)
# a spike excites every mode, including the one that goes unstable
spike = np.zeros(n2)
spike[n2 // 2] = 1.0
print(f"dx = {dx2:.5f}, dt_max = dx^2/(2D) = {dt_max:.3e}\n")
for factor in [0.5, 0.9, 1.05, 1.2]:
dt = factor * dt_max
u = spike.copy()
nsteps = int(0.2 / dt)
for _ in range(nsteps):
u = u + dt * D * (A2 @ u)
print(f" dt = {factor:>4} * dt_max {nsteps:4d} steps "
f"max|u| = {np.max(np.abs(u)):.3e}")Below the threshold the answer is a sensible . A 5% overshoot gives 22, and a 20% overshoot gives 107. There is no gentle degradation: the scheme is fine until it is catastrophically not.
For a fine mesh, an explicit solver is forced into tiny steps by stability rather
than by accuracy -- the problem is stiff. We can switch to an implicit method, which has no such
restriction. We can use solve_ivp(..., method='BDF') and passing the Jacobian D*A.
Second order of convergence¶
Take an initial condition whose exact solution we know. With Dirchilet boundary condition and , the Fourier sine series has the single term , so
We then solve numerically on a sequence of meshes, measure the error, and check that it falls like .
def diffusion_error(n, T=0.5):
"""
max error at time T against the exact solution, on n interior points
"""
dx = L / (n + 1)
x = np.linspace(dx, L - dx, n)
A = laplacian_1d(n, dx)
u0 = np.sin(np.pi * x / L)
# time error driven far below the spatial error we are trying to measure
sol = solve_ivp(lambda t, u: D * (A @ u), (0, T), u0,
t_eval=[T], rtol=1e-11, atol=1e-13)
exact = np.exp(-D * (np.pi / L)**2 * T) * np.sin(np.pi * x / L)
return dx, np.max(np.abs(sol.y[:, -1] - exact))
ns = [10, 20, 40, 80, 160]
dxs, errs = zip(*[diffusion_error(n) for n in ns])
for n, d, e in zip(ns, dxs, errs):
print(f" n = {n:4d} dx = {d:.5f} error = {e:.3e}")
slope = np.polyfit(np.log(dxs), np.log(errs), 1)[0]
print(f"\nfitted order: {slope:.3f} (expected 2)")plt.figure(figsize=(6, 4))
plt.loglog(dxs, errs, 'o-', label='measured error')
plt.loglog(dxs, np.array(dxs)**2 * errs[-1] / dxs[-1]**2, 'k--',
label=r'$\Delta x^2$ reference')
plt.xlabel(r'$\Delta x$'); plt.ylabel('max error'); plt.legend()
plt.title(f'observed order {slope:.2f}')
plt.show()Animating the solution¶
A time-dependent solution is easier to read when animated.
from matplotlib import animation
from IPython.display import HTML
sol = solve_ivp(lambda t, u: D * (A @ u), (0, T), u0,
t_eval=np.linspace(0, T, 40))
fig, ax = plt.subplots(figsize=(6, 3), dpi=72)
line, = ax.plot(x, sol.y[:, 0])
ax.set_xlim(0, L)
ax.set_ylim(-0.05, 1.05)
ax.set_xlabel('$x$')
ax.set_ylabel('$u$')
title = ax.set_title('$t = 0.00$')
def frame(j):
line.set_ydata(sol.y[:, j])
title.set_text(f'$t = {sol.t[j]:.2f}$')
return line, title
anim = animation.FuncAnimation(fig, frame, frames=len(sol.t), interval=80, blit=False)
anim.save('diffusion.gif', writer='pillow')
plt.close(fig) # keep the static figure from also being displayed
HTML(anim.to_jshtml())