Algorithm Search⌘K

Techniqueadvanced

Well-balanced schemes

Also called hydrostatic reconstruction.

Schemes for balance laws that keep a family of steady states exactly, such as the lake at rest over a varying bottom, by discretizing flux gradient and source term so that they cancel.

A well-balanced scheme is a scheme for a balance law ut+f(u)x=S(u,x)u_t + f(u)_x = S(u, x) that keeps a chosen family of steady states f(u)x=S(u,x)f(u)_x = S(u, x) exactly at the discrete level, not only up to the truncation error. The standard case is the shallow water equations over a bottom z(x)z(x), ht+(hu)x=0h_t + (hu)_x = 0 and (hu)t+(hu2+12gh2)x=−ghzx(hu)_t + (hu^2 + \tfrac12gh^2)_x = -ghz_x, with the lake at rest u=0u = 0, h+z=consth + z = \text{const}. In that state the pressure gradient (12gh2)x(\tfrac12gh^2)_x and the bottom force −ghzx-ghz_x cancel. If they are discretized separately, their truncation errors do not cancel, and the scheme makes currents of size O(Δx)O(\Delta x) in still water. These currents are often larger than the waves one wants to compute, such as a tsunami of 1 m over an ocean 4 km deep. Bermúdez and Vázquez (1994) called the exact preservation of the lake at rest the C-property, and Greenberg and LeRoux (1996) introduced the name well-balanced. The hydrostatic reconstruction of Audusse et al. (2004) is a simple and widely used way to make any positive finite volume solver well balanced, including at wet-dry fronts.

In plain words

In a lake at rest over an uneven bottom, the water pushes sideways because it is deeper in some places, and the slope of the bottom pushes back by the same amount. Nothing moves. A computer program computes these two pushes with two different formulas, and the small errors in each formula do not cancel, so the program makes the still water flow. A well-balanced scheme computes the two pushes together, in a way that makes them cancel exactly when the water surface is flat. Then still water stays still, to the last digit of the computer arithmetic, and small real waves on top of it are not hidden by false currents.

When it applies

  • A hyperbolic system with a source term whose steady states are important or long-lived: shallow water over a bottom, gas in a gravitational field (hydrostatic atmospheres and stars), flow in a duct of varying area, chemical kinetics with equilibria.
  • The perturbations to compute are small compared with the truncation error of the balance: tides, tsunamis, stellar oscillations, flood waves over complex topography.
  • Long runs, where a spurious current of size O(Δx)O(\Delta x) builds up into a false steady flow.
  • Problems with dry regions, where the scheme must also keep h≥0h \ge 0, so the well-balanced method must work with a positive solver.

The template

On cells CiC_i with depth hih_i, discharge qi=hiuiq_i = h_iu_i and bottom ziz_i, the hydrostatic reconstruction works as follows at each face i+12i + \tfrac12, with any consistent flux F\mathcal F that keeps h≥0h \ge 0 (Rusanov, HLL, kinetic):

  1. HYDROSTATIC-RECONSTRUCTION-STEP(h, q, z, Δx, Δt, ℱ)
  2. 1for each face i+1/2 do z* ← max(z_i, z_(i+1))
  3. 2h*_L ← max(0, h_i + z_i - z*); h*_R ← max(0, h_(i+1) + z_(i+1) - z*)
  4. 3F* ← ℱ((h*_L, h*_L u_i), (h*_R, h*_R u_(i+1)))
  5. 4F⁻ ← F* + (0, g/2 (h_i² - h*_L²)); F⁺ ← F* + (0, g/2 (h_(i+1)² - h*_R²))
  6. 5for each cell i do (h, q)_i ← (h, q)_i - (Δt/Δx)(F⁻_(i+1/2) - F⁺_(i-1/2))

Walk-through. L2 measures the depths from the higher of the two bottoms, so it reconstructs the water column that the two cells have in common. L3 evaluates the solver on these states. L4 gives each cell its own momentum flux: cell ii sees F−F^- on its right face and cell i+1i + 1 sees F+F^+ on its left face. The difference between F−F^- and F+F^+ is the discrete bottom force at the face. The mass flux is the same on both sides, so mass is conserved exactly.

Why the lake at rest is kept (theorem). Let ui=0u_i = 0 and hi+zi=ηh_i + z_i = \eta for every wet cell. If both cells at a face are wet and η≥z∗\eta \ge z^*, then hL∗=hR∗=η−z∗h^*_L = h^*_R = \eta - z^*. The two reconstructed states are equal, so a consistent flux gives F∗=(0,g2h∗2)F^* = (0, \tfrac g2 h^{*2}) and F−=(0,g2hi2)F^- = (0, \tfrac g2 h_i^2), F+=(0,g2hi+12)F^+ = (0, \tfrac g2 h_{i+1}^2). If one cell is dry with a bottom above η\eta, both reconstructed depths are 00, so F∗=0F^* = 0 and again F−=(0,g2hi2)F^- = (0, \tfrac g2 h_i^2). In every case cell ii sees (0,g2hi2)(0, \tfrac g2 h_i^2) on both of its faces, and its update is zero. In floating point the update is zero up to rounding, because hi+zi−z∗h_i + z_i - z^* and g2(hi2−h∗2)+g2h∗2\tfrac g2(h_i^2 - h^{*2}) + \tfrac g2h^{*2} are computed with rounding errors of a few units in the last place. Audusse et al. (2004) also prove that the scheme keeps h≥0h \ge 0 under the CFL condition of the solver and satisfies a semi-discrete entropy inequality.

Classic examples

  • Shallow water equations: the lake at rest over a bump and over an island, worked out below.
  • Euler equations with gravity: the hydrostatic atmosphere px=−ρgp_x = -\rho g, kept by reconstructing pp relative to a local hydrostatic profile; this matters in astrophysics and weather codes.
  • Godunov's method with an upwinded source: the approach of Bermúdez and Vázquez, which puts the source at the faces and splits it with the same upwinding as the flux.
  • Discontinuous Galerkin method: high-order well-balanced DG uses the hydrostatic reconstruction at the faces and a matching quadrature of the source inside each cell.
  • Positivity-preserving limiter: with high-order schemes it keeps h≥0h \ge 0 at wet-dry fronts without breaking the balance.

One face by hand. Take g=9.81g = 9.81, two cells with depths h=(1,0.5)h = (1, 0.5), bottoms z=(0,0.5)z = (0, 0.5) and no flow, so the surface is at 1 in both. Then z∗=0.5z^* = 0.5 and hL∗=hR∗=0.5h^*_L = h^*_R = 0.5, and the Rusanov flux of two equal states at rest is F∗=(0,g2⋅0.25)=(0,1.22625)F^* = (0, \tfrac g2\cdot 0.25) = (0, 1.22625). The left cell sees F−=(0,1.22625+4.905⋅0.75)=(0,4.905)F^- = (0, 1.22625 + 4.905\cdot 0.75) = (0, 4.905), which is g2h02\tfrac g2 h_0^2, and the right cell sees F+=(0,1.22625+0)=(0,1.22625)F^+ = (0, 1.22625 + 0) = (0, 1.22625), which is g2h12\tfrac g2 h_1^2. With wall faces outside, both cells get zero updates. The plain Rusanov flux at the same face, with no reconstruction, has the mass flux −12a(h1−h0)=12g⋅0.5≈0.783-\tfrac12 a(h_1 - h_0) = \tfrac12\sqrt{g}\cdot 0.5 \approx 0.783, because its dissipation sees the jump in depth, and the scheme starts to move water.

Lake at rest (measurement). On [0,1][0, 1] with walls, g=9.81g = 9.81, surface level 1, forward Euler with Courant number 0.45, to T=0.5T = 0.5. "Bump" is z=0.5e−50(x−0.5)2z = 0.5e^{-50(x - 0.5)^2}. "Island" is z=max⁡(0,1.2−40(x−0.5)2)z = \max(0, 1.2 - 40(x - 0.5)^2), which is dry for ∣x−0.5∣<0.071|x - 0.5| < 0.071. The naive scheme is the Rusanov flux with the centred source −ghi(zi+1−zi−1)/(2Δx)-gh_i(z_{i+1} - z_{i-1})/(2\Delta x). Largest ∣q∣|q| at TT:

cells bump, naive bump, hydrostatic island, naive island, hydrostatic
50 1.020e-1 1.0e-15 4.231e-1 6.4e-16
100 4.874e-2 2.6e-15 1.985e-1 1.9e-16
200 2.303e-2 2.4e-15 9.718e-2 7.3e-16

The naive error is first order: it halves with Δx\Delta x. The hydrostatic reconstruction keeps the lake at rest to rounding, with or without dry cells. With the naive scheme over the island, the largest error of the surface in the wet cells is 0.087, 0.039 and 0.021 for 50, 100 and 200 cells.

Variations

  • Moving water equilibria. The hydrostatic reconstruction keeps only u=0u = 0. States with hu=consthu = \text{const} and 12u2+g(h+z)=const\tfrac12u^2 + g(h + z) = \text{const} need reconstruction in those equilibrium variables.
  • Second and higher order. Reconstruct h+zh + z (the surface) rather than hh, then apply the hydrostatic step at the faces and add a centred source correction inside each cell.
  • Central-upwind schemes. Well-balanced and positive versions of the Kurganov-Tadmor type schemes discretize the source to match the flux.
  • Wave-propagation methods. LeVeque's quasi-steady approach puts the source into the Riemann problem at each face, so the source is balanced by a jump in the face states.
  • Entropy stable and well-balanced. An energy conservative shallow water flux with a matching source discretization is both entropy stable and well balanced.

Pitfalls

  • Reconstructing hh instead of h+zh + z. A second-order slope limiter applied to hh breaks the balance. Reconstruct the surface elevation and recover hh from it.
  • Testing in exact arithmetic only. The property holds to rounding in floating point. Check ∣q∣|q| and ∣h+z−η∣|h + z - \eta| against a tolerance of a few hundred ulps of g2h2\tfrac g2h^2, not against zero.
  • Dry cells. Dividing by hh to get uu fails at h=0h = 0. Set u=0u = 0 for dry cells, or for hh below a small threshold.
  • Steep bottoms. The hydrostatic reconstruction is consistent but can be inaccurate for large bottom jumps on coarse grids, because the reconstructed depths are clipped at 0.
  • Only one equilibrium. A scheme balanced for the lake at rest is not balanced for steady flow over a bump; know which steady state matters for the problem.
  • Source at the cell centre with an upwind flux. As the table shows, this standard approach makes spurious currents of order Δx\Delta x, even though each part is consistent.

Code

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.

well_balanced_scheme.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/well-balanced-scheme/. The authors are listed in prov/DMAAHD.jsonl.

"""Well-balanced first-order scheme for the 1D shallow water equations with a bottom.

Equations: h_t + (hu)_x = 0, (hu)_t + (hu^2 + g h^2 / 2)_x = -g h z_x, with bottom z(x).
Cells of width dx with values (h_i, q_i = h_i u_i) and bottom z_i; solid walls at both ends.
The well-balanced scheme is the hydrostatic reconstruction of Audusse, Bouchut, Bristeau,
Klein and Perthame (2004) with the Rusanov flux: at each face the depths are rebuilt
relative to z* = max(z_i, z_{i+1}), the flux is evaluated at the rebuilt states, and the
momentum fluxes seen by the two cells are corrected by g/2 (h^2 - h*^2). The naive scheme
(Rusanov flux plus a centred source term) is included for comparison.

Precondition: h_i >= 0, dx > 0, dt > 0, and dt max(|u| + sqrt(g h)) <= dx / 2 for h >= 0.
Cost: Theta(m) per step for m cells; memory Theta(m).
"""

import math
from typing import List, Tuple

G = 9.81
State = Tuple[List[float], List[float]]


def phys_flux(h: float, q: float, g: float = G) -> Tuple[float, float]:
    u = q / h if h > 0 else 0.0
    return q, q * u + g * h * h / 2


def rusanov(hl, ql, hr, qr, g=G):
    """Rusanov (local Lax-Friedrichs) flux for shallow water; dry states have speed 0."""
    ul = ql / hl if hl > 0 else 0.0
    ur = qr / hr if hr > 0 else 0.0
    a = max(abs(ul) + math.sqrt(g * hl), abs(ur) + math.sqrt(g * hr))
    fl, fr = phys_flux(hl, ql, g), phys_flux(hr, qr, g)
    return (0.5 * (fl[0] + fr[0]) - 0.5 * a * (hr - hl),
            0.5 * (fl[1] + fr[1]) - 0.5 * a * (qr - ql))


def _with_walls(h, q, z):
    """Ghost cells for solid walls: same depth and bottom, opposite momentum."""
    return [h[0]] + h + [h[-1]], [-q[0]] + q + [-q[-1]], [z[0]] + z + [z[-1]]


def hr_step(h: List[float], q: List[float], z: List[float], dx: float, dt: float, g: float = G) -> State:
    """One forward Euler step of the hydrostatic reconstruction scheme."""
    H, Q, Z = _with_walls(h, q, z)
    n = len(h)
    left, right = [], []                       # flux seen by the cell left / right of each face
    for i in range(n + 1):                     # face between ghost-padded cells i and i + 1
        zs = max(Z[i], Z[i + 1])                                           # @line L1
        hl = max(0.0, H[i] + Z[i] - zs)                                    # @line L2
        hr = max(0.0, H[i + 1] + Z[i + 1] - zs)
        ul = Q[i] / H[i] if H[i] > 0 else 0.0
        ur = Q[i + 1] / H[i + 1] if H[i + 1] > 0 else 0.0
        f0, f1 = rusanov(hl, hl * ul, hr, hr * ur, g)                      # @line L3
        left.append((f0, f1 + g / 2 * (H[i] * H[i] - hl * hl)))            # @line L4
        right.append((f0, f1 + g / 2 * (H[i + 1] * H[i + 1] - hr * hr)))
    lam = dt / dx
    hn = [h[i] - lam * (left[i + 1][0] - right[i][0]) for i in range(n)]   # @line L5
    qn = [q[i] - lam * (left[i + 1][1] - right[i][1]) for i in range(n)]
    return hn, qn


def naive_step(h: List[float], q: List[float], z: List[float], dx: float, dt: float, g: float = G) -> State:
    """Rusanov flux plus the centred source -g h_i (z_{i+1} - z_{i-1}) / (2 dx); not well balanced."""
    H, Q, Z = _with_walls(h, q, z)
    n = len(h)
    F = [rusanov(H[i], Q[i], H[i + 1], Q[i + 1], g) for i in range(n + 1)]
    lam = dt / dx
    hn = [h[i] - lam * (F[i + 1][0] - F[i][0]) for i in range(n)]
    qn = [q[i] - lam * (F[i + 1][1] - F[i][1]) - dt * g * h[i] * (Z[i + 2] - Z[i]) / (2 * dx)
          for i in range(n)]
    return hn, qn


def max_speed(h, q, g=G):
    return max((abs(b / a) + math.sqrt(g * a)) if a > 0 else 0.0 for a, b in zip(h, q))


def run(step, h, q, z, dx, T, cfl=0.45, g=G) -> State:
    """Advance to time T with dt = cfl dx / max speed (a forward Euler scheme)."""
    if not dx > 0:
        raise ValueError("dx must be positive")
    if min(h) < 0:
        raise ValueError("depths must be nonnegative")
    t = 0.0
    while t < T - 1e-14:
        s = max_speed(h, q, g)
        dt = min(cfl * dx / s if s > 0 else T - t, T - t)
        h, q = step(h, q, z, dx, dt, g)
        t += dt
    return h, q
test_well_balanced_scheme.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/well-balanced-scheme/. The authors are listed in prov/DMAAHD.jsonl.

import math
import random

import pytest

from well_balanced_scheme import G, hr_step, naive_step, run, rusanov


def lake(m, island=False, level=1.0):
    dx = 1.0 / m
    xs = [(i + 0.5) * dx for i in range(m)]
    if island:
        z = [max(0.0, 1.2 - 40 * (x - 0.5) ** 2) for x in xs]
    else:
        z = [0.5 * math.exp(-50 * (x - 0.5) ** 2) for x in xs]
    return xs, dx, [max(0.0, level - zi) for zi in z], [0.0] * m, z


def plain_rusanov_step(h, q, dx, dt):
    """Independent first-order Rusanov scheme for a flat bottom with walls."""
    H, Q = [h[0]] + h + [h[-1]], [-q[0]] + q + [-q[-1]]
    F = [rusanov(H[i], Q[i], H[i + 1], Q[i + 1]) for i in range(len(h) + 1)]
    lam = dt / dx
    return ([h[i] - lam * (F[i + 1][0] - F[i][0]) for i in range(len(h))],
            [q[i] - lam * (F[i + 1][1] - F[i][1]) for i in range(len(h))])


def test_face_by_hand():
    # Surface level 1 over a step: depths 1 and 0.5, bottoms 0 and 0.5.
    h, q, z = [1.0, 0.5], [0.0, 0.0], [0.0, 0.5]
    hn, qn = hr_step(h, q, z, 0.5, 0.01)
    assert hn == h and max(abs(v) for v in qn) < 1e-15
    f0, f1 = rusanov(0.5, 0.0, 0.5, 0.0)
    assert f0 == 0.0 and abs(f1 - G / 8) < 1e-15
    assert abs(rusanov(1.0, 0.0, 0.5, 0.0)[0] - 0.25 * (math.sqrt(G) + 0.0)) < 1e-12


@pytest.mark.parametrize("island", [False, True])
def test_lake_at_rest_is_kept_to_rounding(island):
    xs, dx, h, q, z = lake(80, island)
    hh, qq = run(hr_step, h, q, z, dx, 0.3)
    assert max(abs(v) for v in qq) < 1e-13
    for a, b, a0 in zip(hh, z, h):
        if a0 > 0:
            assert abs(a + b - 1.0) < 1e-13
        else:
            assert a == 0.0


@pytest.mark.parametrize("island", [False, True])
def test_naive_source_term_is_not_well_balanced(island):
    xs, dx, h, q, z = lake(80, island)
    hh, qq = run(naive_step, h, q, z, dx, 0.3)
    assert max(abs(v) for v in qq) > 1e-3


def test_naive_error_is_first_order_in_dx():
    err = []
    for m in (50, 100, 200):
        xs, dx, h, q, z = lake(m)
        err.append(max(abs(v) for v in run(naive_step, h, q, z, dx, 0.5)[1]))
    assert 1.7 < err[0] / err[1] < 2.3 and 1.7 < err[1] / err[2] < 2.3


def test_flat_bottom_reduces_to_the_rusanov_scheme():
    rng = random.Random(5)
    m = 30
    dx = 1.0 / m
    h = [rng.uniform(0.5, 1.5) for _ in range(m)]
    q = [rng.uniform(-0.3, 0.3) for _ in range(m)]
    a = hr_step(h, q, [0.0] * m, dx, 0.2 * dx / 4.5)
    b = plain_rusanov_step(h, q, dx, 0.2 * dx / 4.5)
    assert max(abs(x - y) for x, y in zip(a[0] + a[1], b[0] + b[1])) < 1e-14


def test_mass_conserved_and_depth_nonnegative_for_dam_break_onto_dry_bed_over_a_bump():
    m = 100
    dx = 1.0 / m
    xs = [(i + 0.5) * dx for i in range(m)]
    z = [0.3 * math.exp(-100 * (x - 0.7) ** 2) for x in xs]
    h = [1.0 if x < 0.4 else 0.0 for x in xs]
    q = [0.0] * m
    mass0 = sum(h) * dx
    t, steps = 0.0, 0
    while steps < 150:
        hh = run(hr_step, h, q, z, dx, 0.002)
        h, q = hh
        assert min(h) >= 0.0
        steps += 1
    assert abs(sum(h) * dx - mass0) < 1e-13
    assert max(h[int(0.8 * m):]) > 0.0                 # the water has passed the bump


def test_small_perturbation_stays_local():
    # A small bump on the surface: the well-balanced scheme leaves the far region at rest.
    xs, dx, h, q, z = lake(100)
    h = [a + (1e-3 if 0.1 < x < 0.2 else 0.0) for a, x in zip(h, xs)]
    hh, qq = run(hr_step, h, q, z, dx, 0.05)
    far = [i for i, x in enumerate(xs) if x > 0.6]
    assert max(abs(qq[i]) for i in far) < 1e-13
    hn, qn = run(naive_step, h, q, z, dx, 0.05)
    assert max(abs(qn[i]) for i in far) > 1e-3


def test_rejects_negative_depth():
    with pytest.raises(ValueError):
        run(hr_step, [-1.0, 1.0], [0.0, 0.0], [0.0, 0.0], 0.5, 0.1)

Exercises

  1. Show that the naive scheme of the table is consistent of first order, but that for the lake at rest its momentum update in a wet cell is O(Δx)O(\Delta x) and not zero.
  2. Show that the hydrostatic reconstruction keeps the total mass ∑ihi Δx\sum_i h_i\,\Delta x exactly on a grid with walls, in exact arithmetic.
  3. For the Euler equations with gravity, px=−ρgp_x = -\rho g with constant temperature gives p=p0e−x/Hp = p_0e^{-x/H}. Write a reconstruction that keeps this isothermal atmosphere exactly.

References

  1. Alfredo Bermúdez and M. Elena Vázquez, Upwind methods for hyperbolic conservation laws with source terms, Computers and Fluids 23(8) (1994) 1049-1071, the upwind treatment of the source term and the exact conservation property (C-property) for the lake at rest
  2. Emmanuel Audusse, François Bouchut, Marie-Odile Bristeau, Rupert Klein and Benoît Perthame, A fast and stable well-balanced scheme with hydrostatic reconstruction for shallow water flows, SIAM Journal on Scientific Computing 25(6) (2004) 2050-2065, the hydrostatic reconstruction, the proof that it keeps the lake at rest and nonnegative depths, the second-order extension
  3. J. M. Greenberg and A. Y. LeRoux, A well-balanced scheme for the numerical processing of source terms in hyperbolic equations, SIAM Journal on Numerical Analysis 33(1) (1996) 1-16, the name well-balanced and the treatment of the source at the cell faces
  4. Randall J. LeVeque, Finite Volume Methods for Hyperbolic Problems, Cambridge University Press, 2002, Chapter 17 (source terms and balance laws, quasi-steady problems)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW3 standard
  • five exercises