TExcelTAD
Home › Numerical Methods › Two-Dimensional Poisson Problems

Poisson's Equation in 2D

Steady-state heat flow, electrostatic potentials, pressure in incompressible flow and image blending all lead to Poisson's equation −Δu=−(uxx+uyy)=f-\Delta u = -(u_{xx} + u_{yy}) = f 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 hh, apply the centered second difference in each direction:

4ui,j−ui−1,j−ui+1,j−ui,j−1−ui,j+1h2=fi,j.\frac{4u_{i,j} - u_{i-1,j} - u_{i+1,j} - u_{i,j-1} - u_{i,j+1}}{h^2} = f_{i,j}.

Each interior unknown couples to its four neighbours. With NN interior points per direction there are N2N^2 unknowns; numbering them row by row gives a matrix with five nonzero diagonals, which can be written with Kronecker products: A=I⊗T+T⊗IA = I \otimes T + T \otimes I, where T=1h2tridiag⁡(−1,2,−1)T = \frac{1}{h^2}\operatorname{tridiag}(-1, 2, -1).

python · try it yourself
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 = err
N =  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 h2h^2 is added to fi,jf_{i,j}. Here is a plate held at 100100 on the top edge and 00 elsewhere:

python · try it yourself
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 2525.

Solving the system

The cost of the solve dominates. For N2N^2 unknowns:

Method Cost (2D model problem)
dense LU O(N6)O(N^6), impossible beyond small NN
banded LU (bandwidth NN) O(N4)O(N^4)
sparse LU with nested dissection O(N3)O(N^3)
conjugate gradients O(N3)O(N^3), less with preconditioning
multigrid, FFT-based solvers O(N2)O(N^2) or O(N2log⁡N)O(N^2\log N)

Iterative methods take over for large 3D problems (Jacobi and Gauss-Seidel, Conjugate Gradients).

In software

  • scipy.sparse.kron, diags, and spsolve (SuperLU) or scipy.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 ff.

Exercises

Exercise 1: Count

How many unknowns and roughly how many nonzeros does the 5-point system have for N=1000N = 1000?

Answer

10610^6 unknowns, about 5×1065 \times 10^6 nonzeros.

Solution

N2N^2 unknowns, at most 5 nonzeros per row. A dense matrix would need 101210^{12} entries (8 TB).

Exercise 2: The stencil by hand

With h=12h = \frac{1}{2} there is one interior point. Solve −Δu=1-\Delta u = 1 with u=0u = 0 on the boundary.

Answer

u=116u = \frac{1}{16}.

Solution

4u−01/4=1\frac{4u - 0}{1/4} = 1, so 16u=116u = 1. (The true centre value is about 0.07370.0737; the grid is very coarse.)

Exercise 3: Mean value property (code)

For Laplace's equation (f=0f = 0) 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
python · try it yourself
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…

  1. all others
  2. its four grid neighbours
  3. two neighbours
  4. none

The 2D Poisson matrix is…

  1. dense and nonsymmetric
  2. sparse, symmetric positive definite
  3. triangular
  4. diagonal

Nonzero Dirichlet boundary values enter the linear system through…

  1. the matrix diagonal
  2. the right-hand side
  3. extra unknowns
  4. they are ignored