Algorithm Search⌘K

Algorithmadvanced

Runge-Kutta discontinuous Galerkin method

Also called RKDG.

The Cockburn-Shu method for conservation laws: discontinuous Galerkin in space, SSP Runge-Kutta in time and a TVB slope limiter after each stage, so shocks are captured without oscillations.

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
conservativedeterministicexplicit
Origin
B. Cockburn, C. W. Shu, 1989

The Runge-Kutta discontinuous Galerkin (RKDG) method of Cockburn and Shu solves nonlinear conservation laws ut+f(u)x=0u_t + f(u)_x = 0 with shocks. It has three parts. The discontinuous Galerkin method discretizes space with a polynomial of degree kk in each cell and a monotone numerical flux on each face. An explicit SSP Runge-Kutta method advances in time. A slope limiter, applied after every stage, compares the polynomial in each cell with the averages of its neighbours and, where they disagree, replaces it by a linear function with a limited slope. With the plain minmod limiter the cell averages are total variation diminishing (TVDM) under a CFL condition. The TVB version, with a constant MM, leaves the polynomial alone near smooth extrema, so the method keeps order k+1k + 1 in smooth regions and still captures shocks within one or two cells without oscillations.

In plain words

High-degree polynomials in each cell give very accurate answers for smooth flows, but near a shock they wiggle, and the wiggles do not go away when the cells get smaller. RKDG fixes this with a check after every small time step. For each cell it looks at the averages of the cell and its two neighbours. If the polynomial at the cell walls goes above or below what the neighbouring averages allow, the cell is suspect, and its polynomial is replaced by a straight line with a slope that is no steeper than the neighbours permit. Smooth regions pass the check and keep their full polynomials. A tolerance lets small smooth peaks pass the check too, so they are not flattened.

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 entropy solution of ut+f(u)x=0u_t + f(u)_x = 0 on MM cells of width Δx\Delta x, with uh=∑l=0kUj,lPl(ξ)u_h = \sum_{l=0}^k U_{j,l}P_l(\xi) on cell CjC_j as on the DG page and uˉj=Uj,0\bar u_j = U_{j,0} the cell average. The numerical flux F^(a,b)\hat F(a, b) is consistent and monotone (nondecreasing in aa, nonincreasing in bb), with Lipschitz constants L1L_1 and L2L_2 in its two arguments. Here we use Godunov's flux for Burgers' equation, f(u)=u2/2f(u) = u^2/2. The goal is an approximation that is order k+1k + 1 where the solution is smooth and has no growing oscillations at shocks.

The algorithm

For a cell jj let Δ+=uˉj+1−uˉj\Delta^+ = \bar u_{j+1} - \bar u_j, Δ−=uˉj−uˉj−1\Delta^- = \bar u_j - \bar u_{j-1}, and let the face deviations be u~j=uh(xj+1/2−)−uˉj\tilde u_j = u_h(x_{j+1/2}^-) - \bar u_j and u~~j=uˉj−uh(xj−1/2+)\tilde{\tilde u}_j = \bar u_j - u_h(x_{j-1/2}^+). The modified minmod function is

m~(a,b,c)={aif ∣a∣≤MΔx2,m(a,b,c)otherwise,m(a,b,c)={smin⁡(∣a∣,∣b∣,∣c∣)if s=sign⁡a=sign⁡b=sign⁡c,0otherwise.\tilde m(a, b, c) = \begin{cases} a & \text{if } |a| \le M\Delta x^2, \\ m(a, b, c) & \text{otherwise,} \end{cases} \qquad m(a, b, c) = \begin{cases} s\min(|a|, |b|, |c|) & \text{if } s = \operatorname{sign} a = \operatorname{sign} b = \operatorname{sign} c, \\ 0 & \text{otherwise.} \end{cases}
  1. RKDG(U, Δx, Δt, T, f, F̂, M)
  2. 1U ← LIMIT(U); repeat until t = T: ▷ the last step is shortened
  3. 2U¹ ← LIMIT(U + Δt L(U)) ▷ L is the DG operator
  4. 3U² ← LIMIT(¾ U + ¼ (U¹ + Δt L(U¹)))
  5. 4U ← LIMIT(⅓ U + ⅔ (U² + Δt L(U²)))
  6. LIMIT(U): for each cell j do
  7. 5compute Δ⁺, Δ⁻ from the means and the face deviations ũ, ũ̃
  8. 6ũ_mod ← m̃(ũ, Δ⁺, Δ⁻); ũ̃_mod ← m̃(ũ̃, Δ⁺, Δ⁻)
  9. 7if ũ_mod = ũ and ũ̃_mod = ũ̃ then keep the cell unchanged
  10. 8else U_(j,1) ← m̃(U_(j,1), Δ⁺, Δ⁻); U_(j,l) ← 0 for l ≥ 2

Lines L2 to L4 are the three-stage SSP Runge-Kutta method of Shu and Osher, a convex combination of forward Euler steps, with the limiter after each stage. Lines L5 to L8 are the generalized slope limiter of Cockburn and Shu. The limiter never changes the mean Uj,0U_{j,0}, so it keeps conservation. A cell that fails the test at L7 becomes the linear function uˉj+Uj,1ξ\bar u_j + U_{j,1}\xi. For k=1k = 1 both face deviations equal Uj,1U_{j,1}, so L8 is the same minmod slope limiter as in MUSCL, with the half-cell deviation compared to full differences of the means.

The TVB constant MM is a choice. M=0M = 0 gives the TVDM minmod limiter, which also clips smooth extrema. Cockburn and Shu relate the right size of MM to the second derivative of the solution at its extrema, so a larger MM is needed for sharper smooth peaks, and a too large MM lets oscillations through. The time step used here is Δtmax⁡∣f′∣/Δx≤0.2\Delta t\max|f'|/\Delta x \le 0.2.

Example

The limiter on three cells. Take k=1k = 1, Δx=0.1\Delta x = 0.1 and means uˉj−1=0\bar u_{j-1} = 0, uˉj=0.5\bar u_j = 0.5, uˉj+1=1.5\bar u_{j+1} = 1.5, with slope coefficient Uj,1=0.6U_{j,1} = 0.6. Then Δ−=0.5\Delta^- = 0.5, Δ+=1\Delta^+ = 1 and both face deviations are 0.60.6.

  • With M=0M = 0: m(0.6,1,0.5)=0.5≠0.6m(0.6, 1, 0.5) = 0.5 \ne 0.6, so the cell is limited to the slope 0.50.5. Its face values become 00 and 11, which lie between the neighbouring means.
  • With M=100M = 100: MΔx2=1≥0.6M\Delta x^2 = 1 \ge 0.6, so m~\tilde m returns 0.60.6 and the cell is kept.
  • At an extremum, with means 0,1,0.50, 1, 0.5 and slope 0.40.4: Δ+=−0.5\Delta^+ = -0.5 and Δ−=1\Delta^- = 1 have different signs, so with M=0M = 0 the slope becomes 00.

Refinement study on smooth data (measurement). Burgers' equation with u0=12+14sin⁡2πxu_0 = \tfrac12 + \tfrac14\sin 2\pi x on [0,1][0, 1] forms a shock at t=2/π≈0.64t = 2/\pi \approx 0.64. At T=0.2T = 0.2 the solution is smooth and the exact value comes from characteristics, u=u0(x−ut)u = u_0(x - ut). L2L^2 errors with Δt=0.2 Δx\Delta t = 0.2\,\Delta x:

MM cells k=1k = 1, MTVB=0M_{\text{TVB}} = 0 k=1k = 1, MTVB=50M_{\text{TVB}} = 50 k=2k = 2, MTVB=0M_{\text{TVB}} = 0 k=2k = 2, MTVB=50M_{\text{TVB}} = 50
10 1.242e-2 4.680e-3 1.254e-2 3.575e-4
20 3.425e-3 1.232e-3 3.447e-3 4.959e-5
40 9.304e-4 3.155e-4 9.145e-4 6.400e-6
80 2.419e-4 7.975e-5 2.410e-4 8.126e-7
pobsp_{\text{obs}} (40 to 80) 1.94 1.98 1.92 2.98

With MTVB=0M_{\text{TVB}} = 0 the P2P^2 method is limited at the two extrema and falls to the accuracy of P1P^1. With MTVB=50M_{\text{TVB}} = 50 it keeps order 3.

A shock and a rarefaction (measurement). The square wave u0=1u_0 = 1 on [0.25,0.75)[0.25, 0.75), 00 elsewhere, at T=0.3T = 0.3, Δt=0.15 Δx\Delta t = 0.15\,\Delta x, MTVB=0M_{\text{TVB}} = 0, L1L^1 error of the cell means:

MM cells k=0k = 0 (Godunov) k=1k = 1 limited k=1k = 1 no limiter max mean, no limiter
25 5.582e-2 1.237e-2 1.277e-2 1.031
50 4.238e-2 1.035e-2 5.950e-3 1.015
100 2.352e-2 4.173e-3 2.472e-3 1.013

With the limiter, the means stay in [0,1][0, 1] and their total variation stays at its initial value 2. Without it, the means overshoot by more than 1% at the shock at every resolution. The unlimited error is smaller here, but its overshoot does not decrease, and for systems such overshoots can make density or pressure negative.

Correctness

The proof is in proofs/correctness.md. It shows that the limiter keeps every cell mean, so the method is conservative, and that after limiting with M=0M = 0 each face deviation is a fraction in [0,1][0, 1] of both neighbouring differences of the means. From this it writes one forward Euler step of the means in Harten's incremental form with nonnegative coefficients and proves that, if λ(L1+L2)≤12\lambda(L_1 + L_2) \le \tfrac12 with λ=Δt/Δx\lambda = \Delta t/\Delta x, the means are TVD and satisfy a maximum principle. Because each SSP stage is a convex combination of such steps followed by the limiter, the full Runge-Kutta step keeps both properties. The TVBM bound for M>0M > 0 and the convergence to a weak solution are cited from Cockburn and Shu (1989).

Proof: RKDG with the minmod limiter is conservative, and its cell means are TVD and bounded under a CFL conditionfull

Setting. The grid is periodic with MM cells of width Δx\Delta x, λ=Δt/Δx\lambda = \Delta t/\Delta x, and uh=∑l=0kUj,lPl(ξ)u_h = \sum_{l=0}^k U_{j,l}P_l(\xi) on cell jj with mean uˉj=Uj,0\bar u_j = U_{j,0}. The flux F^(a,b)\hat F(a, b) is consistent, nondecreasing in aa with Lipschitz constant L1L_1, and nonincreasing in bb with Lipschitz constant L2L_2. Write Δj+1/2=uˉj+1−uˉj\Delta_{j+1/2} = \bar u_{j+1} - \bar u_j, uj+1/2−=uˉj+u~ju^-_{j+1/2} = \bar u_j + \tilde u_j and uj−1/2+=uˉj−u~~ju^+_{j-1/2} = \bar u_j - \tilde{\tilde u}_j, with the deviations of the main page. LIMIT is lines L5 to L8 with the TVB constant MTVB=0M_{\text{TVB}} = 0, so m~=m\tilde m = m.

Lemma 1 (the limiter keeps the means). LIMIT does not change any Uj,0U_{j,0}.

Proof. L7 keeps the cell, and L8 changes only Uj,lU_{j,l} with l≥1l \ge 1. □\square

Lemma 2 (conservation). With or without the limiter, ∑juˉj\sum_j \bar u_j is the same after every stage and every step.

Proof. The l=0l = 0 row of the DG operator is −(F^j+1/2−F^j−1/2)/Δx-(\hat F_{j+1/2} - \hat F_{j-1/2})/\Delta x, which sums to zero over a periodic grid. Each stage in L2 to L4 is a linear combination of UU and of operator values with coefficients that do not depend on jj, so it keeps ∑juˉj\sum_j \bar u_j. By Lemma 1, so does LIMIT. □\square

Lemma 3 (limited deviations). After LIMIT, for every cell jj there are numbers αj,βj,γj,δj∈[0,1]\alpha_j, \beta_j, \gamma_j, \delta_j \in [0, 1] with

u~j=αjΔj+1/2=βjΔj−1/2,u~~j=γjΔj+1/2=δjΔj−1/2,\tilde u_j = \alpha_j\Delta_{j+1/2} = \beta_j\Delta_{j-1/2}, \qquad \tilde{\tilde u}_j = \gamma_j\Delta_{j+1/2} = \delta_j\Delta_{j-1/2},

where a coefficient may be taken as 00 when the difference it multiplies is 00.

Proof. Say dd is admissible for cell jj if d=m(d,Δj+1/2,Δj−1/2)d = m(d, \Delta_{j+1/2}, \Delta_{j-1/2}). Then either d=0d = 0, or dd has the sign of both differences and ∣d∣≤min⁡(∣Δj+1/2∣,∣Δj−1/2∣)|d| \le \min(|\Delta_{j+1/2}|, |\Delta_{j-1/2}|). In both cases dd is a multiple in [0,1][0, 1] of each difference (if a difference is 00, then mm returns 00 and d=0d = 0). If the cell passes L7, both deviations are admissible by the test. If not, L8 makes the cell linear with slope s=m(Uj,1,Δj+1/2,Δj−1/2)s = m(U_{j,1}, \Delta_{j+1/2}, \Delta_{j-1/2}). Then u~j=u~~j=s\tilde u_j = \tilde{\tilde u}_j = s, and ss is admissible because m(s,Δj+1/2,Δj−1/2)=sm(s, \Delta_{j+1/2}, \Delta_{j-1/2}) = s when ss already has the sign and the bound. The means do not change (Lemma 1), so the differences used are those of the limited data. □\square

Lemma 4 (Harten's form). Let uhu_h be limited and let uˉjnew=uˉj−λ(F^j+1/2−F^j−1/2)\bar u^{\text{new}}_j = \bar u_j - \lambda(\hat F_{j+1/2} - \hat F_{j-1/2}) be one forward Euler step of the means. Then

uˉjnew=uˉj+CjΔj+1/2−DjΔj−1/2,0≤Cj≤2λL2,0≤Dj≤2λL1.\bar u^{\text{new}}_j = \bar u_j + C_j\Delta_{j+1/2} - D_j\Delta_{j-1/2}, \qquad 0 \le C_j \le 2\lambda L_2, \quad 0 \le D_j \le 2\lambda L_1.

Proof. Add and subtract F^(uj+1/2−,uj−1/2+)\hat F(u^-_{j+1/2}, u^+_{j-1/2}):

uˉjnew−uˉj=−λ[F^(uj+1/2−,uj+1/2+)−F^(uj+1/2−,uj−1/2+)]−λ[F^(uj+1/2−,uj−1/2+)−F^(uj−1/2−,uj−1/2+)].\bar u^{\text{new}}_j - \bar u_j = -\lambda\big[\hat F(u^-_{j+1/2}, u^+_{j+1/2}) - \hat F(u^-_{j+1/2}, u^+_{j-1/2})\big] - \lambda\big[\hat F(u^-_{j+1/2}, u^+_{j-1/2}) - \hat F(u^-_{j-1/2}, u^+_{j-1/2})\big].

In the first bracket only the second argument changes, by uj+1/2+−uj−1/2+=Δj+1/2−u~~j+1+u~~j=(1−δj+1+γj)Δj+1/2u^+_{j+1/2} - u^+_{j-1/2} = \Delta_{j+1/2} - \tilde{\tilde u}_{j+1} + \tilde{\tilde u}_j = (1 - \delta_{j+1} + \gamma_j)\Delta_{j+1/2}, using Lemma 3 and Δ(j+1)−1/2=Δj+1/2\Delta_{(j+1)-1/2} = \Delta_{j+1/2}. The factor 1−δj+1+γj1 - \delta_{j+1} + \gamma_j lies in [0,2][0, 2]. Because F^\hat F is nonincreasing in bb with constant L2L_2, the first term is CjΔj+1/2C_j\Delta_{j+1/2} with Cj=λθ(1−δj+1+γj)C_j = \lambda\theta(1 - \delta_{j+1} + \gamma_j) for some θ∈[0,L2]\theta \in [0, L_2] (take Cj=0C_j = 0 when the change is 00). So 0≤Cj≤2λL20 \le C_j \le 2\lambda L_2. In the second bracket only the first argument changes, by uj+1/2−−uj−1/2−=Δj−1/2+u~j−u~j−1=(1+βj−αj−1)Δj−1/2u^-_{j+1/2} - u^-_{j-1/2} = \Delta_{j-1/2} + \tilde u_j - \tilde u_{j-1} = (1 + \beta_j - \alpha_{j-1})\Delta_{j-1/2}, with a factor in [0,2][0, 2]. Because F^\hat F is nondecreasing in aa with constant L1L_1, the second term is −DjΔj−1/2-D_j\Delta_{j-1/2} with 0≤Dj≤2λL10 \le D_j \le 2\lambda L_1. □\square

Theorem (TVDM and maximum principle). If λ(L1+L2)≤12\lambda(L_1 + L_2) \le \tfrac12, then one step of RKDG with MTVB=0M_{\text{TVB}} = 0 gives ∑j∣Δj+1/2new∣≤∑j∣Δj+1/2∣\sum_j|\Delta^{\text{new}}_{j+1/2}| \le \sum_j|\Delta_{j+1/2}| and min⁡iuˉi≤uˉjnew≤max⁡iuˉi\min_i \bar u_i \le \bar u^{\text{new}}_j \le \max_i \bar u_i.

Proof. First one forward Euler step of limited data. By Lemma 4, Cj+Dj+1≤2λ(L1+L2)≤1C_j + D_{j+1} \le 2\lambda(L_1 + L_2) \le 1 and Cj+Dj≤1C_j + D_j \le 1. For the maximum principle, uˉjnew=(1−Cj−Dj)uˉj+Cjuˉj+1+Djuˉj−1\bar u^{\text{new}}_j = (1 - C_j - D_j)\bar u_j + C_j\bar u_{j+1} + D_j\bar u_{j-1} is a convex combination. For the total variation,

Δj+1/2new=(1−Cj−Dj+1)Δj+1/2+Cj+1Δj+3/2+DjΔj−1/2.\Delta^{\text{new}}_{j+1/2} = (1 - C_j - D_{j+1})\Delta_{j+1/2} + C_{j+1}\Delta_{j+3/2} + D_j\Delta_{j-1/2}.

All three coefficients are nonnegative. Take absolute values, sum over jj and shift the indices of the last two sums on the periodic grid: the coefficients of each ∣Δj+1/2∣|\Delta_{j+1/2}| add to (1−Cj−Dj+1)+Cj+Dj+1=1(1 - C_j - D_{j+1}) + C_j + D_{j+1} = 1. So the total variation of the means does not grow.

Now the Runge-Kutta step. Stage L2 is a forward Euler step of limited data followed by LIMIT, which keeps the means, so its means satisfy both properties relative to UU. Stage L3 gives means 34uˉ+14wˉ\tfrac34\bar u + \tfrac14\bar w, where wˉ\bar w are the means of a forward Euler step from the limited U1U^1. The total variation is a seminorm, so it is convex: TV(34uˉ+14wˉ)≤34TV(uˉ)+14TV(wˉ)≤TV(uˉ)TV(\tfrac34\bar u + \tfrac14\bar w) \le \tfrac34 TV(\bar u) + \tfrac14 TV(\bar w) \le TV(\bar u). A convex combination of values in [min⁡uˉ,max⁡uˉ][\min\bar u, \max\bar u] also stays in it. Stage L4 is the same with weights 13\tfrac13 and 23\tfrac23. The limiter after each stage keeps the means, so the bounds pass to the next stage. □\square

For Godunov's flux on data in [a,b][a, b], L1,L2≤max⁡[a,b]∣f′∣L_1, L_2 \le \max_{[a,b]}|f'|, so the condition holds when λmax⁡∣f′∣≤14\lambda\max|f'| \le \tfrac14. The tests use λmax⁡∣f′∣=0.15\lambda\max|f'| = 0.15 and check both properties at every step of a shock and rarefaction problem.

What is cited. With MTVB>0M_{\text{TVB}} > 0 the limiter can leave a cell with a deviation of size up to MTVBΔx2M_{\text{TVB}}\Delta x^2, which adds at most O(MTVBΔx)O(M_{\text{TVB}}\Delta x) to the total variation per unit time; this gives the TVBM bound, compactness and convergence of a subsequence to a weak solution (Cockburn and Shu 1989). The order k+1k + 1 for smooth solutions with a large enough MTVBM_{\text{TVB}} is measured on the main page, not proved.

Termination. The loop L1 runs ⌈T/Δt⌉\lceil T/\Delta t\rceil steps with the last one shortened. Each step makes three operator evaluations and three passes of LIMIT, each a fixed number of operations per cell. ■\blacksquare

Complexity

The DG operator costs Θ(M(k+1)2)\Theta(M(k+1)^2) per stage and the limiter Θ(M(k+1))\Theta(M(k+1)), so NN steps cost Θ(NM(k+1)2)\Theta(NM(k+1)^2) with Θ(M(k+1))\Theta(M(k+1)) memory. The stable time step is about Δx/(2k+1)\Delta x/(2k+1) divided by the wave speed, so a fixed final time needs N=Θ(M(2k+1))N = \Theta(M(2k+1)) steps. For systems the limiter works in characteristic variables, which adds a d×dd \times d eigenvector transform per cell for dd equations.

Properties

  • Conservative. The limiter keeps the means, so shocks move at the right speed (theorem).
  • TVDM with M=0M = 0 for one forward Euler step under λ(L1+L2)≤12\lambda(L_1 + L_2) \le \tfrac12, and so for SSP-RK3 under the same condition (theorem). With M>0M > 0 it is TVBM: the total variation of the means is bounded (Cockburn and Shu 1989).
  • Maximum principle in the means under the same condition (theorem).
  • Order k+1k + 1 in smooth regions with a TVB constant large enough for the extrema (measurement). With M=0M = 0 the order drops near smooth extrema.
  • Compact. The limiter uses only the direct neighbours, so the method stays local.

Variants and improvements

  • Limiting in characteristic variables for systems such as the Euler equations (Cockburn and Shu 1998). Limiting the conserved variables componentwise gives more oscillations.
  • Troubled-cell indicators (KXRCF and others), which mark cells first and limit only those.
  • WENO limiters, which rebuild the polynomial in troubled cells from a WENO reconstruction of the neighbouring data and keep high order.
  • Moment limiters for k≥2k \ge 2, which limit the highest modes first and stop when a mode passes.
  • The positivity-preserving limiter of Zhang and Shu, a different limiter that keeps density and pressure positive without destroying high order.
  • Subcell finite volume limiting, which replaces troubled cells by a robust finite volume scheme on subcells.

When to use it

Use RKDG for conservation laws with shocks when you also want high order in smooth regions and a compact stencil on unstructured meshes, as in compressible aerodynamics and astrophysical flows. For problems dominated by strong shocks on Cartesian grids, finite volume WENO schemes are often simpler and more robust. For smooth problems with no shocks, plain DG without a limiter is enough.

Pitfalls

  • Limiting only once per step. The TVD argument needs the limiter after every stage, not only after the full step.
  • Mixing up the deviation scale. The deviations u~\tilde u are half-cell changes and Δ±\Delta^\pm are full-cell differences. Comparing u~\tilde u with Δ±/2\Delta^\pm/2 gives a more dissipative limiter; changing scales by accident changes the method.
  • MM in the wrong units. The threshold is MΔx2M\Delta x^2, not MM. A fixed threshold independent of Δx\Delta x either limits everything or nothing on fine grids.
  • CFL number of the finite volume scheme. The DG time step is several times smaller than the finite volume one.
  • Componentwise limiting of systems. It is cheap but produces oscillations at strong shocks.
  • Limiting does not give positivity. TVD in the means does not keep the pressure of a gas positive near vacuum; that needs a positivity-preserving limiter.

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.

runge_kutta_discontinuous_galerkin.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/runge-kutta-discontinuous-galerkin/. The authors are listed in prov/FE63NV.jsonl.

"""Runge-Kutta discontinuous Galerkin (RKDG) method of Cockburn and Shu, 1D scalar case.

Space: modal DG with Legendre polynomials P_0..P_k on each cell of a periodic grid of M
cells, xi = 2 (x - x_j) / dx, so U[j][0] is the cell average. Face fluxes come from a
monotone numerical flux. Time: three-stage SSP Runge-Kutta (Shu and Osher 1988). After
the initial projection and after every stage the TVB slope limiter of Cockburn and Shu
is applied: the face deviations u(x_{j+1/2}^-) - mean and mean - u(x_{j-1/2}^+) are passed
through the modified minmod function with the differences of the neighbouring means; if
either changes, the cell is replaced by a linear function with a limited slope. The
constant Mtvb (the TVB constant, a choice) switches limiting off where the deviation is at
most Mtvb dx^2; Mtvb = 0 gives the TVDM (minmod) limiter.

Precondition: M >= 3 cells, 0 <= k <= 2, dx > 0, dt > 0, a consistent monotone flux.
Cost: Theta(M (k + 1)^2) per stage, Theta(N M (k + 1)^2) for N steps; memory Theta(M (k + 1)).
"""

import math
from typing import Callable, List, Tuple

Coeffs = List[List[float]]


def legendre(l: int, x: float) -> float:
    """P_l(x) by the three-term recurrence."""
    p0, p1 = 1.0, x
    if l == 0:
        return p0
    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) = sum over m < l with l - m odd of (2m + 1) P_m(x)."""
    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]]:
    """q-point Gauss-Legendre rule on [-1, 1] by Newton's method on P_q."""
    out = []
    for i in range(q):
        x = math.cos(math.pi * (i + 0.75) / (q + 0.5))
        for _ in range(100):
            dp = q * (legendre(q - 1, x) - x * legendre(q, x)) / (1 - x * x)
            step = legendre(q, x) / dp
            x -= step
            if abs(step) < 1e-16:
                break
        dp = q * (legendre(q - 1, x) - x * legendre(q, x)) / (1 - x * x)
        out.append((x, 2.0 / ((1 - x * x) * dp * dp)))
    out.sort()
    return [a for a, _ in out], [b for _, b in out]


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 = 8) -> Coeffs:
    """L2 projection of u0 onto piecewise polynomials of degree k."""
    dx = (xr - xl) / M
    nodes, weights = gauss_legendre(q)
    return [[(2 * l + 1) / 2 * sum(w * u0(xl + (j + 0.5) * dx + s * dx / 2) * legendre(l, s)
                                   for s, w in zip(nodes, weights)) for l in range(k + 1)]
            for j in range(M)]


def dg_operator(U: Coeffs, dx: float, f: Callable, flux: Callable) -> Coeffs:
    """DG right side: dU[j][l]/dt = (2l+1)/dx (int f(u_h) P_l' - F_{j+1/2} + (-1)^l F_{j-1/2})."""
    M, k = len(U), len(U[0]) - 1
    nodes, weights = gauss_legendre(k + 2)
    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 = [flux(sum(U[j]), sum(c if l % 2 == 0 else -c for l, c in enumerate(U[(j + 1) % M])))
         for j in range(M)]
    R = []
    for j in range(M):
        vals = [f(sum(c * p for c, p in zip(U[j], Pq))) for Pq in P]
        R.append([(2 * l + 1) / dx * (sum(a * b for a, b in zip(WD[l], vals)) - F[j]
                                      + (1 if l % 2 == 0 else -1) * F[j - 1])
                  for l in range(k + 1)])
    return R


def minmod(a: float, b: float, c: float) -> float:
    """s min(|a|, |b|, |c|) if a, b, c have the same sign s, else 0."""
    if a > 0 and b > 0 and c > 0:
        return min(a, b, c)
    if a < 0 and b < 0 and c < 0:
        return max(a, b, c)
    return 0.0


def tvb_minmod(a: float, b: float, c: float, Mdx2: float) -> float:
    """Modified minmod: a itself if |a| <= Mtvb dx^2, else minmod(a, b, c)."""
    return a if abs(a) <= Mdx2 else minmod(a, b, c)


def limit(U: Coeffs, dx: float, Mtvb: float) -> Coeffs:
    """TVB slope limiter of Cockburn and Shu applied to every cell (periodic grid)."""
    M, k = len(U), len(U[0]) - 1
    if k == 0:
        return [list(r) for r in U]
    Mdx2 = Mtvb * dx * dx
    out = []
    for j in range(M):
        mean = U[j][0]
        dp = U[(j + 1) % M][0] - mean                         # @line L5
        dm = mean - U[j - 1][0]
        right = sum(U[j]) - mean                              # u(x_{j+1/2}^-) - mean
        left = mean - sum(c if l % 2 == 0 else -c for l, c in enumerate(U[j]))
        r_mod = tvb_minmod(right, dp, dm, Mdx2)               # @line L6
        l_mod = tvb_minmod(left, dp, dm, Mdx2)
        if r_mod == right and l_mod == left:                  # @line L7
            out.append(list(U[j]))
        else:
            slope = tvb_minmod(U[j][1], dp, dm, Mdx2)         # @line L8
            out.append([mean, slope] + [0.0] * (k - 1))
    return out


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


def rkdg_step(U: Coeffs, dx: float, dt: float, f: Callable, flux: Callable, Mtvb: float) -> Coeffs:
    """One SSP-RK3 step with the limiter after each stage."""
    L = lambda V: dg_operator(V, dx, f, flux)
    U1 = limit(_lin(1, U, dt, L(U)), dx, Mtvb)                                 # @line L2
    U2 = limit(_lin(3 / 4, U, 1 / 4, _lin(1, U1, dt, L(U1))), dx, Mtvb)        # @line L3
    return limit(_lin(1 / 3, U, 2 / 3, _lin(1, U2, dt, L(U2))), dx, Mtvb)      # @line L4


def rkdg_solve(U: Coeffs, dx: float, dt: float, T: float, f: Callable, flux: Callable,
               Mtvb: float = 0.0, limiter: bool = True) -> Coeffs:
    """Advance from t = 0 to t = T; the last step is shortened. limiter=False gives plain DG."""
    if not dx > 0 or not dt > 0:
        raise ValueError("dx and dt must be positive")
    big = float("inf")
    U = limit(U, dx, Mtvb) if limiter else [list(r) for r in U]
    t = 0.0
    while t < T - 1e-14:                                                       # @line L1
        h = min(dt, T - t)
        U = rkdg_step(U, dx, h, f, flux, Mtvb if limiter else big)
        t += h
    return U


def means(U: Coeffs) -> List[float]:
    return [r[0] for r in U]


def total_variation(v: List[float]) -> float:
    """Periodic total variation sum |v_{j+1} - v_j|."""
    return sum(abs(v[(j + 1) % len(v)] - v[j]) for j in range(len(v)))
test_runge_kutta_discontinuous_galerkin.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/runge-kutta-discontinuous-galerkin/. The authors are listed in prov/FE63NV.jsonl.

import math
import random

import pytest

from runge_kutta_discontinuous_galerkin import (
    gauss_legendre, godunov_flux_burgers, legendre, limit, means, minmod, project,
    rkdg_solve, total_variation, tvb_minmod,
)

fb = lambda u: u * u / 2
u0 = lambda x: 0.5 + 0.25 * math.sin(2 * math.pi * x)
square = lambda x: 1.0 if 0.25 <= x < 0.75 else 0.0


def burgers_exact_smooth(x, t):
    """Solution of u = u0(x - u t) by Newton's method (valid before the shock time 2/pi)."""
    u = u0(x)
    for _ in range(60):
        g = u - u0(x - u * t)
        dg = 1 + t * 0.5 * math.pi * math.cos(2 * math.pi * (x - u * t))
        u -= g / dg
    return u


def square_exact(x, t):
    """Rarefaction from 0.25 and shock from 0.75 at speed 1/2 (valid for t < 1)."""
    if 0.25 <= x < 0.25 + t:
        return (x - 0.25) / t
    if 0.25 + t <= x < 0.75 + t / 2:
        return 1.0
    return 0.0


def l2_error(U, ex, q=6):
    M = len(U)
    dx = 1.0 / M
    xs, ws = gauss_legendre(q)
    s = 0.0
    for j in range(M):
        for xi, w in zip(xs, ws):
            uh = sum(c * legendre(l, xi) for l, c in enumerate(U[j]))
            s += w * (uh - ex((j + 0.5) * dx + xi * dx / 2)) ** 2 * dx / 2
    return math.sqrt(s)


def godunov_fv_ssprk3(v, dx, dt, T):
    """Independent first-order finite volume Godunov scheme with SSP-RK3 in time."""
    def L(w):
        n = len(w)
        F = [godunov_flux_burgers(w[j], w[(j + 1) % n]) for j in range(n)]
        return [-(F[j] - F[j - 1]) / dx for j in range(n)]
    t = 0.0
    while t < T - 1e-14:
        h = min(dt, T - t)
        a = [x + h * y for x, y in zip(v, L(v))]
        b = [0.75 * x + 0.25 * (y + h * z) for x, y, z in zip(v, a, L(a))]
        v = [x / 3 + 2 / 3 * (y + h * z) for x, y, z in zip(v, b, L(b))]
        t += h
    return v


def test_minmod_and_tvb_minmod():
    assert minmod(1.0, 2.0, 0.5) == 0.5
    assert minmod(-1.0, -2.0, -0.5) == -0.5
    assert minmod(1.0, -2.0, 0.5) == 0.0
    assert tvb_minmod(0.01, -1.0, 1.0, 0.02) == 0.01
    assert tvb_minmod(0.03, -1.0, 1.0, 0.02) == 0.0


def test_limiter_keeps_a_linear_function():
    M, dx = 10, 0.1
    U = [[0.3 + (j + 0.5) * dx, dx / 2, 0.0] for j in range(M)]
    V = limit(U, dx, 0.0)
    for j in range(1, M - 1):                 # the periodic wrap makes a jump at the ends
        assert V[j] == U[j]


def test_limiter_flattens_a_local_extremum_of_the_means():
    U = [[0.0, 0.0], [1.0, 0.4], [0.0, 0.0], [0.0, 0.0]]
    V = limit(U, 0.25, 0.0)
    assert V[1] == [1.0, 0.0]
    V = limit(U, 0.25, 1e3)                   # a large TVB constant leaves it alone
    assert V[1] == [1.0, 0.4]


def test_degree_zero_is_the_godunov_scheme():
    M = 30
    dx = 1.0 / M
    U = project(square, M, 0, 0.0, 1.0, q=20)
    v = godunov_fv_ssprk3(means(U), dx, 0.4 * dx, 0.2)
    W = means(rkdg_solve(U, dx, 0.4 * dx, 0.2, fb, godunov_flux_burgers))
    assert max(abs(a - b) for a, b in zip(v, W)) < 1e-13


@pytest.mark.parametrize("k,p_min", [(1, 1.85), (2, 2.8)])
def test_order_on_smooth_burgers_with_tvb_constant(k, p_min):
    T = 0.2
    errs = []
    for M in (10, 20, 40):
        dx = 1.0 / M
        U = rkdg_solve(project(u0, M, k, 0.0, 1.0), dx, 0.2 * dx, T, fb, godunov_flux_burgers, Mtvb=50.0)
        errs.append(l2_error(U, lambda x: burgers_exact_smooth(x, T)))
    assert math.log2(errs[1] / errs[2]) > p_min, errs


def test_minmod_limiter_clips_smooth_extrema():
    # With Mtvb = 0 the P2 method is limited at the extrema and loses its third order.
    T, errs = 0.2, []
    for M in (20, 40):
        dx = 1.0 / M
        U = rkdg_solve(project(u0, M, 2, 0.0, 1.0), dx, 0.2 * dx, T, fb, godunov_flux_burgers, Mtvb=0.0)
        errs.append(l2_error(U, lambda x: burgers_exact_smooth(x, T)))
    assert math.log2(errs[0] / errs[1]) < 2.2


@pytest.mark.parametrize("k", [1, 2])
def test_limited_means_stay_in_bounds_and_tv_does_not_grow(k):
    M = 50
    dx = 1.0 / M
    U = rkdg_solve(project(square, M, k, 0.0, 1.0, q=20), dx, 0.15 * dx, 0.0, fb, godunov_flux_burgers)
    tv = total_variation(means(U))
    for _ in range(40):
        U = rkdg_solve(U, dx, 0.15 * dx, 0.15 * dx, fb, godunov_flux_burgers)
        m = means(U)
        assert min(m) > -1e-12 and max(m) < 1 + 1e-12
        assert total_variation(m) <= tv + 1e-12
        tv = total_variation(m)


def test_unlimited_dg_overshoots_at_the_shock():
    M = 50
    dx = 1.0 / M
    U = rkdg_solve(project(square, M, 1, 0.0, 1.0, q=20), dx, 0.15 * dx, 0.3, fb,
                   godunov_flux_burgers, limiter=False)
    assert max(means(U)) > 1.005


def test_limited_p1_beats_first_order_godunov_after_the_shock():
    M, T = 100, 0.3
    dx = 1.0 / M
    exm = [sum(square_exact((j + (i + 0.5) / 100) * dx, T) for i in range(100)) / 100 for j in range(M)]
    e = {}
    for k in (0, 1):
        U = rkdg_solve(project(square, M, k, 0.0, 1.0, q=20), dx, 0.15 * dx, T, fb, godunov_flux_burgers)
        e[k] = sum(abs(a - b) for a, b in zip(means(U), exm)) * dx
    assert e[1] < 0.5 * e[0]
    assert e[1] < 1e-2


def test_mass_is_conserved_with_the_limiter():
    rng = random.Random(11)
    M = 24
    dx = 1.0 / M
    U = [[rng.uniform(0, 1), rng.uniform(-0.2, 0.2), rng.uniform(-0.05, 0.05)] for _ in range(M)]
    m0 = sum(means(U)) * dx
    V = rkdg_solve(U, dx, 0.1 * dx, 0.1, fb, godunov_flux_burgers)
    assert abs(sum(means(V)) * dx - m0) < 1e-13


def test_rejects_bad_steps():
    with pytest.raises(ValueError):
        rkdg_solve([[0.0, 0.0]] * 3, 0.1, -1.0, 1.0, fb, godunov_flux_burgers)

History

Cockburn and Shu developed the method in a series of papers from 1989 to 1998, for scalar laws, one-dimensional systems, multidimensional scalar laws and multidimensional systems. They took the DG space discretization of Reed and Hill (1973) and the TVD Runge-Kutta methods of Shu and Osher (1988), and adapted the TVB idea of Shu (1987) to the limiter. Their survey (Cockburn and Shu 2001) is the standard reference. Later work replaced the minmod limiter by WENO and moment limiters and added positivity preservation (Zhang and Shu 2010).

References

  1. Bernardo Cockburn and Chi-Wang Shu, TVB Runge-Kutta local projection discontinuous Galerkin finite element method for conservation laws II: general framework, Mathematics of Computation 52(186) (1989) 411-435, the TVB limiter with the constant M, the TVDM and TVBM properties, convergence for scalar laws
  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 RKDG method for scalar conservation laws in one dimension, the generalized slope limiter, systems and multidimensional problems
  3. Bernardo Cockburn and Chi-Wang Shu, The Runge-Kutta discontinuous Galerkin method for conservation laws V: multidimensional systems, Journal of Computational Physics 141 (1998) 199-224, the limiter for systems in characteristic variables and on general meshes
  4. Chi-Wang Shu and Stanley Osher, Efficient implementation of essentially non-oscillatory shock-capturing schemes, Journal of Computational Physics 77 (1988) 439-471, the three-stage TVD (SSP) Runge-Kutta method
  5. Jan S. Hesthaven and Tim Warburton, Nodal Discontinuous Galerkin Methods, Springer, 2008, Chapter 5 (nonlinear problems, filtering and limiting)

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