Algorithm Search⌘K

Algorithmadvanced

Nessyahu-Tadmor central scheme

A second order central scheme on staggered cells that needs no Riemann solver and no characteristic decomposition.

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
conservativedeterministicexplicitriemann-solver-free
Origin
Haim Nessyahu, Eitan Tadmor, 1990

The Nessyahu-Tadmor scheme is a second order finite volume scheme for hyperbolic conservation laws that needs no Riemann solver, no eigenvectors and no flux Jacobian. It works on two grids. Each step takes the averages over the cells of one grid and computes averages over the cells of a grid shifted by half a cell, whose cells straddle the faces of the old grid. The flux is needed only at the old cell centers, where the solution is smooth for a short time, so no Riemann problem appears. With constant data in each cell it is the staggered Lax-Friedrichs scheme; with limited straight lines, as in MUSCL, it is second order.

In plain words

Upwind schemes put a cell face at each jump and ask a Riemann solver what happens there. This scheme moves the cell instead: the new cell runs from the center of one old cell to the center of the next, so the jump between the old cells sits in the middle of the new cell. The new average is the mass already in that range, plus the flux in at the left center, minus the flux out at the right center. Near the old centers the solution stays smooth during one step if the time step is short enough, so these fluxes are easy to get from a Taylor step. The next step moves back to the old grid.

The problem

Given cell averages UjU_j of Ut+F(U)x=0U_t + F(U)_x = 0 on a uniform grid with width Δx\Delta x, compute averages at t+Δtt + \Delta t that are second order where the solution is smooth and free of oscillations at shocks, using only the flux FF. 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. NT-STAGGERED-STEP(U, λ = Δt/Δx, F, θ)
  2. 1add two ghost cells on each side (copy for outflow, wrap for periodic)
  3. 2for each cell j: U'_j <- S(U_{j-1}, U_j, U_{j+1}); F'_j <- S(F(U_{j-1}), F(U_j), F(U_{j+1}))
  4. 3U_j^{n+1/2} <- U_j - (λ/2) F'_j ▷ Taylor step to the midpoint in time
  5. 4for each j: W_{j+1/2} <- (U_j + U_{j+1})/2 + (U'_j - U'_{j+1})/8 - λ(F(U_{j+1}^{n+1/2}) - F(U_j^{n+1/2}))
  6. 5the next step applies lines L1 to L4 to W, which gives averages over the original cells

S(a,b,c)=minmod(θ(b−a),(c−a)/2,θ(c−b))S(a, b, c) = \mathrm{minmod}(\theta(b - a), (c - a)/2, \theta(c - b)) is the limited slope, computed per component, with 1≤θ≤21 \le \theta \le 2. The value Wj+1/2W_{j+1/2} is the average over [xj,xj+1][x_j, x_{j+1}], the interval between two old cell centers. The first two terms of line L4 are the exact average of the old piecewise linear data over this interval. The last term is the midpoint rule in time for the fluxes at xjx_j and xj+1x_{j+1}. Line L2 applies the limiter to the flux values, so no Jacobian is needed. The code takes two staggered steps with the same Δt=0.4 Δx/max⁡j(∣uj∣+cj)\Delta t = 0.4\,\Delta x/\max_j(|u_j| + c_j), so that the result is on the original grid, and uses θ=1.5\theta = 1.5 by default.

Example

One step by hand. Take ut+ux=0u_t + u_x = 0, θ=32\theta = \frac32, λ=14\lambda = \frac14, outflow boundaries and u=(0,0,1,3,4,4)u = (0, 0, 1, 3, 4, 4). For f(u)=cuf(u) = cu, line L4 becomes

Wj+1/2=(12+ν)uj+(12−ν)uj+1+κ(uj′−uj+1′),ν=λc,κ=1−4ν28.W_{j+1/2} = \big(\tfrac12 + \nu\big)u_j + \big(\tfrac12 - \nu\big)u_{j+1} + \kappa(u'_j - u'_{j+1}), \qquad \nu = \lambda c, \quad \kappa = \tfrac{1 - 4\nu^2}{8}.

Here ν=14\nu = \frac14 and κ=332\kappa = \frac3{32}. The slopes are u3′=u4′=32u'_3 = u'_4 = \frac32 and zero elsewhere. For the interval between cells 2 and 3, W=34⋅0+14⋅1+332(0−32)=764W = \frac34\cdot 0 + \frac14\cdot 1 + \frac3{32}(0 - \frac32) = \frac7{64}. All the values are (0,764,32,21764,4,4)(0, \frac7{64}, \frac32, \frac{217}{64}, 4, 4), and the step back gives (0,494096,13054096,83594096,148634096,4)(0, \frac{49}{4096}, \frac{1305}{4096}, \frac{8359}{4096}, \frac{14863}{4096}, 4). The test checks both lists exactly in Fraction arithmetic. At ν=12\nu = \frac12, κ=0\kappa = 0 and Wj+1/2=ujW_{j+1/2} = u_j: the scheme moves the data exactly by half a cell.

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

cells MM staggered steps θ=1\theta = 1 θ=1.5\theta = 1.5 θ=2\theta = 2
100 108 to 110 0.007331 0.005485 0.005456
200 218 to 220 0.004301 0.002955 0.002956
400 438 to 440 0.002405 0.001447 0.001446

At this Courant number the errors are lower than those of the Kurganov-Tadmor scheme with Heun's method (0.007000 at M=100M = 100, θ=1.5\theta = 1.5), and close to MUSCL-Hancock with HLLC and minmod (0.00585).

A smooth wave. 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.0017865, 0.0004384 and 0.0001011, so the observed orders are 2.03 and 2.12. For ut+ux=0u_t + u_x = 0 with the averages of sin⁡(2πx)\sin(2\pi x), ν=0.4\nu = 0.4, θ=1.5\theta = 1.5 and one period, the L1L^1 errors at M=20,40,80,160M = 20, 40, 80, 160 are 0.022273, 0.005769, 0.001386 and 0.000327 (orders 1.95, 2.06, 2.08).

Small time steps add viscosity. In the same advection problem with M=40M = 40, the L1L^1 errors at the Courant numbers 0.4, 0.2, 0.1 and 0.05 are 0.005769, 0.017103, 0.029484 and 0.046198. Each step averages neighbors through the term 12(uj+uj+1)\frac12(u_j + u_{j+1}), and more steps mean more averaging. The Kurganov-Tadmor scheme removes this: its error changes by about 1 percent over the same range.

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 ∣ν∣≤12|\nu| \le \frac12 and 1≤θ≤21 \le \theta \le 2, each staggered value is a convex combination of two values that both lie between uju_j and uj+1u_{j+1}, and each of the two sequences of such values has total variation at most TV(u)TV(u). So the scheme is TVD and makes no new extrema.

TVD for nonlinear laws and positivity for the Euler equations are not proved here. The tests check TVD for Burgers' equation on one step problem, which is a measurement.

Proof: The Nessyahu-Tadmor scheme is conservative and consistent, and for linear advection with the minmod-theta slope it is TVD for Courant numbers up to one halffull

Setting. The scheme stores cell averages uju_j on a uniform grid with width Δx\Delta x and cell centers xjx_j, with λ=Δt/Δx\lambda = \Delta t/\Delta x. Lines L2 to L4 of the page compute the slopes uj′=S(uj−1,uj,uj+1)u'_j = S(u_{j-1}, u_j, u_{j+1}) and fj′=S(f(uj−1),f(uj),f(uj+1))f'_j = S(f(u_{j-1}), f(u_j), f(u_{j+1})) with

S(a,b,c)=minmod(θ(b−a),12(c−a),θ(c−b)),1≤θ≤2,S(a, b, c) = \mathrm{minmod}\big(\theta(b - a), \tfrac12(c - a), \theta(c - b)\big), \qquad 1 \le \theta \le 2,

the midpoint values ujn+1/2=uj−λ2fj′u_j^{n+1/2} = u_j - \frac{\lambda}{2}f'_j, and the averages over the staggered cells [xj,xj+1][x_j, x_{j+1}]:

wj+1/2=12(uj+uj+1)+18(uj′−uj+1′)−λ(f(uj+1n+1/2)−f(ujn+1/2)).w_{j+1/2} = \tfrac12(u_j + u_{j+1}) + \tfrac18(u'_j - u'_{j+1}) - \lambda\big(f(u_{j+1}^{n+1/2}) - f(u_j^{n+1/2})\big).

The next step applies the same formula to the ww values and gives averages over the original cells. For systems, every line acts componentwise.

Where the formula comes from. Integrate ut+f(u)x=0u_t + f(u)_x = 0 over [xj,xj+1]×[tn,tn+1][x_j, x_{j+1}] \times [t^n, t^{n+1}] and divide by Δx\Delta x. The average of the piecewise linear data uj+uj′(x−xj)/Δxu_j + u'_j(x - x_j)/\Delta x over the right half of cell jj is uj+14uj′u_j + \frac14 u'_j, and over the left half of cell j+1j + 1 it is uj+1−14uj+1′u_{j+1} - \frac14 u'_{j+1}. Their mean is the first two terms. The fluxes are needed only at xjx_j and xj+1x_{j+1}, the centers of the old cells, where the data are smooth for a short time when λmax⁡∣f′∣≤12\lambda\max|f'| \le \frac12, so no Riemann problem appears. The midpoint rule in time with the Taylor value ujn+1/2u_j^{n+1/2} gives the last term.

Lemma 1 (conservation and consistency). On a periodic grid ∑jwj+1/2=∑juj\sum_j w_{j+1/2} = \sum_j u_j. If uj−1=⋯=uj+2=uˉu_{j-1} = \dots = u_{j+2} = \bar u, then wj+1/2=uˉw_{j+1/2} = \bar u.

Proof. Each uju_j appears with the weight 12\frac12 in wj−1/2w_{j-1/2} and in wj+1/2w_{j+1/2}. Each uj′u'_j appears with +18+\frac18 in wj+1/2w_{j+1/2} and −18-\frac18 in wj−1/2w_{j-1/2}, and each f(ujn+1/2)f(u_j^{n+1/2}) with +λ+\lambda and −λ-\lambda. So the sum is ∑juj\sum_j u_j. For constant data all slopes are zero, both midpoint values are uˉ\bar u, and the flux difference is zero. □\square

The test checks Lemma 1 exactly in Fraction arithmetic for Burgers' equation and three values of θ\theta. By the Lax-Wendroff theorem, bounded Lloc1L^1_{loc} limits of the scheme are weak solutions.

Lemma 2 (the slope). SS is odd and positively homogeneous, so S(ca,cb,cc)=c S(a,b,c)S(ca, cb, cc) = c\,S(a, b, c) for every real cc. If uj−uj−1u_j - u_{j-1} and uj+1−uju_{j+1} - u_j do not have the same strict sign, uj′=0u'_j = 0. Otherwise uj′u'_j has their sign and ∣uj′∣≤θmin⁡(∣uj−uj−1∣,∣uj+1−uj∣)|u'_j| \le \theta\min(|u_j - u_{j-1}|, |u_{j+1} - u_j|).

Proof. minmod is odd and positively homogeneous in its three arguments. It returns zero unless all three have one strict sign, and then it returns the one of least size, which is at most θ\theta times each one-sided difference. □\square

Lemma 3 (the linear case). Let f(u)=cuf(u) = cu and ν=λc\nu = \lambda c. Then

wj+1/2=(12+ν)Aj+(12−ν)Bj+1,Aj=uj+1−2ν4uj′,Bj=uj−1+2ν4uj′.w_{j+1/2} = \big(\tfrac12 + \nu\big)A_j + \big(\tfrac12 - \nu\big)B_{j+1}, \qquad A_j = u_j + \tfrac{1 - 2\nu}{4}u'_j, \quad B_j = u_j - \tfrac{1 + 2\nu}{4}u'_j.

Proof. By Lemma 2, fj′=c uj′f'_j = c\,u'_j, so ujn+1/2=uj−ν2uj′u_j^{n+1/2} = u_j - \frac{\nu}{2}u'_j and f(ujn+1/2)=cuj−cν2uj′f(u_j^{n+1/2}) = c u_j - \frac{c\nu}{2}u'_j. Multiply the flux difference by λ\lambda; then

wj+1/2=(12+ν)uj+(12−ν)uj+1+κ(uj′−uj+1′),κ=18−ν22=(1−2ν)(1+2ν)8.w_{j+1/2} = \big(\tfrac12 + \nu\big)u_j + \big(\tfrac12 - \nu\big)u_{j+1} + \kappa(u'_j - u'_{j+1}), \qquad \kappa = \tfrac18 - \tfrac{\nu^2}{2} = \tfrac{(1 - 2\nu)(1 + 2\nu)}{8}.

Now κ=(12+ν)1−2ν4=(12−ν)1+2ν4\kappa = (\frac12 + \nu)\frac{1 - 2\nu}{4} = (\frac12 - \nu)\frac{1 + 2\nu}{4}, which gives the split into AjA_j and Bj+1B_{j+1}. At ν=12\nu = \frac12, κ=0\kappa = 0, Aj=ujA_j = u_j and the weights are 11 and 00, so wj+1/2=ujw_{j+1/2} = u_j. □\square

The test test_hand_trace_against_the_linear_formula checks the formula with κ\kappa exactly in Fraction arithmetic, and test_courant_one_half_is_an_exact_shift checks the end point ν=12\nu = \frac12: the scheme moves the data exactly by half a cell.

Theorem 1 (TVD for linear advection). For f(u)=cuf(u) = cu, ∣ν∣≤12|\nu| \le \frac12 and 1≤θ≤21 \le \theta \le 2, on a periodic grid, TV(w)≤TV(u)TV(w) \le TV(u) and min⁡kuk≤wj+1/2≤max⁡kuk\min_k u_k \le w_{j+1/2} \le \max_k u_k, where TV(u)=∑j∣uj+1−uj∣TV(u) = \sum_j |u_{j+1} - u_j|. The same holds for the step from ww back to the original grid, so for every number of steps.

Proof. The factors 1−2ν4\frac{1 - 2\nu}{4} and 1+2ν4\frac{1 + 2\nu}{4} lie in [0,12][0, \frac12], and by Lemma 2 ∣uj′∣≤2∣uj+1−uj∣|u'_j| \le 2|u_{j+1} - u_j| with the same sign. So AjA_j lies between uju_j and uj+1u_{j+1}. In the same way BjB_j lies between uj−1u_{j-1} and uju_j. In the sequence u0,A0,u1,A1,u2,…u_0, A_0, u_1, A_1, u_2, \dots, each pair of neighbors uj,Aj,uj+1u_j, A_j, u_{j+1} is monotone, so the total variation of this sequence equals TV(u)TV(u). The sequence (Aj)(A_j) is a subsequence, so by the triangle inequality TV(A)≤TV(u)TV(A) \le TV(u). In the same way TV(B)≤TV(u)TV(B) \le TV(u). By Lemma 3 with weights 12±ν≥0\frac12 \pm \nu \ge 0 that add up to 1,

TV(w)=∑j∣(12+ν)(Aj+1−Aj)+(12−ν)(Bj+2−Bj+1)∣≤(12+ν)TV(A)+(12−ν)TV(B)≤TV(u).TV(w) = \sum_j \big|(\tfrac12 + \nu)(A_{j+1} - A_j) + (\tfrac12 - \nu)(B_{j+2} - B_{j+1})\big| \le (\tfrac12 + \nu)TV(A) + (\tfrac12 - \nu)TV(B) \le TV(u).

Each wj+1/2w_{j+1/2} is a convex combination of AjA_j and Bj+1B_{j+1}, which lie between old values, so no new extrema appear. The step back is the same formula on the grid of the ww values. □\square

The test test_tvd_and_no_new_extrema_for_advection checks Theorem 1 for θ=1,1.5,2\theta = 1, 1.5, 2 and ν=0.2,0.5,−0.4\nu = 0.2, 0.5, -0.4.

What is not proved here. For nonlinear scalar laws this page does not prove TVD; the test checks it for Burgers' equation on one step problem, which is a measurement. For the Euler equations no TVD or positivity property is proved. Second order accuracy is measured: the L1L^1 orders are about 2 on a smooth advection wave and on a smooth Euler wave. The growth of the error at small Courant numbers is also measured, not proved: in Lemma 3 the coefficient κ\kappa tends to 18\frac18 as ν→0\nu \to 0, so the scheme keeps the averaging 12(uj+uj+1)\frac12(u_j + u_{j+1}) in every step, and the number of steps grows like 1/Δt1/\Delta t.

Complexity

Theorem, in the real-RAM model: one staggered step costs O(mM)O(mM) operations: two limiter calls per component and cell, one flux evaluation per cell at the old data and one at the midpoint value. It keeps O(mM)O(mM) numbers. 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). The code evaluates the flux at each midpoint value twice, once for each staggered cell that uses it, which costs a constant factor only.

Properties

  • No Riemann solver and no Jacobian. Only FF is needed. The time step needs an upper bound for the wave speeds.
  • Second order on smooth solutions. Measured above: orders about 2 on smooth advection and on the Euler wave.
  • Conservative. Exact in rational arithmetic; the test checks it in Fraction for Burgers' equation.
  • TVD for linear advection with ∣ν∣≤12|\nu| \le \frac12. Proved.
  • Viscosity grows as Δt\Delta t falls. Measured above. This rules out a semi-discrete form and makes the scheme poor for problems that force small time steps, such as stiff source terms or diffusion.
  • Two grids. The averages alternate between the original grid and the staggered grid, so boundary conditions and output need care.

Variants and improvements

  • Kurganov-Tadmor scheme. Uses local wave speeds to make the staggered cells narrow, then lets Δt→0\Delta t \to 0, which gives a semi-discrete non-staggered scheme without the 1/Δt1/\Delta t viscosity.
  • Higher order central schemes. Piecewise quadratic or ENO reconstructions on the staggered grid give third order and higher central schemes.
  • Multi-dimensional staggered schemes. The same idea works on two staggered grids in two dimensions, with averages over cells centered at the old cell corners.

When to use it

Use it for a simple second order shock capturing scheme when a Riemann solver is not available, the time step is limited only by the Courant condition, and staggered output is acceptable. If small time steps are needed, or the code is built around the method of lines, use the Kurganov-Tadmor scheme instead.

Pitfalls

  • Courant number above one half. The fluxes at the old cell centers stay smooth only if waves from the neighbor faces do not reach the centers during the step, which needs λmax⁡∣f′∣≤12\lambda\max|f'| \le \frac12. The test of TVD uses this bound.
  • Mixing up the grids. After an odd number of steps the values are averages over the staggered cells. Taking two steps per call, as the code does, keeps the output on the original grid.
  • Very small time steps. The error grows as the Courant number falls, by a factor of 8 between 0.4 and 0.05 in the test 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.

nessyahu_tadmor_scheme.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nessyahu-tadmor-scheme/. The authors are listed in prov/40T9VJ.jsonl.

"""The second order staggered central scheme of Nessyahu and Tadmor (1990).

One staggered step maps the averages U_j over the cells [x_{j-1/2}, x_{j+1/2}] to the averages
W_{j+1/2} over the staggered cells [x_j, x_{j+1}]:

    W_{j+1/2} = (U_j + U_{j+1}) / 2 + (U'_j - U'_{j+1}) / 8 - lam (F(U_{j+1}^{n+1/2}) - F(U_j^{n+1/2})),

with U_j^{n+1/2} = U_j - (lam / 2) F'_j and lam = dt / dx. U'_j and F'_j are limited differences
of U and of F(U), so no Riemann solver and no Jacobian is needed. The next step maps W back to the
original cells. States are numbers (scalar laws) or tuples (systems). All divisions are by
integers or by dx, so Fraction data stay exact.
"""

from math import sqrt

GAMMA = 1.4


def lin(*terms):
    """The linear combination sum of c * x over (c, x) pairs, for numbers or tuples."""
    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 _div(x, k):
    if isinstance(x, tuple):
        return tuple(a / k for a in x)
    return x / k


def minmod3(a, b, c):
    if a > 0 and b > 0 and c > 0:
        return min(a, b, c)
    if a < 0 and b < 0 and c < 0:
        return max(a, b, c)
    return 0 * a


def slope(left, mid, right, theta):
    """The minmod-theta slope in cell units: minmod(theta dL, (dL + dR) / 2, theta dR)."""
    if isinstance(mid, tuple):
        return tuple(slope(l, m, r, theta) for l, m, r in zip(left, mid, right))
    dl, dr = mid - left, right - mid
    return minmod3(theta * dl, (dl + dr) / 2, theta * dr)


def staggered_step(cells, lam, flux, theta=1.5, periodic=False, shift=0):
    """One staggered step. shift = 0 gives out[j] from cells j and j + 1 (the averages over
    [x_j, x_{j+1}]); shift = 1 gives out[j] from cells j - 1 and j. Outflow boundaries copy the
    end cells into the ghost cells."""
    m = len(cells)
    if periodic:  # @line L1
        ext = [cells[-2], cells[-1]] + list(cells) + [cells[0], cells[1]]
    else:
        ext = [cells[0], cells[0]] + list(cells) + [cells[-1], cells[-1]]
    fx = [flux(q) for q in ext]
    du, mid = {}, {}
    for k in range(1, len(ext) - 1):
        du[k] = slope(ext[k - 1], ext[k], ext[k + 1], theta)  # @line L2
        df = slope(fx[k - 1], fx[k], fx[k + 1], theta)
        mid[k] = lin((1, ext[k]), (-lam / 2, df))  # @line L3
    out = []
    for j in range(m):
        k = j + 2 - shift
        avg = _div(lin((1, ext[k]), (1, ext[k + 1])), 2)
        out.append(lin((1, avg), (1, _div(lin((1, du[k]), (-1, du[k + 1])), 8)), (-lam, flux(mid[k + 1])), (lam, flux(mid[k]))))  # @line L4
    return out


def step(cells, dt, dx, flux, theta=1.5, periodic=False):
    """Two staggered steps of length dt: to the staggered grid and back. Returns cells at t + 2 dt."""
    lam = dt / dx
    w = staggered_step(cells, lam, flux, theta, periodic, 0)  # @line L5
    return staggered_step(w, lam, flux, theta, periodic, 1)


# 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, cfl=0.4, theta=1.5, periodic=False, g=GAMMA):
    """March to t_end in pairs of staggered steps with dt = cfl dx / max(|u| + c).
    Returns (cells, number of staggered steps)."""
    t, n = 0.0, 0
    flux = lambda q: euler_flux(q, g)
    while t < t_end - 1e-14:
        dt = min(cfl * dx / max(euler_speed(q, g) for q in cells), (t_end - t) / 2)
        cells = step(cells, dt, dx, flux, theta, periodic)
        t += 2 * dt
        n += 2
    return cells, n
test_nessyahu_tadmor_scheme.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nessyahu-tadmor-scheme/. The authors are listed in prov/40T9VJ.jsonl.

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

from nessyahu_tadmor_scheme import prim_to_cons, slope, solve_euler, staggered_step, step

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


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, theta, 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, theta=theta)
    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, nu, theta=1.5, t=1.0):
    dx = 1.0 / m
    n = round(t / (2 * nu * dx))
    u = averages(m, 0.0)
    for _ in range(n):
        u = step(u, t / (2 * n), dx, IDENT, theta, 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_hand_trace_against_the_linear_formula() -> None:
    # For f(u) = u: W_{j+1/2} = (1/2 + nu) u_j + (1/2 - nu) u_{j+1} + kappa (u'_j - u'_{j+1}).
    u = [Fraction(x) for x in (0, 0, 1, 3, 4, 4)]
    th, nu = Fraction(3, 2), Fraction(1, 4)
    kappa = (1 - 4 * nu * nu) / 8
    ext = [u[0], u[0]] + u + [u[-1], u[-1]]
    d = {k: slope(ext[k - 1], ext[k], ext[k + 1], th) for k in range(1, len(ext) - 1)}
    ref = [(Fraction(1, 2) + nu) * ext[k] + (Fraction(1, 2) - nu) * ext[k + 1] + kappa * (d[k] - d[k + 1]) for k in range(2, 8)]
    w = staggered_step(u, nu, IDENT, th)
    assert w == ref == [0, Fraction(7, 64), Fraction(3, 2), Fraction(217, 64), 4, 4]
    assert staggered_step(w, nu, IDENT, th, shift=1) == [0, Fraction(49, 4096), Fraction(1305, 4096), Fraction(8359, 4096), Fraction(14863, 4096), 4]


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 theta in (1, Fraction(3, 2), 2):
        v = u
        for _ in range(2):
            v = step(v, Fraction(1, 10), Fraction(1, 2), lambda x: x * x / 2, theta, True)
            assert sum(v) == total


def test_constant_state_and_consistency() -> 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))
    assert staggered_step([Fraction(3)] * 6, Fraction(1, 3), lambda x: x * x / 2) == [3] * 6


def test_courant_one_half_is_an_exact_shift() -> None:
    # At nu = 1/2 the staggered cell [x_j, x_{j+1}] receives exactly the old cell j.
    rng = random.Random(5)
    u = [Fraction(rng.randint(0, 9)) for _ in range(10)]
    w = staggered_step(u, Fraction(1, 2), IDENT, 2, True)
    assert w == u
    assert advect(40, 0.5)[0] < 1e-14


def test_tvd_and_no_new_extrema_for_advection() -> None:
    m = 60
    for theta in (1.0, 1.5, 2.0):
        for nu in (0.2, 0.5, -0.4):
            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 k in range(40):
                u = staggered_step(u, nu, IDENT, theta, True, k % 2)
                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(30):
        u = step(u, 0.4 * dx / max(abs(v) for v in u), dx, lambda x: x * x / 2)
        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_error_grows_when_the_time_step_falls() -> None:
    errs = [advect(40, nu)[0] for nu in (0.4, 0.2, 0.1, 0.05)]
    assert abs(errs[0] - 0.005769) < 1e-6 and abs(errs[3] - 0.046198) < 1e-6
    assert all(errs[i] < errs[i + 1] for i in range(3))  # the viscosity grows like 1 / dt


def test_second_order_on_smooth_advection() -> None:
    errs = [advect(m, 0.4)[0] for m in (20, 40, 80)]
    assert all(abs(log2(errs[i] / errs[i + 1]) - 2.0) < 0.1 for i in range(2))


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, 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.15 for i in range(2))
    assert abs(errs[0] - 0.0017865) < 1e-7


def test_sod_l1_error() -> None:
    e100, e200 = sod_l1(100, 1.5), sod_l1(200, 1.5)
    assert abs(e100 - 0.005485) < 5e-5 and abs(e200 - 0.002955) < 5e-5
    assert sod_l1(100, 1.0) > e100

History

The first order Lax-Friedrichs scheme, in its staggered form, averages two neighbor cells and differences their fluxes. Nessyahu and Tadmor (1990) replaced the constant data by limited piecewise linear data and the fluxes by a midpoint rule with a Taylor step. This gave a second order non-oscillatory central scheme without Riemann solvers, which led to many central schemes in the 1990s. Kurganov and Tadmor (2000) showed how to remove its 1/Δt1/\Delta t viscosity with local speeds, which gave the Kurganov-Tadmor scheme.

References

  1. Haim Nessyahu and Eitan Tadmor, Non-oscillatory central differencing for hyperbolic conservation laws, Journal of Computational Physics 87(2) (1990) 408-463, the staggered second order central scheme with limited slopes and the midpoint rule for the flux; doi:10.1016/0021-9991(90)90260-8
  2. Alexander Kurganov and Eitan Tadmor, New high-resolution central schemes for nonlinear conservation laws and convection-diffusion equations, Journal of Computational Physics 160(1) (2000) 241-282, the numerical viscosity of the staggered scheme at small time steps and the semi-discrete scheme that removes this limit; doi:10.1006/jcph.2000.6459

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