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
- 29Finite difference stencils for PDEsVon Neumann stability analysisMethod of linesFinite element assemblyGalerkin method
- 09Stationary iterative methodsConjugate gradientPreconditioningChebyshev nodes and Lebesgue constantChebyshev seriesDiscrete Fourier transform and FFTSampling and aliasing
- 03Matrix exponentialDuhamel formula
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 on a uniform grid, damped Jacobi updates . We can see multigrid smoothing on a mode with frequency : its error is multiplied by
With , frequencies are reduced by a factor of at most per sweep in this 1D problem. Frequencies near zero have a factor close to one. With , the mode near has a factor close to 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.
A hierarchy of grids
Two-grid correction takes the residual , restricts it, solves a coarse-grid error problem and prolongs the correction. If interpolates bilinearly, a common 2D choice is . With the Galerkin operator , 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.
If work per level is proportional to the number of nodes, a 2D hierarchy refined by a factor of two has sizes approximately , which sum to . A V-cycle costs if work and the number of sweeps are bounded; obtaining a solution to a given tolerance in 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 and applies a matrix to nodal values. For a Dirichlet problem , use 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 ; 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 , 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.
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
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 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.
Lab: V-cycle
Use 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 can be checked using random dot products.
"""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)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
"""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),vThe following boundary-value problem has known solution 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.
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 , and , centered differences on a uniform grid and Chebyshev at its nodes. In the first two cases the analytical derivative is known; in the third, is excluded. A collocation calculation with singularities may exhibit oscillations and algebraic convergence, and should not be interpreted as exponential accuracy.
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 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
Step 1 of 3. Which interval contains cos ξ?
import numpy as np
def v_cycle(u,f,h,levels=None):
passimport numpy as np
def cheb(N):
pass