Algorithm Search⌘K

Algorithmcore

Discontinuous Galerkin method

Also called DG method.

Space discretization with a polynomial of degree k in each cell and no continuity between cells, coupled only by numerical fluxes on faces. Conservative; order k + 1 for smooth solutions.

Time
Θ(N M (k+1)^2) worst
Space
Θ(M (k+1)) extra
Where
M = the number of cells; N = the number of time steps; k = the polynomial degree
Properties
conservativedeterministicexplicitlocal
Origin
W. H. Reed, T. R. Hill, P. Lesaint, P. A. Raviart, B. Cockburn, C. W. Shu, 1973

The discontinuous Galerkin (DG) method discretizes a conservation law ut+f(u)x=0u_t + f(u)_x = 0 in space with a polynomial of degree kk in each cell and no continuity condition between cells. Each cell does a Galerkin projection of the equation onto its own polynomials, and integration by parts puts a flux on each face. Because the two sides of a face have different values there, that flux is a numerical flux F^(u−,u+)\hat F(u^-, u^+), the same as in a finite volume scheme. This is the only coupling between cells. With k=0k = 0 the method is the first-order Godunov-type finite volume scheme. With degree kk the error for smooth solutions on regular meshes is of order k+1k + 1. The mass matrix is block diagonal, the method is conservative, and hphp adaptivity and unstructured meshes are natural. This page is about the space discretization. The time stepping and the limiter that make it work for shocks are on Runge-Kutta discontinuous Galerkin.

In plain words

Cut the line into cells. In each cell, describe the unknown by a short polynomial, such as a line or a parabola, chosen on its own. The polynomial of one cell does not have to meet the polynomial of the next cell, so at each wall there are two values. A rule picks one flow through the wall from those two values, usually the value that comes from upstream. Each cell then changes its polynomial so that, on average against every shape it can represent, the equation holds, with that wall flow as the only input from the neighbours. Higher degree polynomials give much better accuracy for the same number of cells, and each cell only talks to its direct neighbours, which suits parallel computers.

The problem

Given a flux ff, periodic initial data u0u_0 on [xL,xR][x_L, x_R] and a final time TT, approximate the solution of ut+f(u)x=0u_t + f(u)_x = 0 with MM cells Cj=[xj−1/2,xj+1/2]C_j = [x_{j-1/2}, x_{j+1/2}] of width Δx\Delta x. On CjC_j write ξ=2(x−xj)/Δx∈[−1,1]\xi = 2(x - x_j)/\Delta x \in [-1, 1] and

uh(x,t)=∑l=0kUj,l(t) Pl(ξ),u_h(x, t) = \sum_{l=0}^{k} U_{j,l}(t)\, P_l(\xi),

with PlP_l the Legendre polynomials. Then Uj,0U_{j,0} is the cell average. Multiply the equation by PlP_l, integrate over CjC_j and integrate by parts. With ∫CjPlPm dx=Δx2l+1δlm\int_{C_j} P_l P_m\,dx = \frac{\Delta x}{2l+1}\delta_{lm}, Pl(1)=1P_l(1) = 1 and Pl(−1)=(−1)lP_l(-1) = (-1)^l, the semi-discrete system is

dUj,ldt=2l+1Δx(∫−11f(uh) Pl′(ξ) dξ−F^j+1/2+(−1)lF^j−1/2),F^j+1/2=F^(uj+1/2−,uj+1/2+).\frac{dU_{j,l}}{dt} = \frac{2l+1}{\Delta x}\Big(\int_{-1}^{1} f(u_h)\,P_l'(\xi)\,d\xi - \hat F_{j+1/2} + (-1)^l \hat F_{j-1/2}\Big), \qquad \hat F_{j+1/2} = \hat F(u^-_{j+1/2}, u^+_{j+1/2}).

The face traces are uj+1/2−=∑lUj,lu^-_{j+1/2} = \sum_l U_{j,l} and uj+1/2+=∑l(−1)lUj+1,lu^+_{j+1/2} = \sum_l (-1)^l U_{j+1,l}. The flux must be consistent, F^(u,u)=f(u)\hat F(u, u) = f(u). The usual choices are the upwind flux for f(u)=auf(u) = au and a monotone flux such as Godunov's or Rusanov's for nonlinear ff.

The algorithm

  1. DG(U, Δx, Δt, T, f, F̂)
  2. 1repeat SSP-RK3 steps until t = T, each stage computing R ← DG-OPERATOR(U)
  3. DG-OPERATOR(U):
  4. 2for each face j+1/2 do u⁻ ← Σ_l U_(j,l); u⁺ ← Σ_l (-1)^l U_(j+1,l)
  5. 3F_(j+1/2) ← F̂(u⁻, u⁺)
  6. 4for each cell j and each degree l = 0, ..., k do
  7. 5V ← Σ_q w_q f(u_h(ξ_q)) P_l'(ξ_q) ▷ Gauss rule with k+1 points
  8. 6R_(j,l) ← ((2l+1)/Δx) (V - F_(j+1/2) + (-1)^l F_(j-1/2))
  9. 7return R

Line L1 is the method of lines. Any stable ODE solver works for a smooth solution. The usual choice is the three-stage SSP Runge-Kutta method of Shu and Osher with a Δt/Δx≤1/(2k+1)a\,\Delta t/\Delta x \le 1/(2k+1) (a common rule, not a sharp bound). Lines L2 and L3 do one flux evaluation per face. Lines L4 to L6 are local to each cell: the volume integral VV uses a Gauss-Legendre rule with k+1k + 1 points, which is exact when ff is linear and, for f(u)=u2/2f(u) = u^2/2, when k≤2k \le 2. The initial coefficients are the L2L^2 projection Uj,l=2l+12∫−11u0 Pl dξU_{j,l} = \frac{2l+1}{2}\int_{-1}^{1} u_0\,P_l\,d\xi.

With k=0k = 0, L5 gives V=0V = 0 and L6 is the finite volume update −(F^j+1/2−F^j−1/2)/Δx-(\hat F_{j+1/2} - \hat F_{j-1/2})/\Delta x. With the upwind flux this is the upwind scheme.

Example

One evaluation by hand. Take f(u)=uf(u) = u (advection with a=1a = 1), the upwind flux, k=1k = 1, two periodic cells with Δx=12\Delta x = \tfrac12, and U0=(1,12)U_0 = (1, \tfrac12), U1=(0,14)U_1 = (0, \tfrac14). So uh=1+12ξu_h = 1 + \tfrac12\xi on the first cell and 14ξ\tfrac14\xi on the second.

  • Traces: the first cell has u−=1.5u^- = 1.5 on its right face, and the second cell has u−=0.25u^- = 0.25 on its right face (which is the left face of the first cell, by periodicity). The upwind fluxes are F^1/2=1.5\hat F_{1/2} = 1.5 and F^3/2=F^−1/2=0.25\hat F_{3/2} = \hat F_{-1/2} = 0.25.
  • Volume terms: P0′=0P_0' = 0, P1′=1P_1' = 1, so V=∫−11uh dξV = \int_{-1}^{1} u_h\,d\xi is 22 for the first cell and 00 for the second.
  • First cell: R0,0=2(0−1.5+0.25)=−2.5R_{0,0} = 2(0 - 1.5 + 0.25) = -2.5 and R0,1=6(2−1.5−0.25)=1.5R_{0,1} = 6(2 - 1.5 - 0.25) = 1.5.
  • Second cell: R1,0=2(0−0.25+1.5)=2.5R_{1,0} = 2(0 - 0.25 + 1.5) = 2.5 and R1,1=6(0−0.25−1.5)=−10.5R_{1,1} = 6(0 - 0.25 - 1.5) = -10.5.

The averages change at rates −2.5-2.5 and 2.52.5, so the total mass is constant. The energy rate is ∑Δx2l+1Uj,lRj,l=−1.25+0.125−0.4375=−1.5625\sum \frac{\Delta x}{2l+1}U_{j,l}R_{j,l} = -1.25 + 0.125 - 0.4375 = -1.5625. The jumps u−−u+u^- - u^+ at the two faces are 1.5−(−0.25)=1.751.5 - (-0.25) = 1.75 and 0.25−0.5=−0.250.25 - 0.5 = -0.25, and −12(1.752+0.252)=−1.5625-\tfrac12(1.75^2 + 0.25^2) = -1.5625. This is the energy identity of the next section.

Refinement study (measurement). u0=sin⁡2πxu_0 = \sin 2\pi x on [0,1][0, 1], a=1a = 1, T=0.5T = 0.5, SSP-RK3 with Δt=0.9 Δx/(2k+1)\Delta t = 0.9\,\Delta x/(2k+1), L2L^2 error by an 8-point Gauss rule in each cell:

MM k=0k = 0 k=1k = 1 k=2k = 2
8 5.232e-1 2.883e-2 1.702e-3
16 3.349e-1 6.808e-3 2.118e-4
32 1.918e-1 1.671e-3 2.645e-5
64 1.030e-1 4.155e-4 3.305e-6
pobsp_{\text{obs}} (32 to 64) 0.90 2.01 3.00

The observed order is k+1k + 1. With k=2k = 2, 16 cells give a smaller error than 64 cells with k=1k = 1. For k=0k = 0 the rate is still rising toward 1 on these coarse grids.

Correctness

The proof is in proofs/correctness.md. It derives the cell equations from the weak form, shows that the l=0l = 0 equation is a conservative finite volume update so the total mass changes only through the boundary, and proves the energy identity for f(u)=auf(u) = au with the upwind flux: ddt12∥uh∥2=−∣a∣2∑faces(u−−u+)2\frac{d}{dt}\tfrac12\|u_h\|^2 = -\tfrac{|a|}{2}\sum_{\text{faces}}(u^- - u^+)^2. So the semi-discrete method is L2L^2 stable, and the jumps are the only source of dissipation. The error estimates are cited. Lesaint and Raviart (1974) proved order kk on general triangulations. Johnson and Pitkäranta (1986) proved order k+1/2k + 1/2 in L2L^2, and Peterson (1991) gave meshes on which k+1/2k + 1/2 is sharp. On uniform and many other meshes the observed order is k+1k + 1, as in the table.

Proof: The DG operator is the Galerkin projection with numerical fluxes, it is conservative, and it is L2 stable for upwind advectionfull

Setting. The grid is periodic with MM cells CjC_j of width Δx\Delta x, the degree is k≥0k \ge 0, and VhV_h is the space of functions whose restriction to each cell is a polynomial of degree at most kk. On CjC_j, ξ=2(x−xj)/Δx\xi = 2(x - x_j)/\Delta x and uh=∑lUj,lPl(ξ)u_h = \sum_l U_{j,l} P_l(\xi). The numerical flux F^\hat F is consistent, F^(u,u)=f(u)\hat F(u, u) = f(u). The DG method is: find uh(t)∈Vhu_h(t) \in V_h such that for every cell CjC_j and every polynomial vv of degree at most kk on CjC_j,

∫Cj∂tuh v dx−∫Cjf(uh) vx dx+F^j+1/2 v(xj+1/2−)−F^j−1/2 v(xj−1/2+)=0.(W)\int_{C_j} \partial_t u_h\, v\,dx - \int_{C_j} f(u_h)\, v_x\,dx + \hat F_{j+1/2}\, v(x_{j+1/2}^-) - \hat F_{j-1/2}\, v(x_{j-1/2}^+) = 0. \tag{W}

This is the equation ut+f(u)x=0u_t + f(u)_x = 0 multiplied by vv and integrated by parts over one cell, with the two unknown face values of f(u)f(u) replaced by F^\hat F. The exact solution satisfies (W) when it is smooth, because then F^\hat F at each face equals f(u)f(u) by consistency.

Lemma 1 (the cell equations). (W) is equivalent to lines L2 to L6 of the main page, provided the integral in L5 is exact.

Proof. Take v=Pl(ξ)v = P_l(\xi), l=0,…,kl = 0, \dots, k. These polynomials span the test space, so (W) for all vv is equivalent to (W) for these k+1k + 1 functions. Since dx=Δx2dξdx = \frac{\Delta x}{2}d\xi and ∫−11PlPm dξ=22l+1δlm\int_{-1}^1 P_l P_m\,d\xi = \frac{2}{2l+1}\delta_{lm}, the first term is Δx2l+1dUj,ldt\frac{\Delta x}{2l+1}\frac{dU_{j,l}}{dt}. Since vx=2ΔxPl′(ξ)v_x = \frac{2}{\Delta x}P_l'(\xi), the second term is −∫−11f(uh)Pl′(ξ) dξ=−V-\int_{-1}^1 f(u_h)P_l'(\xi)\,d\xi = -V. The face values of vv are Pl(1)=1P_l(1) = 1 and Pl(−1)=(−1)lP_l(-1) = (-1)^l. So (W) reads Δx2l+1dUj,ldt=V−F^j+1/2+(−1)lF^j−1/2\frac{\Delta x}{2l+1}\frac{dU_{j,l}}{dt} = V - \hat F_{j+1/2} + (-1)^l\hat F_{j-1/2}, which is L6. The traces in L2 are uhu_h at ξ=1\xi = 1 in CjC_j and at ξ=−1\xi = -1 in Cj+1C_{j+1}, which are ∑lUj,l\sum_l U_{j,l} and ∑l(−1)lUj+1,l\sum_l (-1)^l U_{j+1,l}. The Gauss rule with k+1k + 1 points in L5 is exact for polynomials of degree 2k+12k + 1. When ff is linear, f(uh)Pl′f(u_h)P_l' has degree at most 2k−12k - 1, so L5 is exact. □\square

Lemma 2 (conservation). ddt∑jΔx Uj,0=0\frac{d}{dt}\sum_j \Delta x\,U_{j,0} = 0 on a periodic grid. On a nonperiodic grid the total changes only by the two boundary fluxes.

Proof. For l=0l = 0, P0′=0P_0' = 0, so V=0V = 0 and L6 gives Δx dUj,0dt=−(F^j+1/2−F^j−1/2)\Delta x\,\frac{dU_{j,0}}{dt} = -(\hat F_{j+1/2} - \hat F_{j-1/2}). Each face flux appears once with each sign in the sum over jj, so the sum telescopes to zero on a periodic grid and to F^1/2−F^M+1/2\hat F_{1/2} - \hat F_{M+1/2} otherwise. □\square

Each stage of an explicit Runge-Kutta method is a linear combination of UU and of values of the operator, whose l=0l = 0 rows sum to zero, so the fully discrete method also keeps ∑jUj,0\sum_j U_{j,0} fixed (up to rounding). Since ∫Cjuh dx=Δx Uj,0\int_{C_j} u_h\,dx = \Delta x\,U_{j,0}, this is the integral of uhu_h.

Lemma 3 (energy identity). Let f(u)=auf(u) = au with a>0a > 0 and the upwind flux F^(u−,u+)=au−\hat F(u^-, u^+) = a u^-. Then

ddt 12∥uh∥L22=−a2∑j=1M(uj+1/2−−uj+1/2+)2≤0.\frac{d}{dt}\,\frac12\|u_h\|_{L^2}^2 = -\frac{a}{2}\sum_{j=1}^{M}\big(u^-_{j+1/2} - u^+_{j+1/2}\big)^2 \le 0.

For a<0a < 0 the same holds with ∣a∣|a|, by the reflection x↦−xx \mapsto -x.

Proof. Take v=uhv = u_h in (W) on each cell and add over jj. The first terms add to ddt12∥uh∥2\frac{d}{dt}\frac12\|u_h\|^2. In the second term, ∫Cja uh ∂xuh dx=a2((uj+1/2−)2−(uj−1/2+)2)\int_{C_j} a\,u_h\,\partial_x u_h\,dx = \frac{a}{2}\big((u^-_{j+1/2})^2 - (u^+_{j-1/2})^2\big). Collect the terms at one face j+1/2j + 1/2: cell CjC_j gives −a2(u−)2+au−u−-\frac{a}{2}(u^-)^2 + a u^- u^- and cell Cj+1C_{j+1} gives +a2(u+)2−au−u++\frac{a}{2}(u^+)^2 - a u^- u^+, with u±=uj+1/2±u^\pm = u^\pm_{j+1/2}. Their sum is a2((u−)2−2u−u++(u+)2)=a2(u−−u+)2\frac{a}{2}\big((u^-)^2 - 2u^-u^+ + (u^+)^2\big) = \frac{a}{2}(u^- - u^+)^2. So ddt12∥uh∥2+a2∑(u−−u+)2=0\frac{d}{dt}\frac12\|u_h\|^2 + \frac{a}{2}\sum (u^- - u^+)^2 = 0. □\square

In coefficients, ∥uh∥2=∑j∑lΔx2l+1Uj,l2\|u_h\|^2 = \sum_j\sum_l \frac{\Delta x}{2l+1}U_{j,l}^2, so the identity says ∑j,lΔx2l+1Uj,lRj,l=−a2∑(u−−u+)2\sum_{j,l}\frac{\Delta x}{2l+1}U_{j,l}R_{j,l} = -\frac{a}{2}\sum(u^- - u^+)^2. By Lemma 1 the code computes RR exactly in this case, so the identity holds up to rounding; the tests check it on random data.

Corollary (k=0k = 0). With k=0k = 0 and the upwind flux, Rj,0=−aΔx(Uj,0−Uj−1,0)R_{j,0} = -\frac{a}{\Delta x}(U_{j,0} - U_{j-1,0}), the upwind scheme. This follows from L6 with V=0V = 0 and F^j+1/2=aUj,0\hat F_{j+1/2} = aU_{j,0}.

Stability and convergence. Lemma 3 gives ∥uh(t)∥≤∥uh(0)∥≤∥u0∥\|u_h(t)\| \le \|u_h(0)\| \le \|u_0\| for the semi-discrete method, since the L2L^2 projection does not increase the norm. Combined with the consistency of (W), this is the start of the error analysis. The estimates themselves are cited, not proved here: order kk on general meshes (Lesaint and Raviart 1974), ∥u−uh∥L2≤C Δxk+1/2 ∣u0∣Hk+1\|u - u_h\|_{L^2} \le C\,\Delta x^{k+1/2}\,|u_0|_{H^{k+1}} in general (Johnson and Pitkäranta 1986), sharp on some meshes (Peterson 1991). The order k+1k + 1 observed on uniform meshes is a measurement on the main page.

Termination. The time loop runs ⌈T/Δt⌉\lceil T/\Delta t\rceil steps, the last one shortened so the run ends at TT. Each step makes three operator evaluations, and each evaluation is a fixed number of loops over the MM faces and the M(k+1)M(k+1) coefficients. The Newton iteration for the Gauss nodes runs at most 100 times per node. So the method stops after finitely many operations. ■\blacksquare

Complexity

One operator evaluation does MM flux evaluations and, per cell, k+1k + 1 evaluations of ff and (k+1)2(k + 1)^2 multiply-adds for the volume terms (with the values of PlP_l and Pl′P_l' at the Gauss points tabulated once). That is Θ(M(k+1)2)\Theta(M(k+1)^2) per stage and Θ(NM(k+1)2)\Theta(NM(k+1)^2) for NN steps of a three-stage method. The memory is Θ(M(k+1))\Theta(M(k+1)). The mass matrix is diagonal in the Legendre basis, so no linear system is solved. The time step shrinks like Δx/(2k+1)\Delta x/(2k+1), so for a fixed TT, N=Θ(M(2k+1))N = \Theta(M(2k+1)).

Properties

  • Conservative. The cell averages satisfy a finite volume update with the face fluxes F^\hat F (theorem).
  • Local. Each cell needs only the traces of its two neighbours, so the method parallelizes well and handles nonconforming and hphp meshes.
  • L2L^2 stable for linear advection with the upwind flux, in the semi-discrete form (theorem). The fully discrete SSP-RK3 method kept the energy nonincreasing in the tests at Δt=0.1 Δx\Delta t = 0.1\,\Delta x (measurement).
  • Order k+1k + 1 for smooth solutions on regular meshes (measurement here; k+1/2k + 1/2 is the general theorem).
  • Not monotone for k≥1k \ge 1. Near shocks the polynomials oscillate, so a limiter is needed for nonlinear problems.
  • Superconvergence. At the downwind face and at the right Radau points, the DG solution of linear advection is more accurate than order k+1k + 1 (the observed rate is up to 2k+12k + 1 at the faces).

Variants and improvements

  • RKDG. SSP Runge-Kutta time stepping with a TVB slope limiter (Cockburn and Shu), for shocks.
  • Nodal DG. Lagrange basis at Gauss-Lobatto or Gauss points instead of Legendre modes (Hesthaven and Warburton 2008). With Gauss-Lobatto points and a diagonal mass matrix this is the DG spectral element method, which has the summation-by-parts property and admits entropy stable forms.
  • Elliptic and diffusive terms. The symmetric interior penalty method, the local DG method and the hybridizable DG method.
  • Space-time DG and ADER-DG, which treat time with the same polynomial idea.
  • Limiting by subcells. Replace troubled cells by a finite volume scheme on subcells, or use WENO reconstruction as a limiter.

When to use it

Use DG for hyperbolic problems that need high order on unstructured or adaptive meshes: wave propagation in electromagnetics and acoustics, compressible flow with smooth regions, and transport. It is local and explicit, so it scales well on parallel machines and GPUs. For problems that are mostly shocks on a Cartesian grid, a finite volume scheme with WENO reconstruction is simpler and cheaper per unknown. For elliptic problems a continuous finite element method has fewer unknowns.

Pitfalls

  • Time step too large. Explicit DG is stable only for Courant numbers of about 1/(2k+1)1/(2k+1) with SSP-RK3. Using the finite volume CFL number makes the method blow up for k≥1k \ge 1.
  • Central flux for advection. The average 12(f(u−)+f(u+))\tfrac12(f(u^-) + f(u^+)) conserves energy, so it gives no dissipation, and in practice it loses one order of accuracy for odd kk. Use an upwind or monotone flux.
  • Too few quadrature points. For nonlinear ff, an inexact volume integral (aliasing) can make an unlimited DG method unstable. Use more points or a split form.
  • Wrong signs at the left face. The left face enters equation ll with the factor (−1)l=Pl(−1)(-1)^l = P_l(-1). Mistakes here keep k=0k = 0 correct and break k≥1k \ge 1.
  • No limiter at shocks. For k≥1k \ge 1, an unlimited method produces oscillations near discontinuities that do not decay as Δx→0\Delta x \to 0.
  • Initial data by interpolation. Interpolating u0u_0 instead of projecting it can lower the observed order and puts a different mass in each cell.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

discontinuous_galerkin_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/discontinuous-galerkin-method/. The authors are listed in prov/TAT3SX.jsonl.

"""Modal discontinuous Galerkin method for a 1D scalar conservation law u_t + f(u)_x = 0.

The grid is periodic with M cells of width dx. On cell C_j the solution is
u_h(x) = sum_{l=0}^{k} U[j][l] P_l(xi), with xi = 2 (x - x_j) / dx in [-1, 1] and P_l the
Legendre polynomials, so U[j][0] is the cell average. The space operator is the DG
operator with a numerical flux on each face; time stepping is the three-stage SSP
Runge-Kutta method of Shu and Osher (method of lines). No limiter is applied.

Precondition: M >= 1 cells, degree k >= 0, dx > 0, dt > 0, and a numerical flux that is
consistent (flux(u, u) = f(u)). With q = k + 1 Gauss points the volume integral is exact
when f is linear; for f(u) = u^2 / 2 it is exact for k <= 2.

Cost: one evaluation of the operator takes Theta(M (k + 1)^2) operations after the
basis tables are built, three evaluations make one step, and the memory is Theta(M (k + 1)).
"""

import math
from typing import Callable, List, Sequence, Tuple

Coeffs = List[List[float]]


def legendre(l: int, x: float) -> float:
    """P_l(x) by the three-term recurrence."""
    if l == 0:
        return 1.0 + 0 * x
    p0, p1 = 1.0 + 0 * x, x
    for n in range(1, l):
        p0, p1 = p1, ((2 * n + 1) * x * p1 - n * p0) / (n + 1)
    return p1


def legendre_deriv(l: int, x: float) -> float:
    """P_l'(x) from the identity P_l' = sum over m < l with l - m odd of (2m + 1) P_m."""
    return sum((2 * m + 1) * legendre(m, x) for m in range(l - 1, -1, -2))


def gauss_legendre(q: int) -> Tuple[List[float], List[float]]:
    """Nodes and weights of the q-point Gauss-Legendre rule on [-1, 1] (Newton on P_q)."""
    nodes, weights = [], []
    for i in range(q):
        x = math.cos(math.pi * (i + 0.75) / (q + 0.5))
        for _ in range(100):
            p, dp = legendre(q, x), q * (legendre(q - 1, x) - x * legendre(q, x)) / (1 - x * x)
            dx = p / dp
            x -= dx
            if abs(dx) < 1e-16:
                break
        dp = q * (legendre(q - 1, x) - x * legendre(q, x)) / (1 - x * x)
        nodes.append(x)
        weights.append(2.0 / ((1 - x * x) * dp * dp))
    order = sorted(range(q), key=lambda i: nodes[i])
    return [nodes[i] for i in order], [weights[i] for i in order]


def upwind_flux(a: float) -> Callable:
    """Upwind flux for f(u) = a u."""
    return lambda ul, ur: a * ul if a >= 0 else a * ur


def godunov_flux_burgers(ul: float, ur: float) -> float:
    """Exact Godunov flux for f(u) = u^2 / 2."""
    if ul > ur:
        return max(ul * ul, ur * ur) / 2
    if ul > 0:
        return ul * ul / 2
    if ur < 0:
        return ur * ur / 2
    return 0.0


def project(u0: Callable, M: int, k: int, xl: float, xr: float, q: int = 0) -> Coeffs:
    """L2 projection of u0 onto piecewise polynomials of degree k (Gauss quadrature)."""
    dx = (xr - xl) / M
    nodes, weights = gauss_legendre(q or k + 3)
    U = []
    for j in range(M):
        xc = xl + (j + 0.5) * dx
        U.append([(2 * l + 1) / 2 * sum(w * u0(xc + s * dx / 2) * legendre(l, s)
                                         for s, w in zip(nodes, weights)) for l in range(k + 1)])
    return U


def dg_operator(U: Coeffs, dx: float, f: Callable, flux: Callable, quad=None) -> Coeffs:
    """Right side R = L(U) of the semi-discrete DG system dU/dt = L(U), periodic grid."""
    M, k = len(U), len(U[0]) - 1
    nodes, weights = quad or gauss_legendre(k + 1)
    P = [[legendre(l, s) for l in range(k + 1)] for s in nodes]
    WD = [[w * legendre_deriv(l, s) for s, w in zip(nodes, weights)] for l in range(k + 1)]
    F = []
    for j in range(M):                                        # face j + 1/2
        um = sum(U[j])                                        # @line L2
        up = sum(c if l % 2 == 0 else -c for l, c in enumerate(U[(j + 1) % M]))
        F.append(flux(um, up))                                # @line L3
    R = []
    for j in range(M):                                        # @line L4
        vals = [f(sum(c * p for c, p in zip(U[j], Pq))) for Pq in P]
        row = []
        for l in range(k + 1):
            V = sum(wd * v for wd, v in zip(WD[l], vals))     # @line L5
            sign = 1 if l % 2 == 0 else -1
            row.append((2 * l + 1) / dx * (V - F[j] + sign * F[j - 1]))  # @line L6
        R.append(row)
    return R                                                  # @line L7


def _axpy(a, X, b, Y):
    return [[a * x + b * y for x, y in zip(rx, ry)] for rx, ry in zip(X, Y)]


def ssp_rk3_step(U: Coeffs, dt: float, L: Callable) -> Coeffs:
    """One step of the three-stage SSP Runge-Kutta method of Shu and Osher (1988)."""
    U1 = _axpy(1, U, dt, L(U))
    U2 = _axpy(3 / 4, U, 1 / 4, _axpy(1, U1, dt, L(U1)))
    return _axpy(1 / 3, U, 2 / 3, _axpy(1, U2, dt, L(U2)))


def dg_solve(U: Coeffs, dx: float, dt: float, T: float, f: Callable, flux: Callable) -> Coeffs:
    """Advance the DG coefficients from t = 0 to t = T; the last step is shortened."""
    if not dx > 0 or not dt > 0:
        raise ValueError("dx and dt must be positive")
    quad = gauss_legendre(len(U[0]))
    t = 0.0
    U = [list(r) for r in U]
    while t < T - 1e-14:                                      # @line L1
        h = min(dt, T - t)
        U = ssp_rk3_step(U, h, lambda V: dg_operator(V, dx, f, flux, quad))
        t += h
    return U


def evaluate(U: Coeffs, j: int, xi: float) -> float:
    """u_h at the reference point xi of cell j."""
    return sum(c * legendre(l, xi) for l, c in enumerate(U[j]))


def l2_error(U: Coeffs, exact: Callable, xl: float, xr: float, q: int = 8) -> float:
    """||u_h - exact||_2 over the domain, by q-point Gauss quadrature in each cell."""
    M = len(U)
    dx = (xr - xl) / M
    nodes, weights = gauss_legendre(q)
    s = 0.0
    for j in range(M):
        xc = xl + (j + 0.5) * dx
        s += sum(w * (evaluate(U, j, xi) - exact(xc + xi * dx / 2)) ** 2
                 for xi, w in zip(nodes, weights)) * dx / 2
    return math.sqrt(s)


def total_mass(U: Coeffs, dx: float) -> float:
    """sum_j U[j][0] dx, the integral of u_h."""
    return sum(r[0] for r in U) * dx


def energy(U: Coeffs, dx: float) -> float:
    """||u_h||_2^2 = sum_j sum_l dx / (2l + 1) U[j][l]^2."""
    return sum(dx / (2 * l + 1) * c * c for r in U for l, c in enumerate(r))
test_discontinuous_galerkin_method.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/discontinuous-galerkin-method/. The authors are listed in prov/TAT3SX.jsonl.

import math
import random

import pytest

from discontinuous_galerkin_method import (
    dg_operator, dg_solve, energy, gauss_legendre, godunov_flux_burgers, l2_error,
    legendre, legendre_deriv, project, total_mass, upwind_flux,
)

A = 1.0
f_lin = lambda u: A * u
u0 = lambda x: math.sin(2 * math.pi * x)


def run_advection(M, k, T=0.5, cfl=None):
    dx = 1.0 / M
    cfl = cfl or 0.9 / (2 * k + 1)
    U = project(u0, M, k, 0.0, 1.0)
    U = dg_solve(U, dx, cfl * dx / A, T, f_lin, upwind_flux(A))
    return l2_error(U, lambda x: u0(x - A * T), 0.0, 1.0)


def test_gauss_legendre_exact_for_degree_2q_minus_1():
    for q in range(1, 6):
        xs, ws = gauss_legendre(q)
        for p in range(2 * q):
            exact = 2 / (p + 1) if p % 2 == 0 else 0.0
            assert abs(sum(w * x ** p for x, w in zip(xs, ws)) - exact) < 1e-13


def test_legendre_derivative_matches_finite_difference():
    for l in range(6):
        for x in (-0.7, -0.1, 0.3, 0.9):
            h = 1e-6
            fd = (legendre(l, x + h) - legendre(l, x - h)) / (2 * h)
            assert abs(legendre_deriv(l, x) - fd) < 1e-7


def test_degree_zero_is_the_upwind_scheme():
    rng = random.Random(1)
    M, dx = 12, 1.0 / 12
    U = [[rng.uniform(-1, 1)] for _ in range(M)]
    R = dg_operator(U, dx, f_lin, upwind_flux(A))
    for j in range(M):
        assert abs(R[j][0] - (-(A / dx) * (U[j][0] - U[j - 1][0]))) < 1e-12


def test_exact_operator_on_a_quadratic_with_no_jumps():
    # u = x^2 on [0, 1] is not periodic, so test one inner cell of a long grid by hand:
    # with continuous data and the upwind flux, the DG operator returns the L2 projection of -u_x.
    M, k, dx = 8, 2, 0.125
    U = project(lambda x: x * x, M, k, 0.0, 1.0)
    R = dg_operator(U, dx, f_lin, upwind_flux(A))
    for j in range(1, M):
        xc = (j + 0.5) * dx
        assert abs(R[j][0] - (-2 * xc)) < 1e-12        # mean of -2x
        assert abs(R[j][1] - (-dx)) < 1e-12            # -2x = -2 xc - dx xi
        assert abs(R[j][2]) < 1e-12


@pytest.mark.parametrize("k,p_min", [(0, 0.85), (1, 1.85), (2, 2.85)])
def test_order_k_plus_one_on_smooth_advection(k, p_min):
    errs = [run_advection(M, k) for M in (8, 16, 32, 64)]
    rates = [math.log2(errs[i] / errs[i + 1]) for i in range(3)]
    assert rates[-1] > p_min, rates


def test_mass_is_conserved_for_burgers():
    rng = random.Random(7)
    M, k = 20, 2
    U = [[rng.uniform(-1, 1) for _ in range(k + 1)] for _ in range(M)]
    dx = 1.0 / M
    m0 = total_mass(U, dx)
    V = dg_solve(U, dx, 0.02 * dx, 0.01, lambda u: u * u / 2, godunov_flux_burgers)
    assert abs(total_mass(V, dx) - m0) < 1e-13


def test_semi_discrete_energy_identity_for_upwind_flux():
    rng = random.Random(3)
    M, k = 10, 3
    dx = 1.0 / M
    U = [[rng.uniform(-1, 1) for _ in range(k + 1)] for _ in range(M)]
    R = dg_operator(U, dx, f_lin, upwind_flux(A))
    rate = sum(dx / (2 * l + 1) * U[j][l] * R[j][l] for j in range(M) for l in range(k + 1))
    jumps = sum((sum(U[j]) - sum(c if l % 2 == 0 else -c for l, c in enumerate(U[(j + 1) % M]))) ** 2
                for j in range(M))
    assert abs(rate - (-(A / 2) * jumps)) < 1e-11


def test_energy_does_not_grow_under_a_small_step():
    rng = random.Random(5)
    M, k = 16, 2
    dx = 1.0 / M
    U = [[rng.uniform(-1, 1) for _ in range(k + 1)] for _ in range(M)]
    e0 = energy(U, dx)
    V = dg_solve(U, dx, 0.1 * dx, 0.2, f_lin, upwind_flux(A))
    assert energy(V, dx) <= e0 + 1e-14


def test_rejects_bad_steps():
    with pytest.raises(ValueError):
        dg_solve([[0.0]], 0.0, 0.1, 1.0, f_lin, upwind_flux(A))

History

Reed and Hill (1973) introduced the method at Los Alamos for the steady neutron transport equation, a linear hyperbolic problem, where the solution in each triangle can be computed cell by cell in the direction of the flow. Lesaint and Raviart (1974) gave the first analysis. Johnson and Pitkäranta (1986) proved the L2L^2 estimate of order k+1/2k + 1/2, and Peterson (1991) showed that it cannot be improved in general. Cockburn and Shu extended the method to nonlinear conservation laws and systems in a series of papers from 1989 to 1998, with Runge-Kutta time stepping and a limiter. Hesthaven and Warburton (2008) is the standard text on nodal DG methods.

References

  1. Jan S. Hesthaven and Tim Warburton, Nodal Discontinuous Galerkin Methods, Springer, 2008 (Texts in Applied Mathematics 54), Chapters 2 to 5 (the key ideas, the method in one dimension, stability and error estimates, nonlinear problems)
  2. Bernardo Cockburn and Chi-Wang Shu, Runge-Kutta discontinuous Galerkin methods for convection-dominated problems, Journal of Scientific Computing 16(3) (2001) 173-261, the scalar one-dimensional case, the L2 stability of the semi-discrete method, the error estimates
  3. W. H. Reed and T. R. Hill, Triangular mesh methods for the neutron transport equation, Los Alamos Scientific Laboratory report LA-UR-73-479, 1973, the method for the steady neutron transport equation on triangles
  4. P. Lesaint and P.-A. Raviart, On a finite element method for solving the neutron transport equation, in C. de Boor (ed.), Mathematical Aspects of Finite Elements in Partial Differential Equations, Academic Press, 1974, 89-123, the first error analysis
  5. Claes Johnson and Juhani Pitkäranta, An analysis of the discontinuous Galerkin method for a scalar hyperbolic equation, Mathematics of Computation 46(173) (1986) 1-26, the L2 error estimate of order k + 1/2
  6. Todd E. Peterson, A note on the convergence of the discontinuous Galerkin method for a scalar hyperbolic equation, SIAM Journal on Numerical Analysis 28(1) (1991) 133-140, a family of meshes on which the order k + 1/2 is sharp

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example