Poisson's Equation in 2D
Steady-state heat flow, electrostatic potentials, pressure in incompressible flow and image blending all lead to Poisson's equation on a region, with values (or fluxes) given on the boundary. Discretizing it on a grid produces a large, sparse, symmetric positive definite linear system, the model problem for sparse linear algebra. The theory is in Laplace's Equation.
The five-point stencil
On a square grid with spacing , apply the centered second difference in each direction:
Each interior unknown couples to its four neighbours. With interior points per direction there are unknowns; numbering them row by row gives a matrix with five nonzero diagonals, which can be written with Kronecker products: , where .
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import spsolve
def poisson_matrix(N):
h = 1 / (N + 1)
T = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(N, N)) / h**2
I = sp.identity(N)
return (sp.kron(I, T) + sp.kron(T, I)).tocsc(), h
# exact solution u = sin(pi x) sin(2 pi y) on the unit square, u = 0 on the boundary
prev = None
for N in (15, 31, 63, 127):
A, h = poisson_matrix(N)
g = np.arange(1, N + 1) * h
X, Y = np.meshgrid(g, g) # rows vary in y, columns in x
exact = np.sin(np.pi * X) * np.sin(2 * np.pi * Y)
f = 5 * np.pi**2 * exact
u = spsolve(A, f.ravel()).reshape(N, N)
err = np.max(np.abs(u - exact))
print(f"N = {N:3d}: unknowns {N * N:6d}, nonzeros {A.nnz:6d}, max error {err:.2e}" + ("" if prev is None else f", ratio {prev / err:.2f}"))
prev = errN = 15: unknowns 225, nonzeros 1065, max error 1.10e-02
N = 31: unknowns 961, nonzeros 4681, max error 2.73e-03, ratio 4.02
N = 63: unknowns 3969, nonzeros 19593, max error 6.83e-04, ratio 4.00
N = 127: unknowns 16129, nonzeros 80137, max error 1.71e-04, ratio 4.00
Second-order accuracy, and the matrix has only about 5 nonzeros per row.
Boundary values
Nonzero boundary values move to the right-hand side: for an unknown next to the boundary, the known neighbour value divided by is added to . Here is a plate held at on the top edge and elsewhere:
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import spsolve
N = 49
h = 1 / (N + 1)
T = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(N, N)) / h**2
A = (sp.kron(sp.identity(N), T) + sp.kron(T, sp.identity(N))).tocsc()
b = np.zeros((N, N))
b[-1, :] += 100 / h**2 # last row of unknowns touches the top edge (y = 1)
u = spsolve(A, b.ravel()).reshape(N, N)
c = N // 2
print(f"temperature at the centre: {u[c, c]:.4f} (exact series value 25)")
print(f"symmetric left-right: {np.allclose(u, u[:, ::-1])}")temperature at the centre: 25.0000 (exact series value 25)
symmetric left-right: True
By superposition (four rotated copies sum to a plate at 100 everywhere), the exact centre value is .
Solving the system
The cost of the solve dominates. For unknowns:
| Method | Cost (2D model problem) |
|---|---|
| dense LU | , impossible beyond small |
| banded LU (bandwidth ) | |
| sparse LU with nested dissection | |
| conjugate gradients | , less with preconditioning |
| multigrid, FFT-based solvers | or |
Iterative methods take over for large 3D problems (Jacobi and Gauss-Seidel, Conjugate Gradients).
In software
scipy.sparse.kron,diags, andspsolve(SuperLU) orscipy.sparse.linalg.cg; PyAMG for algebraic multigrid.- Image editing's "seamless clone" (Poisson image editing, in OpenCV as
cv2.seamlessClone) solves exactly this system with the image gradient as .
Exercises
Exercise 1: Count
How many unknowns and roughly how many nonzeros does the 5-point system have for ?
Answer
unknowns, about nonzeros.
Solution
unknowns, at most 5 nonzeros per row. A dense matrix would need entries (8 TB).
Exercise 2: The stencil by hand
With there is one interior point. Solve with on the boundary.
Answer
.
Solution
, so . (The true centre value is about ; the grid is very coarse.)
Exercise 3: Mean value property (code)
For Laplace's equation () the discrete solution at each interior point equals the average of its four neighbours. Check this for the heated-plate solution of the lesson.
Answer
The largest deviation is at rounding level.
Solution
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import spsolve
N = 49; h = 1 / (N + 1)
T = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(N, N)) / h**2
A = (sp.kron(sp.identity(N), T) + sp.kron(T, sp.identity(N))).tocsc()
b = np.zeros((N, N)); b[-1, :] += 100 / h**2
U = np.zeros((N + 2, N + 2)); U[-1, 1:-1] = 100
U[1:-1, 1:-1] = spsolve(A, b.ravel()).reshape(N, N)
avg = (U[:-2, 1:-1] + U[2:, 1:-1] + U[1:-1, :-2] + U[1:-1, 2:]) / 4
print(f"{np.max(np.abs(avg - U[1:-1, 1:-1])):.1e}")4.3e-14
Test yourself
The 5-point Laplacian couples each unknown to…
- all others
- its four grid neighbours
- two neighbours
- none
The 2D Poisson matrix is…
- dense and nonsymmetric
- sparse, symmetric positive definite
- triangular
- diagonal
Nonzero Dirichlet boundary values enter the linear system through…
- the matrix diagonal
- the right-hand side
- extra unknowns
- they are ignored