Algorithm Search⌘K

Algorithmadvanced

Unconditionally stable MacCormack method

Also called semi-Lagrangian MacCormack.

Advect forward, trace the result back, and add half the round trip error to the forward result. Second order for smooth fields; a limiter keeps each value in its stencil range.

Time
Θ(g) limiter · step
Space
Θ(g) extra
Where
g = the number of grid samples of the field
Properties
not conservativedeterministicnot exactunconditionally stable
Origin
Andrew Selle, Ronald Fedkiw, ByungMoon Kim, Yingjie Liu, Jarek Rossignac, 2008

The unconditionally stable MacCormack method of Selle, Fedkiw, Kim, Liu and Rossignac (2008) is a sharper advection step for grid fluids. It does one semi-Lagrangian step forward and one back, and uses half of the round trip error to correct the forward result. That makes it second order for smooth fields, at the cost of two plain steps, one fewer than BFECC. A limiter falls back to the plain step wherever the corrected value leaves the range of the old values that the plain step used. With the limiter, the step stays bounded for any time step and any velocity. The name refers to the predictor-corrector structure. The method is not the 1969 MacCormack method for compressible flow, which is explicit and has a CFL limit.

In plain words

Moving smoke one step with the plain method blurs it a little. This method measures that blur and takes it back.

It moves the smoke forward one step, which gives a blurred result. Then it moves that result back one step with the same method. If nothing were lost, this would give back the start. In fact it gives a picture that was blurred twice. Half of the difference from the start is about one blur, so the method adds that half to the forward result.

The correction can push a value past the old range near a sharp edge. There the method simply keeps the plain forward value, which never leaves that range.

The problem

Given a field qq on a grid, a velocity field u\mathbf u and a time step Δt\Delta t, find the field at the next step for the advection equation ∂q/∂t+u⋅∇q=0\partial q / \partial t + \mathbf u \cdot \nabla q = 0. The plain semi-Lagrangian step of stable fluids is stable for any Δt\Delta t but first order, and it smears small features. The goal is a second order step that keeps that stability and costs only a small multiple of the plain step.

The algorithm

Let AA be the plain semi-Lagrangian step and ARA^R the same step with −Δt-\Delta t.

  1. MACCORMACK(q, u, dt)
  2. 1q_hat <- A(q) ▷ predictor: the plain forward step
  3. 2q_check <- A^R(q_hat) ▷ trace the predictor back to the start time
  4. 3q_new <- q_hat + (q - q_check) / 2 ▷ corrector: add half the round trip error
  5. 4for each sample: [lo, hi] <- range of the values of q that L1 mixed at its foot
  6. 5where q_new is outside [lo, hi]: q_new <- q_hat (revert), or clamp it to [lo, hi]

Why it works. If the plain step has the error ee, then q^≈qexact+e\hat q \approx q_{\text{exact}} + e, and the round trip qˇ≈q+2e\check q \approx q + 2e. So 12(q−qˇ)≈−e\frac12 (q - \check q) \approx -e, and line L3 removes the error of the forward step. For y′=λyy' = \lambda y with forward Euler as the plain step, line L3 gives exactly (1+λh+12λ2h2)y(1 + \lambda h + \frac12 \lambda^2 h^2) y, the second order Taylor step.

The relation to BFECC. BFECC uses the same error estimate, but it corrects the start and then does a third plain step. MacCormack corrects the end directly, which saves one step. Selle and colleagues report that both are second order on smooth problems, and the analysis on the proof page agrees.

The limiter (L4, L5). The plain value at a point is a weighted mean of the four (in 3D, eight) old values around the foot of its backtrace, so it lies in their range. The corrected value may not. There are two choices: clamp to the range, or revert to the plain value. Selle and colleagues revert, and this page does the same by default. In the tests of this page the two give similar results.

On a MAC grid. Advect uu, vv and each scalar with their own sample points, and take all backtraces in the velocity field from the start of the step.

Example

One step by hand. A row of 7 cells with Δx=1\Delta x = 1 m, u=0.5u = 0.5 m/s and Δt=1\Delta t = 1 s, so the CFL number is 0.50.5. The plain step is (Aq)a=12qa+12qa−1(A q)_a = \frac12 q_a + \frac12 q_{a - 1}, and the reverse step is 12qa+12qa+1\frac12 q_a + \frac12 q_{a+1}. Start with a spike at cell 3:

cell 1 2 3 4 5
qq 0 0 1 0 0
q^\hat q (L1) 0 0 0.5 0.5 0
qˇ\check q (L2) 0 0.25 0.5 0.25 0
qnewq^{\text{new}} (L3) 0 -0.125 0.75 0.375 0
after revert (L5) 0 0 0.75 0.375 0

The exact spike would sit at the position 3.53.5. The plain step splits it into 0.50.5 and 0.50.5. MacCormack keeps more height but is not symmetric: it moves the mass less than the exact half cell, and it dips to −0.125-0.125 at cell 2. The plain step at cell 2 mixes two zeros, so the limiter reverts that value to 0. The sum is 1 before the limiter and 1.125 after it.

Measured on a smooth bump. A bump of radius 0.3 m moves for 0.25 s with the velocity (1,0.5)(1, 0.5) m/s on a square of 1 m, at the CFL number 4/34/3 in xx:

method 16 by 16 32 by 32 observed order
plain semi-Lagrangian 0.197 0.106 0.89
MacCormack 0.158 0.0492 1.68
MacCormack with revert 0.158 0.0503 1.65

On the same test, BFECC has the error 0.00684 at 32 cells. The proof page explains the gap: the error constant of MacCormack has a term that does not shrink when the step grows. At 32 cells, the MacCormack error is 0.0486 with 12 steps and 0.0492 with 6 steps.

Rotation and a sharp edge, measured. A bump of radius 0.2 m turns a quarter turn on a 32 by 32 grid in 16 steps. The largest error is 0.157 without the limiter, 0.188 with revert and 0.160 with clamp, against 0.375 for the plain step. A square of height 1 moved for five steps reaches 1.31 and -0.25 without the limiter, and it stays in [0,1][0, 1] with either limiter.

Correctness

The claims are proved in proofs/correctness.md.

  1. Constants. A constant field stays exactly the same.
  2. Stability. On a periodic grid with a constant velocity, the step without the limiter multiplies each Fourier mode by G=A+12(1−∣A∣2)G = A + \frac12 (1 - |A|^2), where AA is the factor of the plain step. For every CFL number, ∣G∣≤1|G| \le 1.
  3. Order. Under the same conditions, GG differs from the exact factor by O(θ3)O(\theta^3), so the error after a fixed time is O(Δx2)O(\Delta x^2) at a fixed CFL number. The constant is α+β/c\alpha + \beta / c, where α\alpha and β\beta depend only on the fractional part of the CFL number cc.
  4. Limiter. With "revert" or "clamp", each new value lies in the range of the old values at the foot of its backtrace. So the field stays between its old minimum and maximum, for any velocity and any Δt\Delta t.

The tests check the symbol against the code to 10−1310^{-13}, the measured order, the error at two step sizes, the exact result at a whole number of cells per step, the rotation, and the range of the limited values.

Proof: The MacCormack step is second order and stable under constant velocity, and the limiter gives a maximum principlefull

We use the line numbers of the page. AA is one semi-Lagrangian step with time step Δt\Delta t (the helper's RK2 backtrace and bilinear sample), and ARA^R is the same step with −Δt-\Delta t. The step is

q^=Aq,qˇ=ARq^,qnew=q^+12(q−qˇ),\hat q = A q, \qquad \check q = A^R \hat q, \qquad q^{\text{new}} = \hat q + \tfrac12 (q - \check q),

followed by the limiter. All statements are in exact arithmetic.

Lemma 1 (constants). A constant field stays the same, with or without the limiter.

Proof. AA and ARA^R take convex combinations, so q^=qˇ=q=κ\hat q = \check q = q = \kappa and qnew=κ+12(κ−κ)=κq^{\text{new}} = \kappa + \frac12 (\kappa - \kappa) = \kappa. The stencil range is [κ,κ][\kappa, \kappa], so the limiter does nothing. □\square

Lemma 2 (an ordinary differential equation). Apply the same steps to y′=λyy' = \lambda y, with forward Euler Ay=(1+λh)yA y = (1 + \lambda h) y and its reverse ARy=(1−λh)yA^R y = (1 - \lambda h) y. Then the step is y↦(1+λh+12λ2h2) yy \mapsto (1 + \lambda h + \frac12 \lambda^2 h^2)\, y, which is the second order Taylor step, the same as the two-stage Runge-Kutta methods on this equation.

Proof. yˇ=(1−λh)(1+λh)y=(1−λ2h2)y\check y = (1 - \lambda h)(1 + \lambda h) y = (1 - \lambda^2 h^2) y, so ynew=(1+λh)y+12λ2h2yy^{\text{new}} = (1 + \lambda h) y + \frac12 \lambda^2 h^2 y. □\square

This is the simplest view of the method: a first order step plus half of its round trip error.

Setting for the next results. A periodic grid of spacing Δx\Delta x in 1D, a constant velocity u>0u > 0, and c=uΔt/Δx=m+φc = u \Delta t / \Delta x = m + \varphi with an integer m≥0m \ge 0 and φ∈[0,1)\varphi \in [0, 1). The RK2 backtrace is exact for a constant velocity, so AA multiplies the mode eiθae^{\mathrm i \theta a} by A(θ)=e−imθ(1−φ+φe−iθ)A(\theta) = e^{-\mathrm i m \theta}(1 - \varphi + \varphi e^{-\mathrm i \theta}), and ARA^R multiplies it by A(θ)‾\overline{A(\theta)}, as on the BFECC proof page. The test file checks the symbol below against the code to 10−1310^{-13} in the interior of a 1D grid of 40 cells.

Lemma 3 (the symbol). One MacCormack step without the limiter multiplies the mode by

G(θ)=A+12(1−∣A∣2),1−∣A∣2=2φ(1−φ)(1−cos⁡θ).G(\theta) = A + \tfrac12 (1 - |A|^2), \qquad 1 - |A|^2 = 2 \varphi (1 - \varphi)(1 - \cos \theta).

Proof. qˇ=AˉAq=∣A∣2q\check q = \bar A A q = |A|^2 q, so qnew=Aq+12(1−∣A∣2)qq^{\text{new}} = A q + \frac12 (1 - |A|^2) q. The modulus is computed on the BFECC page. □\square

Theorem 1 (stability for any Δt\Delta t, without the limiter). For every c≥0c \ge 0 and every θ\theta, ∣G(θ)∣≤1|G(\theta)| \le 1. So on the periodic grid the step does not increase the ℓ2\ell^2 norm, at any CFL number.

Proof. Let s=∣A∣∈[0,1]s = |A| \in [0, 1]. By the triangle inequality, ∣G∣≤s+12(1−s2)|G| \le s + \frac12 (1 - s^2), and 1−s−12(1−s2)=12(1−s)2≥01 - s - \frac12 (1 - s^2) = \frac12 (1 - s)^2 \ge 0. Parseval's identity gives the norm bound. □\square

Unlike BFECC, the MacCormack step can damp a mode more than the plain step does, because 12(1−∣A∣2)\frac12 (1 - |A|^2) is added to AA as a real number. For c=1.5c = 1.5 and θ=1.3\theta = 1.3, ∣A∣=0.796|A| = 0.796 and ∣G∣=0.748|G| = 0.748. The test file checks that such modes exist.

Theorem 2 (second order). Let α=12φ(1−φ)\alpha = \frac12 \varphi (1 - \varphi) and β=16φ(1−φ)(1−2φ)\beta = \frac16 \varphi(1 - \varphi)(1 - 2 \varphi). Then

G(θ)=e−icθ(1+i(β+αc) θ3+O(θ4)).G(\theta) = e^{-\mathrm i c \theta}\left(1 + \mathrm i (\beta + \alpha c)\, \theta^3 + O(\theta^4)\right).

For a periodic trigonometric polynomial q=∑kq^keikxq = \sum_k \hat q_k e^{\mathrm i k x}, with Δx\Delta x small enough that ∣kΔx∣≤π|k \Delta x| \le \pi for each of its modes, the error after the time TT at a fixed CFL number is O(Δx2)O(\Delta x^2), with the leading term at most

Tu(α+βc)Δx2∑k∣k∣3∣q^k∣T u \left(\alpha + \frac{\beta}{c}\right) \Delta x^2 \sum_k |k|^3 |\hat q_k|

up to higher order terms.

Proof. The BFECC page shows Aeicθ=exp⁡(−αθ2+iβθ3+O(θ4))=1−αθ2+iβθ3+O(θ4)A e^{\mathrm i c \theta} = \exp(-\alpha \theta^2 + \mathrm i \beta \theta^3 + O(\theta^4)) = 1 - \alpha \theta^2 + \mathrm i \beta \theta^3 + O(\theta^4). By Lemma 3, 12(1−∣A∣2)=φ(1−φ)(1−cos⁡θ)=αθ2+O(θ4)\frac12 (1 - |A|^2) = \varphi (1 - \varphi)(1 - \cos \theta) = \alpha \theta^2 + O(\theta^4). So

Geicθ=1−αθ2+iβθ3+αθ2(1+icθ+O(θ2))+O(θ4)=1+i(β+αc)θ3+O(θ4).G e^{\mathrm i c \theta} = 1 - \alpha \theta^2 + \mathrm i \beta \theta^3 + \alpha \theta^2 (1 + \mathrm i c \theta + O(\theta^2)) + O(\theta^4) = 1 + \mathrm i (\beta + \alpha c) \theta^3 + O(\theta^4).

Since ∣G∣≤1|G| \le 1, the telescoping bound ∣GN−e−iNcθ∣≤N∣G−e−icθ∣|G^N - e^{-\mathrm i N c \theta}| \le N |G - e^{-\mathrm i c \theta}| holds. With θ=kΔx\theta = k \Delta x and N=Tu/(cΔx)N = T u / (c \Delta x) steps, the error of mode kk is at most TucΔx(∣β+αc∣ ∣kΔx∣3+O(∣kΔx∣4))\frac{T u}{c \Delta x} \left( |\beta + \alpha c|\, |k \Delta x|^3 + O(|k \Delta x|^4) \right), which gives the bound. □\square

The error constant shows a difference from BFECC. The BFECC constant is β/c\beta / c, which shrinks as the CFL number grows. The MacCormack constant has the extra term α\alpha, which depends only on the fractional part φ\varphi. So at a fixed grid, a larger step does not make MacCormack more accurate. The test file moves a smooth bump for 0.25 s on a 32 by 32 grid and finds the error 0.04860.0486 at c=2/3c = 2/3 and 0.04920.0492 at c=4/3c = 4/3. At c=4c = 4, a whole number of cells, both α\alpha and β\beta vanish, and the step is exact. In 2D with a constant velocity, A=AxAyA = A_x A_y and AR=AˉA^R = \bar A. Theorem 1 holds with the same proof, and in Theorem 2 the term 12(1−∣A∣2)\frac12(1 - |A|^2) cancels the real second order part of log⁡A\log A in the same way, so the step is second order in 2D too. The test file measures the order 1.68 between 16 and 32 cells, against 0.89 for the plain step.

Theorem 3 (the limiter, line L5). Let [ℓa,ha][\ell_a, h_a] be the range of the four values of qq that the plain step AA mixes at sample aa (line L4). With the "revert" or the "clamp" limiter, every new value lies in [ℓa,ha][\ell_a, h_a]. So min⁡q≤qnew≤max⁡q\min q \le q^{\text{new}} \le \max q, for any velocity field and any Δt\Delta t.

Proof. With "revert", a value outside the range is replaced by q^a=(Aq)a\hat q_a = (A q)_a, a convex combination of the four values, which lies in the range. With "clamp", it is replaced by the nearest end of the range. A value inside the range stays. □\square

This bound is what keeps the method stable at any step size: with the limiter, every value is bounded by the old extremes for any velocity, as for the plain semi-Lagrangian step. The linear Theorems 1 and 2 hold only where the limiter does not act. Without the limiter, a square of height 1 reaches 1.311.31 and −0.25-0.25 after five steps in the test file, and with either limiter it stays in [0,1][0, 1].

Complexity

Let gg be the number of samples. Each plain step costs Θ(g)\Theta(g), so lines L1 to L3 cost about twice the plain step. The limiter needs the stencil range at the foot of each forward backtrace. An implementation can record it during line L1; the code here recomputes the backtraces. The extra space is Θ(g)\Theta(g) for q^\hat q, qˇ\check q and the ranges.

Properties

  • Second order for smooth fields under a constant velocity, with two plain steps per step.
  • Bounded at any step size with the limiter, for any velocity field.
  • Not conservative. The sum of the field is not kept, and the limiter changes it more.
  • Not symmetric. The correction is applied to the forward result, so a spike moves unevenly, as in the example above.
  • Generic. It wraps any advection step that has a reverse, without looking inside it.

Variants and improvements

  • BFECC. BFECC corrects the start instead and does a third plain step. In the bump test of this page it is about 7 times more accurate, at 1.5 times the cost.
  • Clamp or revert. The two limiters of the paper. Reverting keeps the plain value and can lose more detail near smooth extrema; clamping keeps more of the correction.
  • Higher order interpolation. A cubic sample in place of the bilinear one reduces the error of each plain step, and the correction then works on a smaller error.
  • Velocity advection. Applied to the velocity, the method keeps more of the small swirls than the plain step. A vorticity confinement force may then be weaker or not needed.

When to use it

Use it as the default advection in a grid smoke or fire solver when the plain step smears too much. It adds one plain step per field and a limiter, and it keeps the large steps that make semi-Lagrangian solvers attractive. Use BFECC instead if the extra plain step is affordable and the field is smooth.

For liquid surfaces, use it on the level set together with a limiter, or use particles such as the particle level set or FLIP for thin features.

Pitfalls

  • Confusing it with the 1969 MacCormack method. That scheme is an explicit finite difference predictor-corrector for compressible flow. It has a CFL limit, and this method has none.
  • No limiter. The step creates new extrema at sharp edges. Smoke density goes negative, and a velocity field can gain energy.
  • The wrong range. The limiter must use the values of qq that the forward step mixed, not those of q^\hat q or a global range.
  • The reverse step. Use the same velocity field with −Δt-\Delta t. A reverse step with an updated velocity breaks the cancellation.
  • Boundaries. Near walls and inflow borders the clamped samples are not symmetric, and the order drops.
  • Stable is not accurate. The error constant does not shrink with a larger step, so a large step is not a cheap way to reach a given accuracy.

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.

macgrid.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A 2D MAC grid with sampling, divergence, pressure projection and advection.

This file is copied byte for byte into each impl/python folder that needs it.
Do not edit a copy. The reference is in
graphics-and-signals/fluid-animation/mac-grid/impl/python/.

Layout (the MAC layout of Harlow and Welch 1965, as in Bridson 2015):
- The grid has nx by ny cells of size dx. i is the x index, j is the y index.
- p[i][j] is at ((i + 1/2) dx, (j + 1/2) dx), for i < nx and j < ny.
- u[i][j] is at (i dx, (j + 1/2) dx), for i = 0..nx and j < ny.
- v[i][j] is at ((i + 1/2) dx, j dx), for i < nx and j = 0..ny.
- label[i][j] is FLUID, SOLID or AIR. A cell outside the grid counts as
  SOLID, so the border of the grid is a fixed wall.

Units are SI. In 2D a density rho is in kg/m^2 if you read the grid as a
sheet, or in kg/m^3 per unit depth; the code does not care.
"""

import math
from collections import deque

FLUID, SOLID, AIR = 0, 1, 2


class Grid:
    """The arrays of a MAC grid. All arrays are lists of lists indexed [i][j]."""

    def __init__(self, nx, ny, dx):
        if nx < 1 or ny < 1 or dx <= 0:
            raise ValueError("need nx >= 1, ny >= 1 and dx > 0")
        self.nx = nx
        self.ny = ny
        self.dx = float(dx)
        self.p = zeros(nx, ny)
        self.u = zeros(nx + 1, ny)
        self.v = zeros(nx, ny + 1)
        self.label = [[FLUID] * ny for _ in range(nx)]


def make_grid(nx, ny, dx):
    """A grid of nx by ny FLUID cells of size dx, with p, u and v set to zero."""
    return Grid(nx, ny, dx)


def zeros(a, b):
    """An a by b list of lists of 0.0."""
    return [[0.0] * b for _ in range(a)]


def copy_field(q):
    """A deep copy of a 2D field."""
    return [list(col) for col in q]


def cell_label(g, i, j):
    """The label of cell (i, j). A cell outside the grid is SOLID."""
    if 0 <= i < g.nx and 0 <= j < g.ny:
        return g.label[i][j]
    return SOLID


def cell_center(g, i, j):
    """The position ((i + 1/2) dx, (j + 1/2) dx) of the center of cell (i, j)."""
    return ((i + 0.5) * g.dx, (j + 0.5) * g.dx)


def sample(q, x, y, dx, ox, oy):
    """Bilinear sample at (x, y) of a field whose value q[a][b] is at ((a + ox) dx, (b + oy) dx).

    A point outside the sample positions is clamped to the nearest one, so the
    result is always a convex combination of at most four values of q.
    """
    na, nb = len(q), len(q[0])
    fx = x / dx - ox
    fy = y / dx - oy
    fx = min(max(fx, 0.0), float(na - 1))
    fy = min(max(fy, 0.0), float(nb - 1))
    a0 = min(int(math.floor(fx)), na - 2) if na > 1 else 0
    b0 = min(int(math.floor(fy)), nb - 2) if nb > 1 else 0
    a1 = a0 + 1 if na > 1 else a0
    b1 = b0 + 1 if nb > 1 else b0
    s = fx - a0
    t = fy - b0
    return ((1.0 - s) * ((1.0 - t) * q[a0][b0] + t * q[a0][b1])
            + s * ((1.0 - t) * q[a1][b0] + t * q[a1][b1]))


def u_at(g, x, y):
    """The x velocity at (x, y), by bilinear sampling of u."""
    return sample(g.u, x, y, g.dx, 0.0, 0.5)


def v_at(g, x, y):
    """The y velocity at (x, y), by bilinear sampling of v."""
    return sample(g.v, x, y, g.dx, 0.5, 0.0)


def vel_at(g, x, y):
    """The velocity (u, v) at (x, y)."""
    return (u_at(g, x, y), v_at(g, x, y))


def center_at(g, q, x, y):
    """Bilinear sample at (x, y) of a cell centered field q (same layout as p)."""
    return sample(q, x, y, g.dx, 0.5, 0.5)


def divergence(g):
    """The discrete divergence (u[i+1][j] - u[i][j] + v[i][j+1] - v[i][j]) / dx of every cell."""
    d = zeros(g.nx, g.ny)
    for i in range(g.nx):
        ui, ui1 = g.u[i], g.u[i + 1]
        vi = g.v[i]
        for j in range(g.ny):
            d[i][j] = (ui1[j] - ui[j] + vi[j + 1] - vi[j]) / g.dx
    return d


def max_fluid_divergence(g):
    """The largest |divergence| over the FLUID cells (0.0 if there is none)."""
    d = divergence(g)
    m = 0.0
    for i in range(g.nx):
        for j in range(g.ny):
            if g.label[i][j] == FLUID:
                m = max(m, abs(d[i][j]))
    return m


def is_solid_u_face(g, i, j):
    """True if the u face (i, j), between cells (i - 1, j) and (i, j), touches a SOLID cell."""
    return cell_label(g, i - 1, j) == SOLID or cell_label(g, i, j) == SOLID


def is_solid_v_face(g, i, j):
    """True if the v face (i, j), between cells (i, j - 1) and (i, j), touches a SOLID cell."""
    return cell_label(g, i, j - 1) == SOLID or cell_label(g, i, j) == SOLID


def set_solid_boundaries(g, solid_velocity=None):
    """Set the normal velocity on every face that touches a SOLID cell.

    A face on the border of the grid is a fixed wall and gets 0. A face inside
    the grid that touches a SOLID cell gets the normal component of
    solid_velocity(x, y) at the face center, or 0 if solid_velocity is None.
    """
    dx = g.dx
    for i in range(g.nx + 1):
        for j in range(g.ny):
            if is_solid_u_face(g, i, j):
                if i == 0 or i == g.nx or solid_velocity is None:
                    g.u[i][j] = 0.0
                else:
                    g.u[i][j] = float(solid_velocity(i * dx, (j + 0.5) * dx)[0])
    for i in range(g.nx):
        for j in range(g.ny + 1):
            if is_solid_v_face(g, i, j):
                if j == 0 or j == g.ny or solid_velocity is None:
                    g.v[i][j] = 0.0
                else:
                    g.v[i][j] = float(solid_velocity((i + 0.5) * dx, j * dx)[1])


def _fluid_system(g, dt, rho):
    """Index the FLUID cells and build the 5-point Laplacian and the right side.

    Returns (cells, diag, nbrs, b, has_air) where cells[k] = (i, j), diag[k] is
    the number of neighbors that are not SOLID, nbrs[k] lists the indices of the
    FLUID neighbors, and b[k] = -(rho dx / dt) (u[i+1][j] - u[i][j] + v[i][j+1] - v[i][j]).
    has_air[k] is True if the cell has an AIR neighbor.
    """
    idx = {}
    cells = []
    for i in range(g.nx):
        for j in range(g.ny):
            if g.label[i][j] == FLUID:
                idx[(i, j)] = len(cells)
                cells.append((i, j))
    diag, nbrs, b, has_air = [], [], [], []
    scale = -rho * g.dx / dt
    for (i, j) in cells:
        dcount = 0
        nb = []
        air = False
        for (a, c) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
            lab = cell_label(g, a, c)
            if lab == SOLID:
                continue
            dcount += 1
            if lab == FLUID:
                nb.append(idx[(a, c)])
            else:
                air = True
        diag.append(dcount)
        nbrs.append(nb)
        has_air.append(air)
        b.append(scale * (g.u[i + 1][j] - g.u[i][j] + g.v[i][j + 1] - g.v[i][j]))
    return cells, diag, nbrs, b, has_air


def _components(nbrs):
    """The connected components of the FLUID cells, as lists of indices."""
    n = len(nbrs)
    comp = [-1] * n
    out = []
    for s in range(n):
        if comp[s] >= 0:
            continue
        comp[s] = len(out)
        members = [s]
        queue = deque([s])
        while queue:
            k = queue.popleft()
            for m in nbrs[k]:
                if comp[m] < 0:
                    comp[m] = comp[s]
                    members.append(m)
                    queue.append(m)
        out.append(members)
    return out


def _apply(diag, nbrs, x):
    return [diag[k] * x[k] - sum(x[m] for m in nbrs[k]) for k in range(len(x))]


def pressure_solve(g, dt, rho, tol=1e-12, max_iter=None):
    """Solve the pressure Poisson equation by conjugate gradients and store p in g.p.

    The system is A p = b on the FLUID cells, with the 5-point Laplacian A
    (Neumann at SOLID faces, p = 0 in AIR cells) and
    b = -(rho dx^2 / dt) times the divergence. A connected group of FLUID cells
    with no AIR neighbor has a singular block: the mean of b is removed on it
    before the solve (the compatibility condition) and the mean of p is removed
    after it. CG stops when max |r| <= tol * max |b|. Returns the number of
    iterations. p is 0 in SOLID and AIR cells.
    """
    cells, diag, nbrs, b, has_air = _fluid_system(g, dt, rho)
    n = len(cells)
    g.p = zeros(g.nx, g.ny)
    if n == 0:
        return 0
    closed = [c for c in _components(nbrs) if not any(has_air[k] for k in c)]
    for c in closed:
        mean = sum(b[k] for k in c) / len(c)
        for k in c:
            b[k] -= mean
    bmax = max(abs(t) for t in b)
    x = [0.0] * n
    it = 0
    if bmax > 0.0:
        if max_iter is None:
            max_iter = max(100, 4 * n)
        r = list(b)
        d = list(r)
        rr = sum(t * t for t in r)
        while it < max_iter and max(abs(t) for t in r) > tol * bmax:
            q = _apply(diag, nbrs, d)
            dq = sum(d[k] * q[k] for k in range(n))
            if dq <= 0.0:
                break
            alpha = rr / dq
            for k in range(n):
                x[k] += alpha * d[k]
                r[k] -= alpha * q[k]
            rr_new = sum(t * t for t in r)
            beta = rr_new / rr
            rr = rr_new
            for k in range(n):
                d[k] = r[k] + beta * d[k]
            it += 1
    for c in closed:
        mean = sum(x[k] for k in c) / len(c)
        for k in c:
            x[k] -= mean
    for k, (i, j) in enumerate(cells):
        g.p[i][j] = x[k]
    return it


def subtract_pressure_gradient(g, dt, rho):
    """u[i][j] -= dt / (rho dx) (p[i][j] - p[i-1][j]), and the same for v.

    Only faces with a FLUID cell on at least one side and no SOLID cell are
    changed. The pressure of an AIR cell is 0.
    """
    s = dt / (rho * g.dx)
    for i in range(1, g.nx):
        for j in range(g.ny):
            a, c = g.label[i - 1][j], g.label[i][j]
            if a == SOLID or c == SOLID or (a != FLUID and c != FLUID):
                continue
            g.u[i][j] -= s * (g.p[i][j] - g.p[i - 1][j])
    for i in range(g.nx):
        for j in range(1, g.ny):
            a, c = g.label[i][j - 1], g.label[i][j]
            if a == SOLID or c == SOLID or (a != FLUID and c != FLUID):
                continue
            g.v[i][j] -= s * (g.p[i][j] - g.p[i][j - 1])


def project(g, dt, rho, tol=1e-12, solid_velocity=None):
    """Make the velocity divergence free in the FLUID cells. Returns the CG iteration count."""
    set_solid_boundaries(g, solid_velocity)
    it = pressure_solve(g, dt, rho, tol)
    subtract_pressure_gradient(g, dt, rho)
    return it


def backtrace(g, x, y, dt):
    """The start point of the path that ends at (x, y) after time dt, by an RK2 (midpoint) step.

    A negative dt traces forward in time.
    """
    u1, v1 = vel_at(g, x, y)
    xm, ym = x - 0.5 * dt * u1, y - 0.5 * dt * v1
    u2, v2 = vel_at(g, xm, ym)
    return (x - dt * u2, y - dt * v2)


def advect(g, q, dt, ox=0.5, oy=0.5):
    """Semi-Lagrangian advection of the field q by the velocity of g, for time dt.

    q[a][b] is at ((a + ox) dx, (b + oy) dx): the default is a cell centered
    field; use (0, 0.5) for u and (0.5, 0) for v. Each new value is the bilinear
    sample of q at the RK2 backtrace of its sample point. Returns a new field.
    """
    dx = g.dx
    out = zeros(len(q), len(q[0]))
    for a in range(len(q)):
        for b in range(len(q[0])):
            xb, yb = backtrace(g, (a + ox) * dx, (b + oy) * dx, dt)
            out[a][b] = sample(q, xb, yb, dx, ox, oy)
    return out


def advect_velocity(g, dt):
    """Advect u and v by the velocity of g. Returns (new_u, new_v); g is not changed."""
    return advect(g, g.u, dt, 0.0, 0.5), advect(g, g.v, dt, 0.5, 0.0)


def kinetic_energy(g, rho):
    """(1/2) rho dx^2 times the sum of u^2 and v^2 over all faces (per unit depth in 2D)."""
    s = sum(t * t for col in g.u for t in col) + sum(t * t for col in g.v for t in col)
    return 0.5 * rho * g.dx * g.dx * s
unconditionally_stable_maccormack.py 97 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unconditionally-stable-maccormack/. The authors are listed in prov/5R0MXZ.jsonl.

"""The unconditionally stable MacCormack method of Selle et al. (2008) on a 2D MAC grid.

The basic step A is the semi-Lagrangian advection of the shared helper
macgrid.py (an RK2 backtrace and a bilinear sample), and A^R is the same step
with -dt. The method is

    q_hat = A(q),  q_back = A^R(q_hat),  q_new = q_hat + (q - q_back) / 2,

followed by a limiter that keeps q_new in the range of the four values of q
that A mixed at the same point: "revert" (the paper's choice) uses q_hat
there, and "clamp" clamps to the range. A field q has q[a][b] at
((a + ox) dx, (b + oy) dx), as in macgrid.advect.
"""

import math

import macgrid


def semi_lagrangian(g, q, dt, ox=0.5, oy=0.5):
    """One semi-Lagrangian step of q by the velocity of g. A negative dt runs it backward."""
    return macgrid.advect(g, q, dt, ox, oy)


def stencil(q, x, y, dx, ox, oy):
    """The (up to) four values of q that macgrid.sample mixes at (x, y), with the same clamping."""
    na, nb = len(q), len(q[0])
    fx = min(max(x / dx - ox, 0.0), float(na - 1))
    fy = min(max(y / dx - oy, 0.0), float(nb - 1))
    a0 = min(int(math.floor(fx)), na - 2) if na > 1 else 0
    b0 = min(int(math.floor(fy)), nb - 2) if nb > 1 else 0
    a1 = a0 + 1 if na > 1 else a0
    b1 = b0 + 1 if nb > 1 else b0
    return (q[a0][b0], q[a0][b1], q[a1][b0], q[a1][b1])


def stencil_bounds(g, q, dt, ox=0.5, oy=0.5):
    """For each sample point, the min and the max of the values of q at the foot of its backtrace."""
    dx = g.dx
    lo = macgrid.zeros(len(q), len(q[0]))
    hi = macgrid.zeros(len(q), len(q[0]))
    for a in range(len(q)):
        for b in range(len(q[0])):
            xb, yb = macgrid.backtrace(g, (a + ox) * dx, (b + oy) * dx, dt)
            s = stencil(q, xb, yb, dx, ox, oy)  # @line L4
            lo[a][b], hi[a][b] = min(s), max(s)
    return lo, hi


def maccormack(g, q, dt, ox=0.5, oy=0.5, limiter="revert"):
    """One MacCormack step of q by the velocity of g. limiter is "revert", "clamp" or None. Returns a new field."""
    if limiter not in (None, "clamp", "revert"):
        raise ValueError("limiter must be None, 'clamp' or 'revert'")
    na, nb = len(q), len(q[0])
    fwd = semi_lagrangian(g, q, dt, ox, oy)  # @line L1
    back = semi_lagrangian(g, fwd, -dt, ox, oy)  # @line L2
    new = [[fwd[a][b] + 0.5 * (q[a][b] - back[a][b]) for b in range(nb)] for a in range(na)]  # @line L3
    if limiter is None:
        return new
    lo, hi = stencil_bounds(g, q, dt, ox, oy)
    for a in range(na):
        for b in range(nb):
            t = new[a][b]
            if not lo[a][b] <= t <= hi[a][b]:
                new[a][b] = fwd[a][b] if limiter == "revert" else min(max(t, lo[a][b]), hi[a][b])  # @line L5
    return new


def maccormack_velocity(g, dt, limiter="revert"):
    """The MacCormack step applied to u and to v, both moved by the old velocity. Returns (new_u, new_v)."""
    return maccormack(g, g.u, dt, 0.0, 0.5, limiter), maccormack(g, g.v, dt, 0.5, 0.0, limiter)


def constant_velocity(g, uc, vc):
    """Set every face of g to the constant velocity (uc, vc), walls included (for transport tests)."""
    g.u = [[float(uc)] * g.ny for _ in range(g.nx + 1)]
    g.v = [[float(vc)] * (g.ny + 1) for _ in range(g.nx)]


def rotation_velocity(g, omega, cx, cy):
    """Set u = -omega (y - cy) and v = omega (x - cx) at the face centers: a rigid rotation, divergence free on the MAC grid."""
    dx = g.dx
    g.u = [[-omega * ((j + 0.5) * dx - cy) for j in range(g.ny)] for _ in range(g.nx + 1)]
    g.v = [[omega * ((i + 0.5) * dx - cx) for _ in range(g.ny + 1)] for i in range(g.nx)]


def cell_field(g, f):
    """The cell centered field f(x, y)."""
    dx = g.dx
    return [[f((i + 0.5) * dx, (j + 0.5) * dx) for j in range(g.ny)] for i in range(g.nx)]


def max_error(q, r):
    return max(abs(a - b) for c1, c2 in zip(q, r) for a, b in zip(c1, c2))
test_unconditionally_stable_maccormack.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unconditionally-stable-maccormack/. The authors are listed in prov/5R0MXZ.jsonl.

"""Tests of the unconditionally stable MacCormack method on the MAC grid of macgrid.py."""

import cmath
import math
import random

import pytest

import macgrid
import unconditionally_stable_maccormack as U


def bump(x, y, cx, cy, r):
    """A smooth bump (1 - |x - c|^2 / r^2)^4 with compact support of radius r."""
    t = ((x - cx) ** 2 + (y - cy) ** 2) / (r * r)
    return (1.0 - t) ** 4 if t < 1.0 else 0.0


def move_bump(n, steps, limiter, plain=False):
    """Move the bump of radius 0.3 by the constant velocity (1, 0.5) m/s for 0.25 s; return the max error."""
    g = macgrid.make_grid(n, n, 1.0 / n)
    U.constant_velocity(g, 1.0, 0.5)
    dt = 0.25 / steps
    q = U.cell_field(g, lambda x, y: bump(x, y, 0.35, 0.4, 0.3))
    for _ in range(steps):
        q = U.semi_lagrangian(g, q, dt) if plain else U.maccormack(g, q, dt, limiter=limiter)
    return U.max_error(q, U.cell_field(g, lambda x, y: bump(x, y, 0.6, 0.525, 0.3)))


def test_constant_field_is_exact():
    rng = random.Random(1)
    g = macgrid.make_grid(8, 8, 0.125)
    for col in g.u + g.v:
        for k in range(len(col)):
            col[k] = rng.uniform(-3.0, 3.0)
    q = [[0.7] * 8 for _ in range(8)]
    for lim in (None, "clamp", "revert"):
        assert U.max_error(U.maccormack(g, q, 0.2, limiter=lim), q) < 1e-14


def test_interior_matches_the_fourier_symbol():
    n = 40
    g = macgrid.make_grid(n, 1, 1.0)
    damped_more = False
    for c in (0.3, 1.5, 2.7):
        U.constant_velocity(g, c, 0.0)
        m, phi = int(c), c - int(c)
        for th in (0.4, 1.3, 2.9):
            q = [[math.cos(th * a)] for a in range(n)]
            out = U.maccormack(g, q, 1.0, limiter=None)
            amp = cmath.exp(-1j * m * th) * ((1.0 - phi) + phi * cmath.exp(-1j * th))
            sym = amp + (1.0 - abs(amp) ** 2) / 2.0
            r = 2 * (m + 1) + 1
            assert max(abs(out[a][0] - (sym * cmath.exp(1j * th * a)).real) for a in range(r, n - r)) < 1e-13
            assert abs(sym) <= 1.0
            damped_more = damped_more or abs(sym) < abs(amp)
    assert damped_more  # some modes are damped more than by the plain step


def test_second_order_on_a_smooth_bump():
    sl16, sl32 = move_bump(16, 3, None, True), move_bump(32, 6, None, True)
    mc16, mc32 = move_bump(16, 3, None), move_bump(32, 6, None)
    rv32 = move_bump(32, 6, "revert")
    assert abs(sl32 - 0.1062) < 1e-4 and abs(mc32 - 0.04924) < 1e-5
    assert 0.8 < math.log2(sl16 / sl32) < 1.0
    assert math.log2(mc16 / mc32) > 1.6
    assert mc32 < rv32 < sl32 / 2.0


def test_error_does_not_shrink_with_a_larger_step():
    e12, e6 = move_bump(32, 12, None), move_bump(32, 6, None)
    assert abs(e12 - 0.0486) < 1e-4 and abs(e6 - 0.0492) < 1e-4
    assert move_bump(32, 2, None) < 1e-14  # CFL number 4: whole cells, exact


def test_rotation_quarter_turn():
    n = 32
    g = macgrid.make_grid(n, n, 1.0 / n)
    U.rotation_velocity(g, 2.0 * math.pi, 0.5, 0.5)
    q0 = U.cell_field(g, lambda x, y: bump(x, y, 0.5, 0.75, 0.2))
    exact = U.cell_field(g, lambda x, y: bump(x, y, 0.25, 0.5, 0.2))
    q = q0
    for _ in range(16):
        q = U.maccormack(g, q, 1.0 / 64.0)
    assert abs(U.max_error(q, exact) - 0.1876) < 1e-3
    assert min(map(min, q)) >= 0.0 and max(map(max, q)) <= 1.0


def test_limiters_keep_the_range_of_a_step():
    g = macgrid.make_grid(24, 24, 1.0 / 24.0)
    U.constant_velocity(g, 1.0, 0.4)
    q0 = U.cell_field(g, lambda x, y: 1.0 if 0.2 < x < 0.5 and 0.3 < y < 0.6 else 0.0)
    q = q0
    for _ in range(5):
        q = U.maccormack(g, q, 0.03, limiter=None)
    assert max(map(max, q)) > 1.3 and min(map(min, q)) < -0.25
    for lim in ("clamp", "revert"):
        q = q0
        for _ in range(5):
            lo, hi = U.stencil_bounds(g, q, 0.03)
            q = U.maccormack(g, q, 0.03, limiter=lim)
            assert all(lo[a][b] <= q[a][b] <= hi[a][b] for a in range(24) for b in range(24))
        assert 0.0 <= min(map(min, q)) and max(map(max, q)) <= 1.0


def test_velocity_and_errors():
    g = macgrid.make_grid(6, 6, 1.0 / 6.0)
    U.constant_velocity(g, 0.8, -0.3)
    u, v = U.maccormack_velocity(g, 0.5)
    assert U.max_error(u, g.u) < 1e-14 and U.max_error(v, g.v) < 1e-14
    with pytest.raises(ValueError):
        U.maccormack(g, [[0.0] * 6 for _ in range(6)], 0.1, limiter="minmod")

History

The back and forth idea came from Dupont and Liu (2003), who used it for level sets as BFECC. Kim, Liu, Llamas and Rossignac then used BFECC with semi-Lagrangian steps in fluid animation. In 2008, Selle, Fedkiw, Kim, Liu and Rossignac observed that the error estimate of BFECC can correct the forward result directly. This removes one of the three steps and gives a scheme with the predictor-corrector form of MacCormack's method. They added the limiter that keeps it bounded for any step and showed second order convergence in their tests.

References

  1. Andrew Selle, Ronald Fedkiw, ByungMoon Kim, Yingjie Liu and Jarek Rossignac, An unconditionally stable MacCormack method, Journal of Scientific Computing 35(2-3), 350-371, 2008, the two-step method, its relation to BFECC and to Runge-Kutta on an ordinary differential equation, the limiter, and the convergence tables
  2. Todd F. Dupont and Yingjie Liu, Back and forth error compensation and correction methods for removing errors induced by uneven gradients of the level set function, Journal of Computational Physics 190(1), 311-324, 2003, the BFECC step that the method simplifies
  3. Robert Bridson, Fluid Simulation for Computer Graphics, second edition, CRC Press, 2015, the chapter Advection Algorithms

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.limiter
  • a full proof of time.step
  • 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