Algorithm Search⌘K

Algorithmadvanced

Piecewise parabolic method

Also called Colella-Woodward method.

Reconstructs a monotone parabola in each cell with steepening at contacts, a high order Godunov scheme for gas dynamics.

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
Phillip Colella, Paul R. Woodward, 1984

The piecewise parabolic method (PPM) is a finite volume scheme for hyperbolic conservation laws that gives each cell a parabola instead of the straight line of MUSCL. The parabola has the cell average as its mean and matches face values from a fourth order interpolation. Three simple tests then change the face values so that the parabola is monotone in the cell and stays inside the range of the neighbors. For linear advection, moving the parabolas exactly gives a scheme that is TVD and sharper than MUSCL. For gas dynamics, Colella and Woodward add a steeper reconstruction at contacts and flattening near strong shocks, and the scheme is much used in astrophysics codes.

In plain words

A straight line in each cell cannot follow a curved profile well, so make it a parabola. Pick the values at the cell edges first, by fitting a cubic through four neighbor averages and reading off its value at the edge. Then fit the parabola in each cell with those two edge values and the cell average. If the cell is a local peak or dip, the parabola would overshoot, so make it flat. If the parabola would turn around inside the cell, pull the edge value on the far side toward the average until it no longer turns. What remains moves along with the flow.

The problem

Given cell averages aja_j of ut+f(u)x=0u_t + f(u)_x = 0 on a uniform grid with width hh, find a reconstruction that is accurate for smooth data and creates no new extrema, and use it in a conservative update. The page treats linear advection ut+cux=0u_t + cu_x = 0 with c>0c > 0 in full, and uses the same reconstruction for the Euler equations with U=(ρ,ρu,E)U = (\rho, \rho u, E) and γ=1.4\gamma = 1.4. The values are cell averages, so errors are measured against exact cell averages.

The algorithm

  1. PPM-ADVECTION-STEP(a, ν) ▷ u_t + c u_x = 0, c > 0, ν = cΔt/h ≤ 1
  2. 1add three ghost cells on each side (wrap for periodic, copy for outflow)
  3. 2δa_j <- MC slope: minmod((a_{j+1} - a_{j-1})/2, 2(a_j - a_{j-1}), 2(a_{j+1} - a_j))
  4. 3a_{j+1/2} <- (a_j + a_{j+1})/2 - (δa_{j+1} - δa_j)/6 ▷ 7/12 and -1/12 when no slope is limited
  5. 4for each cell: a_L, a_R <- a_{j-1/2}, a_{j+1/2}, changed by the three monotonicity tests
  6. 5F_{j+1/2} <- a_R - (ν/2)(Δa - (1 - 2ν/3) a_6), Δa = a_R - a_L, a_6 = 6(a_j - (a_L + a_R)/2)
  7. 6a_j <- a_j - ν(F_{j+1/2} - F_{j-1/2})

The parabola in cell jj is P(ξ)=aL+ξ(Δa+a6(1−ξ))P(\xi) = a_L + \xi(\Delta a + a_6(1 - \xi)) for ξ∈[0,1]\xi \in [0, 1], and its mean is aja_j. The three tests of line L4 are:

  1. if aja_j is not strictly between aLa_L and aRa_R, set aL=aR=aja_L = a_R = a_j (flat at extrema);
  2. if the parabola would turn inside the cell near the left edge, set aL=3aj−2aRa_L = 3a_j - 2a_R;
  3. if it would turn near the right edge, set aR=3aj−2aLa_R = 3a_j - 2a_L.

Line L5 is cc times the average of PP over the right part [1−ν,1][1 - \nu, 1] of the cell, which is the amount that crosses the face in one step divided by cΔtc\Delta t. For the Euler equations, the code computes aLa_L and aRa_R for each conserved component with lines L1 to L4, puts the values on the two sides of each face into the HLL flux with Davis speeds, and integrates with SSP RK3 at Courant number 0.5. This is a method of lines form. The original gas dynamics PPM instead traces characteristics through the parabolas to get time averaged face states for an exact Riemann solver, and adds contact steepening and flattening; the code leaves these out.

Example

One step by hand. Take a=(0,0,1,3,4,4)a = (0, 0, 1, 3, 4, 4), outflow boundaries and ν=12\nu = \frac12. The MC slopes are 32\frac32 in cells 3 and 4 and zero elsewhere. Line L3 gives the face values 12−14=14\frac12 - \frac14 = \frac14 between cells 2 and 3, 22 between cells 3 and 4, and 72+14=154\frac72 + \frac14 = \frac{15}4 between cells 4 and 5. In cell 3, aL=14a_L = \frac14, aR=2a_R = 2 and a3=1a_3 = 1; then Δa=74\Delta a = \frac74 and a6=6(1−98)=−34a_6 = 6(1 - \frac98) = -\frac34, so the tests do not apply (∣a6∣≤∣Δa∣|a_6| \le |\Delta a|). The flux out of cell 3 is 2−14(74+23⋅34)=23162 - \frac14(\frac74 + \frac23\cdot\frac34) = \frac{23}{16}, and the new value is 1−12⋅2316=9321 - \frac12\cdot\frac{23}{16} = \frac9{32}. The whole step gives (0,0,932,2,11932,4)(0, 0, \frac9{32}, 2, \frac{119}{32}, 4). The test checks the face values and the step exactly in Fraction arithmetic. MUSCL with MC gives 516=1032\frac5{16} = \frac{10}{32} in cell 3 on the same data.

Smooth advection. For the cell averages of sin⁡(2πx)\sin(2\pi x), ν=0.5\nu = 0.5 and one period, these L1L^1 errors are measurements made with the code on this page.

MM 20 40 80 160
error 0.0189537 0.0039237 0.0007292 0.0001404
order 2.27 2.43 2.38

The orders lie between 2 and 3: the face values are fourth order, but test 1 flattens the parabolas at the crest and the trough. On the same runs, the MUSCL-Hancock code of the MUSCL page with the MC limiter has the errors 0.0228951, 0.0056305, 0.0012618 and 0.0002487, so PPM is better by a factor between 1.2 and 1.8. For a square wave on 100 cells after one period at ν=0.5\nu = 0.5, the L1L^1 error is 0.01941 for PPM and 0.02862 for MUSCL with MC.

Euler equations. For ρ=1+0.2sin⁡(2π(x−t))\rho = 1 + 0.2\sin(2\pi(x - t)), u=1u = 1, p=1p = 1 on a periodic grid to t=0.1t = 0.1, the L1L^1 density errors at M=25,50,100M = 25, 50, 100 are 0.00124528, 0.00030744 and 0.00007047 (orders 2.02 and 2.13). For Sod's tube to t=0.2t = 0.2, the L1L^1 density error is 0.005261 at M=100M = 100 (87 steps) and 0.002812 at M=200M = 200 (175 steps). The MUSCL page reports 0.00462 and 0.00265 for MUSCL-Hancock with the HLLC flux and the van Leer limiter. So this method of lines form, with the HLL flux and without contact steepening, does not do better than MUSCL on Sod's tube; the gain of PPM shows on the advection runs above.

Correctness

The proof is in proofs/correctness.md. Theorem: with the MC slopes, every face value lies between its two neighbor averages. After the three tests each parabola has the cell average as its mean, is monotone, and stays between the smallest and the largest of the three averages around it. The piecewise parabolic function then has exactly the total variation of the averages. For linear advection with 0≤ν≤10 \le \nu \le 1, the step is the exact average of the moved parabolas, so it is conservative, TVD, and makes no new extrema; at ν=1\nu = 1 it is the exact shift.

The order of accuracy is measured, not proved. For the Euler equations no TVD or positivity property is proved here.

Proof: The PPM reconstruction is exact for cubics away from limiting, gives monotone parabolas inside the range of the neighbors, and PPM for linear advection is conservative and TVD for Courant numbers up to 1full

Setting. The cell averages aja_j live on cells of width hh. Lines L2 to L4 of the page compute the slopes

δaj={sgn(Δj+1/2)min⁡(12∣aj+1−aj−1∣,2∣Δj−1/2∣,2∣Δj+1/2∣)if Δj−1/2Δj+1/2>0,0otherwise,\delta a_j = \begin{cases}\mathrm{sgn}(\Delta_{j+1/2})\min\big(\tfrac12|a_{j+1} - a_{j-1}|, 2|\Delta_{j-1/2}|, 2|\Delta_{j+1/2}|\big) & \text{if } \Delta_{j-1/2}\Delta_{j+1/2} > 0,\\ 0 & \text{otherwise,}\end{cases}

with Δj+1/2=aj+1−aj\Delta_{j+1/2} = a_{j+1} - a_j, the face values aj+1/2=12(aj+aj+1)−16(δaj+1−δaj)a_{j+1/2} = \frac12(a_j + a_{j+1}) - \frac16(\delta a_{j+1} - \delta a_j), and then, in each cell, aL=aj−1/2a_L = a_{j-1/2} and aR=aj+1/2a_R = a_{j+1/2} changed by three tests:

  1. if (aR−aj)(aj−aL)≤0(a_R - a_j)(a_j - a_L) \le 0, set aL=aR=aja_L = a_R = a_j;
  2. else if d m>d2/6d\,m > d^2/6, set aL=3aj−2aRa_L = 3a_j - 2a_R;
  3. else if d m<−d2/6d\,m < -d^2/6, set aR=3aj−2aLa_R = 3a_j - 2a_L;

where d=aR−aLd = a_R - a_L and m=aj−12(aL+aR)m = a_j - \frac12(a_L + a_R). The parabola in cell jj, with ξ∈[0,1]\xi \in [0, 1] across the cell, is

Pj(ξ)=aL+ξ(d+a6(1−ξ)),a6=6m.P_j(\xi) = a_L + \xi\big(d + a_6(1 - \xi)\big), \qquad a_6 = 6m.

Lemma 1 (mean and fourth order face values). ∫01Pj=aj\int_0^1 P_j = a_j. If no slope is limited, that is δaj=12(aj+1−aj−1)\delta a_j = \frac12(a_{j+1} - a_{j-1}) for all jj, then aj+1/2=712(aj+aj+1)−112(aj−1+aj+2)a_{j+1/2} = \frac7{12}(a_j + a_{j+1}) - \frac1{12}(a_{j-1} + a_{j+2}), and this is exact when the aja_j are the averages of a cubic.

Proof. ∫01ξ dξ=12\int_0^1 \xi\,d\xi = \frac12 and ∫01ξ(1−ξ) dξ=16\int_0^1 \xi(1 - \xi)\,d\xi = \frac16, so the integral is aL+d2+m=aja_L + \frac d2 + m = a_j. Inserting the central slopes gives the second formula. For the third claim, let VV be the primitive of the cubic, so hak=V(xk+1/2)−V(xk−1/2)h a_k = V(x_{k+1/2}) - V(x_{k-1/2}). The formula is a linear combination of the values of VV at five faces, and its value at the face equals V′(xj+1/2)V'(x_{j+1/2}) for V=1,x,…,x4V = 1, x, \dots, x^4 by direct computation, so it is exact for VV of degree 4. □\square

The test checks the cubic case exactly in Fraction arithmetic on the averages of x3+xx^3 + x, where no slope is limited.

Lemma 2 (face values lie between neighbors). aj+1/2a_{j+1/2} lies between aja_j and aj+1a_{j+1}.

Proof. If Δj+1/2=0\Delta_{j+1/2} = 0, both slopes are 0, because each has a factor Δj+1/2\Delta_{j+1/2} in its sign test, and aj+1/2=aja_{j+1/2} = a_j. Let Δ=Δj+1/2>0\Delta = \Delta_{j+1/2} > 0 (the other sign is the mirror image). Both δaj\delta a_j and δaj+1\delta a_{j+1} are zero or have the sign of Δ\Delta, and both are at most 2Δ2\Delta. So 16(δaj+1−δaj)∈[−13Δ,13Δ]\frac16(\delta a_{j+1} - \delta a_j) \in [-\frac13\Delta, \frac13\Delta] and aj+1/2∈[aj+16Δ,aj+56Δ]a_{j+1/2} \in [a_j + \frac16\Delta, a_j + \frac56\Delta]. □\square

Lemma 3 (the tests give monotone parabolas). After the three tests, PjP_j is monotone on [0,1][0, 1], aja_j lies between aLa_L and aRa_R, and aLa_L and aRa_R lie between the values they had before the tests and aja_j.

Proof. Pj′(ξ)=d+a6(1−2ξ)P'_j(\xi) = d + a_6(1 - 2\xi) is linear, so PjP_j is monotone on [0,1][0, 1] if and only if Pj′(0)=d+a6P'_j(0) = d + a_6 and Pj′(1)=d−a6P'_j(1) = d - a_6 do not have strict opposite signs, which holds when ∣a6∣≤∣d∣|a_6| \le |d|, that is ∣m∣≤∣d∣/6|m| \le |d|/6. Test 1 gives a constant. If test 1 does not apply, aja_j is strictly between aLa_L and aRa_R, so d≠0d \ne 0. If tests 2 and 3 do not apply, ∣d m∣≤d2/6|d\,m| \le d^2/6, so ∣m∣≤∣d∣/6|m| \le |d|/6. In test 2, the new values aL′=3aj−2aRa'_L = 3a_j - 2a_R, d′=3(aR−aj)d' = 3(a_R - a_j) and m′=12(aR−aj)m' = \frac12(a_R - a_j) give d′m′=d′2/6d'm' = d'^2/6, so ∣m′∣=∣d′∣/6|m'| = |d'|/6 and PjP_j is monotone. Also aL′a'_L is on the same side of aja_j as aLa_L, since aj−aL′=2(aR−aj)a_j - a'_L = 2(a_R - a_j) has the sign of aj−aLa_j - a_L, and aL′a'_L lies between aLa_L and aja_j, because d m>d2/6d\,m > d^2/6 is the same as aL′−aLa'_L - a_L having the sign of dd. Test 3 is the mirror image. □\square

Corollary. Every value of PjP_j lies between the smallest and the largest of aj−1,aj,aj+1a_{j-1}, a_j, a_{j+1}. The test test_parabolas_are_monotone_and_bounded checks this at 17 points in every cell for random data.

Lemma 4 (the reconstruction keeps the total variation). On a periodic grid, let pp be the function equal to PjP_j on cell jj. Then TV(p)=∑j∣aj+1−aj∣TV(p) = \sum_j |a_{j+1} - a_j|.

Proof. Write aR,ja_{R,j} and aL,j+1a_{L,j+1} for the values on the two sides of the face j+1/2j + 1/2 after the tests. Suppose aj≤aj+1a_j \le a_{j+1}. By Lemma 2 the face value aj+1/2a_{j+1/2} is in [aj,aj+1][a_j, a_{j+1}]. The tests in cell jj move aR,ja_{R,j} from aj+1/2a_{j+1/2} toward aja_j (Lemma 3, or test 1), and the tests in cell j+1j + 1 move aL,j+1a_{L,j+1} from aj+1/2a_{j+1/2} toward aj+1a_{j+1}. So aj≤aR,j≤aj+1/2≤aL,j+1≤aj+1a_j \le a_{R,j} \le a_{j+1/2} \le a_{L,j+1} \le a_{j+1}. The case aj>aj+1a_j > a_{j+1} is the mirror image. In each cell, PjP_j is monotone from aL,ja_{L,j} to aR,ja_{R,j} and passes through the level aja_j, which lies between them. So the function pp, read from left to right, visits aj,aR,j,aL,j+1,aj+1a_j, a_{R,j}, a_{L,j+1}, a_{j+1} monotonically between every two neighbor averages, and its variation between the levels aja_j and aj+1a_{j+1} is exactly ∣aj+1−aj∣|a_{j+1} - a_j|. Summing over jj gives the claim. □\square

Theorem 1 (PPM for linear advection). For ut+cux=0u_t + cu_x = 0 with c>0c > 0, ν=cΔt/h∈[0,1]\nu = c\Delta t/h \in [0, 1] and line L5, the step of line L6 sets ajn+1a_j^{n+1} to the average over cell jj of pp moved right by νh\nu h. On a periodic grid the step is conservative, TV(an+1)≤TV(an)TV(a^{n+1}) \le TV(a^n), and every new value lies between the smallest and the largest old value. At ν=1\nu = 1 the step is the exact shift ajn+1=aj−1na_j^{n+1} = a_{j-1}^n.

Proof. The value of line L5 is 1ν∫1−ν1Pj\frac1\nu\int_{1-\nu}^1 P_j, by direct integration of the parabola; the test compares it with Simpson's rule, which is exact for parabolas, in Fraction arithmetic. Since ν≤1\nu \le 1, the part of pp that crosses the face j+1/2j + 1/2 in the step comes only from cell jj, so line L6 computes the average over cell jj of the moved function exactly. The fluxes telescope, so the sum is kept. For the total variation, let qq be the moved function. Then

∑j∣aj+1n+1−ajn+1∣=∑j∣1h∫0h(q(xj+1/2+s)−q(xj−1/2+s)) ds∣≤1h∫0h∑j∣q(xj+1/2+s)−q(xj−1/2+s)∣ ds≤TV(q),\sum_j |a^{n+1}_{j+1} - a^{n+1}_j| = \sum_j \Big|\frac1h\int_0^h \big(q(x_{j+1/2} + s) - q(x_{j-1/2} + s)\big)\,ds\Big| \le \frac1h\int_0^h \sum_j |q(x_{j+1/2} + s) - q(x_{j-1/2} + s)|\,ds \le TV(q),

and TV(q)=TV(p)=TV(an)TV(q) = TV(p) = TV(a^n) by Lemma 4. The bounds follow from the Corollary, because each new value is an average of values of pp. At ν=1\nu = 1 the flux is ∫01Pj=aj\int_0^1 P_j = a_j by Lemma 1, so ajn+1=aj−(aj−aj−1)a_j^{n+1} = a_j - (a_j - a_{j-1}). □\square

The tests check Theorem 1 on a square wave at ν=0.3,0.5,0.9,1\nu = 0.3, 0.5, 0.9, 1 and on 100 random data sets, and check conservation exactly in Fraction arithmetic.

What is not proved here. The order of accuracy is measured, not proved: on a sine wave for advection the L1L^1 orders are 2.27, 2.43 and 2.38, above 2 because the face values are fourth order, and below 3 because test 1 flattens the parabolas at extrema. For the Euler equations the page uses the reconstruction in a method of lines with the HLL flux and SSP RK3, without the characteristic tracing, contact steepening and flattening of the full gas dynamics scheme. No TVD or positivity property is proved for that case.

Complexity

Theorem, in the real-RAM model: lines L2 to L6 do a constant amount of work per cell and component, so one step costs O(mM)O(mM) and keeps O(mM)O(mM) numbers. A fixed end time at a fixed Courant number needs K=O(M)K = O(M) steps. Per step PPM costs a small constant factor more than MUSCL, and for the Euler runs here the SSP RK3 time stepper adds three flux evaluations per face and step.

Properties

  • Fourth order face values, flat at extrema. Exact for cubics where no slope is limited; the order on smooth data with extrema is between 2 and 3.
  • TVD for linear advection with ν≤1\nu \le 1, and exact at ν=1\nu = 1. Proved.
  • Conservative. The parabola has the cell average as its mean, and the fluxes telescope.
  • Low numerical diffusion. On the advection runs of the example, PPM has a smaller error than MUSCL with the MC limiter, for both the sine and the square wave.
  • Not positivity preserving for the Euler equations in general.

Variants and improvements

  • Contact steepening and flattening. Colella and Woodward steepen the face values at contacts, detected from the density and pressure, and flatten the parabolas behind strong shocks to reduce oscillations there.
  • Characteristic tracing. For systems, the original scheme averages the parabolas over the domain of dependence of each characteristic family and solves a Riemann problem with the time averaged states.
  • Better treatment of smooth extrema. Later work changes test 1 so that smooth peaks are not flattened, which restores higher order there.
  • Method of lines. The face values of lines L1 to L4 can be used with any Riemann flux and Runge-Kutta method, as the code does for the Euler equations.

When to use it

Use PPM for gas dynamics with strong shocks and contacts where low numerical diffusion matters, for example in astrophysical codes with adaptive mesh refinement. For a simpler code, MUSCL with a good limiter is often enough. For very high order on smooth flows, use WENO.

Pitfalls

  • Unlimited face values. The fourth order interpolation alone overshoots at jumps. Lines L2 and L4 are both needed.
  • Extrema are flattened. Test 1 cuts smooth peaks to a constant, so the max norm error at extrema is first order. This is by design and not a bug.
  • Three ghost cells. The face values need slopes, which need neighbors, so the stencil reaches three cells past each face.
  • Courant number above 1. Line L5 assumes the part that crosses the face comes from one cell only.
  • Calling the method of lines form PPM without saying so. The code's Euler runs use only the reconstruction. Results differ from the full gas dynamics scheme near contacts and strong shocks.

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.

piecewise_parabolic_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/piecewise-parabolic-method/. The authors are listed in prov/4Q3HCS.jsonl.

"""The piecewise parabolic method of Colella and Woodward (1984).

Each cell gets a parabola with the cell average as its mean. The face values come from a fourth
order interpolation with limited slopes, and three tests make the parabola monotone in the cell.
For linear advection, advect_step moves the parabolas exactly over one time step (the PPM scheme
for u_t + c u_x = 0 with c > 0). For the Euler equations, solve_euler uses the PPM face values per
conserved component in a method of lines with the HLL flux and SSP RK3; it leaves out the contact
steepening, flattening and characteristic tracing of the full gas dynamics scheme.
Fraction data stay exact.
"""

from math import sqrt

GAMMA = 1.4


def mc_slope(left, mid, right):
    """The monotonized central slope of Colella and Woodward, in cell units."""
    dl, dr = mid - left, right - mid
    if dl * dr <= 0:
        return 0 * dl
    s = min(abs(dl + dr) / 2, 2 * abs(dl), 2 * abs(dr))
    return s if dl > 0 else -s


def constrain(al, a, ar):
    """The three monotonicity tests: returns the new (aL, aR) for a cell with average a."""
    if (ar - a) * (a - al) <= 0:  # @line L4
        return a, a
    d, m = ar - al, a - (al + ar) / 2
    if d * m > d * d / 6:
        return 3 * a - 2 * ar, ar
    if -d * d / 6 > d * m:
        return al, 3 * a - 2 * al
    return al, ar


def ppm_faces(cells, periodic=False):
    """The constrained face values (aL, aR) of every cell, for scalar data."""
    m = len(cells)
    if periodic:  # @line L1
        ext = list(cells[-3:]) + list(cells) + list(cells[:3])
    else:
        ext = [cells[0]] * 3 + list(cells) + [cells[-1]] * 3
    d = [0 * ext[0]] + [mc_slope(ext[k - 1], ext[k], ext[k + 1]) for k in range(1, len(ext) - 1)]  # @line L2
    face = {k: (ext[k] + ext[k + 1]) / 2 - (d[k + 1] - d[k]) / 6 for k in range(1, len(ext) - 2)}  # @line L3
    out = []
    for j in range(m):
        k = j + 3
        out.append(constrain(face[k - 1], ext[k], face[k]))
    return out


def parabola(al, a, ar, xi):
    """The parabola of a cell at the local coordinate xi in [0, 1]."""
    return al + xi * ((ar - al) + 6 * (a - (al + ar) / 2) * (1 - xi))


def right_flux_average(al, a, ar, nu):
    """The average of the parabola over [1 - nu, 1]: the flux through the right face divided by c."""
    return ar - nu / 2 * ((ar - al) - (1 - 2 * nu / 3) * 6 * (a - (al + ar) / 2))  # @line L5


def advect_step(cells, nu, periodic=True):
    """One PPM step for u_t + c u_x = 0, c > 0, with Courant number 0 <= nu <= 1."""
    pf = ppm_faces(cells, periodic)
    flux = [right_flux_average(al, a, ar, nu) for (al, ar), a in zip(pf, cells)]
    inflow = flux[-1] if periodic else cells[0]
    return [a - nu * (flux[j] - (flux[j - 1] if j > 0 else inflow)) for j, a in enumerate(cells)]  # @line L6


# Euler equations with U = (rho, rho u, E), in a method of lines.


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 hll_flux(ql, qr, g=GAMMA):
    """HLL 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)
    fl, fr = euler_flux(ql, g), euler_flux(qr, g)
    if sl >= 0:
        return fl
    if sr <= 0:
        return fr
    return tuple((sr * a - sl * b + sl * sr * (y - x)) / (sr - sl) for a, b, x, y in zip(fl, fr, ql, qr))


def rate(cells, dx, periodic=False, g=GAMMA):
    m = len(cells)
    comps = [ppm_faces([q[c] for q in cells], periodic) for c in range(3)]
    left = [tuple(comps[c][j][0] for c in range(3)) for j in range(m)]
    right = [tuple(comps[c][j][1] for c in range(3)) for j in range(m)]
    if periodic:
        pairs = [(right[j - 1], left[j]) for j in range(m)] + [(right[-1], left[0])]
    else:
        pairs = [(cells[0], left[0])] + [(right[j - 1], left[j]) for j in range(1, m)] + [(right[-1], cells[-1])]
    h = [hll_flux(a, b, g) for a, b in pairs]
    return [tuple(-(h[j + 1][c] - h[j][c]) / dx for c in range(3)) for j in range(m)]


def solve_euler(cells, dx, t_end, cfl=0.5, periodic=False, g=GAMMA):
    """March to t_end with SSP RK3 and dt = cfl dx / max(|u| + c). Returns (cells, steps)."""
    t, n = 0.0, 0

    def speed(q):
        rho, u, p = cons_to_prim(q, g)
        return abs(u) + sqrt(g * p / rho)

    def comb(a, x, b, y, s, z):
        return tuple(a * xi + b * yi + s * zi for xi, yi, zi in zip(x, y, z))

    while t < t_end - 1e-14:
        dt = min(cfl * dx / max(speed(q) for q in cells), t_end - t)
        L1 = rate(cells, dx, periodic, g)
        u1 = [comb(1.0, c, 0.0, c, dt, d) for c, d in zip(cells, L1)]
        L2 = rate(u1, dx, periodic, g)
        u2 = [comb(0.75, c, 0.25, a, 0.25 * dt, d) for c, a, d in zip(cells, u1, L2)]
        L3 = rate(u2, dx, periodic, g)
        cells = [comb(1.0 / 3.0, c, 2.0 / 3.0, a, 2.0 / 3.0 * dt, d) for c, a, d in zip(cells, u2, L3)]
        t += dt
        n += 1
    return cells, n
test_piecewise_parabolic_method.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/piecewise-parabolic-method/. The authors are listed in prov/4Q3HCS.jsonl.

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

from piecewise_parabolic_method import advect_step, parabola, ppm_faces, prim_to_cons, right_flux_average, solve_euler

SOD = ((1.0, 0.0, 1.0), (0.125, 0.0, 0.1))


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 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, nu=0.5, t=1.0):
    dx = 1.0 / m
    n = round(t / (nu * dx))
    u = averages(m, 0.0)
    for _ in range(n):
        u = advect_step(u, t / (n * dx))
    return sum(abs(a - b) for a, b in zip(u, averages(m, t))) * dx


def tv(u):
    return sum(abs(u[j] - u[j - 1]) for j in range(len(u)))


def test_hand_trace_in_fractions() -> None:
    u = [Fraction(x) for x in (0, 0, 1, 3, 4, 4)]
    q = Fraction
    assert ppm_faces(u) == [(0, 0), (0, 0), (q(1, 4), 2), (2, q(15, 4)), (4, 4), (4, 4)]
    assert advect_step(u, q(1, 2), periodic=False) == [0, 0, q(9, 32), 2, q(119, 32), 4]


def test_face_values_are_exact_for_cubics() -> None:
    # Averages of x^3 + x over [n, n + 1]: the slopes are not limited, so the faces use 7/12 and -1/12.
    prim = lambda x: Fraction(x) ** 4 / 4 + Fraction(x) ** 2 / 2
    v = [prim(n + 1) - prim(n) for n in range(2, 14)]
    pf = ppm_faces(v)
    for j in range(1, 10):
        x = Fraction(j + 3)
        assert pf[j][1] == x ** 3 + x == Fraction(7, 12) * (v[j] + v[j + 1]) - Fraction(1, 12) * (v[j - 1] + v[j + 2])


def test_flux_formula_matches_direct_integration() -> None:
    rng = random.Random(2)
    for _ in range(50):
        al, a, ar = (Fraction(rng.randint(-9, 9), 4) for _ in range(3))
        nu = Fraction(rng.randint(1, 10), 10)
        lo = 1 - nu  # Simpson's rule is exact for parabolas
        simpson = (parabola(al, a, ar, lo) + 4 * parabola(al, a, ar, (lo + 1) / 2) + parabola(al, a, ar, Fraction(1))) / 6
        assert right_flux_average(al, a, ar, nu) == simpson
        assert right_flux_average(al, a, ar, Fraction(1)) == a  # the mean of the parabola is the cell average


def test_parabolas_are_monotone_and_bounded() -> None:
    rng = random.Random(4)
    u = [Fraction(rng.randint(0, 20)) for _ in range(40)]
    pf = ppm_faces(u, periodic=True)
    for j, (al, ar) in enumerate(pf):
        lo, hi = min(u[j - 1], u[j], u[(j + 1) % 40]), max(u[j - 1], u[j], u[(j + 1) % 40])
        vals = [parabola(al, u[j], ar, Fraction(k, 16)) for k in range(17)]
        steps = [vals[k + 1] - vals[k] for k in range(16)]
        assert all(s >= 0 for s in steps) or all(s <= 0 for s in steps)
        assert all(lo <= x <= hi for x in vals)


def test_exact_conservation_in_fractions() -> None:
    rng = random.Random(3)
    u = [Fraction(rng.randint(-8, 8), 4) for _ in range(16)]
    total = sum(u)
    for _ in range(3):
        u = advect_step(u, Fraction(3, 7))
        assert sum(u) == total


def test_courant_one_is_an_exact_shift() -> None:
    rng = random.Random(6)
    u = [Fraction(rng.randint(0, 9)) for _ in range(12)]
    assert advect_step(u, Fraction(1)) == u[-1:] + u[:-1]


def test_tvd_and_no_new_extrema_for_advection() -> None:
    m = 80
    for nu in (0.3, 0.5, 0.9, 1.0):
        u = [1.0 if 20 <= j < 40 else (0.5 if 50 <= j < 55 else 0.0) for j in range(m)]
        t0 = tv(u)
        for _ in range(60):
            u = advect_step(u, nu)
            assert tv(u) <= t0 + 1e-12 and -1e-12 <= min(u) and max(u) <= 1.0 + 1e-12
            t0 = tv(u)
    rng = random.Random(1)
    for _ in range(100):
        u = [rng.random() for _ in range(30)]
        v = advect_step(u, rng.random())
        assert tv(v) <= tv(u) + 1e-12 and min(u) - 1e-12 <= min(v) and max(v) <= max(u) + 1e-12


def test_order_on_smooth_advection() -> None:
    e = [advect(m) for m in (20, 40, 80)]
    assert abs(e[0] - 0.0189537) < 1e-7
    assert all(2.2 < log2(e[i] / e[i + 1]) < 2.5 for i in range(2))  # above 2, below 3: clipped extrema


def test_euler_wave_and_sod() -> 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, 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(1.9 < log2(errs[i] / errs[i + 1]) < 2.3 for i in range(2))
    m, t = 100, 0.2
    cells = [prim_to_cons(SOD[0] if (j + 0.5) / m < 0.5 else SOD[1]) for j in range(m)]
    cells, n = solve_euler(cells, 1.0 / m, t)
    err = sum(abs(q[0] - sum(exact_sod_density(((j + (k + 0.5) / 16) / m - 0.5) / t) for k in range(16)) / 16) for j, q in enumerate(cells)) / m
    assert n == 87 and abs(err - 0.005261) < 5e-5

History

Van Leer's MUSCL (1979) used limited straight lines in each cell. Colella and Woodward (1984) used parabolas, with face values from a fourth order interpolation of the primitive function and three monotonicity tests. For gas dynamics they gave both a Lagrangian scheme with a remap and a direct Eulerian scheme, each with contact steepening and flattening near strong shocks. PPM is used in several astrophysics codes.

References

  1. Phillip Colella and Paul R. Woodward, The piecewise parabolic method (PPM) for gas-dynamical simulations, Journal of Computational Physics 54(1) (1984) 174-201, the interpolation of face values, the monotonicity tests on the parabolas, the scheme for linear advection, and the gas dynamics scheme with contact steepening and flattening; doi:10.1016/0021-9991(84)90143-8
  2. Chi-Wang Shu and Stanley Osher, Efficient implementation of essentially non-oscillatory shock-capturing schemes, Journal of Computational Physics 77(2) (1988) 439-471, the TVD (SSP) Runge-Kutta method of third order used for the Euler runs on this page; doi:10.1016/0021-9991(88)90177-5

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
  • at least three sources
  • a scene preset for the example