Algorithm Search⌘K

Algorithmcore

MUSCL scheme

Also called MUSCL-Hancock scheme.

Reconstructs limited linear slopes in each cell and solves Riemann problems between interface values, second order away from shocks.

Time
O(m M K) worst
Space
O(m M) extra
Where
K = the number of time steps (O(M) for a fixed end time and Courant number); M = the number of cells; m = the number of conserved components
Properties
conservativedeterministicexplicit
Origin
Bram van Leer, Steve Hancock, Peter K. Sweby, 1979

MUSCL (Monotone Upstream-centered Scheme for Conservation Laws) is van Leer's second order extension of Godunov's method. Godunov's method takes the solution in each cell as constant, so it is first order. MUSCL gives each cell a straight line instead, with a slope that a limiter makes smaller near jumps. The values of these lines at the two sides of each face go into a Riemann solver. The result is second order where the solution is smooth and free of oscillations near shocks, which is possible only because the limiter makes the scheme nonlinear (see the Godunov order barrier). This page uses the MUSCL-Hancock form: a half time step predictor inside each cell, then one flux evaluation per face, with forward Euler in time.

In plain words

First order schemes blur everything, because they assume the gas is uniform inside each cell. A better guess is a straight line through the cell average, tilted to match the neighbors. Near a shock, a steep line would overshoot and create a wiggle, so the slope is cut back: if the left and right differences disagree in sign, the slope is zero, and otherwise it is no larger than the limiter allows. Each line gives two edge values per cell. These edge values are pushed forward half a time step, and then each face solves a small Riemann problem between the values on its two sides.

The problem

Given cell averages UjnU_j^n of a hyperbolic conservation law Ut+F(U)x=0U_t + F(U)_x = 0 on a uniform grid with width Δx\Delta x, compute Ujn+1U_j^{n+1} at tn+1=tn+Δtt^{n+1} = t^n + \Delta t with an error of order Δx2\Delta x^2 in smooth regions and without new oscillations at discontinuities. The page uses scalar laws ut+f(u)x=0u_t + f(u)_x = 0 and the Euler equations with U=(ρ,ρu,E)U = (\rho, \rho u, E), E=p/(γ−1)+ρu2/2E = p/(\gamma - 1) + \rho u^2/2, c=γp/ρc = \sqrt{\gamma p/\rho} and γ=1.4\gamma = 1.4. The values are cell averages, so errors are measured against exact cell averages.

The algorithm

  1. MUSCL-HANCOCK-STEP(U, Δt, Δx, LIM, RIEMANN)
  2. 1add two ghost cells on each side (copy for outflow, wrap for periodic)
  3. 2for each cell j: d_j <- LIM(U_j - U_{j-1}, U_{j+1} - U_j) / 2 ▷ half slope, per component
  4. 3U_j^- <- U_j - d_j; U_j^+ <- U_j + d_j
  5. 4Ū_j^± <- U_j^± - (Δt / 2Δx)(F(U_j^+) - F(U_j^-)) ▷ Hancock predictor
  6. 5for each face j+1/2: F_{j+1/2} <- RIEMANN(Ū_j^+, Ū_{j+1}^-)
  7. 6for each cell j: U_j <- U_j - (Δt/Δx)(F_{j+1/2} - F_{j-1/2})

The limiter of line L2 is a choice. The code has three, all zero when ab≤0ab \le 0:

  • minmod: the one of aa, bb with the smaller size. It is the most diffusive.
  • van Leer: 2ab/(a+b)2ab/(a + b), the harmonic mean.
  • MC (monotonized central): minmod(2a,(a+b)/2,2b)\mathrm{minmod}(2a, (a + b)/2, 2b). It is the least diffusive of the three.

For the Euler equations, the code reconstructs the conserved variables componentwise and uses the HLLC flux with the speed estimates of Davis in line L5. The time step is Δt=0.8 Δx/max⁡j(∣uj∣+cj)\Delta t = 0.8\,\Delta x/\max_j(|u_j| + c_j). For scalar laws the code uses the exact Riemann flux: the upwind flux auLa u_L for ut+aux=0u_t + a u_x = 0 with a>0a > 0, and Godunov's flux for Burgers' equation.

Example

One step by hand. Take linear advection with a=1a = 1, Δx=1\Delta x = 1, Δt=12\Delta t = \frac12 (so ν=12\nu = \frac12), outflow boundaries, and u=(0,0,1,3,4,4)u = (0, 0, 1, 3, 4, 4). With minmod, the slopes are (0,0,1,1,0,0)(0, 0, 1, 1, 0, 0): in cell 3 the differences are 11 and 22, and in cell 4 they are 22 and 11. For a>0a > 0 the face flux is auˉj+=uj+1−ν2δja\bar u_j^+ = u_j + \frac{1-\nu}{2}\delta_j, so the fluxes leaving cells 3 to 6 are 54\frac54, 134\frac{13}4, 44 and 44. The update gives

un+1=(0, 0, 1−12⋅54, 3−12(134−54), 4−12(4−134), 4)=(0,0,38,2,298,4).u^{n+1} = \Big(0,\ 0,\ 1 - \tfrac12\cdot\tfrac54,\ 3 - \tfrac12\big(\tfrac{13}4 - \tfrac54\big),\ 4 - \tfrac12\big(4 - \tfrac{13}4\big),\ 4\Big) = \Big(0, 0, \tfrac38, 2, \tfrac{29}8, 4\Big).

With MC the slopes in cells 3 and 4 are 32\frac32 and the result is (0,0,516,2,5916,4)(0, 0, \frac5{16}, 2, \frac{59}{16}, 4): the steeper slopes move less mass out of cell 3. The first order upwind scheme gives (0,0,12,2,72,4)(0, 0, \frac12, 2, \frac72, 4). The sum falls from 12 to 10 because ν⋅4=2\nu \cdot 4 = 2 leaves through the right boundary. The test checks both results exactly in Fraction arithmetic.

Sod's tube. On [0,1][0, 1] with the jump at x=0.5x = 0.5, outflow boundaries and Courant number 0.8, the scheme runs to t=0.2t = 0.2. These L1L^1 errors of the density against exact cell averages are measurements made with the code on this page.

cells MM steps minmod van Leer MC
100 54 0.00585 0.00462 0.00435
200 109 0.00347 0.00265 0.00247
400 219 0.00190 0.00138 0.00126

The first order HLL scheme has the error 0.01505 at M=100M = 100, more than twice the minmod value. Near the shock and the contact the error is O(Δx)O(\Delta x) in L1L^1 for every scheme, so the observed orders here are 0.76 to 0.97, not 2.

A smooth wave. For ρ=1+0.2sin⁡(2π(x−t))\rho = 1 + 0.2\sin(2\pi(x - t)), u=1u = 1 and p=1p = 1 on a periodic grid, the L1L^1 density errors at t=0.1t = 0.1 for M=25,50,100,200M = 25, 50, 100, 200 give these observed orders.

limiter error at M=25M = 25 error at M=200M = 200 orders
minmod 0.0015985 0.0000323 1.85, 1.88, 1.89
van Leer 0.0008917 0.0000127 2.02, 2.06, 2.05
MC 0.0006558 0.0000079 2.22, 1.94, 2.23

The limiter at extrema. For ut+ux=0u_t + u_x = 0 with the cell averages of sin⁡(2πx)\sin(2\pi x), ν=0.8\nu = 0.8 and one period (t=1t = 1), van Leer gives the L1L^1 errors 0.019367, 0.004899, 0.001225 and 0.000294 for M=20,40,80,160M = 20, 40, 80, 160 (orders 1.98, 2.00, 2.06), but the max norm orders are only 1.32, 1.36 and 1.39. The largest errors sit at the crest and the trough, where the limiter sets the slope to zero.

Correctness

The proof is in proofs/correctness.md. Theorem: the scheme is conservative and consistent, so by the Lax-Wendroff theorem bounded L1L^1 limits are weak solutions. For linear advection with the upwind flux, 0≤ν≤10 \le \nu \le 1 and any limiter in Sweby's TVD region (0≤φ(r)≤min⁡(2,2r)0 \le \varphi(r) \le \min(2, 2r)), the update has Harten's incremental form with coefficients in [ν2,ν(2−ν)][\nu^2, \nu(2 - \nu)], so the scheme is TVD and makes no new extrema. With a contact preserving solver such as HLLC, an isolated stationary contact is kept exactly, because all slopes are zero.

The page does not prove TVD for nonlinear laws or positivity for the Euler equations. The tests check TVD for Burgers' equation on one step problem, which is a measurement.

Proof: The MUSCL-Hancock scheme is conservative and consistent, and for linear advection with a TVD limiter it is TVD for Courant numbers up to 1full

Setting. The scheme stores cell averages UjnU_j^n on a uniform grid with width Δx\Delta x, with λ=Δt/Δx\lambda = \Delta t/\Delta x. Lines L2 to L6 of the page compute, in each cell, a slope δj=lim(Uj−Uj−1,Uj+1−Uj)\delta_j = \mathrm{lim}(U_j - U_{j-1}, U_{j+1} - U_j) (componentwise for systems), the boundary values Uj±=Uj±12δjU_j^\pm = U_j \pm \frac12\delta_j, the half step values

Uˉj±=Uj±−λ2(F(Uj+)−F(Uj−)),\bar U_j^\pm = U_j^\pm - \tfrac{\lambda}{2}\big(F(U_j^+) - F(U_j^-)\big),

the face flux Fj+1/2=R(Uˉj+,Uˉj+1−)F_{j+1/2} = \mathcal R(\bar U_j^+, \bar U_{j+1}^-) from a two-point Riemann flux R\mathcal R, and the update Ujn+1=Ujn−λ(Fj+1/2−Fj−1/2)U_j^{n+1} = U_j^n - \lambda(F_{j+1/2} - F_{j-1/2}).

Each limiter is odd and positively homogeneous: lim(sa,sb)=s lim(a,b)\mathrm{lim}(sa, sb) = s\,\mathrm{lim}(a, b) for every real ss. It is 00 when ab≤0ab \le 0. For a≠0a \ne 0 write lim(a,b)=a φ(b/a)\mathrm{lim}(a, b) = a\,\varphi(b/a). The three limiters of the page give

φminmod(r)=max⁡(0,min⁡(1,r)),φvL(r)=r+∣r∣1+∣r∣,φMC(r)=max⁡(0,min⁡(2r,1+r2,2)).\varphi_{\mathrm{minmod}}(r) = \max(0, \min(1, r)), \quad \varphi_{\mathrm{vL}}(r) = \frac{r + |r|}{1 + |r|}, \quad \varphi_{\mathrm{MC}}(r) = \max\big(0, \min(2r, \tfrac{1+r}{2}, 2)\big).

All three satisfy

0≤φ(r)≤min⁡(2,2r) for r>0,φ(r)=0 for r≤0.(S)0 \le \varphi(r) \le \min(2, 2r) \text{ for } r > 0, \qquad \varphi(r) = 0 \text{ for } r \le 0. \tag{S}

This is the TVD region of Sweby (1984). The test test_limiters checks (S) at sample points.

Lemma 1 (conservation and consistency). On a periodic grid, ∑jUjn+1=∑jUjn\sum_j U_j^{n+1} = \sum_j U_j^n. If Uj−2=⋯=Uj+2=UU_{j-2} = \dots = U_{j+2} = U and R(U,U)=F(U)\mathcal R(U, U) = F(U), then Fj±1/2=F(U)F_{j\pm1/2} = F(U) and Ujn+1=UU_j^{n+1} = U.

Proof. The face flux Fj+1/2F_{j+1/2} enters cell jj with the factor −λ-\lambda and cell j+1j+1 with +λ+\lambda, so the sum telescopes to zero. The test checks this exactly in Fraction arithmetic for Burgers' equation with all three limiters. For a constant state all differences are zero, so δ=0\delta = 0, U±=UU^\pm = U, the flux difference in the half step is zero, Uˉ±=U\bar U^\pm = U, and both face fluxes are R(U,U)=F(U)\mathcal R(U, U) = F(U). □\square

So the scheme is conservative, and the Lax-Wendroff theorem applies: if the numerical solutions converge boundedly in Lloc1L^1_{loc} as Δx,Δt→0\Delta x, \Delta t \to 0, the limit is a weak solution.

Lemma 2 (the flux for linear advection). Let F(u)=auF(u) = au with a>0a > 0, R\mathcal R the upwind flux R(uL,uR)=auL\mathcal R(u_L, u_R) = a u_L, and ν=aλ\nu = a\lambda. Then

Fj+1/2=a(uj+1−ν2δj).F_{j+1/2} = a\Big(u_j + \frac{1 - \nu}{2}\delta_j\Big).

Proof. F(uj+)−F(uj−)=aδjF(u_j^+) - F(u_j^-) = a\delta_j, so uˉj+=uj+12δj−ν2δj\bar u_j^+ = u_j + \frac12\delta_j - \frac{\nu}{2}\delta_j. The upwind flux takes the left value. □\square

With δj=0\delta_j = 0 this is the first order upwind scheme. With the unlimited slope δj=12(uj+1−uj−1)\delta_j = \frac12(u_{j+1} - u_{j-1}) it is Fromm's scheme, which is second order for smooth solutions (LeVeque 2002, Chapter 6). The limiter switches between these flux forms by the local ratio of differences, which is the flux limiter form of flux limiter methods.

Lemma 3 (Harten 1983). Suppose ujn+1=uj−Cj−1/2(uj−uj−1)u_j^{n+1} = u_j - C_{j-1/2}(u_j - u_{j-1}) on a periodic grid with 0≤Cj−1/2≤10 \le C_{j-1/2} \le 1 for all jj. Then TV(un+1)≤TV(un)TV(u^{n+1}) \le TV(u^n), where TV(u)=∑j∣uj+1−uj∣TV(u) = \sum_j |u_{j+1} - u_j|.

Proof. Write Δj−1/2=uj−uj−1\Delta_{j-1/2} = u_j - u_{j-1}. Then

uj+1n+1−ujn+1=(1−Cj+1/2)Δj+1/2+Cj−1/2Δj−1/2.u_{j+1}^{n+1} - u_j^{n+1} = (1 - C_{j+1/2})\Delta_{j+1/2} + C_{j-1/2}\Delta_{j-1/2}.

Both coefficients are in [0,1][0, 1]. Take absolute values, sum over jj and shift the index of the second sum:

TV(un+1)≤∑j(1−Cj+1/2)∣Δj+1/2∣+∑jCj+1/2∣Δj+1/2∣=TV(un).□TV(u^{n+1}) \le \sum_j (1 - C_{j+1/2})|\Delta_{j+1/2}| + \sum_j C_{j+1/2}|\Delta_{j+1/2}| = TV(u^n). \quad\square

Theorem 1 (TVD for linear advection). For F(u)=auF(u) = au with a>0a > 0, the upwind flux, any limiter that satisfies (S), and 0≤ν≤10 \le \nu \le 1, the scheme is TVD and creates no new extrema: min⁡kukn≤ujn+1≤max⁡kukn\min_k u_k^n \le u_j^{n+1} \le \max_k u_k^n.

Proof. By Lemma 2,

ujn+1=uj−ν(Δj−1/2+1−ν2(δj−δj−1)).u_j^{n+1} = u_j - \nu\Big(\Delta_{j-1/2} + \frac{1 - \nu}{2}(\delta_j - \delta_{j-1})\Big).

If Δj−1/2≠0\Delta_{j-1/2} \ne 0, write δj=φ(rj)Δj−1/2\delta_j = \varphi(r_j)\Delta_{j-1/2} with rj=Δj+1/2/Δj−1/2r_j = \Delta_{j+1/2}/\Delta_{j-1/2}, because δj=lim(Δj−1/2,Δj+1/2)\delta_j = \mathrm{lim}(\Delta_{j-1/2}, \Delta_{j+1/2}). Also δj−1=lim(Δj−3/2,Δj−1/2)=ψjΔj−1/2\delta_{j-1} = \mathrm{lim}(\Delta_{j-3/2}, \Delta_{j-1/2}) = \psi_j\Delta_{j-1/2} with ψj=φ(rj−1)/rj−1\psi_j = \varphi(r_{j-1})/r_{j-1} when rj−1>0r_{j-1} > 0, and ψj=0\psi_j = 0 when δj−1=0\delta_{j-1} = 0. By (S), 0≤φ(rj)≤20 \le \varphi(r_j) \le 2 and 0≤ψj≤20 \le \psi_j \le 2. So

ujn+1=uj−Cj−1/2Δj−1/2,Cj−1/2=ν(1+1−ν2(φ(rj)−ψj)).u_j^{n+1} = u_j - C_{j-1/2}\Delta_{j-1/2}, \qquad C_{j-1/2} = \nu\Big(1 + \frac{1 - \nu}{2}\big(\varphi(r_j) - \psi_j\big)\Big).

The bracket lies in [1−(1−ν),1+(1−ν)]=[ν,2−ν][1 - (1 - \nu), 1 + (1 - \nu)] = [\nu, 2 - \nu], so ν2≤Cj−1/2≤ν(2−ν)≤1\nu^2 \le C_{j-1/2} \le \nu(2 - \nu) \le 1. If Δj−1/2=0\Delta_{j-1/2} = 0, then δj−1=0\delta_{j-1} = 0 and δj=0\delta_j = 0 by the definition of the limiter, so ujn+1=uju_j^{n+1} = u_j and any Cj−1/2∈[0,1]C_{j-1/2} \in [0, 1] works. Lemma 3 gives TVD. For the extrema, ujn+1=(1−Cj−1/2)uj+Cj−1/2uj−1u_j^{n+1} = (1 - C_{j-1/2})u_j + C_{j-1/2}u_{j-1} is a convex combination of two old values. □\square

For a<0a < 0 the same proof works with the mirror image. The test test_tvd_and_no_new_extrema_for_advection checks Theorem 1 for the three limiters at ν=0.3\nu = 0.3, 0.90.9 and 11.

Theorem 2 (a stationary contact is kept). For the Euler equations with a Riemann flux R\mathcal R that keeps an isolated stationary contact exactly (HLLC does, by the result on the HLLC page), let the data be (ρL,0,p)(\rho_L, 0, p) for j<kj < k and (ρR,0,p)(\rho_R, 0, p) for j≥kj \ge k. Then Un+1=UnU^{n+1} = U^n.

Proof. Every component of UU is piecewise constant with one jump, between cells k−1k - 1 and kk. In each cell at least one of the two one-sided differences is zero, so every slope is zero. Then Uˉj±=Uj\bar U_j^\pm = U_j and the face fluxes are R(Uj,Uj+1)\mathcal R(U_j, U_{j+1}). The faces away from k−1/2k - 1/2 see equal states and give F(Uj)=(0,p,0)F(U_j) = (0, p, 0). At the contact face the flux of a contact preserving solver is also (0,p,0)(0, p, 0). So every flux difference is zero. □\square

What is not proved here. For Burgers' equation and for the Euler equations, the page does not prove TVD or positivity. The test checks the TVD property for Burgers' equation on one step problem, which is a measurement. Second order accuracy away from extrema is a classical result for the unlimited scheme (Fromm's scheme for linear advection); with a limiter, the order at smooth extrema drops, because (S) sets the slope to zero in a cell where the two differences have opposite signs. The test measures it: about 2 in L1L^1 and between 1.1 and 1.6 in the max norm on a sine wave.

Complexity

Theorem, in the real-RAM model: one step costs O(mM)O(mM) operations: mm limiter calls per cell, two physical flux evaluations per cell for the predictor, and one Riemann flux per face. The memory is O(mM)O(mM). A fixed end time at a fixed Courant number needs K=O(M)K = O(M) steps, so the total is O(mM2)O(mM^2). A step costs about three times a first order step with the same solver, but on Sod's problem MUSCL with 100 cells is more accurate than HLL with 400 cells (0.00585 against 0.00629).

Properties

  • Second order in smooth monotone regions. The measured L1L^1 order on smooth data is about 2. At smooth extrema the limiter clips the slope, so the max norm order is between 1.3 and 1.5 in the advection test.
  • TVD for linear advection. Proved for ν≤1\nu \le 1 with the three limiters (see Correctness). The test checks this at ν=0.3\nu = 0.3, 0.90.9 and 11.
  • Conservative. Exact in rational arithmetic; the test checks it in Fraction for Burgers' equation.
  • Keeps a stationary contact. With HLLC, as proved. With HLL or Rusanov in line L5 the contact would smear.
  • Not positivity preserving in general. The predictor of line L4 can make the density or pressure negative near vacuum. A positivity limiter or a smaller time step is needed there.

Variants and improvements

  • Primitive or characteristic variables. Reconstructing (ρ,u,p)(\rho, u, p), or the characteristic variables L(Uj)UL(U_j)U, gives fewer small oscillations for the Euler equations than the componentwise conserved reconstruction used here (Toro 2009, Chapter 14).
  • Method of lines. Skip the predictor, use the reconstructed values directly in the method of lines, and integrate with a second order SSP Runge-Kutta method. With the Rusanov flux this is close to the Kurganov-Tadmor scheme.
  • Higher order reconstruction. The piecewise parabolic method uses parabolas, and ENO and WENO use adaptive stencils.
  • Other limiters. Superbee sits on the upper edge of Sweby's region and steepens contacts; it can square smooth waves.

When to use it

Use MUSCL-Hancock as the default second order finite volume scheme for gas dynamics and other systems with shocks, when the code already has a Riemann solver. It needs only one flux evaluation per face per step and two ghost cells. For smooth flows with fine structure, use a higher order method such as WENO; for flows near vacuum, add a positivity limiter.

Pitfalls

  • Limiting the wrong variables. Componentwise limiting of conserved variables can give small oscillations behind strong shocks in systems. Limit primitive or characteristic variables when they matter.
  • Too few ghost cells. The slope in the first and last cell needs a second ghost cell on each side. One ghost cell silently gives a first order or wrong boundary.
  • Limiter choice as a tuning knob. Minmod, van Leer and MC differ by a factor of about 1.3 in the Sod errors above. The choice is a rule of thumb, not a result; MC and superbee steepen contacts but can flatten smooth peaks.
  • Measuring order on a solution with extrema. In the max norm the order drops to between 1 and 2, which can be mistaken for a bug.
  • Courant number. The TVD proof needs ν≤1\nu \le 1 for linear advection. The code uses 0.8 for the Euler equations, which the tests show to work; it is not a proven bound.

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.

muscl_scheme.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/muscl-scheme/. The authors are listed in prov/7J4C0V.jsonl.

"""MUSCL-Hancock scheme (van Leer 1979; Toro 2009, Chapter 14) for scalar laws and the 1D Euler equations.

Each cell gets a limited linear slope. The two boundary values of the cell are moved by half a time
step with the flux difference across the cell, and a Riemann solver gives the face flux from the
values on the two sides of the face. The reconstruction is done on the conserved variables.
"""

from math import sqrt

GAMMA = 1.4


def minmod(a, b):
    if a * b <= 0:
        return 0 * a
    return a if abs(a) < abs(b) else b


def van_leer(a, b):
    if a * b <= 0:
        return 0 * a
    return 2 * a * b / (a + b)


def mc(a, b):
    """The monotonized central limiter: minmod(2a, (a + b) / 2, 2b)."""
    if a * b <= 0:
        return 0 * a
    c = (a + b) / 2
    s = 1 if a > 0 else -1
    return s * min(2 * abs(a), abs(c), 2 * abs(b))


LIMITERS = {"minmod": minmod, "vanleer": van_leer, "mc": mc}


def _pad(cells, periodic):
    if periodic:
        return [cells[-2], cells[-1]] + list(cells) + [cells[0], cells[1]]
    return [cells[0], cells[0]] + list(cells) + [cells[-1], cells[-1]]


def _comb(x, y, s):
    """x + s y for numbers or tuples."""
    if isinstance(x, tuple):
        return tuple(a + s * b for a, b in zip(x, y))
    return x + s * y


def _diff(x, y):
    return _comb(x, y, -1)


def _slope(left, mid, right, lim):
    if isinstance(mid, tuple):
        return tuple(lim(m - l, r - m) for l, m, r in zip(left, mid, right))
    return lim(mid - left, right - mid)


def step(cells, dt, dx, flux, riemann, limiter="minmod", periodic=False):
    """One MUSCL-Hancock step. flux(U) is the physical flux, riemann(UL, UR) the face flux."""
    lim = LIMITERS[limiter]
    ext = _pad(cells, periodic)  # @line L1
    half = dt / (2 * dx)
    lo, hi = [], []
    for k in range(1, len(ext) - 1):
        d = _halve(_slope(ext[k - 1], ext[k], ext[k + 1], lim))  # @line L2
        um, up = _comb(ext[k], d, -1), _comb(ext[k], d, 1)  # @line L3
        df = _diff(flux(up), flux(um))
        lo.append(_comb(um, df, -half))  # @line L4
        hi.append(_comb(up, df, -half))
    faces = [riemann(hi[k], lo[k + 1]) for k in range(len(cells) + 1)]  # @line L5
    lam = dt / dx
    return [_comb(cells[j], _diff(faces[j + 1], faces[j]), -lam) for j in range(len(cells))]  # @line L6


def _halve(d):
    """Half of a slope; exact for Fraction data."""
    if isinstance(d, tuple):
        return tuple(x / 2 for x in d)
    return d / 2


# Scalar laws.


def upwind_flux(a):
    """The exact Riemann flux of u_t + a u_x = 0."""
    return lambda ul, ur: a * ul if a >= 0 else a * ur


def burgers_godunov(ul, ur):
    """The exact Riemann (Godunov) flux of Burgers' equation u_t + (u^2 / 2)_x = 0."""
    if ul <= ur:
        if ul > 0:
            return ul * ul / 2
        if ur < 0:
            return ur * ur / 2
        return 0 * ul
    return max(ul * ul, ur * ur) / 2


# Euler equations with U = (rho, rho u, E).


def prim_to_cons(w, g=GAMMA):
    rho, u, p = w
    return (rho, rho * u, p / (g - 1.0) + 0.5 * rho * u * u)


def cons_to_prim(q, g=GAMMA):
    rho, m, e = q
    u = m / rho
    return (rho, u, (g - 1.0) * (e - 0.5 * m * u))


def euler_flux(q, g=GAMMA):
    rho, m, e = q
    u = m / rho
    p = (g - 1.0) * (e - 0.5 * m * u)
    return (m, m * u + p, u * (e + p))


def hllc_flux(ql, qr, g=GAMMA):
    """HLLC flux (Toro, Spruce and Speares 1994) with the speed estimates of Davis."""
    rl, ul, pl = cons_to_prim(ql, g)
    rr, ur, pr = cons_to_prim(qr, g)
    cl, cr = sqrt(g * pl / rl), sqrt(g * pr / rr)
    sl, sr = min(ul - cl, ur - cr), max(ul + cl, ur + cr)
    if sl >= 0.0:
        return euler_flux(ql, g)
    if sr <= 0.0:
        return euler_flux(qr, g)
    ss = (pr - pl + rl * ul * (sl - ul) - rr * ur * (sr - ur)) / (rl * (sl - ul) - rr * (sr - ur))
    q, s, rho, u, p = (ql, sl, rl, ul, pl) if ss >= 0.0 else (qr, sr, rr, ur, pr)
    k = rho * (s - u) / (s - ss)
    star = (k, k * ss, k * (q[2] / rho + (ss - u) * (ss + p / (rho * (s - u)))))
    f = euler_flux(q, g)
    return tuple(a + s * (b - c) for a, b, c in zip(f, star, q))


def max_speed(cells, g=GAMMA):
    smax = 0.0
    for q in cells:
        rho, u, p = cons_to_prim(q, g)
        smax = max(smax, abs(u) + sqrt(g * p / rho))
    return smax


def solve_euler(cells, dx, t_end, cfl=0.8, limiter="minmod", periodic=False, g=GAMMA):
    """March to t_end with dt = cfl dx / max(|u| + c). Returns (cells, number of steps)."""
    t, n = 0.0, 0
    flux, riemann = (lambda q: euler_flux(q, g)), (lambda a, b: hllc_flux(a, b, g))
    while t < t_end - 1e-14:
        dt = min(cfl * dx / max_speed(cells, g), t_end - t)
        cells = step(cells, dt, dx, flux, riemann, limiter, periodic)
        t += dt
        n += 1
    return cells, n
test_muscl_scheme.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/muscl-scheme/. The authors are listed in prov/7J4C0V.jsonl.

import random
from fractions import Fraction
from math import cos, log2, pi, sqrt

from muscl_scheme import (
    burgers_godunov,
    cons_to_prim,
    euler_flux,
    hllc_flux,
    mc,
    minmod,
    prim_to_cons,
    solve_euler,
    step,
    upwind_flux,
    van_leer,
)

SOD = ((1.0, 0.0, 1.0), (0.125, 0.0, 0.1))
LIMS = ("minmod", "vanleer", "mc")


def exact_sod_density(xi, g=1.4):
    """Reference: the exact Sod density at xi = x / t, from the star state found by bisection."""
    (rl, ul, pl), (rr, ur, pr) = SOD
    cl, cr = sqrt(g * pl / rl), sqrt(g * pr / rr)
    z = (g - 1.0) / (2.0 * g)

    def fl(p):  # rarefaction to the left
        return 2.0 * cl / (g - 1.0) * ((p / pl) ** z - 1.0)

    def fr(p):  # shock to the right
        return (p - pr) * sqrt(2.0 / ((g + 1.0) * rr) / (p + (g - 1.0) / (g + 1.0) * pr))

    lo, hi = pr, pl
    for _ in range(100):
        mid = 0.5 * (lo + hi)
        lo, hi = (lo, mid) if fl(mid) + fr(mid) > 0.0 else (mid, hi)
    ps = 0.5 * (lo + hi)
    us = 0.5 * (fr(ps) - fl(ps))
    r = ps / pr
    rs_r = rr * (r + (g - 1.0) / (g + 1.0)) / ((g - 1.0) / (g + 1.0) * r + 1.0)
    shock = ur + cr * sqrt((g + 1.0) / (2.0 * g) * r + z)
    cs = cl * (ps / pl) ** z
    if xi <= -cl:
        return rl
    if xi <= us - cs:
        return rl * (2.0 / (g + 1.0) + (g - 1.0) / ((g + 1.0) * cl) * (-xi)) ** (2.0 / (g - 1.0))
    if xi <= us:
        return rl * (ps / pl) ** (1.0 / g)
    return rs_r if xi <= shock else rr


def sod_l1(m, limiter, t=0.2):
    cells = [prim_to_cons(SOD[0] if (j + 0.5) / m < 0.5 else SOD[1]) for j in range(m)]
    cells, _ = solve_euler(cells, 1.0 / m, t, limiter=limiter)
    err = 0.0
    for j, q in enumerate(cells):
        ex = sum(exact_sod_density(((j + (k + 0.5) / 16) / m - 0.5) / t) for k in range(16)) / 16
        err += abs(q[0] - ex) / m
    return err


def averages(m, t):
    """Exact cell averages of sin(2 pi (x - t)) on [0, 1]."""
    dx = 1.0 / m
    return [(cos(2 * pi * (j * dx - t)) - cos(2 * pi * ((j + 1) * dx - t))) / (2 * pi * dx) for j in range(m)]


def advect(m, limiter, t=1.0, nu=0.8):
    dx = 1.0 / m
    n = round(t / (nu * dx))
    u = averages(m, 0.0)
    for _ in range(n):
        u = step(u, t / n, dx, lambda v: v, upwind_flux(1.0), limiter, periodic=True)
    e = [a - b for a, b in zip(u, averages(m, t))]
    return sum(abs(x) for x in e) * dx, max(abs(x) for x in e)


def test_limiters() -> None:
    assert minmod(1.0, 2.0) == 1.0 and minmod(-3.0, -2.0) == -2.0 and minmod(1.0, -1.0) == 0.0
    assert van_leer(1.0, 3.0) == 1.5 and van_leer(2.0, 0.0) == 0.0
    assert mc(1.0, 3.0) == 2.0 and abs(mc(1.0, 1.2) - 1.1) < 1e-15 and mc(-1.0, -3.0) == -2.0 and mc(1.0, -2.0) == 0.0
    for lim in (minmod, van_leer, mc):
        for r in (0.1, 0.5, 1.0, 2.0, 7.0):
            phi = lim(1.0, r)
            assert 0.0 <= phi <= min(2.0, 2.0 * r) + 1e-15  # the TVD region used in the proof
        assert lim(1.0, 1.0) == 1.0


def test_hand_trace_in_fractions() -> None:
    u = [Fraction(x) for x in (0, 0, 1, 3, 4, 4)]
    half = Fraction(1, 2)
    new = step(u, half, Fraction(1), lambda v: v, upwind_flux(1), "minmod")
    assert new == [0, 0, Fraction(3, 8), 2, Fraction(29, 8), 4]
    new = step(u, half, Fraction(1), lambda v: v, upwind_flux(1), "mc")
    assert new == [0, 0, Fraction(5, 16), 2, Fraction(59, 16), 4]


def test_constant_state_and_consistency() -> None:
    q = prim_to_cons((0.7, 0.3, 0.9))
    assert all(abs(a - b) < 1e-14 for a, b in zip(hllc_flux(q, q), euler_flux(q)))
    cells, _ = solve_euler([q] * 20, 0.05, 0.1)
    assert all(abs(a - b) < 1e-13 for c in cells for a, b in zip(c, q))


def test_exact_conservation_for_burgers_in_fractions() -> None:
    rng = random.Random(3)
    u = [Fraction(rng.randint(-8, 8), 4) for _ in range(12)]
    total = sum(u)
    for lim in LIMS:
        v = u
        for _ in range(4):
            v = step(v, Fraction(1, 10), Fraction(1, 2), lambda x: x * x / 2, burgers_godunov, lim, periodic=True)
            assert sum(v) == total


def test_tvd_and_no_new_extrema_for_advection() -> None:
    m = 60
    for lim in LIMS:
        for nu in (0.3, 0.9, 1.0):
            u = [1.0 if 10 <= j < 25 else (0.5 if 35 <= j < 40 else 0.0) for j in range(m)]
            tv0 = sum(abs(u[j] - u[j - 1]) for j in range(m))
            for _ in range(40):
                u = step(u, nu, 1.0, lambda v: v, upwind_flux(1.0), lim, periodic=True)
                tv = sum(abs(u[j] - u[j - 1]) for j in range(m))
                assert tv <= tv0 + 1e-12 and -1e-12 <= min(u) and max(u) <= 1.0 + 1e-12
                tv0 = tv


def test_tvd_for_burgers() -> None:
    m, dx = 80, 1.0 / 80
    u = [1.0 if 0.2 < (j + 0.5) * dx < 0.5 else -0.5 for j in range(m)]
    tv0 = sum(abs(u[j + 1] - u[j]) for j in range(m - 1))
    for _ in range(60):
        dt = 0.8 * dx / max(abs(v) for v in u)
        u = step(u, dt, dx, lambda x: x * x / 2, burgers_godunov, "minmod")
        tv = sum(abs(u[j + 1] - u[j]) for j in range(m - 1))
        assert tv <= tv0 + 1e-12 and -0.5 - 1e-12 <= min(u) and max(u) <= 1.0 + 1e-12
        tv0 = tv


def test_second_order_in_l1_and_clipping_in_max_norm() -> None:
    errs = [advect(m, "vanleer") for m in (20, 40, 80)]
    p1 = [log2(errs[i][0] / errs[i + 1][0]) for i in range(2)]
    pinf = [log2(errs[i][1] / errs[i + 1][1]) for i in range(2)]
    assert all(abs(p - 2.0) < 0.2 for p in p1)
    assert all(1.1 < p < 1.6 for p in pinf)  # the limiter clips the extrema
    assert abs(errs[0][0] - 0.019367) < 1e-6


def test_second_order_on_a_smooth_euler_wave() -> None:
    t, errs = 0.1, []
    for m in (25, 50, 100):
        dx = 1.0 / m
        cells = [prim_to_cons((1.0 + 0.2 * r, 1.0, 1.0)) for r in averages(m, 0.0)]
        cells, _ = solve_euler(cells, dx, t, limiter="vanleer", periodic=True)
        errs.append(sum(abs(q[0] - 1.0 - 0.2 * e) for q, e in zip(cells, averages(m, t))) * dx)
    assert all(abs(log2(errs[i] / errs[i + 1]) - 2.0) < 0.2 for i in range(2))


def test_sod_l1_error() -> None:
    e100, e200 = sod_l1(100, "minmod"), sod_l1(200, "minmod")
    assert abs(e100 - 0.00585) < 5e-5 and abs(e200 - 0.00347) < 5e-5
    assert sod_l1(100, "mc") < e100


def test_stationary_contact_is_kept_exactly() -> None:
    m = 40
    cells = [prim_to_cons((1.0 if j < m // 2 else 0.5, 0.0, 1.0)) for j in range(m)]
    for lim in LIMS:
        out, _ = solve_euler(cells, 1.0 / m, 0.1, limiter=lim)
        w = [cons_to_prim(q) for q in out]
        assert all(abs(a[0] - b[0]) < 1e-13 and abs(a[1]) < 1e-13 and abs(a[2] - 1.0) < 1e-13 for a, b in zip(w, map(cons_to_prim, cells)))

History

Van Leer developed MUSCL in a series of papers titled "Towards the ultimate conservative difference scheme" in the 1970s. The fifth paper (1979) applied limited piecewise linear reconstruction to Godunov's method for gas dynamics, with a Lagrangian step and a remap. Hancock's predictor, reported by van Leer in the 1980s and described in Toro's book, gives the simple Eulerian form used here. Harten (1983) defined TVD schemes and gave the incremental form lemma, and Sweby (1984) mapped out the region of limiters that give TVD schemes. Colella and Woodward (1984) extended the idea to parabolas with the piecewise parabolic method.

References

  1. Bram van Leer, Towards the ultimate conservative difference scheme. V. A second-order sequel to Godunov's method, Journal of Computational Physics 32(1) (1979) 101-136, the piecewise linear reconstruction of cell averages with limited slopes and the second order Godunov type scheme; doi:10.1016/0021-9991(79)90145-1
  2. P. K. Sweby, High resolution schemes using flux limiters for hyperbolic conservation laws, SIAM Journal on Numerical Analysis 21(5) (1984) 995-1011, the TVD region of flux limiters for linear advection; doi:10.1137/0721062
  3. Ami Harten, High resolution schemes for hyperbolic conservation laws, Journal of Computational Physics 49 (1983) 357-393, the incremental form and the lemma on TVD coefficients; doi:10.1016/0021-9991(83)90136-5
  4. Eleuterio F. Toro, Riemann Solvers and Numerical Methods for Fluid Dynamics, third edition, Springer, 2009, Chapter 13 (high order and TVD methods for scalar equations, slope limiters) and Chapter 14 (the MUSCL-Hancock method for nonlinear systems)
  5. Randall J. LeVeque, Finite Volume Methods for Hyperbolic Problems, Cambridge University Press, 2002, Chapter 6 (high resolution methods, slope and flux limiters, TVD) and Chapter 10 (other approaches to high resolution)

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