Skip to content

Poisson in 2-D, four ways: FEM, FDM, FVM and spectral

FEM · FDM · FVM · spectral poisson_2d.py

One problem, four discretisations. The Poisson equation \(-\Delta u = f\) on the unit square with \(u = 0\) on the boundary, and the source chosen so that the solution is known exactly: \(u^\*(x,y) = \sin(2\pi x)\sin(3\pi y)\), \(f = 13\pi^2 u^\*\). Finite elements solve the weak form; finite differences, finite volumes and the spectral method read one and the same strong-form term list.

The same solution, six lobes of alternating sign on a red-white-blue scale, drawn four times as each method computes it. FEM: a smooth field over a triangle mesh whose edges are drawn. FDM: one coloured dot per mesh node. FVM: one flat colour per triangle. Spectral: a smooth field with the grid lines of its 24 Chebyshev nodes per axis, which crowd towards the walls.

Each panel draws what its method computes: the P1 field over its triangles (FEM), one value per mesh node (FDM), one average per cell (FVM), and the Chebyshev interpolant with the lines through its nodes (spectral).

The problem

\[-\Delta u = f\quad\text{on }[0,1]^2,\qquad u=0\ \text{on the boundary},\qquad u^\*=\sin(2\pi x)\sin(3\pi y),\quad f=13\pi^2u^\* .\]

Finite elements solve the weak form \(\int\nabla u\cdot\nabla v=\int fv\); finite differences, finite volumes and the spectral method take the strong form \(-(u_{xx}+u_{yy})-f=0\).

The jNO code

The unknown and its test function come from the domain, and the gradient is written once:

def fem(h):
    d, (x, y), b = square(size=h)
    u = d.unknown()
    v = u.test()
    grad = lambda w: jno.np.jacobian(w, [x, y])
    prob = jno.fem([jno.np.inner(grad(u), grad(v)) - source(x, y) * v, u(*b) - 0.0])  # the weak form
    return d, np.asarray(prob.solve()).ravel(), np.asarray(prob.points)[:, :2]

The other three methods read one and the same strong-form term list; only the function that reads it changes, and for spectral the unknown's space:

def strong(method, d, x, y, b, u):
    """FDM, FVM and spectral: the same strong form, -Δu = f, with u = 0 on the boundary."""
    ui = u.bind(x=x, y=y)
    return method([-(ui.xx + ui.yy) - source(x, y), u(*b) - 0.0])


def fdm(h):
    d, (x, y), b = square(size=h)
    sol = strong(jno.fdm, d, x, y, b, d.unknown()).solve()  # values at the mesh nodes
    return d, np.asarray(sol).ravel(), np.asarray(d.mesh_connectivity["points"])[:, :2]


def fvm(h):
    d, (x, y), b = square(size=h)
    prob = strong(jno.fvm, d, x, y, b, d.unknown())  # one value per triangle, its cell average
    return d, np.asarray(prob.solve()).ravel(), np.asarray(prob.centroids)[:, :2]


def spectral(n):
    d = jno.shape.rect(0, 0, 1, 1).domain()  # geometry only: no mesh
    u = d.unknown(space="spectral", order=(n, n))  # Chebyshev on both axes: the walls are not periodic
    (x, y), b = d.variable("interior", split=True)[:2], d.variable("boundary", split=True)[:2]
    sol = strong(jno.spectral, d, x, y, b, u).solve()  # values at the Chebyshev-Gauss-Lobatto nodes
    return u, np.asarray(sol).ravel(), np.asarray(u.basis.nodes).reshape(-1, 2)
  • jno.fdm collocates the equation at the mesh nodes; ui.xx on a nodal field is a finite-difference second derivative.
  • jno.fvm integrates every term over a control volume, so ui.xx + ui.yy is the face sum of the face gradient, one value per triangle.
  • jno.spectral takes an unknown with space="spectral": Chebyshev–Gauss–Lobatto nodes and derivatives from the basis. No mesh is built.

Result

Each method at two resolutions, relative \(L^2\) error at its own unknowns:

method unknowns rel. \(L^2\) error error ratio
FEM (P1) 144 → 514 \(1.1\times10^{-2}\) \(2.2\times10^{-3}\) 4.9
FDM 144 → 514 \(8.2\times10^{-2}\) \(2.0\times10^{-2}\) 4.1
FVM (cell-centred) 246 → 946 \(2.8\times10^{-2}\) \(6.9\times10^{-3}\) 4.1
spectral (Chebyshev) 144 → 576 \(2.3\times10^{-5}\) \(1.4\times10^{-12}\) \(1.6\times10^{7}\)

The three mesh methods are second order: half the mesh size, a quarter of the error. The spectral method converges geometrically, because the solution is smooth and the square is a single spectral element. See Finite Volume Method, Finite differences and Spectral methods.

Full script

The whole script, as it runs in the tests
"""2-D Poisson equation, -Δu = f on the unit square with u = 0 on the boundary, four ways.

Manufactured solution u*(x, y) = sin(2πx) sin(3πy), so f = 13π² u*. Finite elements solve the weak form;
finite differences, finite volumes and the spectral method read one and the same strong-form term list.
Each method runs at two resolutions: the mesh methods converge at second order, the spectral method
geometrically.
"""

import jax

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

import numpy as np

import jno

run = jno.setup(__file__)
KX, KY = 2, 3  # half-waves of the solution along x and y
exact = lambda x, y: np.sin(KX * np.pi * x) * np.sin(KY * np.pi * y)
source = lambda x, y: (KX**2 + KY**2) * np.pi**2 * jno.np.sin(KX * np.pi * x) * jno.np.sin(KY * np.pi * y)


def square(**kw):
    """The unit square, its interior and boundary points."""
    d = jno.shape.rect(0, 0, 1, 1, **kw).domain()
    return d, d.variable("interior", split=True)[:2], d.variable("boundary", split=True)[:2]


def fem(h):
    d, (x, y), b = square(size=h)
    u = d.unknown()
    v = u.test()
    grad = lambda w: jno.np.jacobian(w, [x, y])
    prob = jno.fem([jno.np.inner(grad(u), grad(v)) - source(x, y) * v, u(*b) - 0.0])  # the weak form
    return d, np.asarray(prob.solve()).ravel(), np.asarray(prob.points)[:, :2]




def strong(method, d, x, y, b, u):
    """FDM, FVM and spectral: the same strong form, -Δu = f, with u = 0 on the boundary."""
    ui = u.bind(x=x, y=y)
    return method([-(ui.xx + ui.yy) - source(x, y), u(*b) - 0.0])


def fdm(h):
    d, (x, y), b = square(size=h)
    sol = strong(jno.fdm, d, x, y, b, d.unknown()).solve()  # values at the mesh nodes
    return d, np.asarray(sol).ravel(), np.asarray(d.mesh_connectivity["points"])[:, :2]


def fvm(h):
    d, (x, y), b = square(size=h)
    prob = strong(jno.fvm, d, x, y, b, d.unknown())  # one value per triangle, its cell average
    return d, np.asarray(prob.solve()).ravel(), np.asarray(prob.centroids)[:, :2]


def spectral(n):
    d = jno.shape.rect(0, 0, 1, 1).domain()  # geometry only: no mesh
    u = d.unknown(space="spectral", order=(n, n))  # Chebyshev on both axes: the walls are not periodic
    (x, y), b = d.variable("interior", split=True)[:2], d.variable("boundary", split=True)[:2]
    sol = strong(jno.spectral, d, x, y, b, u).solve()  # values at the Chebyshev-Gauss-Lobatto nodes
    return u, np.asarray(sol).ravel(), np.asarray(u.basis.nodes).reshape(-1, 2)




rel_l2 = lambda sol, p: float(np.linalg.norm(sol - exact(*p.T)) / np.linalg.norm(exact(*p.T)))
runs = {"FEM": (fem, (0.1, 0.05)), "FDM": (fdm, (0.1, 0.05)), "FVM": (fvm, (0.1, 0.05)), "spectral": (spectral, (12, 24))}
results = {}
for name, (solve, sizes) in runs.items():
    out_ = [solve(s) for s in sizes]
    errs = [rel_l2(sol, p) for _, sol, p in out_]
    results[name] = (out_[-1], errs, [len(sol) for _, sol, _ in out_])
    print(f"{name:8s}: unknowns {' -> '.join(str(len(s)) for _, s, _ in out_)}   rel_L2 {errs[0]:.2e} -> {errs[1]:.2e}")
for name in ("FEM", "FDM", "FVM"):
    errs = results[name][1]
    assert errs[1] < 3e-2 and errs[0] / errs[1] > 3.0, name  # second order: half the mesh size, a quarter the error
assert results["spectral"][1][1] < 1e-9  # geometric: 24 nodes per axis reach round-off scale