Algorithm Search⌘K

Algorithmadvanced

ENO schemes

Also called essentially non-oscillatory schemes.

Builds a high order reconstruction from the stencil with the smoothest data, chosen by divided differences, so that shocks cause almost no oscillations.

Time
O(r^3 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; r = the order of the reconstruction
Properties
conservativedeterministicexplicit
Origin
Ami Harten, Bjorn Engquist, Stanley Osher, Sukumar R. Chakravarthy, Chi Wang Shu, 1987

ENO (essentially non-oscillatory) schemes reach any order rr on smooth solutions of hyperbolic conservation laws and still capture shocks without large oscillations. A fixed stencil of rr cells cannot do this: near a shock its polynomial overshoots, and by the Godunov order barrier no linear scheme above first order avoids new extrema. ENO makes the stencil depend on the data. In each cell it grows a stencil of rr cells one cell at a time, always toward the side where the divided differences are smaller, so the stencil stays on the smooth side of a jump. The reconstructed face values then go into a two-point flux, and a strong stability preserving Runge-Kutta method advances the cell averages.

In plain words

To guess the values at the edges of a cell from the cell averages, fit a polynomial through a few neighbor cells. If the neighbors include a shock, the fit wiggles. So pick the neighbors with care. Start with the cell itself. Then try adding one more cell on the left or on the right, and keep the choice where the data look smoother, measured by how large the differences are. Repeat until there are rr cells. Next to a shock, the stencil leans away from the shock. Far from shocks, any choice is accurate.

The problem

Given cell averages viv_i on a uniform grid with width hh, compute the values vi+1/2−v^-_{i+1/2} and vi−1/2+v^+_{i-1/2} at the two faces of each cell with error O(hr)O(h^r) where the data are smooth, without oscillations at isolated jumps. Use them in a conservative scheme for Ut+F(U)x=0U_t + F(U)_x = 0. The page uses scalar laws and 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. ENO-RATE(v, h, F, SPEED, r)
  2. 1add r ghost cells on each side (copy for outflow, wrap for periodic)
  3. 2for each cell i: s <- i ▷ the stencil is {s, ..., s+l-1}
  4. 3for l = 1 to r-1: if |Δ^l v_{s-1}| < |Δ^l v_s| then s <- s-1 ▷ add the smoother side
  5. 4v^-_{i+1/2}, v^+_{i-1/2} <- derivative at the two faces of cell i of the Newton interpolant of the primitive on the faces of {s, ..., s+r-1}
  6. 5for each face: H_{i+1/2} <- (F(v^-) + F(v^+))/2 - (a/2)(v^+ - v^-), a = max(SPEED(v^-), SPEED(v^+))
  7. 6return L_i = -(H_{i+1/2} - H_{i-1/2}) / h
  8. 7advance dv/dt = L(v) with the SSP RK3 of Shu and Osher

Δlva\Delta^l v_a is the ll-th undivided difference of the averages over the cells a,…,a+la, \dots, a + l, which is a multiple of a divided difference of the primitive function V(x)=∫xuV(x) = \int^x u. The primitive is known exactly at the faces from sums of averages, and its derivative is the point value of uu. So line L4 is an exact linear map from rr averages to a face value, with weights that depend only on rr and the shift k=i−sk = i - s. For r=3r = 3 the right face weights are (13,56,−16)(\frac13, \frac56, -\frac16), (−16,56,13)(-\frac16, \frac56, \frac13) and (13,−76,116)(\frac13, -\frac76, \frac{11}6) for k=0,1,2k = 0, 1, 2. The code computes the weights once, in Fraction. Line L5 is the Rusanov flux. For systems the code reconstructs each conserved component separately. The time step is Δt=0.5 h/max⁡i(∣ui∣+ci)\Delta t = 0.5\,h/\max_i(|u_i| + c_i).

Example

One reconstruction by hand. Take r=3r = 3, outflow boundaries and v=(0,0,1,3,4,4)v = (0, 0, 1, 3, 4, 4). In cell 3 (value 1), the first differences are 11 on the left and 22 on the right, so the left cell joins: {2,3}\{2, 3\}. The second differences are 1−2⋅0+0=11 - 2\cdot 0 + 0 = 1 over {1,2,3}\{1, 2, 3\} and 3−2⋅1+0=13 - 2\cdot 1 + 0 = 1 over {2,3,4}\{2, 3, 4\}. The test is strict, so the right cell joins and the stencil is {2,3,4}\{2, 3, 4\} with k=1k = 1. The face values are

v3+1/2−=−16⋅0+56⋅1+13⋅3=116,v3−1/2+=13⋅0+56⋅1−16⋅3=13.v^-_{3+1/2} = -\tfrac16\cdot 0 + \tfrac56\cdot 1 + \tfrac13\cdot 3 = \tfrac{11}6, \qquad v^+_{3-1/2} = \tfrac13\cdot 0 + \tfrac56\cdot 1 - \tfrac16\cdot 3 = \tfrac13.

In cell 4 the stencil is {4,5,6}\{4, 5, 6\} and the face values are 136\frac{13}6 and 113\frac{11}3. Over all cells, from the left ghost cell, the right face values are (0,0,0,116,113,4,4,4)(0, 0, 0, \frac{11}6, \frac{11}3, 4, 4, 4) and the left face values are (0,0,0,13,136,4,4,4)(0, 0, 0, \frac13, \frac{13}6, 4, 4, 4). The test checks both lists exactly in Fraction arithmetic. The values at the face between cells 3 and 4 differ (116\frac{11}6 and 136\frac{13}6), and the Rusanov flux handles the jump.

Smooth advection. For ut+ux=0u_t + u_x = 0 with the cell averages of sin⁡(2πx)\sin(2\pi x), Courant number 0.5 and one period, these L1L^1 errors are measurements made with the code on this page.

rr M=20M = 20 M=40M = 40 M=80M = 80 orders
1 0.3989069 0.2477481 0.1391560 0.69, 0.83
2 0.1020351 0.0452852 0.0133387 1.17, 1.76
3 0.0107088 0.0013658 0.0001714 2.97, 2.99

For r=2r = 2 the stencil choice acts like the minmod limiter at the extrema, so the order approaches 2 slowly. For the Euler wave ρ=1+0.2sin⁡(2π(x−t))\rho = 1 + 0.2\sin(2\pi(x - t)), u=1u = 1, p=1p = 1 to t=0.1t = 0.1, r=3r = 3 gives the errors 0.00022819, 0.0000289 and 0.00000362 at M=25,50,100M = 25, 50, 100 (orders 2.98 and 3.00).

Sod's tube. On [0,1][0, 1] with the jump at x=0.5x = 0.5 and outflow boundaries, to t=0.2t = 0.2, the L1L^1 density errors are:

cells MM steps r=1r = 1 r=2r = 2 r=3r = 3
100 82 to 87 0.025915 0.009678 0.007662
200 170 to 174 0.018100 0.005508 0.004379

With r=1r = 1 the scheme is the first order Rusanov scheme. The central flux of line L5 smears the contact, so these errors are larger than those of MUSCL-Hancock with HLLC (0.00585 at M=100M = 100).

Correctness

The proof is in proofs/correctness.md. Theorem: for every stencil the rule can choose, the face values are exact for polynomials of degree r−1r - 1, so for smooth data the error is O(hr)O(h^r), and the stencil choice does not affect the order. For piecewise constant data with jumps at least rr cells apart, every chosen stencil lies inside one constant piece, so the face values have no overshoot. The scheme is conservative and consistent, so by the Lax-Wendroff theorem bounded L1L^1 limits are weak solutions.

ENO is not TVD, and no bound on the growth of the total variation is proved here. On a square wave with r=3r = 3, the test measures a new maximum 2.6×10−52.6 \times 10^{-5} above the old one after 80 steps.

Proof: ENO reconstruction is exact for polynomials of degree r - 1, has error O(dx^r) for smooth data, and keeps stencils away from isolated jumps; the scheme is conservativefull

Setting. The cell averages viv_i live on cells [xi−1/2,xi+1/2][x_{i-1/2}, x_{i+1/2}] of width hh. Lines L2 and L3 of the page choose, for each cell ii, a stencil of rr consecutive cells {s,s+1,…,s+r−1}\{s, s+1, \dots, s+r-1\} that contains ii. They start with {i}\{i\} and, r−1r - 1 times, add one cell on the left or on the right of the current stencil {s,…,s+l−1}\{s, \dots, s+l-1\}. The left cell is added if

∣Δlvs−1∣<∣Δlvs∣,Δlva=∑n=0l(−1)l−n(ln)va+n,|\Delta^l v_{s-1}| < |\Delta^l v_s|, \qquad \Delta^l v_a = \sum_{n=0}^{l} (-1)^{l-n}\binom{l}{n} v_{a+n},

and the right cell otherwise. Here Δlva\Delta^l v_a is the ll-th undivided difference over the cells a,…,a+la, \dots, a + l. Line L4 sets k=i−sk = i - s and computes the face values

vi+1/2−=∑n=0r−1wr,k,nR vs+n,vi−1/2+=∑n=0r−1wr,k,nL vs+n,v^-_{i+1/2} = \sum_{n=0}^{r-1} w^R_{r,k,n}\,v_{s+n}, \qquad v^+_{i-1/2} = \sum_{n=0}^{r-1} w^L_{r,k,n}\,v_{s+n},

where the weights come from the Newton form described in Lemma 1. Since Δlva\Delta^l v_a is (l+1)! hl(l+1)!\,h^l times the divided difference of order l+1l + 1 of the primitive function on the l+2l + 2 faces xa−1/2,…,xa+l+1/2x_{a-1/2}, \dots, x_{a+l+1/2}, the rule compares divided differences of the primitive, as in Harten, Engquist, Osher and Chakravarthy (1987).

Lemma 1 (exact for polynomials). If vnv_n are the averages of a polynomial pp of degree at most r−1r - 1, then the face values are p(xi+1/2)p(x_{i+1/2}) and p(xi−1/2)p(x_{i-1/2}) for every stencil.

Proof. Let V(x)=∫xs−1/2xpV(x) = \int_{x_{s-1/2}}^{x} p, a polynomial of degree at most rr. At the r+1r + 1 faces of the stencil, V(xs+m−1/2)=h∑n<mvs+nV(x_{s+m-1/2}) = h\sum_{n<m} v_{s+n}, so these values are known from the averages. The interpolating polynomial of degree at most rr through r+1r + 1 points is unique, so the Newton interpolant of these values is VV itself, and its derivative at a face is V′=pV' = p there. The code computes the derivative of the Newton interpolant on unit spaced nodes, with h=1h = 1, for each unit vector v=env = e_n; by linearity this gives the weights, and they do not depend on hh because the face value of a constant is the constant and the map commutes with scaling of xx. □\square

The test compares the weights for r≤4r \le 4 with a direct fit of a polynomial to the cell averages by Gaussian elimination in Fraction arithmetic, and checks Lemma 1 on random polynomials of degree r−1r - 1 for r=2,3,4r = 2, 3, 4.

Theorem 1 (order r). If uu has rr bounded derivatives near xi+1/2x_{i+1/2} and vnv_n are its cell averages, then ∣vi+1/2−−u(xi+1/2)∣≤Chr|v^-_{i+1/2} - u(x_{i+1/2})| \le C h^r, with CC depending only on rr and max⁡∣u(r)∣\max|u^{(r)}|, for every stencil the rule can choose.

Proof. Let pp be the Taylor polynomial of uu of degree r−1r - 1 at xi+1/2x_{i+1/2}, and e=u−pe = u - p, so ∣e(x)∣≤max⁡∣u(r)∣ ∣x−xi+1/2∣r/r!|e(x)| \le \max|u^{(r)}|\,|x - x_{i+1/2}|^r/r!. Every stencil cell lies within rhrh of the face, so every average of ee over a stencil cell is at most max⁡∣u(r)∣(rh)r/r!\max|u^{(r)}|(rh)^r/r! in size. The face value is linear in the averages, so by Lemma 1 it equals p(xi+1/2)=u(xi+1/2)p(x_{i+1/2}) = u(x_{i+1/2}) plus the weighted sum of the averages of ee. There are finitely many weight vectors (one for each kk), so ∑n∣wr,k,n∣\sum_n |w_{r,k,n}| is bounded by a constant that depends only on rr. □\square

So the choice of stencil does not affect the order; it only decides which of the rr candidates of order rr is used.

Lemma 2 (stencils avoid isolated jumps). Let the data be piecewise constant, with any two jumps at least rr cells apart. Then every chosen stencil lies inside one constant piece, and every face value equals the cell average of its cell.

Proof. By induction on ll, the stencil {s,…,s+l−1}\{s, \dots, s+l-1\} after l−1l - 1 choices is constant with value aa. For l=1l = 1 this is clear. The left candidate {s−1,…,s+l−1}\{s-1, \dots, s+l-1\} is constant, so Δl=0\Delta^l = 0, unless cell s−1s - 1 has another value bb. Then all but the first of its l+1l + 1 values are aa, and Δlvs−1=(−1)l(b−a)≠0\Delta^l v_{s-1} = (-1)^l(b - a) \ne 0. In the same way, the right candidate has Δl=0\Delta^l = 0 or Δl=b′−a≠0\Delta^l = b' - a \ne 0. Both candidates cannot cross a jump, because then two jumps would have only the l≤r−1l \le r - 1 cells of the stencil between them. If the left candidate crosses a jump, its difference is nonzero and the right one is zero, so the strict test adds the right cell. If the right one crosses, the left difference is zero and strictly smaller, so the left cell is added. If neither crosses, either choice is constant. So the final stencil is constant. The weights add up to 1 by Lemma 1 with p=1p = 1, so both face values are aa. □\square

The test test_stencils_avoid_jumps checks Lemma 2 for r=2,3,4r = 2, 3, 4 exactly. A fixed centered stencil would put a jump inside the stencil and give overshoots at the faces.

Lemma 3 (conservation and consistency). With the Rusanov face flux Hi+1/2=12(f(v−)+f(v+))−a2(v+−v−)H_{i+1/2} = \frac12(f(v^-) + f(v^+)) - \frac{a}{2}(v^+ - v^-) and the rate Li=−(Hi+1/2−Hi−1/2)/hL_i = -(H_{i+1/2} - H_{i-1/2})/h, on a periodic grid ∑iLi=0\sum_i L_i = 0, so the SSP RK3 step keeps ∑ivi\sum_i v_i. For constant data H=f(v)H = f(v).

Proof. The sum telescopes. Each SSP RK3 stage adds multiples of ΔtL(⋅)\Delta t L(\cdot) to convex combinations of earlier stages. For constant data the face values are the constant by Lemma 1, and the diffusion term is zero. □\square

The test checks Lemma 3 exactly in Fraction arithmetic for Burgers' equation with r=1,2,3r = 1, 2, 3.

What is not proved here. ENO schemes are not TVD. The test on a square wave with r=3r = 3 measures a new maximum of about 2.6×10−52.6 \times 10^{-5} above the old one. No bound on the growth of the total variation is proved here. The order of the full scheme is measured: with SSP RK3 and Courant number 0.5, the L1L^1 orders for r=3r = 3 are 2.97 and 2.99 on smooth advection and 2.98 and 3.00 on a smooth Euler wave. Positivity for the Euler equations is not proved.

Complexity

Theorem, in the real-RAM model: the stencil choice in one cell computes r−1r - 1 pairs of undivided differences, and the code computes the ll-th one from scratch in O(l2)O(l^2) operations, so a cell costs O(r3)O(r^3) per component. Keeping a table of all differences once per step lowers this to O(r2)O(r^2) and the face values cost O(r)O(r). One rate evaluation is O(r3mM)O(r^3 mM) in the code, and SSP RK3 uses three. A fixed end time at a fixed Courant number needs K=O(M)K = O(M) steps. The weights are computed once for each pair (r,k)(r, k), at a cost that does not depend on MM.

Properties

  • Order rr on smooth solutions. Proved for the reconstruction; measured for the scheme with r=3r = 3.
  • Almost no oscillations. Exactly none for isolated jumps in piecewise constant data, as proved; small overshoots of order 10−510^{-5} in the square wave test.
  • Conservative. Exact in rational arithmetic; the test checks it in Fraction for Burgers' equation.
  • Not TVD. The total variation can grow by a small amount.
  • Nonsmooth in the data. The stencil choice switches discretely, so the scheme is not a differentiable function of the averages, and in smooth regions small changes in the data can switch stencils.

Variants and improvements

  • WENO. Instead of one stencil, take a convex combination of all rr candidates with weights that depend on smoothness. In smooth regions this gives order 2r−12r - 1, and the result is a smooth function of the data.
  • Finite difference ENO on fluxes. Shu and Osher (1988, 1989) reconstruct the flux values at points instead of averages, which is cheaper in several dimensions.
  • Characteristic decomposition. For systems, reconstructing in characteristic variables gives cleaner shocks than the componentwise reconstruction used here.
  • Upwind fluxes. Replacing the Rusanov flux of line L5 with an upwind Riemann solver such as HLLC sharpens contacts.

When to use it

Use ENO with r=3r = 3 when smooth parts of the flow need third order accuracy and shocks must stay clean, and the cost of a wider stencil is acceptable. In most new codes WENO has replaced ENO, because it is more accurate for the same stencil and smooth in the data. ENO is still a clear way to learn adaptive stencils, and it is the base of WENO.

Pitfalls

  • Ties in the test. With a strict comparison the stencil leans to the right when the two differences are equal. Both choices are valid, but the code and the hand trace must agree.
  • Too few ghost cells. Order rr needs rr ghost cells on each side, because the stencil of a boundary face can reach r−1r - 1 cells past the end of the grid.
  • Time stepping of low order. Forward Euler limits the scheme to first order in time. Use SSP RK3 for r=3r = 3.
  • Stencil switching on smooth data. Near zeros of the derivatives of uu, small changes in the data switch the stencil. Near extrema the choice also cuts the slope, like a limiter, which is why r=2r = 2 shows the orders 1.17 and 1.76 in the table above.

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.

eno_scheme.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eno-scheme/. The authors are listed in prov/Z4ZSZ2.jsonl.

"""Finite volume ENO reconstruction of order r (Harten, Engquist, Osher and Chakravarthy 1987)
with the Rusanov flux and the SSP RK3 of Shu and Osher (1988).

In each cell the stencil of r cells grows one cell at a time, to the side where the undivided
difference of the cell averages is smaller in size. The face values are the derivatives of the
Newton interpolant of the primitive function on the r + 1 faces of the stencil. States are numbers
(scalar laws) or tuples (systems, reconstructed componentwise). Fraction data stay exact.
"""

from fractions import Fraction
from functools import lru_cache
from math import sqrt

GAMMA = 1.4


def newton_derivative(values, x):
    """P'(x), where P interpolates values[m] at the nodes m = 0, 1, ..., in Newton form."""
    c = list(values)
    n = len(c)
    for lev in range(1, n):  # divided differences on unit spaced nodes
        for i in range(n - 1, lev - 1, -1):
            c[i] = (c[i] - c[i - 1]) / lev
    total = 0
    for k in range(1, n):  # d/dx of prod_{q<k} (x - q)
        for s in range(k):
            p = c[k]
            for q in range(k):
                if q != s:
                    p *= x - q
            total += p
    return total


@lru_cache(maxsize=None)
def face_weights(r, k):
    """Weights for the stencil of cells i - k, ..., i - k + r - 1: the value at the right face of
    cell i is sum(wr[n] v[i - k + n]) and at the left face sum(wl[n] v[i - k + n])."""
    wr, wl = [], []
    for n in range(r):
        prim = [Fraction(1 if m > n else 0) for m in range(r + 1)]  # primitive of the unit vector e_n
        wr.append(newton_derivative(prim, Fraction(k + 1)))
        wl.append(newton_derivative(prim, Fraction(k)))
    return tuple(wr), tuple(wl)


def _undivided(v, a, l):
    """The l-th undivided difference of v over the cells a, ..., a + l."""
    d = v[a:a + l + 1]
    for _ in range(l):
        d = [d[i + 1] - d[i] for i in range(len(d) - 1)]
    return d[0]


def eno_faces(v, r):
    """For a list v with r ghost cells on each side, return (minus, plus) for the cells r - 1, ...,
    len(v) - r: the reconstructed values at the right face and at the left face of each cell."""
    exact = isinstance(v[0], Fraction) or isinstance(v[0], int)
    minus, plus = [], []
    for i in range(r - 1, len(v) - r + 1):
        left = i  # @line L2
        for l in range(1, r):
            if abs(_undivided(v, left - 1, l)) < abs(_undivided(v, left, l)):  # @line L3
                left -= 1
        wr, wl = face_weights(r, i - left)  # @line L4
        if not exact:
            wr, wl = [float(w) for w in wr], [float(w) for w in wl]
        cells = v[left:left + r]
        minus.append(sum(w * c for w, c in zip(wr, cells)))
        plus.append(sum(w * c for w, c in zip(wl, cells)))
    return minus, plus


def _comp(x, i):
    return x[i] if isinstance(x, tuple) else x


def rate(cells, dx, flux, speed, r=3, periodic=False):
    """dU_j/dt = -(H_{j+1/2} - H_{j-1/2}) / dx with ENO face values and the Rusanov flux."""
    m = len(cells)
    if periodic:  # @line L1
        ext = list(cells[-r:]) + list(cells) + list(cells[:r])
    else:
        ext = [cells[0]] * r + list(cells) + [cells[-1]] * r
    system = isinstance(cells[0], tuple)
    if system:
        parts = [eno_faces([q[c] for q in ext], r) for c in range(len(cells[0]))]
        minus = [tuple(p[0][j] for p in parts) for j in range(m + 2)]
        plus = [tuple(p[1][j] for p in parts) for j in range(m + 2)]
    else:
        minus, plus = eno_faces(ext, r)
    h = []
    for j in range(m + 1):  # face between list entries j and j + 1, that is cells j - 1 and j
        ul, ur = minus[j], plus[j + 1]
        a = max(speed(ul), speed(ur))
        fl, fr = flux(ul), flux(ur)
        if system:
            h.append(tuple((fl[c] + fr[c] - a * (ur[c] - ul[c])) / 2 for c in range(len(ul))))  # @line L5
        else:
            h.append((fl + fr - a * (ur - ul)) / 2)
    if system:
        return [tuple(-(h[j + 1][c] - h[j][c]) / dx for c in range(len(h[0]))) for j in range(m)]  # @line L6
    return [-(h[j + 1] - h[j]) / dx for j in range(m)]


def _axpy(*terms):
    x0 = terms[0][1]
    if isinstance(x0, tuple):
        return tuple(sum(c * x[i] for c, x in terms) for i in range(len(x0)))
    return sum(c * x for c, x in terms)


def step(cells, dt, dx, flux, speed, r=3, periodic=False):
    """One step of the SSP RK3 of Shu and Osher."""
    L = lambda v: rate(v, dx, flux, speed, r, periodic)
    u1 = [_axpy((1, c), (dt, d)) for c, d in zip(cells, L(cells))]  # @line L7
    q = Fraction(1, 4) if isinstance(dt, Fraction) else 0.25
    u2 = [_axpy((1 - q, c), (q, a), (q * dt, d)) for c, a, d in zip(cells, u1, L(u1))]
    t = Fraction(2, 3) if isinstance(dt, Fraction) else 2.0 / 3.0
    return [_axpy((1 - t, c), (t, a), (t * dt, d)) for c, a, d in zip(cells, u2, L(u2))]


# 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 euler_speed(q, g=GAMMA):
    rho, u, p = cons_to_prim(q, g)
    return abs(u) + sqrt(g * p / rho)


def solve_euler(cells, dx, t_end, r=3, cfl=0.5, 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, speed = (lambda q: euler_flux(q, g)), (lambda q: euler_speed(q, g))
    while t < t_end - 1e-14:
        dt = min(cfl * dx / max(speed(q) for q in cells), t_end - t)
        cells = step(cells, dt, dx, flux, speed, r, periodic)
        t += dt
        n += 1
    return cells, n
test_eno_scheme.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eno-scheme/. The authors are listed in prov/Z4ZSZ2.jsonl.

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

from eno_scheme import eno_faces, face_weights, prim_to_cons, solve_euler, step

SOD = ((1.0, 0.0, 1.0), (0.125, 0.0, 0.1))
IDENT, ONE = (lambda v: v), (lambda v: 1.0)


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, r, 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, r=r)
    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, r, 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 = step(u, t / n, dx, IDENT, ONE, r, True)
    e = [a - b for a, b in zip(u, averages(m, t))]
    return sum(abs(x) for x in e) * dx


def brute_weights(r, x):
    """Reference: fit the polynomial of degree r - 1 whose averages over the unit cells [n, n + 1]
    are the unit vectors, by Gaussian elimination in Fraction, and evaluate it at x."""
    out = []
    for target in range(r):
        a = [[Fraction((n + 1) ** (p + 1) - n ** (p + 1), p + 1) for p in range(r)] + [Fraction(int(n == target))] for n in range(r)]
        for c in range(r):
            piv = next(i for i in range(c, r) if a[i][c] != 0)
            a[c], a[piv] = a[piv], a[c]
            for i in range(r):
                if i != c:
                    f = a[i][c] / a[c][c]
                    a[i] = [x1 - f * x2 for x1, x2 in zip(a[i], a[c])]
        coef = [a[p][r] / a[p][p] for p in range(r)]
        out.append(sum(cf * Fraction(x) ** p for p, cf in enumerate(coef)))
    return tuple(out)


def test_weights_match_a_brute_force_fit() -> None:
    for r in (1, 2, 3, 4):
        for k in range(r):
            wr, wl = face_weights(r, k)
            assert wr == brute_weights(r, k + 1) and wl == brute_weights(r, k)
            assert sum(wr) == 1 and sum(wl) == 1
    assert face_weights(3, 1)[0] == (Fraction(-1, 6), Fraction(5, 6), Fraction(1, 3))


def test_polynomials_are_reconstructed_exactly() -> None:
    rng = random.Random(7)
    for r in (2, 3, 4):
        coef = [Fraction(rng.randint(-5, 5)) for _ in range(r)]
        prim = lambda x: sum(c * Fraction(x) ** (p + 1) / (p + 1) for p, c in enumerate(coef))
        poly = lambda x: sum(c * Fraction(x) ** p for p, c in enumerate(coef))
        v = [prim(n + 1) - prim(n) for n in range(-r, 12 + r)]  # averages over [n, n + 1]
        minus, plus = eno_faces(v, r)
        assert minus == [poly(n + 1) for n in range(-1, 13)] and plus == [poly(n) for n in range(-1, 13)]


def test_hand_trace_in_fractions() -> None:
    u = [Fraction(x) for x in (0, 0, 1, 3, 4, 4)]
    minus, plus = eno_faces([u[0]] * 3 + u + [u[-1]] * 3, 3)
    assert minus == [0, 0, 0, Fraction(11, 6), Fraction(11, 3), 4, 4, 4]
    assert plus == [0, 0, 0, Fraction(1, 3), Fraction(13, 6), 4, 4, 4]


def test_stencils_avoid_jumps() -> None:
    # Piecewise constant data with jumps at least r cells apart: every face value is the cell value.
    for r in (2, 3, 4):
        u = [Fraction(x) for x in [0] * 6 + [5] * r + [2] * 6 + [-1] * r + [3] * 6]
        v = [u[0]] * r + u + [u[-1]] * r
        minus, plus = eno_faces(v, r)
        assert minus == plus == v[r - 1:len(v) - r + 1]


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


def test_constant_state() -> None:
    q = prim_to_cons((0.7, 0.3, 0.9))
    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_order_r_on_smooth_advection() -> None:
    e1 = [advect(m, 1) for m in (20, 40)]
    e3 = [advect(m, 3) for m in (20, 40, 80)]
    assert abs(log2(e1[0] / e1[1]) - 0.69) < 0.02  # first order, still far from the asymptote
    assert all(abs(log2(e3[i] / e3[i + 1]) - 3.0) < 0.1 for i in range(2))
    assert abs(e3[0] - 0.0107088) < 1e-7


def test_third_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, r=3, 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]) - 3.0) < 0.1 for i in range(2))


def test_small_overshoot_on_a_square_wave() -> None:
    m = 80
    u = [1.0 if 20 <= j < 40 else 0.0 for j in range(m)]
    for _ in range(80):
        u = step(u, 0.5 / m, 1.0 / m, IDENT, ONE, 3, True)
    over = max(u) - 1.0
    assert 1e-6 < over < 1e-4  # not TVD, but the overshoot is tiny
    assert min(u) > -1e-6


def test_sod_l1_error() -> None:
    e = [sod_l1(100, r) for r in (1, 2, 3)]
    assert abs(e[0] - 0.025915) < 5e-5 and abs(e[1] - 0.009678) < 5e-5 and abs(e[2] - 0.007662) < 5e-5

History

Harten, Engquist, Osher and Chakravarthy (1987) gave the reconstruction from cell averages through the primitive function, with the stencil chosen by divided differences. Shu and Osher (1988, 1989) gave a finite difference form on point values of fluxes, which is cheaper in several dimensions, together with the TVD Runge-Kutta methods now known as SSP methods. WENO schemes, which combine the same candidate stencils with smooth weights, followed in the 1990s.

References

  1. Ami Harten, Bjorn Engquist, Stanley Osher and Sukumar R. Chakravarthy, Uniformly high order accurate essentially non-oscillatory schemes, III, Journal of Computational Physics 71(2) (1987) 231-303, reconstruction from cell averages by the primitive function, with the stencil chosen by divided differences; doi:10.1016/0021-9991(87)90031-3
  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 Runge-Kutta methods used for the time steps and the method of lines form of ENO; doi:10.1016/0021-9991(88)90177-5
  3. Chi-Wang Shu and Stanley Osher, Efficient implementation of essentially non-oscillatory shock-capturing schemes, II, Journal of Computational Physics 83(1) (1989) 32-78, the continuation of the 1988 paper with further forms and tests of finite difference ENO schemes; doi:10.1016/0021-9991(89)90222-2

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