A finite difference formula approximates a derivative from a few neighboring values, and
its error is for some fixed order .
A spectral method instead fits one global function through all the grid values using Fourier transform, and differentiates that function exactly.
For smooth periodic functions the error then decreases faster than any power of .
The fast Fourier transform makes every operation cost .
import time
import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse as sparse
import scipy.sparse.linalg as spla
from scipy.fft import fft, ifft, fft2, ifft2, fftfreqFourier series on a grid¶
Take equally spaced points , , on a periodic interval . Recall that any vector of values can be written exactly as a combination of complex exponentials,
where fft(u) and the wavenumbers are integer multiples of . The
FFT returns the coefficients in the order (times
), and fftfreq produces the wavenumbers in the same order.
Since
differentiating takes three steps: transform, multiply coefficient by , transform back.
One detail needs care. For even , the value for the mode is used by both and , so the actual interpolant is , whose first derivative vanishes at every grid point. For odd derivatives we therefore set that coefficient to zero; otherwise a real function would get a complex derivative.
def spectral_derivative(u, L=2 * np.pi, order=1):
"""
derivative of the trigonometric interpolant of periodic samples u on [0, L)
"""
N = len(u)
k = 2 * np.pi * fftfreq(N, d=L / N)
if order % 2 == 1 and N % 2 == 0:
k[N // 2] = 0
return np.real(ifft((1j * k)**order * fft(u)))
def fd2(N, h):
"""
second-order centered difference matrix for u' on N periodic grid points with spacing h
"""
D = sparse.diags([-1.0, 1.0], [-1, 1], shape=(N, N), format='lil')
D[0, -1], D[-1, 0] = -1.0, 1.0 # wrap around
return D.tocsr() / (2 * h)
def fd4(N, h):
"""
fourth-order centered difference matrix for u' on N periodic grid points with spacing h
"""
D = sparse.diags([1.0, -8.0, 8.0, -1.0], [-2, -1, 1, 2], shape=(N, N), format='lil')
D[0, -2], D[0, -1], D[1, -1] = 1.0, -8.0, 1.0 # wrap around
D[-2, 0], D[-1, 0], D[-1, 1] = -1.0, 8.0, -1.0
return D.tocsr() / (12 * h)The finite difference derivatives fd2 and fd4 are sparse matrices, built like the
periodic laplacian_1d in Time-Dependent PDEs: sparse.diags
for the bands, plus the entries that wrap around the corners. Compare the three on , whose derivative is .
u = lambda x: np.exp(np.sin(x))
du = lambda x: np.cos(x) * np.exp(np.sin(x))
Ns = np.array([8, 12, 16, 24, 32, 48, 64, 96, 128, 256, 512, 1024])
errors = {"2nd-order FD": [], "4th-order FD": [], "spectral": []}
for N in Ns:
x = 2 * np.pi * np.arange(N) / N
h = 2 * np.pi / N
errors["2nd-order FD"].append(np.max(np.abs(fd2(N, h) @ u(x) - du(x))))
errors["4th-order FD"].append(np.max(np.abs(fd4(N, h) @ u(x) - du(x))))
errors["spectral"].append(np.max(np.abs(spectral_derivative(u(x)) - du(x))))
plt.figure(figsize=(6, 4))
for name, e in errors.items():
plt.loglog(Ns, e, 'o-', label=name)
plt.xlabel('number of points $N$')
plt.ylabel("max error in $u'$")
plt.legend()
plt.title(r'differentiating $e^{\sin x}$')
plt.show()
for N, e in zip(Ns, errors["spectral"]):
if N <= 48:
print(f"N = {N:3d}: spectral error {e:.1e}")The finite difference errors fall like and , straight lines on a log-log plot. The spectral error falls faster than any straight line, and this behavior is called spectral accuracy.
Past that point the spectral error creeps up slowly from round-off error.
Smoothness sets the rate¶
The error of the spectral derivative is roughly the size of the Fourier coefficients that the grid cannot represent, so it is governed by how fast the coefficients decay.
That is decided by smoothness. A jump in gives coefficients of size about , a jump in the -th derivative gives about , and an analytic function like has coefficients that decay geometrically.
N = 512
x = 2 * np.pi * np.arange(N) / N
funcs = {
r"$e^{\sin x}$ (analytic)": np.exp(np.sin(x)),
r"$|\sin x|^3$ (jump in $u'''$)": np.abs(np.sin(x))**3,
r"$|\sin x|$ (jump in $u'$)": np.abs(np.sin(x)),
r"step (jump in $u$)": (x < np.pi).astype(float),
}
k = np.arange(1, N // 2)
plt.figure(figsize=(7, 4.5))
for name, v in funcs.items():
c = np.abs(fft(v))[1:N // 2] / N
keep = c > 1e-15 # coefficients that vanish by symmetry cannot go on a log plot
plt.loglog(k[keep], c[keep], '.', label=name)
for p in [1, 2, 4]:
plt.loglog(k, 0.5 / k**p, 'k:', lw=1)
plt.text(k[-1] * 1.1, 0.5 / k[-1]**p, f'$k^{{-{p}}}$', va='center')
plt.ylim(1e-17, 2)
plt.xlabel('wavenumber $k$')
plt.ylabel(r'$|\hat u_k| / N$')
plt.legend(loc='lower left')
plt.title('Fourier coefficients and smoothness')
plt.show()The derivative inherits these rates. For the spectral derivative converges only algebraically:
v = lambda x: np.abs(np.sin(x))**3
dv = lambda x: 3 * np.sin(x) * np.abs(np.sin(x)) * np.cos(x)
for N in [16, 32, 64, 128, 256]:
x = 2 * np.pi * np.arange(N) / N
print(f"N = {N:3d}: max error {np.max(np.abs(spectral_derivative(v(x)) - dv(x))):.2e}")Each doubling of divides the error by 4, so it is . This is roughly the same as a second-order finite difference.
Spectral methods are good for smooth periodic problems and lose most of their advantage when the solution has kinks, jumps, or shocks. A truncated Fourier series of a discontinuous function also overshoots near the jump by about 9%, however many modes you keep (the Gibbs phenomenon).
Linear PDEs: exact evolution in Fourier space¶
For a linear PDE with constant coefficients on a periodic domain, all the Fourier modes evolve independently. For the heat equation
we can Fourier transform on both sides
So that the Fourier mode with the coefficient satisfies
This solves the semi-discrete problem exactly in time, at any , with one FFT and one inverse FFT. There is no time step and no stability limit. The high wavenumbers decay fastest with decay rate .
def heat_fourier(u0, t, D=1.0, L=2 * np.pi):
"""
exact solution at time t of u_t = D u_xx on [0, L), periodic, from samples u0
"""
N = len(u0)
k = 2 * np.pi * fftfreq(N, d=L / N)
return np.real(ifft(np.exp(-D * k**2 * t) * fft(u0)))
N = 256
x = 2 * np.pi * np.arange(N) / N
u0 = (np.abs(x - np.pi) < 1).astype(float) # + 0.2 * np.sin(20 * x)
plt.figure(figsize=(7, 4))
for t in [0, 0.002, 0.02, 0.2, 2.0]:
plt.plot(x, heat_fourier(u0, t), label=f'$t = {t}$')
plt.xlabel('$x$')
plt.ylabel('$u$')
plt.legend()
plt.title('heat equation, solved in Fourier space')
plt.show()Advection¶
The advection equation
moves any profile to the right at speed without changing its shape .
In Fourier space
We move a narrow bump once around the domain, after which the exact solution is the initial condition again, and compare
second-order differences with RK4 in time
spectral differentiation with RK4 in time
all with the same time step .
def rk4_steps(rhs, u0, dt, nsteps):
"""
nsteps of classical RK4 for the autonomous system u' = rhs(u)
"""
u = u0.copy()
for _ in range(nsteps):
k1 = rhs(u)
k2 = rhs(u + dt / 2 * k1)
k3 = rhs(u + dt / 2 * k2)
k4 = rhs(u + dt * k3)
u = u + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
return u
N, c = 200, 1.0
h = 2 * np.pi / N
x = h * np.arange(N)
u0 = np.exp(-20 * (x - np.pi)**2)
T = 2 * np.pi / c # one trip around the domain
nsteps = int(round(T / (0.5 * h / c)))
dt = T / nsteps
Dx = fd2(N, h)
u_fd = rk4_steps(lambda u: -c * (Dx @ u), u0, dt, nsteps)
u_sp = rk4_steps(lambda u: -c * spectral_derivative(u), u0, dt, nsteps)
plt.figure(figsize=(8, 4))
plt.plot(x, u0, 'k--', lw=2, label='exact')
plt.plot(x, u_fd, label='centered FD + RK4')
plt.plot(x, u_sp, label='spectral + RK4')
plt.xlabel('$x$')
plt.legend()
plt.title(f'after one period, N = {N}')
plt.show()
for name, v in [("centered FD", u_fd), ("spectral", u_sp)]:
print(f"{name:12}: max error {np.max(np.abs(v - u0)):.1e}")The finite difference fails because waves of different lengths travel at different speeds.
Applied to , the centered difference gives
instead of , so mode moves at speed
. The short waves lag behind and leave a trail. This is also called
numerical dispersion.
The spectral derivative is exact for every mode the grid can represent, so the only error left is from RK4 in time.
Finite differences are accurate only for well-resolved modes, , which means many points per wavelength. The spectral derivative is exact up to the grid’s limit , two points per wavelength.
Poisson’s equation¶
On the square with periodic boundary conditions, the Poisson equation becomes, mode by mode,
Every mode except can be solved by division. For the mode,
is the average of over the periodic square. Adding a constant to also satisfy the Poisson equation, so we can safely fix (zero mean).
def poisson_periodic(f, L=2 * np.pi):
"""
zero-mean solution of -Laplacian(u) = f on the periodic square [0, L)^2
f must have (numerically) zero mean
"""
N = f.shape[0]
k = 2 * np.pi * fftfreq(N, d=L / N)
kx, ky = np.meshgrid(k, k, indexing='ij')
k2 = kx**2 + ky**2
k2[0, 0] = 1.0 # avoid dividing by zero; fixed below
u_hat = fft2(f) / k2
u_hat[0, 0] = 0.0 # choose the solution with zero mean
return np.real(ifft2(u_hat))Check it with a manufactured solution: pick , compute by hand, and see if we get back.
for N in [64, 128, 256, 1024]:
x = 2 * np.pi * np.arange(N) / N
X, Y = np.meshgrid(x, x, indexing='ij')
u_exact = np.exp(np.sin(X)) * np.cos(2 * Y)
f = -(np.cos(X)**2 - np.sin(X) - 4) * u_exact # -(u_xx + u_yy)
start = time.perf_counter()
u = poisson_periodic(f)
elapsed = time.perf_counter() - start
print(f"N = {N:4d} ({N * N:8d} unknowns): error {np.max(np.abs(u - u_exact)):.1e}, "
f"{1e3 * elapsed:6.1f} ms")For comparison, here is a sparse direct solve of the second-order finite difference version of the same problem.
def periodic_laplacian_2d(N, L=2 * np.pi):
"""
five-point finite difference Laplacian on an N x N periodic grid
"""
h = L / N
D = sparse.diags([1.0, -2.0, 1.0], [-1, 0, 1], shape=(N, N), format='lil')
D[0, -1] = D[-1, 0] = 1.0
D = D.tocsr() / h**2
I = sparse.identity(N, format='csr')
return sparse.kron(D, I) + sparse.kron(I, D)
for N in [64, 128, 256]:
A = (-periodic_laplacian_2d(N)).tolil()
A[0, :] = 0
A[0, 0] = 1.0 # pin u at one point
A = A.tocsc()
b = np.random.default_rng(0).standard_normal(N * N)
start = time.perf_counter()
spla.spsolve(A, b)
print(f"N = {N:4d}: sparse direct solve {time.perf_counter() - start:.3f} s")The sparse solve is already hundreds of times slower at , and it is only second-order accurate. Fast Poisson solvers based on the FFT, and on its relatives the discrete sine and cosine transforms for Dirichlet and Neumann boundaries are standard building blocks in fluid dynamics and electrostatics codes.
Time splitting for nonlinear problems¶
We have shown that derivatives are cheap in Fourier space, while products and other nonlinear functions of are cheap on the real space grid. Many PDEs have the form
where is linear with constant coefficients, so that it can be solved exactly in Fourier space as above, and acts point by point. Time splitting (also called operator splitting) advances the two parts one after the other. Write for the map that takes to the solution of a time later, and for the same map for . One step of size is
Lie splitting: , a full nonlinear step followed by a full linear step;
Strang splitting: , a half nonlinear step, a full linear step, and another half nonlinear step. (The order can be changed depending on which is easier)
If the two parts commute, both are exact. In general they do not. For matrices and , expanding the exponentials gives
so Lie splitting makes an error of order in every step, and of order after the steps needed to reach a time . Strang splitting is symmetric, which cancels the term, and it is second order.
Example: the KdV equation¶
The Korteweg-de Vries (KdV) equation
is a model for shallow water waves. It has soliton solutions, solitary waves that keep their shape,
which move at a speed proportional to their height. The linear part is solved exactly in Fourier space,
The nonlinear part has no such
formula, so we advance it with one step of rk4_steps from above. We also write
. Here the half steps of the Strang splitting are the cheap derivatives, so each step needs only one RK4 step.
One more detail. If contains wavenumbers up to , then contains wavenumbers up to , which the grid cannot represent. They show up as lower wavenumbers instead (this is called aliasing) and can make the computation blow up. The standard fix is the 2/3 rule: drop the top third of the wavenumbers when differentiating .
def kdv(u0, T, nsteps, save_every=None):
"""
solution at time T of u_t + u u_x + u_xxx = 0 on [-pi, pi), periodic, by Strang splitting:
exact half steps of u_t + u_xxx = 0 around one RK4 step of u_t + u u_x = 0;
returns the final state and a list of snapshots
"""
dt = T / nsteps
N = len(u0)
k = fftfreq(N, d=1 / N)
k[N // 2] = 0 # odd derivatives: drop the Nyquist mode
half_step = np.exp(0.5 * dt * k**3 * 1j)
ik = 1j * k * (np.abs(k) < N / 3) # derivative with the 2/3 rule
linear = lambda u: np.real(ifft(half_step * fft(u)))
nonlinear = lambda u: -0.5 * np.real(ifft(ik * fft(u**2))) # -u u_x = -(u^2 / 2)_x
u = u0.copy()
snapshots = [u0]
for n in range(1, nsteps + 1):
u = linear(rk4_steps(nonlinear, linear(u), dt, 1))
if save_every and n % save_every == 0:
snapshots.append(u)
return u, snapshots
def soliton(x, c, x0=0.0):
return 3 * c / np.cosh(0.5 * np.sqrt(c) * (x - x0))**2Before using it, check it. A soliton with speed goes once around the domain of length in time and should come back to where it started.
N = 256
x = 2 * np.pi / N * np.arange(-N // 2, N // 2) # grid on [-pi, pi)
u0 = soliton(x, c=100.0)
uT, _ = kdv(u0, 2 * np.pi / 100, 5000)
print(f"relative error after one trip: {np.max(np.abs(uT - u0)) / np.max(u0):.1e}")Now a tall soliton starts behind a short one. The tall one is faster, catches up, and passes through.
u0 = soliton(x, 625, x0=-2) + soliton(x, 256, x0=-1) # speeds 625 and 256
uT, snapshots = kdv(u0, 0.006, 2000, save_every=200)
plt.figure(figsize=(8, 6))
for j, s in enumerate(snapshots):
plt.plot(x, s + 700 * j, 'k', lw=0.8) # later times higher up
plt.xlabel('$x$')
plt.yticks([])
plt.title('two KdV solitons (time increases upward)')
plt.show()After the collision both solitons come out with their original shapes and speeds.
Exercises¶
Exercise 1¶
Real data has conjugate-symmetric Fourier coefficients, so half of them are redundant.
Rewrite spectral_derivative using rfft, irfft, and rfftfreq from scipy.fft.
Check that it agrees with the version above to rounding error, and time both for
.
# Your code hereExercise 2¶
Compute the second derivative of spectrally (order=2) and with the
second-order formula . How many points does each need for
an error below 10-8?
# Your code here