Module contents
Lesson 11 of 27Advanced 110 min

Advanced numerical methods: multigrid and spectral methods

Multigrid combines smoothing and coarse-grid corrections to solve discretized PDE systems efficiently. Spectral methods use Chebyshev polynomials or Fourier modes to exploit smoothness. This lesson builds both approaches and examines when to choose them.

After this lesson you can

  • Use Fourier analysis to explain how damped Jacobi and Gauss-Seidel smooth the error.
  • Implement a geometric multigrid V-cycle with restriction and prolongation and check its convergence as the grid is refined.
  • Use algebraic multigrid (AMG) to precondition an unstructured FEM matrix.
  • Construct the Chebyshev differentiation matrix and solve boundary-value problems with spectral convergence.
  • Solve a nonlinear periodic PDE using a Fourier pseudospectral method, dealiasing and exponential integration.

Before you start

Error has scales

Poisson equations and implicit diffusion steps produce increasingly large sparse systems as the grid is refined. Two observations change how we solve them: iterative methods reduce frequencies at different rates, and if the solution is very smooth, a global approximation can need far fewer degrees of freedom than a local stencil. Neither observation removes the cost of modeling boundaries or checking accuracy.

For −u′′=f-u''=f on a uniform grid, damped Jacobi updates um+1=um+ωD−1(f−Aum)u^{m+1}=u^m+\omega D^{-1}(f-Au^m). We can see multigrid smoothing on a mode with frequency ξ\xi: its error is multiplied by

gω(ξ)=1−ω(1−cos⁡ξ).g_\omega(\xi)=1-\omega(1-\cos\xi).

With ω=2/3\omega=2/3, frequencies ξ∈[π/2,π]\xi\in[\pi/2,\pi] are reduced by a factor of at most 1/31/3 per sweep in this 1D problem. Frequencies near zero have a factor close to one. With ω=1\omega=1, the mode near π\pi has a factor close to −1-1 and oscillates without effective damping. Gauss-Seidel also smooths the model problem, but its symbol and effect depend on the sweep order; its factor is not the Jacobi factor. In 2D, the frequencies and smoothing constant are analyzed together.

InteractiveWhich frequencies does Jacobi remove?
  • Mode k=2
  • Mode k=55

On a coarser grid the smooth mode occupies a larger fraction of representable modes. The displayed weight is rounded; the exact initial value is 2/3.

0.67
0
Smooth mode amplitude1.0000
High mode amplitude1.0000
Two Dirichlet eigenmodes are multiplied by their exact factor after each sweep; the low-frequency mode survives longer.

A hierarchy of grids

Two-grid correction takes the residual rh=fh−Ahuhr_h=f_h-A_hu_h, restricts it, solves a coarse-grid error problem and prolongs the correction. If PP interpolates bilinearly, a common 2D choice is R=PT/4R=P^T/4. With the Galerkin operator AH=RAhPA_H=RA_hP, the transfer operators and the operator are consistent; another option is to rediscretize the PDE at each level, as the lab does. These matrices are not identical in every case.

The V-cycle smooths before and after descending recursively and solves the coarsest level. The smoother reduces error that oscillates on a grid; smooth error becomes more oscillatory when represented on a coarser grid. Incorrect restriction, incompatible boundaries or an unsuitable smoother can destroy this complementarity.

InteractiveA V-cycle and its residuals
Residual or correction by level
Relative residual
  • V-cycle
  • CG

The graph uses log₁₀ of iteration count and relative residual. The animation grid has 31 nodes per axis and a two-mode source; the curves use reproducible random sources. V work counts seven stencil applications per level, weighted by nodes; it omits transfers and fixed costs. CG uses one application per iteration plus inner products; these are not measured times.

0
Interior nodes per axis
Stageresidual after smoothing
Displayed level size31
V-cycles to 10⁻⁸9
CG iterations to 10⁻⁸98
Approximate V work81.6 fine-grid sweeps
Step through the levels of an actual run and compare V-cycle and CG residual curves for the stated grids and data.

If work per level is proportional to the number of nodes, a 2D hierarchy refined by a factor of two has sizes approximately N,N/4,N/16,…N,N/4,N/16,\ldots, which sum to 4N/34N/3. A V-cycle costs O(N)O(N) if work and the number of sweeps are bounded; obtaining a solution to a given tolerance in O(N)O(N) also requires uniform convergence and a suitable accuracy criterion. W-cycles visit coarse levels multiple times; F-cycles combine traversals. Full multigrid starts on a coarse grid, interpolates the solution to finer grids and applies cycles at each level: it is not merely another name for a V-cycle.

Algebraic multigrid builds levels from the matrix, for example by grouping strongly connected nodes and smoothing interpolation. It is useful for FEM systems without a structured grid; anisotropy, heterogeneous coefficients and null spaces require appropriate choices. As a CG preconditioner, the resulting operator must be symmetric positive definite on the relevant space. Building and storing the hierarchy also has a cost: optimal speed is not guaranteed for every matrix. The analogy with a U-Net or graph pooling helps visualize resolutions, but does not turn a network into a solver with guarantees.

Spectral approximation

Chebyshev collocation interpolates at xj=cos⁡(jπ/N)x_j=\cos(j\pi/N) and applies a matrix DD to nodal values. For a Dirichlet problem −u′′=f-u''=f, use −D2-D^2 at the interior nodes and incorporate the known boundary values. These nodes cluster near the endpoints and avoid the interpolation oscillations that can occur with equally spaced nodes.

Spectral convergence depends on regularity. A function analytic in a suitable complex region can exhibit geometric error decay in NN; a nearby pole slows it, and a cusp limits convergence. After rapid decay, rounding and the ill-conditioning of derivatives can dominate. The following graph compares first-derivative errors, not PDE solution errors; the FD and Chebyshev grids evaluate different nodes.

FD maxima are computed only where the stencil fits, so refinement includes points closer to the endpoint and the pole. This change in the set can increase the maximum before reaching the asymptotic regime. For ∣x∣|x|, the second-order stencil is exact at the evaluated nodes because each side is linear and the cusp is excluded; this does not indicate global accuracy at a singularity. The fourth-order stencil crosses the cusp from some nearby nodes.

InteractiveDerivatives: spectral and finite differences
  • FD order 2
  • FD order 4
  • Chebyshev

Vertical axis: log₁₀ of the maximum error at evaluated nodes; N is the number of subintervals. The point where |x| is nondifferentiable is excluded and a plotting floor of 10⁻¹⁵ is used. FD and Chebyshev grids have different nodes.

Function
Errors computed for exp(x), a nearby pole and |x|; the nondifferentiable point is excluded and a plotting floor is stated.

For simple geometry and smooth data, spectral methods can be very efficient. For complex geometries or layers and discontinuities, finite elements and local refinement are often more flexible. Spectral elements combine high-degree bases with a partition into elements; the choice is assessed through errors and costs, not a universal rule. Trefethen’s original book and programs include collocation examples.

Fourier and nonlinearity

On a periodic domain, Fourier diagonalizes derivatives. For Kuramoto-Sivashinsky we use

ut=−uux−uxx−uxxxx,∂tu^=(k2−k4)u^−ik2u2^.u_t=-u u_x-u_{xx}-u_{xxxx},\qquad \partial_t\hat u=(k^2-k^4)\hat u-\frac{ik}{2}\widehat{u^2}.

The pseudospectral calculation evaluates the product on the physical grid using an FFT. Product frequencies above the largest representable frequency can fold back to low frequencies: this is aliasing. The strict two-thirds rule discards modes with ∣m∣≥N/3|m|\ge N/3 both before and after the quadratic product. The Nyquist mode is set to zero here. The filter changes the discretization; comparing long-term chaotic trajectories alone does not establish which calculation is correct.

Exponential integrators treat the linear part exactly at each step and approximate the integral of the nonlinear part. ETDRK4 uses four evaluations of the nonlinearity. Its coefficients contain quotients subject to cancellation near zero; the contour formula of Kassam and Trefethen evaluates them stably. Stability of the linear part does not eliminate the need to check the time step and spatial resolution.

InteractiveKuramoto-Sivashinsky evolution

Blue and orange show opposite signs; newer rows appear at the top. Height adjusts to the number of visible samples, up to 80; changing steps per advance changes the time interval between samples. The method uses N=64, length 32π, Δt=0.25 and ETDRK4; the direct browser DFT gives the same discretization as the lab FFT. The spectrum’s vertical axis is log₁₀ of amplitude.

Dealiasing
4
Time0.00
Visible samples1
Spatial mean0.00000
Maximum |u|1.2977
Changing the filter resets the initial condition. The space-time history and spectrum are shown; an unfiltered run does not establish that every difference is physical.

Lab: V-cycle

Use n=2k−1n=2^k-1 interior unknowns per axis and a zero boundary. Each cycle consists of three Jacobi sweeps before and after, full weighting and bilinear prolongation; the last level is solved directly. The identity R=PT/4R=P^T/4 can be checked using random dot products.

[ ]Geometric multigrid from scratchBrowser
"""Ciclo V geométrico 2D para -Δu=f y frontera Dirichlet homogénea."""
import numpy as np

def apply_A(u,h):
    z=np.pad(u,1)
    return (4*u-z[1:-1,:-2]-z[1:-1,2:]-z[:-2,1:-1]-z[2:,1:-1])/h**2

def jacobi(u,f,h,steps=3,omega=2/3):
    for _ in range(steps):u=u+omega*(h*h/4)*(f-apply_A(u,h))
    return u

def restrict(r):
    z=np.pad(r,1)
    return (4*z[2:-1:2,2:-1:2]+2*(z[1:-2:2,2:-1:2]+z[3::2,2:-1:2]+z[2:-1:2,1:-2:2]+z[2:-1:2,3::2])
            +z[1:-2:2,1:-2:2]+z[1:-2:2,3::2]+z[3::2,1:-2:2]+z[3::2,3::2])/16

def prolong(c):
    n=2*c.shape[0]+1;z=np.zeros((n+2,n+2));z[2:-1:2,2:-1:2]=c
    z[1:-1:2,2:-1:2]=(z[:-2:2,2:-1:2]+z[2::2,2:-1:2])/2
    z[1:-1,1:-1:2]=(z[1:-1,:-2:2]+z[1:-1,2::2])/2
    return z[1:-1,1:-1]

def v_cycle(u,f,h,levels=None):
    """V: tres Jacobi pre y post, solución exacta en la malla gruesa."""
    u=np.asarray(u,dtype=float);f=np.asarray(f,dtype=float);n=u.shape[0]
    if u.shape!=(n,n) or f.shape!=u.shape or n<1 or ((n+1)&n)!=0:raise ValueError('n debe ser 2^k−1 y malla cuadrada')
    if levels is None:levels=int(np.log2(n+1))
    if levels<1:raise ValueError('niveles inválidos')
    if n==1 or levels==1:
        # Resuelve exactamente el nivel final incluso si levels corta antes de n=1.
        from scipy.sparse import diags,eye,kron
        from scipy.sparse.linalg import spsolve
        D=diags([-np.ones(n-1),2*np.ones(n),-np.ones(n-1)],[-1,0,1],shape=(n,n))
        A=(kron(eye(n),D)+kron(D,eye(n)))/h**2
        return spsolve(A.tocsr(),f.ravel()).reshape(n,n)
    u=jacobi(u,f,h);r=f-apply_A(u,h);coarse=restrict(r)
    e=v_cycle(np.zeros_like(coarse),coarse,2*h,levels-1)
    return jacobi(u+prolong(e),f,h)
[ ]Cycles and conjugate gradientBrowser
from scipy.sparse.linalg import cg,LinearOperator
rng=np.random.default_rng(42)
for n in (15,31,63):
    h=1/(n+1);f=rng.normal(size=(n,n));u=np.zeros_like(f);base=np.linalg.norm(f)
    count=0
    while np.linalg.norm(f-apply_A(u,h))/base>1e-8 and count<20:
        u=v_cycle(u,f,h);count+=1
    A=LinearOperator((n*n,n*n),matvec=lambda x:apply_A(x.reshape(n,n),h).ravel())
    calls=[0]
    def callback(x):calls[0]+=1
    z,info=cg(A,f.ravel(),rtol=1e-8,atol=0,callback=callback)
    print('n',n,'ciclos V',count,'CG',calls[0],'info',info,'residuo CG',np.linalg.norm(f.ravel()-A@z)/base)

The figure extends the experiment to 255 interior unknowns per axis, with pseudorandom normal sources and seed 42. Each size uses the next sample from the same generator; these are not the same rescaled inputs. In this sample, nine cycles and 49, 98, 195, 381 and 757 CG iterations are needed for 15, 31, 63, 127 and 255 respectively. This is an observation for this operator and criterion, not a general guarantee.

Lab: Chebyshev and KS

[ ]Chebyshev collocation and ETDRK4Browser
"""Colocación Chebyshev y Kuramoto-Sivashinsky por ETDRK4."""
import numpy as np

def cheb(N):
    if N<0:raise ValueError('N no negativo')
    if N==0:return np.array([1.]),np.zeros((1,1))
    x=np.cos(np.pi*np.arange(N+1)/N)
    c=np.ones(N+1);c[[0,-1]]=2;c*=(-1.)**np.arange(N+1)
    dx=x[:,None]-x[None,:]
    D=(c[:,None]/c[None,:])/(dx+np.eye(N+1))
    D-=np.diag(D.sum(axis=1))
    return x,D

def ks_etdrk4(n=64,length=32*np.pi,dt=.25,steps=400,dealias=True,save_every=10):
    """u_t=-u*u_x-u_xx-u_xxxx, periódico; filtro estricto de dos tercios."""
    if n%2 or n<8 or length<=0 or dt<=0:raise ValueError('parámetros inválidos')
    x=length*np.arange(n)/n;k=2*np.pi*np.fft.fftfreq(n,d=length/n)
    k[n//2]=0 # derivada impar en Nyquist
    linear=k*k-k**4;linear[n//2]=-(np.pi*n/length)**4+(np.pi*n/length)**2
    E=np.exp(dt*linear);E2=np.exp(dt*linear/2)
    roots=np.exp(1j*np.pi*(np.arange(1,33)-.5)/32)
    LR=dt*linear[:,None]+roots[None,:]
    Q=dt*np.real(np.mean((np.exp(LR/2)-1)/LR,axis=1))
    f1=dt*np.real(np.mean((-4-LR+np.exp(LR)*(4-3*LR+LR**2))/LR**3,axis=1))
    f2=dt*np.real(np.mean((2+LR+np.exp(LR)*(-2+LR))/LR**3,axis=1))
    f3=dt*np.real(np.mean((-4-3*LR-LR**2+np.exp(LR)*(4-LR))/LR**3,axis=1))
    modes=np.fft.fftfreq(n)*n;mask=np.abs(modes)<n/3 if dealias else np.ones(n,dtype=bool);mask[n//2]=False
    v=np.fft.fft(np.cos(2*np.pi*x/length)*(1+np.sin(2*np.pi*x/length)))*mask
    def nonlinear(v):
        v=v*mask;u=np.fft.ifft(v).real
        return (-.5j*k*np.fft.fft(u*u))*mask
    history=[np.fft.ifft(v).real.copy()];times=[0.]
    for step in range(1,steps+1):
        Nv=nonlinear(v);a=E2*v+Q*Nv;Na=nonlinear(a);b=E2*v+Q*Na;Nb=nonlinear(b)
        c=E2*a+Q*(2*Nb-Nv);Nc=nonlinear(c)
        v=(E*v+f1*Nv+2*f2*(Na+Nb)+f3*Nc)*mask
        if step%save_every==0:history.append(np.fft.ifft(v).real.copy());times.append(step*dt)
    return x,np.array(times),np.array(history),v

The following boundary-value problem has known solution u=sin⁡(πx)u=\sin(\pi x) and zero boundary data. In the KS time-step comparison, both runs use the same spatial discretization and final time; chaotic trajectories can diverge later.

[ ]Boundary-value problem and time refinementBrowser
for n in (8,16,32):
    x,D=cheb(n);A=-(D@D)[1:-1,1:-1];rhs=np.pi**2*np.sin(np.pi*x[1:-1])
    u=np.r_[0,np.linalg.solve(A,rhs),0]
    print('Chebyshev',n,'error máximo',np.max(np.abs(u-np.sin(np.pi*x))))
reference=ks_etdrk4(dt=.0625,steps=160,save_every=160)[2][-1]
for dt in (.5,.25,.125):
    result=ks_etdrk4(dt=dt,steps=int(10/dt),save_every=int(10/dt))[2][-1]
    print('KS dt',dt,'diferencia L2 discreta',np.linalg.norm(result-reference))

The derivative figure is reproduced using exe^x, 1/(1.05−x)1/(1.05-x) and ∣x∣|x|, centered differences on a uniform grid and Chebyshev at its nodes. In the first two cases the analytical derivative is known; in the third, x=0x=0 is excluded. A collocation calculation with singularities may exhibit oscillations and algebraic convergence, and should not be interpreted as exponential accuracy.

[ ]Derivative errors for three levels of regularityBrowser
for kind in ('smooth','pole','cusp'):
    def fun(x):
        return np.exp(x) if kind=='smooth' else 1/(1.05-x) if kind=='pole' else np.abs(x)
    def derivative(x):
        return np.exp(x) if kind=='smooth' else 1/(1.05-x)**2 if kind=='pole' else np.sign(x)
    for n in (8,12,16,24,32,48,64):
        x=np.linspace(-1,1,n+1);h=2/n;y=fun(x)
        ids=np.arange(2,n-1);ids=ids[np.abs(x[ids])>1e-12]
        d2=(y[ids+1]-y[ids-1])/(2*h)
        d4=(y[ids-2]-8*y[ids-1]+8*y[ids+1]-y[ids+2])/(12*h)
        xc,D=cheb(n);keep=np.abs(xc)>1e-12
        errors=[np.max(np.abs(d2-derivative(x[ids]))),
                np.max(np.abs(d4-derivative(x[ids]))),
                np.max(np.abs((D@fun(xc))[keep]-derivative(xc[keep])))]
        print(kind,n,'FD2, FD4, Chebyshev:',errors)

AMG with FEM

This cell uses PyAMG with compiled extensions included in the browser environment, together with NumPy and SciPy. It assembles a custom triangular P1 matrix with zero Dirichlet conditions and compares CG with smoothed aggregation. Interior grid nodes are perturbed using a fixed seed and maximum amplitude 0.15h per coordinate. The numbers are for this grid and system, not a complex geometry.

[ ]FEM and AMG preconditioningBrowser
"""FEM P1 propio en cuadrado y CG con/sin precondicionador PyAMG."""
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import cg
import pyamg

def fem_matrix(n):
    x=np.linspace(0,1,n+1);X,Y=np.meshgrid(x,x);p=np.column_stack((X.ravel(),Y.ravel()))
    interior=(p[:,0]>0)&(p[:,0]<1)&(p[:,1]>0)&(p[:,1]<1)
    rng=np.random.default_rng(7);p[interior]+=rng.uniform(-.15/n,.15/n,(np.count_nonzero(interior),2))
    a=(np.arange(n)[:,None]*(n+1)+np.arange(n)[None,:]).ravel();b=a+1;c=a+n+1;d=c+1
    t=np.vstack((np.column_stack((a,b,d)),np.column_stack((a,d,c))))
    q=p[t];J=np.stack((q[:,1]-q[:,0],q[:,2]-q[:,0]),axis=-1);area=np.abs(np.linalg.det(J))/2
    grad=np.einsum('ij,ejk->eik',np.array([[-1.,-1.],[1.,0.],[0.,1.]]),np.linalg.inv(J))
    local=area[:,None,None]*np.einsum('eik,ejk->eij',grad,grad)
    rows=np.broadcast_to(t[:,:,None],local.shape).ravel();cols=np.broadcast_to(t[:,None,:],local.shape).ravel()
    A=coo_matrix((local.ravel(),(rows,cols)),shape=(len(p),len(p))).tocsr()
    free=np.flatnonzero((p[:,0]>0)&(p[:,0]<1)&(p[:,1]>0)&(p[:,1]<1))
    return A[free][:,free]

def compare(n=64):
    A=fem_matrix(n);rng=np.random.default_rng(42);b=rng.normal(size=A.shape[0])
    ml=pyamg.smoothed_aggregation_solver(A,symmetry='symmetric')
    for name,M in [('CG',None),('CG+AMG',ml.aspreconditioner(cycle='V'))]:
        count=[0]
        def callback(x):count[0]+=1
        x,info=cg(A,b,M=M,rtol=1e-8,atol=0,callback=callback)
        print(name,'n',A.shape[0],'iteraciones',count[0],'info',info,'residuo relativo',np.linalg.norm(b-A@x)/np.linalg.norm(b))
    print('niveles',len(ml.levels),'complejidad operador',ml.operator_complexity())

if __name__=='__main__':compare()

Exercises

ProofJacobi smoothing
Prove: Prove the high-frequency bound for ω=2/3 in 1D.
0
The error symbol is g=1−ω(1−cos ξ), with ξ between π/2 and π.

Step 1 of 3. Which interval contains cos ξ?

NumericCost by level
In 2D, if each level costs one quarter of the previous one, what is the limiting ratio of the sum of costs to the cost of the fine level?
QuizChoose a discretization and solver
For a periodic domain with a smooth solution, which option directly exploits diagonalization of the derivatives?
CodeGeometric V-cycle
Implement v_cycle(u,f,h,levels) for −Δu=f on a square with zero boundary conditions; n=2^k−1. Use damped Jacobi, full-weighting restriction and bilinear prolongation. The tests apply 12 cycles to 63 and 255 interior nodes per axis.
import numpy as np
def v_cycle(u,f,h,levels=None):
  pass
Shift+Enter to run
CodeChebyshev differentiation
Implement cheb(N), returning nodes cos(jπ/N) and the matrix that differentiates values at those nodes. Include N=0.
import numpy as np
def cheb(N):
  pass
Shift+Enter to run
Key idea
Multigrid distributes error across scales; spectral methods exploit global regularity. Both require discretization and validation suited to the problem.