Algorithm Search⌘K

Algorithmadvanced

Back and forth error compensation and correction

Also called BFECC.

Advect forward and back, take half the difference from the start as the error, and advect the corrected field. It is second order for smooth fields and needs a limiter at sharp edges.

Time
Θ(g) limiter · step
Space
Θ(g) extra
Where
g = the number of grid samples of the field
Properties
not conservativedeterministicnot exactunconditionally stable
Origin
Todd F. Dupont, Yingjie Liu, 2003

Back and forth error compensation and correction (BFECC) makes a first order advection step second order. It moves the field forward one step, moves the result back, and compares it with the start. If the step had no error, the round trip would return the start. Half of the difference is an estimate of the error of one step, so BFECC adds it to the start and moves the corrected field forward. With semi-Lagrangian steps, as in stable fluids, the result is second order for smooth fields, damps much less, and still has no step limit under a constant velocity. It can overshoot at sharp edges, so it is used with a limiter.

In plain words

Moving a picture of smoke one step with the plain method blurs it a little. BFECC measures that blur.

It moves the picture one step forward and then one step back with the same method. A perfect method would give back the start. The real method gives a picture that has been blurred twice, once each way. So the difference between the start and the round trip is about two blurs, and half of it is one blur.

BFECC adds that half to the start, which sharpens it in advance, and then moves the sharpened picture forward. The blur of this last move cancels most of the sharpening.

Near a hard edge the sharpening can push values past the old range. A limiter catches those values.

The problem

Given a field qq on a grid (smoke density, temperature, a level set or a velocity component), 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. Plain semi-Lagrangian advection is stable for any Δt\Delta t but first order, and its numerical diffusion smears small features. The goal is a step that keeps them, at a cost that is a small multiple of the plain step.

The algorithm

Let AA be the plain semi-Lagrangian step: trace back from each sample point and interpolate the old field there. Let ARA^R be the same step with −Δt-\Delta t, which traces forward.

  1. BFECC(q, u, dt)
  2. 1q_hat <- A(q) ▷ forward, the plain step
  3. 2q_check <- A^R(q_hat) ▷ back to the start time
  4. 3q_bar <- q + (q - q_check) / 2 ▷ subtract half the round trip error
  5. 4q_new <- A(q_bar) ▷ forward again
  6. 5limiter: where q_new leaves the range of the old values at the foot, clamp it (or use q_hat)

Why half. If one step has the error ee, so that Aq≈qexact+eA q \approx q_{\text{exact}} + e, then the round trip has about 2e2e: ARAq≈q+2eA^R A q \approx q + 2e. Line L3 gives qˉ=q−e\bar q = q - e. Line L4 adds the error ee of one more step, so Aqˉ≈qexactA \bar q \approx q_{\text{exact}}. The proof page makes this exact for a constant velocity: the second order term of the error cancels.

The velocity. All three steps use the same velocity field, the one at the start of the step. To advect the velocity itself on a MAC grid, apply BFECC to uu and to vv with their own sample points.

The limiter (L5). The corrected value at a point should lie between the values that the plain step mixes at the same point. The "clamp" limiter clamps it into that range. The "revert" limiter uses the plain value q^\hat q there instead. Selle and colleagues describe both for the MacCormack variant, and they apply to BFECC in the same way.

Example

One step by hand. A row of 7 cells with Δx=1\Delta x = 1 m, a constant velocity 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 gives (Aq)a=12qa+12qa−1(A q)_a = \frac12 q_a + \frac12 q_{a-1}, and the reverse step gives 12qa+12qa+1\frac12 q_a + \frac12 q_{a+1}. Start with a spike at cell 3:

cell 1 2 3 4 5 6
qq 0 0 1 0 0 0
q^=Aq\hat q = A q (L1) 0 0 0.5 0.5 0 0
qˇ=ARq^\check q = A^R \hat q (L2) 0 0.25 0.5 0.25 0 0
qˉ\bar q (L3) 0 -0.125 1.25 -0.125 0 0
qnew=Aqˉq^{\text{new}} = A \bar q (L4) 0 -0.0625 0.5625 0.5625 -0.0625 0
with the limiter (L5) 0 0 0.5625 0.5625 0 0

The exact solution moves the spike to the position 3.53.5. The plain step splits it into two halves. BFECC keeps more height at the peak, 0.56250.5625, but it dips below 0 next to it. At cell 2 the plain step mixes cells 1 and 2, both 0, so the limiter sets the value to 0. The sum is 1 before the limiter and 1.125 after it, so the limited step does not keep the total.

Order, measured. A smooth 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. The largest errors are:

method 16 by 16 32 by 32 observed order
plain semi-Lagrangian 0.197 0.106 0.89
BFECC 0.0364 0.00684 2.41
BFECC with clamp 0.0680 0.0153 2.15
BFECC with revert 0.120 0.0364 1.72

At 32 cells BFECC is 15 times more accurate than the plain step. The limiters act near the top of the bump, where the corrected value overshoots the stencil, and lose some of the gain.

Rotation, measured. A bump of radius 0.2 m turns a quarter turn about the center of a 32 by 32 grid in 16 steps, at a CFL number of about 1.51.5 at the edge of the grid. The largest error is 0.3750.375 for the plain step, whose peak falls from 1 to 0.600.60, against 0.0590.059 for BFECC and 0.0760.076 for BFECC with clamp.

Correctness

The claims are proved in proofs/correctness.md.

  1. Constants. A constant field stays exactly the same, with or without the limiter.
  2. Stability. On a periodic grid with a constant velocity, BFECC multiplies each Fourier mode by G=A(3−∣A∣2)/2G = A (3 - |A|^2)/2, where AA is the factor of the plain step. For every CFL number, ∣A∣≤∣G∣≤1|A| \le |G| \le 1. So BFECC damps less than the plain step and never amplifies a mode.
  3. Order. Under the same conditions, the second order term of the error cancels, and the error after a fixed time is O(Δx2)O(\Delta x^2) at a fixed CFL number. The plain step is O(Δx)O(\Delta x). The same holds in 2D.
  4. Limiter. With "clamp" or "revert", each new value lies in the range of the old values at the foot of its backtrace, so the new field stays between the old minimum and maximum.

Without the limiter there is no maximum principle: a square of height 1 reaches 1.241.24 and −0.12-0.12 after five steps. Where the limiter acts, the step is no longer linear and the order drops.

The tests check that the code matches the symbol GG to 10−1310^{-13} in the interior of a 1D grid, the measured orders, the rotation, the range of the limited values, and that a constant velocity field advects itself exactly.

Proof: BFECC 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, which traces forward. The BFECC step is

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

All statements are in exact arithmetic.

Lemma 1 (constants). If qq is constant, the BFECC step returns the same constant, with or without the limiter.

Proof. Each value of AqA q is a convex combination of values of qq, so AA and ARA^R keep a constant κ\kappa. Then q^=qˇ=κ\hat q = \check q = \kappa, qˉ=κ+12(κ−κ)=κ\bar q = \kappa + \frac12(\kappa - \kappa) = \kappa and Aqˉ=κA \bar q = \kappa. The stencil range at every point is [κ,κ][\kappa, \kappa], so the limiter changes nothing. □\square

Setting for the next results. Take a periodic grid of spacing Δx\Delta x in 1D and a constant velocity u>0u > 0. Let 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 the foot of sample aa is at a−ca - c in cell units, between samples a−m−1a - m - 1 and a−ma - m. So

(Aq)a=(1−φ) qa−m+φ qa−m−1,(ARq)a=(1−φ) qa+m+φ qa+m+1.(A q)_a = (1 - \varphi)\, q_{a - m} + \varphi\, q_{a - m - 1}, \qquad (A^R q)_a = (1 - \varphi)\, q_{a + m} + \varphi\, q_{a + m + 1}.

A Fourier mode qa=eiθaq_a = e^{\mathrm i \theta a}, θ∈[−π,π]\theta \in [-\pi, \pi], is multiplied by A(θ)=e−imθ(1−φ+φe−iθ)A(\theta) = e^{-\mathrm i m \theta} \left(1 - \varphi + \varphi e^{-\mathrm i \theta}\right) under AA, and by A(θ)‾\overline{A(\theta)} under ARA^R. The test file checks on a grid of 40 cells that the interior values of one BFECC step of cos⁡(θa)\cos(\theta a) equal the real part of the symbol below to 10−1310^{-13}, for c∈{0.3,1.5,2.7}c \in \{0.3, 1.5, 2.7\} and three values of θ\theta. On a non-periodic grid, these results hold at the samples whose three backtraces stay inside the grid.

Lemma 2 (the symbol). One BFECC step multiplies the mode by

G(θ)=A(1+12(1−∣A∣2))=A 3−∣A∣22,∣A∣2=1−2φ(1−φ)(1−cos⁡θ).G(\theta) = A \left(1 + \tfrac12 (1 - |A|^2)\right) = A\, \frac{3 - |A|^2}{2}, \qquad |A|^2 = 1 - 2 \varphi (1 - \varphi)(1 - \cos \theta).

Proof. q^=Aq\hat q = A q and qˇ=AˉAq=∣A∣2q\check q = \bar A A q = |A|^2 q for the mode. Then qˉ=(1+12(1−∣A∣2))q\bar q = (1 + \frac12 (1 - |A|^2)) q, and the last step multiplies by AA. For the modulus, ∣1−φ+φe−iθ∣2=(1−φ)2+φ2+2φ(1−φ)cos⁡θ|1 - \varphi + \varphi e^{-\mathrm i \theta}|^2 = (1 - \varphi)^2 + \varphi^2 + 2 \varphi (1 - \varphi) \cos \theta, which is the formula. □\square

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

Proof. Let s=∣A∣∈[0,1]s = |A| \in [0, 1]. Then ∣G∣=f(s)|G| = f(s) with f(s)=s(3−s2)/2f(s) = s (3 - s^2)/2. f′(s)=32(1−s2)≥0f'(s) = \frac32 (1 - s^2) \ge 0, so ff increases on [0,1][0, 1] from f(0)=0f(0) = 0 to f(1)=1f(1) = 1, so f(s)≤1f(s) \le 1. Also f(s)−s=12s(1−s2)≥0f(s) - s = \frac12 s (1 - s^2) \ge 0. By Parseval, a step that multiplies each mode by a factor of modulus at most 1 does not increase the ℓ2\ell^2 norm. □\square

So BFECC damps every mode less than plain semi-Lagrangian advection, and never amplifies one. It is not stable in the maximum norm: the test file moves a square of height 1 for five steps and gets values from −0.124-0.124 to 1.2401.240.

Theorem 2 (second order). For a fixed φ\varphi,

G(θ)=e−icθexp⁡(i φ(1−φ)(1−2φ)6 θ3+O(θ4)),G(\theta) = e^{-\mathrm i c \theta} \exp\left(\mathrm i\, \frac{\varphi (1 - \varphi)(1 - 2\varphi)}{6}\, \theta^3 + O(\theta^4)\right),

while plain semi-Lagrangian advection has A(θ)=e−icθexp⁡(−φ(1−φ)2θ2+O(θ3))A(\theta) = e^{-\mathrm i c \theta} \exp\left(-\frac{\varphi(1 - \varphi)}{2} \theta^2 + O(\theta^3)\right). Let q(x)=∑kq^keikxq(x) = \sum_k \hat q_k e^{\mathrm i k x} be a periodic trigonometric polynomial (a finite sum), and let Δx\Delta x be small enough that ∣kΔx∣≤π|k \Delta x| \le \pi for each of its modes. At a fixed CFL number cc, the error of BFECC after the time TT is O(Δx2)O(\Delta x^2), and the error of plain semi-Lagrangian advection is O(Δx)O(\Delta x) when φ≠0\varphi \ne 0.

Proof. Write 1−φ+φe−iθ=1+z1 - \varphi + \varphi e^{-\mathrm i \theta} = 1 + z with z=φ(e−iθ−1)=φ(−iθ−12θ2+i6θ3+O(θ4))z = \varphi (e^{-\mathrm i \theta} - 1) = \varphi(-\mathrm i \theta - \frac12 \theta^2 + \frac{\mathrm i}{6} \theta^3 + O(\theta^4)). Then z2=φ2(−θ2+iθ3)+O(θ4)z^2 = \varphi^2 (-\theta^2 + \mathrm i \theta^3) + O(\theta^4) and z3=iφ3θ3+O(θ4)z^3 = \mathrm i \varphi^3 \theta^3 + O(\theta^4), so

log⁡(1+z)=z−12z2+13z3+O(θ4)=−iφθ−12φ(1−φ)θ2+i6φ(1−φ)(1−2φ)θ3+O(θ4).\log(1 + z) = z - \tfrac12 z^2 + \tfrac13 z^3 + O(\theta^4) = -\mathrm i \varphi \theta - \tfrac12 \varphi (1 - \varphi) \theta^2 + \tfrac{\mathrm i}{6} \varphi (1 - \varphi)(1 - 2 \varphi) \theta^3 + O(\theta^4).

With e−imθe−iφθ=e−icθe^{-\mathrm i m \theta} e^{-\mathrm i \varphi \theta} = e^{-\mathrm i c \theta} this gives the form of AA. By Lemma 2, 3−∣A∣22=1+φ(1−φ)(1−cos⁡θ)=exp⁡(12φ(1−φ)θ2+O(θ4))\frac{3 - |A|^2}{2} = 1 + \varphi (1 - \varphi)(1 - \cos \theta) = \exp\left(\frac12 \varphi (1 - \varphi) \theta^2 + O(\theta^4)\right). The product cancels the θ2\theta^2 term and gives the form of GG.

The function h(θ)=(G(θ)eicθ−1)/θ3h(\theta) = (G(\theta) e^{\mathrm i c \theta} - 1) / \theta^3 is continuous on [−π,π][-\pi, \pi] (the numerator is smooth and vanishes to third order at 0), so ∣G(θ)−e−icθ∣≤C∣θ∣3|G(\theta) - e^{-\mathrm i c \theta}| \le C |\theta|^3 for a constant CC that depends on φ\varphi. On the grid, the mode eikxe^{\mathrm i k x} is eiθae^{\mathrm i \theta a} with θ=kΔx\theta = k \Delta x. Since ∣G∣≤1|G| \le 1 and ∣e−icθ∣=1|e^{-\mathrm i c \theta}| = 1, ∣GN−e−iNcθ∣≤N∣G−e−icθ∣|G^N - e^{-\mathrm i N c \theta}| \le N |G - e^{-\mathrm i c \theta}| by the telescoping sum GN−EN=∑jGj(G−E)EN−1−jG^N - E^N = \sum_{j} G^{j} (G - E) E^{N - 1 - j}. After N=Tu/(cΔx)N = T u / (c \Delta x) steps, the error of each sample is at most

∑k∣q^k∣ NC∣kΔx∣3=TuCcΔx2∑k∣k∣3∣q^k∣,\sum_k |\hat q_k| \, N C |k \Delta x|^3 = \frac{T u C}{c} \Delta x^2 \sum_k |k|^3 |\hat q_k|,

which is O(Δx2)O(\Delta x^2). A smooth periodic function is close to such a polynomial, and its coefficients decay fast enough for the same bound. For plain semi-Lagrangian advection, the θ2\theta^2 term does not cancel, the same argument gives O(Δx)O(\Delta x), and the stable fluids proof gives a direct bound. □\square

The error constant has the factor 1−2φ1 - 2\varphi, so for φ=12\varphi = \frac12 the θ3\theta^3 term vanishes and the error is smaller still. For φ=0\varphi = 0 both methods are exact. In 2D with a constant velocity, the bilinear sample is the product of two 1D samples, so A=AxAyA = A_x A_y and AR=A‾A^R = \overline{A}. Lemma 2 and Theorem 1 hold with the same proof, since they use only ∣A∣≤1|A| \le 1 and AR=AˉA^R = \bar A. In Theorem 2, 1−∣A∣2=φx(1−φx)θx2+φy(1−φy)θy2+O(∣θ∣4)1 - |A|^2 = \varphi_x(1 - \varphi_x)\theta_x^2 + \varphi_y (1 - \varphi_y) \theta_y^2 + O(|\theta|^4) 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 moves a smooth bump of radius 0.3 with the velocity (1,0.5)(1, 0.5) m/s for 0.25 s at cx=4/3c_x = 4/3. Between 16 and 32 cells, the observed order is 2.41 for BFECC and 0.89 for plain semi-Lagrangian advection, and the errors at 32 cells are 0.006840.00684 and 0.10620.1062.

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. With the "clamp" or the "revert" 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 and any Δt\Delta t.

Proof. With "clamp", a value outside [ℓa,ha][\ell_a, h_a] is replaced by the nearest end of the interval. With "revert", it is replaced by q^a=(Aq)a\hat q_a = (A q)_a, which is a convex combination of those four values (Lemma 1 of the stable fluids proof), so it lies in [ℓa,ha][\ell_a, h_a]. A value inside the interval stays. □\square

The limiter is not linear, so Theorems 1 and 2 do not apply where it acts. It acts at discontinuities and also at smooth maxima, where the second order value overshoots the stencil. The test file measures the order on the smooth bump as 2.15 with "clamp" and 1.72 with "revert". At a discontinuity the order drops below the smooth order for all of these methods.

Complexity

Let gg be the number of samples of the field. Each plain step costs Θ(g)\Theta(g): one backtrace and one bilinear sample per point. BFECC does three plain steps and one sweep for line L3, so it costs about three times the plain step. The limiter needs the range of the stencil at the foot of each forward backtrace; the code here recomputes the backtraces, which adds one more pass, and an implementation can store the feet of line L1 instead. The extra space is Θ(g)\Theta(g) for the fields q^\hat q, qˇ\check q and qˉ\bar q.

Properties

  • Second order for smooth fields under a constant velocity, in space and time at a fixed CFL number.
  • No step limit in the linear analysis, and a maximum principle with the limiter, for any velocity.
  • Less dissipation. In the bump test above, the error at 32 cells drops from 0.1060.106 to 0.00680.0068.
  • Not conservative. Neither the plain step nor BFECC keeps the sum of the field, and the limiter can change it more.
  • Not monotone without the limiter. New extrema appear next to sharp edges.
  • Generic. BFECC wraps any advection step AA for which a reverse step exists. It does not need to know how AA works.

Variants and improvements

  • MacCormack. The unconditionally stable MacCormack method of Selle and colleagues reuses the error estimate of line L3 to correct q^\hat q directly. It needs two plain steps instead of three and has the same order. It is not the 1969 MacCormack method for compressible flow.
  • Level sets. Dupont and Liu first used BFECC to advect a level set function, where it reduces the errors caused by uneven gradients. Their later paper analyzes BFECC for semi-Lagrangian schemes.
  • Fluids. Kim and colleagues used BFECC with semi-Lagrangian steps for the advection in fluid simulation. Applied to the velocity, it keeps more swirl, so a weaker vorticity confinement force may be enough.
  • Other limiters. A limiter may clamp to the stencil range, revert to the plain step, or blend the two by a smooth weight.
  • Higher order interpolation. A cubic or WENO sample in place of the bilinear one also reduces the error. It can be combined with BFECC.

When to use it

Use BFECC when plain semi-Lagrangian advection smears smoke, fire or a level set too much, and a finer grid is too expensive. It drops into an existing solver: it calls the plain step three times and needs no new data structure. Use it with a limiter for fields with sharp edges, such as smoke density or a liquid level set.

If the cost of three plain steps matters, use the MacCormack variant. For liquids with thin sheets and splashes, particles such as FLIP or the particle level set keep more detail than any grid advection.

Pitfalls

  • No limiter. The corrected field overshoots near edges. Smoke density can go negative, and a velocity can gain energy.
  • The wrong reverse step. ARA^R must trace forward with the same velocity field, that is, use −Δt-\Delta t. Using a different field breaks the cancellation.
  • Boundaries. The analysis holds where all three backtraces stay inside the domain. Near walls and inflow borders the clamped samples are not symmetric, and the step loses its order there.
  • The range of the limiter. Take the range from the values of qq that the first forward step mixes at the same point, not from qˉ\bar q or from a fixed global range.
  • Order is not everything. A second order step can still be wrong at a large CFL number. The error constant grows with the fractional part of the CFL number. Stable is not accurate.

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.

bfecc.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bfecc/. The authors are listed in prov/Z26PRS.jsonl.

"""Back and forth error compensation and correction (BFECC) on a 2D MAC grid.

The basic step is the semi-Lagrangian advection of the shared helper
macgrid.py: an RK2 backtrace and a bilinear sample. BFECC calls it three
times: forward, backward, and forward again on a corrected field. A field q
has q[a][b] at ((a + ox) dx, (b + oy) dx), as in macgrid.advect; the default
is a cell centered field, (0, 0.5) is u and (0.5, 0) is v.

The optional limiter keeps each new value inside the range of the four old
values that the plain semi-Lagrangian step mixes at the same point. "clamp"
clamps to that range; "revert" uses the plain semi-Lagrangian value instead.
"""

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 (macgrid.advect). 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)
            lo[a][b], hi[a][b] = min(s), max(s)
    return lo, hi


def limit(new, plain, lo, hi, limiter):
    """Apply the limiter to new: None keeps it, "clamp" clamps it to [lo, hi], "revert" uses plain outside [lo, hi]."""
    if limiter is None:
        return new
    if limiter not in ("clamp", "revert"):
        raise ValueError("limiter must be None, 'clamp' or 'revert'")
    out = macgrid.zeros(len(new), len(new[0]))
    for a in range(len(new)):
        for b in range(len(new[0])):
            t, l, h = new[a][b], lo[a][b], hi[a][b]
            if l <= t <= h:
                out[a][b] = t
            elif limiter == "clamp":
                out[a][b] = min(max(t, l), h)  # @line L5
            else:
                out[a][b] = plain[a][b]
    return out


def bfecc(g, q, dt, ox=0.5, oy=0.5, limiter=None):
    """One BFECC step of q by the velocity of g. Returns a new field; q and g are not changed."""
    fwd = semi_lagrangian(g, q, dt, ox, oy)  # @line L1
    back = semi_lagrangian(g, fwd, -dt, ox, oy)  # @line L2
    bar = [[q[a][b] + 0.5 * (q[a][b] - back[a][b]) for b in range(len(q[0]))]  # @line L3
           for a in range(len(q))]
    new = semi_lagrangian(g, bar, dt, ox, oy)  # @line L4
    if limiter is None:
        return new
    lo, hi = stencil_bounds(g, q, dt, ox, oy)
    return limit(new, fwd, lo, hi, limiter)


def bfecc_velocity(g, dt, limiter=None):
    """BFECC applied to u and to v, both moved by the old velocity. Returns (new_u, new_v)."""
    return bfecc(g, g.u, dt, 0.0, 0.5, limiter), bfecc(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))
macgrid.py 347 lines
# 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
test_bfecc.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bfecc/. The authors are listed in prov/Z26PRS.jsonl.

"""Tests of BFECC advection on the MAC grid of macgrid.py."""

import cmath
import math
import random

import pytest

import macgrid
import bfecc as B


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)
    B.constant_velocity(g, 1.0, 0.5)
    dt = 0.25 / steps
    q = B.cell_field(g, lambda x, y: bump(x, y, 0.35, 0.4, 0.3))
    for _ in range(steps):
        q = B.semi_lagrangian(g, q, dt) if plain else B.bfecc(g, q, dt, limiter=limiter)
    return B.max_error(q, B.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"):
        out = B.bfecc(g, q, 0.2, limiter=lim)
        assert B.max_error(out, q) < 1e-14


def test_interior_matches_the_fourier_symbol():
    n = 40
    g = macgrid.make_grid(n, 1, 1.0)
    for c in (0.3, 1.5, 2.7):
        B.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 = B.bfecc(g, q, 1.0)
            amp = cmath.exp(-1j * m * th) * ((1.0 - phi) + phi * cmath.exp(-1j * th))
            sym = amp * (3.0 - abs(amp) ** 2) / 2.0
            r = 3 * (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(amp) <= abs(sym) <= 1.0


def test_second_order_on_a_smooth_bump():
    sl16, sl32 = move_bump(16, 3, None, True), move_bump(32, 6, None, True)
    bf16, bf32 = move_bump(16, 3, None), move_bump(32, 6, None)
    cl16, cl32 = move_bump(16, 3, "clamp"), move_bump(32, 6, "clamp")
    rv32 = move_bump(32, 6, "revert")
    assert abs(sl32 - 0.1062) < 1e-4 and abs(bf32 - 0.00684) < 1e-5
    assert 0.8 < math.log2(sl16 / sl32) < 1.0
    assert math.log2(bf16 / bf32) > 2.3
    assert math.log2(cl16 / cl32) > 2.0
    assert bf32 < cl32 < rv32 < sl32


def test_rotation_quarter_turn():
    n = 32
    g = macgrid.make_grid(n, n, 1.0 / n)
    B.rotation_velocity(g, 2.0 * math.pi, 0.5, 0.5)
    assert macgrid.max_fluid_divergence(g) < 1e-12
    q0 = B.cell_field(g, lambda x, y: bump(x, y, 0.5, 0.75, 0.2))
    exact = B.cell_field(g, lambda x, y: bump(x, y, 0.25, 0.5, 0.2))
    err = {}
    for name, lim in (("sl", None), ("bfecc", None), ("clamp", "clamp")):
        q = q0
        for _ in range(16):
            q = B.semi_lagrangian(g, q, 1.0 / 64.0) if name == "sl" else B.bfecc(g, q, 1.0 / 64.0, limiter=lim)
        err[name] = B.max_error(q, exact)
        if name == "clamp":
            assert min(map(min, q)) >= 0.0
    assert err["bfecc"] < err["clamp"] < err["sl"] / 4.0
    assert abs(err["sl"] - 0.3754) < 1e-3 and abs(err["bfecc"] - 0.0594) < 1e-3


def test_limiters_keep_the_range_of_a_step():
    g = macgrid.make_grid(24, 24, 1.0 / 24.0)
    B.constant_velocity(g, 1.0, 0.4)
    q0 = B.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 = B.bfecc(g, q, 0.03)
    assert max(map(max, q)) > 1.2 and min(map(min, q)) < -0.1
    for lim in ("clamp", "revert"):
        q = q0
        for _ in range(5):
            lo, hi = B.stencil_bounds(g, q, 0.03)
            q = B.bfecc(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_semi_lagrangian_stays_in_its_stencil():
    rng = random.Random(2)
    g = macgrid.make_grid(10, 10, 0.1)
    for col in g.u + g.v:
        for k in range(len(col)):
            col[k] = rng.uniform(-2.0, 2.0)
    q = [[rng.random() for _ in range(10)] for _ in range(10)]
    lo, hi = B.stencil_bounds(g, q, 0.13)
    out = B.semi_lagrangian(g, q, 0.13)
    assert all(lo[a][b] - 1e-15 <= out[a][b] <= hi[a][b] + 1e-15 for a in range(10) for b in range(10))


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

History

Todd Dupont and Yingjie Liu introduced BFECC in 2003 to repair level set functions whose gradients become uneven during advection. They analyzed it for semi-Lagrangian schemes in a later paper. Byungmoon Kim, Yingjie Liu, Ignacio Llamas and Jarek Rossignac used BFECC with semi-Lagrangian steps for the advection in fluid simulation, in a paper published in 2007. In 2008, Andrew Selle, Ronald Fedkiw, ByungMoon Kim, Yingjie Liu and Jarek Rossignac derived the cheaper MacCormack variant and described its limiters.

References

  1. 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 for the level set function
  2. Byungmoon Kim, Yingjie Liu, Ignacio Llamas and Jarek Rossignac, Advections with significantly reduced dissipation and diffusion, IEEE Transactions on Visualization and Computer Graphics 13(1), 135-144, 2007, BFECC with semi-Lagrangian steps for the advection in fluid simulation
  3. 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 description of BFECC with three advections, the limiter, and the convergence tables
  4. Todd F. Dupont and Yingjie Liu, Back and forth error compensation and correction methods for semi-Lagrangian schemes with application to level set interface computations, Mathematics of Computation 76(258), 647-668, 2007, the analysis of BFECC for semi-Lagrangian schemes

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.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