Algorithm Search⌘K

Algorithmcore

Stable fluids

Also called Stam stable fluids.

Advance a grid fluid by semi-Lagrangian advection, implicit diffusion and pressure projection. It is stable for any time step, but first order and dissipative, so stable is not accurate.

Time
Θ(g) advectO(g k) diffuse · project · step
Space
Θ(g) extra
Where
g = the number of grid cells; k = the number of conjugate gradient iterations of a solve
Properties
not conservativedeterministicnot exactunconditionally stable
Origin
Jos Stam, 1999

Stable fluids is the grid fluid solver of Jos Stam (1999). Each time step adds the forces, moves the velocity along itself by semi-Lagrangian advection, diffuses it by an implicit step, and projects it onto the divergence-free fields. None of the four parts has a limit on the time step, so the solver does not blow up at any Δt\Delta t. That made interactive fluids possible and made the method the base of most grid solvers for smoke and fire in animation. The price is accuracy: the advection is first order and smooths the flow, so a stable step is not an accurate step.

In plain words

Each frame, the solver does four things to the velocity on a grid.

First it adds the pushes, such as gravity or a fan. Then it moves the flow along itself. For each grid point it asks where the fluid there came from, walks back along the flow, and reads the old value at that spot by mixing the four nearest grid values. A mix of old values can never be larger than the largest old value, so nothing can grow without limit, whatever the step size.

Next it spreads the velocity a little to model friction inside the fluid. It solves for the spread state at the end of the step, which also cannot grow.

Last it removes the part of the flow that would squeeze or stretch the fluid, so the fluid keeps its volume. Smoke and other quantities then ride along on the new flow.

The problem

Given a velocity field u\mathbf u on a grid, a density ρ\rho, a viscosity ν\nu, a force field f\mathbf f and a time step Δt\Delta t, compute the velocity at the next step for the incompressible Navier-Stokes equations

∂u∂t=−(u⋅∇)u−1ρ∇p+ν∇2u+f,∇⋅u=0,\frac{\partial \mathbf u}{\partial t} = -(\mathbf u \cdot \nabla)\mathbf u - \frac{1}{\rho}\nabla p + \nu \nabla^2 \mathbf u + \mathbf f, \qquad \nabla \cdot \mathbf u = 0,

and move the passive scalars ss (smoke density, temperature) by ∂s/∂t=−u⋅∇s+κ∇2s−ass\partial s / \partial t = -\mathbf u \cdot \nabla s + \kappa \nabla^2 s - a_s s. The goal of fluid simulation for animation is plausible motion at the step that the frame rate or the artist sets, without a limit from the grid. The output must stay bounded and divergence free for any Δt\Delta t.

The algorithm

The step splits the equation into four parts and solves each part by a method that is stable on its own. The order is the one of Stam's paper: force, advect, diffuse, project. This page uses the MAC grid layout, with uu on the vertical faces, vv on the horizontal faces and pp and the scalars at the cell centers, as Fedkiw, Stam and Jensen (2001) did for smoke. Stam's 1999 paper stored all components at the cell centers and solved the projection with the fast Fourier transform on a periodic domain, or with a fast Poisson solver for fixed walls.

  1. STABLE-FLUIDS-STEP(u, v, s, dt)
  2. 1add dt f(x) to the velocity at each face center x
  3. 2for each sample point x of u, v: x_b <- x - dt U(x - (dt/2) U(x)) ▷ RK2 backtrace
  4. 3new value at x <- bilinear sample of the old field at x_b, clamped to the grid
  5. 4for each of u and v: solve (I + alpha L) w = (advected field), alpha = nu dt / dx^2
  6. 5set the normal velocity to 0 on each face with a SOLID side
  7. 6build A p = b on the FLUID cells, b = -(rho dx / dt) (net outflow of the cell)
  8. 7solve A p = b by conjugate gradients; on a closed region remove the mean of b, then of p
  9. 8on each open face: u <- u - dt / (rho dx) (pressure difference across the face)
  10. 9for each scalar s: advect by L2 and L3, diffuse with kappa by L4, then s <- s / (1 + dt a_s)

Forces (L1). This is one forward Euler step of ∂u/∂t=f\partial \mathbf u / \partial t = \mathbf f. With a bounded force it adds at most Δtmax⁡∣f∣\Delta t \max |\mathbf f| to each face. Buoyancy and vorticity confinement enter here.

Advection (L2, L3). The term −(u⋅∇)u-(\mathbf u \cdot \nabla)\mathbf u says that velocity is carried along by the flow. Along a path x(t)\mathbf x(t) with dx/dt=ud\mathbf x / dt = \mathbf u, the value stays the same, which is the method of characteristics. So the new value at a sample point is the old value at the point that reaches it after Δt\Delta t. Line L2 finds that point by one midpoint step backward in time; line L3 reads the old field there by bilinear interpolation. Each component uses its own sample points and offsets. The old velocity moves itself: all backtraces use the field from before the advection. This is the semi-Lagrangian method: the grid stays fixed (Eulerian), and each value is found by a Lagrangian trace.

Diffusion (L4). This is one backward Euler step of the heat equation ∂w/∂t=ν∇2w\partial w / \partial t = \nu \nabla^2 w for each component, with the 5-point graph Laplacian LL of the array. The matrix I+αLI + \alpha L is symmetric positive definite, and conjugate gradients solve it. Smoke usually uses ν=0\nu = 0 and skips the step, because the advection already smooths more than the physical viscosity of air.

Projection (L5 to L8). Line L5 closes the walls. Lines L6 and L7 solve the pressure Poisson equation, and line L8 subtracts the pressure gradient, so every FLUID cell has zero net outflow. This is the Chorin projection, and the field that results is the divergence-free part of the Helmholtz-Hodge decomposition of the discrete field. The MAC grid page derives the matrix; the slug file writes it out again.

Scalars (L9). A scalar moves with the new velocity by the same advection, diffuses with the coefficient κ\kappa, and fades by s/(1+Δt as)s / (1 + \Delta t\, a_s), which is backward Euler for ds/dt=−assds/dt = -a_s s as in Stam's paper.

Example

One advection step by hand. Take a row of five cells with Δx=1\Delta x = 1 m, a constant velocity u=1u = 1 m/s and Δt=1.5\Delta t = 1.5 s, so the CFL number is 1.51.5. The scalar is s=(0,0,1,0,0)s = (0, 0, 1, 0, 0). Positions below are in cell index units. The foot of cell aa is 1.51.5 cells to the left, halfway between cells a−2a - 2 and a−1a - 1, so the new value is 12sa−2+12sa−1\frac12 s_{a-2} + \frac12 s_{a-1}:

cell 0 1 2 3 4
before 0 0 1 0 0
foot of the backtrace -1.5 (clamped to 0) -0.5 (clamped to 0) 0.5 1.5 2.5
after 0 0 0 0.5 0.5

The exact solution moves the spike to the position 3.53.5, between two cells. The grid cannot hold it there, so the spike splits into two halves. No value is larger than 1 and no value is negative, at any step size. The same mixing at every step is the numerical diffusion of the method.

One diffusion step by hand. Two cells with w=(1,0)w = (1, 0) and α=1\alpha = 1. The system is (2−1−12)w′=(10)\begin{pmatrix} 2 & -1 \\ -1 & 2 \end{pmatrix} w' = \begin{pmatrix} 1 \\ 0 \end{pmatrix}, so w′=(23,13)w' = (\tfrac23, \tfrac13). The sum stays 1, the values stay in [0,1][0, 1], and the sum of squares drops from 1 to 59\tfrac59. As α\alpha grows, w′w' tends to (12,12)(\tfrac12, \tfrac12), never past it.

First order, measured. A Gaussian bump with σ=0.1\sigma = 0.1 m moves by 0.31250.3125 m with u=1u = 1 m/s at the CFL number 2.52.5 on grids of 8, 16 and 32 cells over 1 m. The largest errors are 0.1540.154, 0.08870.0887 and 0.04440.0444. The error halves when the grid spacing halves: the observed order between 16 and 32 cells is 1.001.00. The proof page gives the bound TuΔxϕ(1−ϕ)K/(2c)≈0.0488T u \Delta x \phi(1 - \phi) K / (2c) \approx 0.0488 for 32 cells, where ϕ=0.5\phi = 0.5 is the fractional part of the CFL number and K=100K = 100 bounds the second derivative.

A large step, measured. On a 16 by 16 box with Δx=1/16\Delta x = 1/16 m, a random divergence-free velocity from random.Random(11) (largest face speed 1.081.08 m/s) and a square of smoke, ten steps with Δt=0.29\Delta t = 0.29 s, a CFL number of 5, run without trouble. After each step the largest divergence is below 10−810^{-8} (it is 2.9×10−132.9 \times 10^{-13} at the end). The kinetic energy drops at every step, from 0.1500.150 J to 0.03960.0396 J after one step and to 0.00210.0021 J after ten, per unit depth with ρ=1\rho = 1. The smoke stays in [0,1][0, 1], but its total grows from 16 to 16.84, because semi-Lagrangian advection does not conserve mass. The run is stable and also very wrong: an inviscid fluid in a closed box keeps its energy.

Correctness

The claims are about the discrete step. They are proved in proofs/correctness.md.

  1. Advection. Each new value is a convex combination of four old values, for any velocity and any Δt\Delta t. A constant field stays the same, and the values stay between the old minimum and maximum.
  2. Diffusion. The backward Euler step keeps the sum of the array, keeps the values between the old minimum and maximum, and does not increase the sum of squares, for any α≥0\alpha \ge 0.
  3. Projection. After lines L5 to L8, every FLUID cell has zero divergence, and the kinetic energy has not increased. The projection is orthogonal in the inner product ∑u2+∑v2\sum u^2 + \sum v^2.
  4. One step. With no force, the velocity after a step is bounded by a bound that depends on the old velocity and the number of faces, but not on Δt\Delta t or ν\nu. Each scalar stays inside its old range times 1/(1+Δt as)1 / (1 + \Delta t\, a_s).
  5. Order. For a constant velocity and a smooth field, the advection error after a fixed time is O(Δx)O(\Delta x) at a fixed CFL number. The leading error is a diffusion term. Away from a whole number of cells per step, the method is first order in space and time.

The tests check the advection, the interpolation and the projection of the slug file against the shared helper macgrid.py on the same input. They also check diffusion against a dense solve and its sum, bound and energy properties, the measured order, and the bounded run at a CFL number of 5.

Proof: Each part of the stable fluids step is stable for any time step, and the advection is first orderfull

We use the MAC layout and the line numbers of the page. All statements are in exact arithmetic. A cell outside the grid is SOLID, and the walls are fixed. A face field is a value on each face, and ∥w∥∞\|w\|_\infty is the largest ∣wf∣|w_f|. "Stable for any Δt\Delta t" means here that the output of a part is bounded by its input in a stated norm, with a bound that does not depend on Δt\Delta t, ν\nu or Δx\Delta x.

Lemma 1 (advection, lines L2 and L3). For any velocity field, any Δt\Delta t and any field qq, each value of ADVECT(q)(q) is a convex combination of at most four values of qq. So a constant field stays the same, and min⁡q≤ADVECT(q)≤max⁡q\min q \le \text{ADVECT}(q) \le \max q at every sample point.

Proof. Line L2 gives some point (xb,yb)(x_b, y_b), whatever the velocity and Δt\Delta t. Line L3 clamps the point to the box of the sample points and returns ∑kλkqk\sum_k \lambda_k q_k over four samples, with weights (1−s)(1−t)(1-s)(1-t), (1−s)t(1-s)t, s(1−t)s(1-t) and stst, where s,t∈[0,1]s, t \in [0, 1]. The weights are nonnegative and sum to 1. A convex combination of equal values is that value, and it lies between the least and the largest of its terms. □\square

The lemma holds for uu and vv separately, so ∥u∥∞\|u\|_\infty and ∥v∥∞\|v\|_\infty do not increase in the advection of the velocity. It does not say that the sum of qq is kept: semi-Lagrangian advection is not conservative.

Lemma 2 (diffusion, line L4). Let LL be the graph Laplacian of the array, (Lw)k=∑m∈N(k)(wk−wm)(L w)_k = \sum_{m \in N(k)} (w_k - w_m) over the neighbors N(k)N(k) inside the array, and α=νΔt/Δx2≥0\alpha = \nu \Delta t / \Delta x^2 \ge 0. Then I+αLI + \alpha L is symmetric positive definite, and the solution ww of (I+αL)w=q(I + \alpha L) w = q satisfies

  1. ∑kwk=∑kqk\sum_k w_k = \sum_k q_k,
  2. min⁡q≤wk≤max⁡q\min q \le w_k \le \max q for all kk,
  3. ∑kwk2≤∑kqk2\sum_k w_k^2 \le \sum_k q_k^2.

Proof. LL is symmetric, and xTLx=∑{k,m}(xk−xm)2≥0x^T L x = \sum_{\{k, m\}} (x_k - x_m)^2 \ge 0 over the neighbor pairs, so xT(I+αL)x≥xTx>0x^T (I + \alpha L) x \ge x^T x > 0 for x≠0x \ne 0. For claim 1, the column sums of LL are zero, so 1T(I+αL)w=1Tw=1Tq\mathbf 1^T (I + \alpha L) w = \mathbf 1^T w = \mathbf 1^T q. For claim 2, let kk be an index with the largest wkw_k. Then each term wk−wmw_k - w_m is ≥0\ge 0, so qk=wk+α∑m(wk−wm)≥wkq_k = w_k + \alpha \sum_{m} (w_k - w_m) \ge w_k, and wk≤qk≤max⁡qw_k \le q_k \le \max q. The lower bound follows in the same way at the smallest wkw_k. For claim 3, the eigenvalues of LL are μi≥0\mu_i \ge 0 with an orthonormal eigenbasis, so the eigenvalues of (I+αL)−1(I + \alpha L)^{-1} are 1/(1+αμi)∈(0,1]1 / (1 + \alpha \mu_i) \in (0, 1], and ∥w∥2=∥(I+αL)−1q∥2≤∥q∥2\|w\|_2 = \|(I + \alpha L)^{-1} q\|_2 \le \|q\|_2. □\square

This is backward Euler on the heat equation ∂q/∂t=ν∇2q\partial q / \partial t = \nu \nabla^2 q with the 5-point Laplacian. The bounds hold for any α\alpha, so the step size has no limit. As α→∞\alpha \to \infty, ww tends to the mean of qq on each connected array, which is the correct limit of the heat equation and also shows how much a large step can smooth.

Lemma 3 (projection, lines L5 to L8). Let ww be the face field after line L5, so that w=0w = 0 on every face with a SOLID side. Let pp solve Ap=bA p = b with AA and bb from line L6, and let w′w' be the field after line L8. Then w′w' has zero divergence on every FLUID cell, and ∑fwf′2≤∑fwf2\sum_f w_f'^2 \le \sum_f w_f^2.

Proof. Call a face open if no side is SOLID and at least one side is FLUID. For a cell field qq with q=0q = 0 on AIR cells, let (Gq)f=(qhigh−qlow)/Δx(G q)_f = (q_{\text{high}} - q_{\text{low}})/\Delta x on open faces, between the cells of larger and smaller index, and (Gq)f=0(G q)_f = 0 on the other faces. Let (Dw)c(D w)_c be the net outflow of cell cc divided by Δx\Delta x. Line L8 is w′=w−ΔtρGpw' = w - \frac{\Delta t}{\rho} G p.

Zero divergence. For a FLUID cell cc, each face is open or has a SOLID side. On an open face toward the neighbor nn, the outward flux of GpG p is (pn−pc)/Δx(p_n - p_c)/\Delta x, with pn=0p_n = 0 for an AIR cell. So Δx2(DGp)c=∑n not SOLID(pn−pc)=−(Ap)c\Delta x^2 (D G p)_c = \sum_{n \text{ not SOLID}} (p_n - p_c) = -(A p)_c, which is how line L6 counts the diagonal and the off-diagonal entries. Line L6 sets bc=−ρΔx2Δt(Dw)cb_c = -\frac{\rho \Delta x^2}{\Delta t} (D w)_c. Then (Dw′)c=(Dw)c+ΔtρΔx2(Ap)c=(Dw)c+ΔtρΔx2bc=0(D w')_c = (D w)_c + \frac{\Delta t}{\rho \Delta x^2} (A p)_c = (D w)_c + \frac{\Delta t}{\rho \Delta x^2} b_c = 0.

The system is solvable. AA is symmetric positive semidefinite, and its null space is spanned by the indicators of the connected FLUID regions with no AIR neighbor (the proof is on the MAC grid page). On such a closed region, the sum of Δx(Dw)c\Delta x (D w)_c is the net flow through its solid faces, which is zero after line L5, so bb is orthogonal to the null space. Line L7 removes the mean of bb on each closed region, which changes nothing in exact arithmetic, and the mean of pp, which picks one of the solutions.

Energy. Let zz be a face field with z=0z = 0 on every face with a SOLID side, and q=Δtρpq = \frac{\Delta t}{\rho} p. Write ∑f(Gq)fzf=1Δx∑f open(qhigh−qlow)zf\sum_f (G q)_f z_f = \frac{1}{\Delta x} \sum_{f \text{ open}} (q_{\text{high}} - q_{\text{low}}) z_f and give each term to its cell. The terms of an AIR cell are zero, and the faces of a FLUID cell that are not open carry z=0z = 0, so ∑f(Gq)fzf=−∑c FLUIDqc(Dz)c\sum_f (G q)_f z_f = -\sum_{c \text{ FLUID}} q_c (D z)_c. With z=w′z = w', the right side is zero, so w′w' and GqG q are orthogonal, and ∑fwf2=∑f(wf′+(Gq)f)2=∑fwf′2+∑f(Gq)f2\sum_f w_f^2 = \sum_f (w'_f + (G q)_f)^2 = \sum_f w_f'^2 + \sum_f (G q)_f^2. □\square

Lemma 4 (dissipation of a scalar, line L9). For as≥0a_s \ge 0 and Δt≥0\Delta t \ge 0, s←s/(1+Δt as)s \leftarrow s / (1 + \Delta t\, a_s) is backward Euler for ds/dt=−assds/dt = -a_s s, and the factor is in (0,1](0, 1].

Proof. Backward Euler gives sn+1=sn−Δt assn+1s^{n+1} = s^n - \Delta t\, a_s s^{n+1}, so sn+1=sn/(1+Δt as)s^{n+1} = s^n / (1 + \Delta t\, a_s), and 1+Δt as≥11 + \Delta t\, a_s \ge 1. □\square

Theorem 1 (stability of one step). With no force, for any Δt>0\Delta t > 0, ν≥0\nu \ge 0, κ≥0\kappa \ge 0 and as≥0a_s \ge 0:

  1. Each value of a scalar field after the step lies in [γmin⁡sn,γmax⁡sn][\gamma \min s^n, \gamma \max s^n], where sns^n is the field before the step and γ=1/(1+Δt as)\gamma = 1 / (1 + \Delta t\, a_s).
  2. The velocity after the step has zero divergence on the FLUID cells, and ∑fwf2≤F⋅max⁡(∥un∥∞,∥vn∥∞)2\sum_f w_f^2 \le F \cdot \max(\|u^n\|_\infty, \|v^n\|_\infty)^2, where FF is the number of faces.

Proof. Claim 1 follows from Lemma 1, Lemma 2 (claim 2) and Lemma 4, applied in this order. For claim 2, Lemma 1 bounds each component after advection by its old maximum, Lemma 2 does not increase the maximum, so after line L4 ∑fwf2≤Fmax⁡(∥un∥∞,∥vn∥∞)2\sum_f w_f^2 \le F \max(\|u^n\|_\infty, \|v^n\|_\infty)^2. Line L5 only sets values to zero, and Lemma 3 does not increase ∑fwf2\sum_f w_f^2 and gives zero divergence. □\square

The bound in claim 2 does not depend on Δt\Delta t or ν\nu. That is the sense of "stable for any time step" in Stam's paper: advection takes values only from inside the old field, and the other parts are implicit or are projections. We do not claim that the velocity stays bounded uniformly over many steps with a constant independent of FF. Lemma 1 bounds the advection in the maximum norm and Lemma 3 bounds the projection in the energy norm, and the two norms differ by up to the factor F\sqrt F. The test file measures the energy over ten steps at a CFL number of 5 and finds that it decreases at every step.

Theorem 2 (first order advection). On an infinite or periodic 1D grid of spacing Δx\Delta x, let the velocity be a constant u>0u > 0, let c=uΔt/Δx=m+ϕc = u \Delta t / \Delta x = m + \phi with an integer m≥0m \ge 0 and ϕ∈[0,1)\phi \in [0, 1), and let qq be a smooth function with ∣q′′∣≤K|q''| \le K. After NN steps of lines L2 and L3, with T=NΔtT = N \Delta t, the error at every sample point is at most

T u Δx ϕ(1−ϕ)2cK.\frac{T\,u\,\Delta x\,\phi (1 - \phi)}{2 c} K.

At a fixed CFL number cc with ϕ>0\phi > 0, the error is O(Δx)O(\Delta x): the method is first order.

Proof. With a constant velocity, both stages of the RK2 backtrace use uu, so line L2 is exact: the foot of sample xax_a is xa−cΔxx_a - c \Delta x, at the distance ϕΔx\phi \Delta x from xa−mx_{a - m} and (1−ϕ)Δx(1 - \phi) \Delta x from xa−m−1x_{a - m - 1}. Line L3 is linear interpolation between these two samples. For a smooth qq, the error of linear interpolation at a point between two nodes at distances θΔx\theta \Delta x and (1−θ)Δx(1 - \theta) \Delta x is at most 12θ(1−θ)Δx2K\frac12 \theta (1 - \theta) \Delta x^2 K; here θ=ϕ\theta = \phi. Let ene^n be the error at step nn against the exact solution q(x−utn)q(x - u t_n), which has the same bound KK on its second derivative. One step gives ean+1=I(en)a+τae^{n+1}_a = I(e^n)_a + \tau_a, where II is the interpolation and ∣τa∣≤12ϕ(1−ϕ)Δx2K|\tau_a| \le \frac12 \phi(1 - \phi) \Delta x^2 K. II is a convex combination, so ∥I(en)∥∞≤∥en∥∞\|I(e^n)\|_\infty \le \|e^n\|_\infty, and ∥eN∥∞≤N⋅12ϕ(1−ϕ)Δx2K\|e^N\|_\infty \le N \cdot \frac12 \phi (1 - \phi) \Delta x^2 K. With N=T/Δt=Tu/(cΔx)N = T / \Delta t = T u / (c \Delta x) this is the bound. □\square

The leading term of the local error is 12ϕ(1−ϕ)Δx2q′′\frac12 \phi(1-\phi)\Delta x^2 q'', a diffusion term. So on a bump the bound is close to the actual error: the method smooths with an effective viscosity u Δx ϕ(1−ϕ)/(2c)u\,\Delta x\,\phi(1 - \phi)/(2c). For ϕ=0\phi = 0 the step moves the field by whole cells and is exact. The test file moves a Gaussian bump with σ=0.1\sigma = 0.1 (K=1/σ2=100K = 1/\sigma^2 = 100) by 0.31250.3125 at c=2.5c = 2.5. For nx=32n_x = 32 the bound is 0.3125⋅(1/32)⋅0.25⋅100/5≈0.04880.3125 \cdot (1/32) \cdot 0.25 \cdot 100 / 5 \approx 0.0488, and the measured error is 0.04440.0444. The order between nx=16n_x = 16 and nx=32n_x = 32 is 1.00.

The theorem is for the interior of the domain. At an inflow border, line L3 clamps the foot to the last sample, which is a first order boundary condition.

Complexity

Let gg be the number of cells. Lines L1 to L3, L5, L8 and the scalar advection cost Θ(g)\Theta(g): each face or cell does a constant amount of work, and the backtrace and the sample cost O(1)O(1) each. The extra space is Θ(g)\Theta(g) for the new fields and the solver vectors.

The linear solves dominate. A conjugate gradient iteration costs Θ(g)\Theta(g) on a 5-point matrix, so each solve costs O(gk)O(g k). For the pressure on an NN by NN grid, k=O(N)k = O(N) for a fixed reduction of the error, because the condition number of AA grows as N2N^2; multigrid brings the solve to O(g)O(g). For the diffusion, the condition number of I+αLI + \alpha L is at most 1+8α1 + 8\alpha, so the solve is cheap when α\alpha is small and approaches the cost of a Poisson solve when α\alpha is large. Stam's periodic version replaces both solves by FFTs, which cost O(glog⁡g)O(g \log g).

Properties

  • No step limit. The CFL condition does not limit Δt\Delta t, because the backtrace may cross many cells. Large steps lose accuracy, not stability. Many solvers still keep the CFL number at a few cells per step, as a rule of thumb for accuracy.
  • Dissipative. Linear interpolation smooths the field at every step, with an effective viscosity of order u Δxu\,\Delta x. Smoke loses its small swirls, and the total kinetic energy decays even with ν=0\nu = 0. Vorticity confinement, BFECC and the unconditionally stable MacCormack method are the usual repairs.
  • Not conservative. The sum of an advected scalar is not kept. Smoke mass and liquid volume drift over time.
  • First order. The splitting is first order in time, and the advection is first order at a fixed CFL number.
  • Simple and robust. Every part is either a convex combination or a symmetric positive (semi)definite solve.

Variants and improvements

  • Collocated grid with FFT. Stam's original form, with all components at the cell centers and the diffusion and the projection done in Fourier space on a periodic domain, where both are diagonal.
  • A version for games. Stam later published a short version for games (2003) that relaxes the linear systems with a fixed number of Gauss-Seidel sweeps. It is cheaper and less accurate than a converged solve.
  • Staggered grid. The MAC layout of this page (Fedkiw, Stam and Jensen 2001), which avoids the checkerboard modes of the collocated projection.
  • Less dissipation. Higher order interpolation (monotone cubic), BFECC, the unconditionally stable MacCormack method, and particle methods such as FLIP and APIC that do not interpolate the velocity at every step.
  • Liquids. Add a free surface tracked by a level set or particles, AIR cells with p=0p = 0 and the ghost fluid method at the surface.
  • Better splitting. Advection-reflection methods reflect the velocity at the half step instead of only projecting it. They lose less energy, at the cost of a second projection.

When to use it

Use stable fluids for smoke, fire, dust and other gases in animation and games, where the step is set by the frame rate and the look matters more than the accuracy. It is also the base for liquid solvers and the grid stage of particle-grid hybrids. It is easy to write, easy to run on a GPU, and robust.

Do not use it where accuracy matters: in engineering flow, for drag or heat transfer, or where mass must be conserved. Use a conservative finite volume method with a step inside the CFL limit there. For thin liquid sheets, splashes and small features, the numerical diffusion is too strong; use particles.

Pitfalls

  • Stable is not accurate. A step at a CFL number of 5 runs, but it can lose most of the kinetic energy in a few steps, as the measured run shows. Pick Δt\Delta t for accuracy, not only for stability.
  • Advecting in place. The backtraces must use the velocity from before the step. Writing the new values into the same arrays during the sweep mixes old and new values.
  • Half-cell offsets. On a MAC grid, uu, vv and the scalars have different sample points. Trace from the sample point of each component and sample with its offsets.
  • Boundaries. A backtrace that leaves the domain must read a boundary value. Clamping returns the nearest sample, which is right for a wall and wrong for an inflow with a given value.
  • The order of the steps. Advect with a divergence-free field. A force added after the projection is not projected and adds divergence to the next advection.
  • Diffusing walls. The diffusion of this page treats the border of each array with a zero normal derivative. A no-slip wall needs zero velocity at the wall in the diffusion step, not only in the projection.
  • The singular pressure system. A closed box has a free constant in pp. Remove the mean of bb before conjugate gradients, or the solve stalls.

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
stable_fluids.py 300 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stable-fluids/. The authors are listed in prov/4DDRB0.jsonl.

"""Stable fluids (Stam 1999) on a 2D MAC grid.

One step adds the forces, advects by the semi-Lagrangian method, diffuses by
backward Euler and projects the velocity onto the divergence-free fields. All
four parts are written out here. The grid object and its layout come from the
shared helper macgrid.py: p[i][j] at ((i + 1/2) dx, (j + 1/2) dx), u[i][j] at
(i dx, (j + 1/2) dx) and v[i][j] at ((i + 1/2) dx, j dx). Stam used a cell
centered grid; this file uses the MAC layout of Fedkiw, Stam and Jensen 2001.

Each part is stable for any time step. The step is first order in time and
dissipative, so a large step is stable but not accurate.
"""

import math
from collections import deque

from macgrid import FLUID, SOLID


def label_at(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


# ---- forces ----

def add_force(g, dt, force):
    """u <- u + dt f_x and v <- v + dt f_y at each face center; force(x, y) returns (f_x, f_y) in m/s^2."""
    dx = g.dx
    for i in range(g.nx + 1):
        for j in range(g.ny):
            g.u[i][j] += dt * force(i * dx, (j + 0.5) * dx)[0]  # @line L1
    for i in range(g.nx):
        for j in range(g.ny + 1):
            g.v[i][j] += dt * force((i + 0.5) * dx, j * dx)[1]


# ---- advection ----

def interp(q, x, y, dx, ox, oy):
    """Bilinear interpolation at (x, y) of q, where q[a][b] is at ((a + ox) dx, (b + oy) dx).

    A point outside the box of the sample points is clamped to it.
    """
    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
    s = fx - a0
    t = fy - b0
    return ((1.0 - s) * ((1.0 - t) * q[a0][b0] + t * q[a0][b1])  # @line L3
            + s * ((1.0 - t) * q[a1][b0] + t * q[a1][b1]))


def velocity(g, x, y):
    """The velocity (u, v) at (x, y), from the face values of g."""
    return (interp(g.u, x, y, g.dx, 0.0, 0.5), interp(g.v, x, y, g.dx, 0.5, 0.0))


def trace_back(g, x, y, dt):
    """The point that reaches (x, y) after time dt along the velocity of g, by one midpoint (RK2) step."""
    u1, v1 = velocity(g, x, y)
    u2, v2 = velocity(g, x - 0.5 * dt * u1, y - 0.5 * dt * v1)
    return (x - dt * u2, y - dt * v2)  # @line L2


def advect(g, q, dt, ox=0.5, oy=0.5):
    """Semi-Lagrangian advection of q, whose samples have offsets (ox, oy), by the velocity of g.

    Returns a new field. Each new value is the old field interpolated at the
    backtrace of its own sample point, so it lies between the smallest and the
    largest of the four old values used.
    """
    dx = g.dx
    out = [[0.0] * len(q[0]) for _ in range(len(q))]
    for a in range(len(q)):
        for b in range(len(q[0])):
            xb, yb = trace_back(g, (a + ox) * dx, (b + oy) * dx, dt)
            out[a][b] = interp(q, xb, yb, dx, ox, oy)
    return out


def advect_velocity(g, dt):
    """Advect u and v by the velocity of g (the old velocity moves itself). Returns (u, v)."""
    return advect(g, g.u, dt, 0.0, 0.5), advect(g, g.v, dt, 0.5, 0.0)


# ---- conjugate gradients ----

def cg(apply, b, tol=1e-12, max_iter=None):
    """Solve M x = b for a symmetric positive (semi)definite M given as apply(x) = M x.

    Starts from x = 0 and stops when max |r| <= tol * max |b|. Returns (x, iterations).
    """
    n = len(b)
    x = [0.0] * n
    bmax = max((abs(t) for t in b), default=0.0)
    if bmax == 0.0:
        return x, 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)
    it = 0
    while it < max_iter and max(abs(t) for t in r) > tol * bmax:
        q = apply(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
    return x, it


# ---- diffusion ----

def diffuse(q, alpha, tol=1e-12):
    """One backward Euler step of the heat equation on the array q: solve (I + alpha L) w = q.

    L is the graph Laplacian of the array (5 points, a missing neighbor at the
    border of the array is left out, which is a zero normal derivative), and
    alpha = nu dt / dx^2. Returns (w, iterations).
    """
    na, nb = len(q), len(q[0])
    if alpha == 0.0:
        return [list(col) for col in q], 0
    nbrs = []
    for a in range(na):
        for b in range(nb):
            nbrs.append([a2 * nb + b2 for (a2, b2) in ((a - 1, b), (a + 1, b), (a, b - 1), (a, b + 1))
                         if 0 <= a2 < na and 0 <= b2 < nb])

    def apply(x):
        return [x[k] + alpha * (len(nbrs[k]) * x[k] - sum(x[m] for m in nbrs[k])) for k in range(len(x))]

    flat = [q[a][b] for a in range(na) for b in range(nb)]
    w, it = cg(apply, flat, tol)  # @line L4
    return [[w[a * nb + b] for b in range(nb)] for a in range(na)], it


# ---- projection ----

def set_walls(g):
    """Set the normal velocity to zero on every face with a SOLID cell on one side (fixed walls)."""
    for i in range(g.nx + 1):
        for j in range(g.ny):
            if label_at(g, i - 1, j) == SOLID or label_at(g, i, j) == SOLID:
                g.u[i][j] = 0.0  # @line L5
    for i in range(g.nx):
        for j in range(g.ny + 1):
            if label_at(g, i, j - 1) == SOLID or label_at(g, i, j) == SOLID:
                g.v[i][j] = 0.0


def pressure_system(g, dt, rho):
    """The pressure equations A p = b over the FLUID cells.

    Returns (cells, diag, nbrs, b, open_cell). Row k has diag[k] = the number of
    neighbors that are not SOLID and -1 for each FLUID neighbor in nbrs[k];
    b[k] = -(rho dx / dt) times the net outflow of the cell. open_cell[k] is True
    if the cell has an AIR neighbor, where p = 0.
    """
    index = {}
    cells = []
    for i in range(g.nx):
        for j in range(g.ny):
            if g.label[i][j] == FLUID:
                index[(i, j)] = len(cells)
                cells.append((i, j))
    diag, nbrs, b, open_cell = [], [], [], []
    for (i, j) in cells:
        count, nb, air = 0, [], False
        for (a, c) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
            lab = label_at(g, a, c)
            if lab == SOLID:
                continue
            count += 1  # @line L6
            if lab == FLUID:
                nb.append(index[(a, c)])
            else:
                air = True
        diag.append(count)
        nbrs.append(nb)
        open_cell.append(air)
        b.append(-rho * g.dx / dt * (g.u[i + 1][j] - g.u[i][j] + g.v[i][j + 1] - g.v[i][j]))
    return cells, diag, nbrs, b, open_cell


def closed_regions(nbrs, open_cell):
    """The connected groups of FLUID cells with no AIR neighbor, as lists of row indices."""
    n = len(nbrs)
    seen = [False] * n
    out = []
    for s in range(n):
        if seen[s]:
            continue
        seen[s] = True
        group, queue = [s], deque([s])
        while queue:
            k = queue.popleft()
            for m in nbrs[k]:
                if not seen[m]:
                    seen[m] = True
                    group.append(m)
                    queue.append(m)
        if not any(open_cell[k] for k in group):
            out.append(group)
    return out


def solve_pressure(g, dt, rho, tol=1e-12):
    """Solve A p = b by conjugate gradients and store p in g.p (0 outside the FLUID cells). Returns the iterations."""
    cells, diag, nbrs, b, open_cell = pressure_system(g, dt, rho)
    g.p = [[0.0] * g.ny for _ in range(g.nx)]
    if not cells:
        return 0
    closed = closed_regions(nbrs, open_cell)
    for group in closed:
        mean = sum(b[k] for k in group) / len(group)
        for k in group:
            b[k] -= mean

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

    x, it = cg(apply, b, tol)  # @line L7
    for group in closed:
        mean = sum(x[k] for k in group) / len(group)
        for k in group:
            x[k] -= mean
    for k, (i, j) in enumerate(cells):
        g.p[i][j] = x[k]
    return it


def subtract_gradient(g, dt, rho):
    """u -= dt / (rho dx) times the pressure difference on each face with no SOLID side and a FLUID side."""
    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 and c != SOLID and (a == FLUID or c == FLUID):
                g.u[i][j] -= s * (g.p[i][j] - g.p[i - 1][j])  # @line L8
    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 and c != SOLID and (a == FLUID or c == FLUID):
                g.v[i][j] -= s * (g.p[i][j] - g.p[i][j - 1])


def project(g, dt, rho, tol=1e-12):
    """Make the velocity of g divergence free on the FLUID cells. Returns the CG iterations."""
    set_walls(g)
    it = solve_pressure(g, dt, rho, tol)
    subtract_gradient(g, dt, rho)
    return it


# ---- one step ----

def step(g, dt, rho, nu=0.0, force=None, scalars=(), kappa=0.0, decay=0.0):
    """One stable fluids step of length dt. Changes g and returns the new scalar fields as a list.

    nu is the kinematic viscosity (m^2/s), kappa the diffusion coefficient of
    the scalars and decay the rate a_s (1/s) of their dissipation. The scalars
    are cell centered and move with the new velocity.
    """
    if force is not None:
        add_force(g, dt, force)
    g.u, g.v = advect_velocity(g, dt)
    if nu > 0.0:
        alpha = nu * dt / (g.dx * g.dx)
        g.u = diffuse(g.u, alpha)[0]
        g.v = diffuse(g.v, alpha)[0]
    project(g, dt, rho)
    out = []
    for s in scalars:
        s = advect(g, s, dt)
        if kappa > 0.0:
            s = diffuse(s, kappa * dt / (g.dx * g.dx))[0]
        f = 1.0 / (1.0 + dt * decay)
        out.append([[f * t for t in col] for col in s])  # @line L9
    return out
test_stable_fluids.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stable-fluids/. The authors are listed in prov/4DDRB0.jsonl.

"""Tests of the stable fluids step and of its parts against the shared helper."""

import math
import random

import macgrid
from macgrid import AIR, SOLID
import stable_fluids as sf


def random_grid(nx, ny, dx, seed):
    rng = random.Random(seed)
    g = macgrid.make_grid(nx, ny, dx)
    for col in g.u:
        for j in range(ny):
            col[j] = rng.uniform(-1.0, 1.0)
    for col in g.v:
        for j in range(ny + 1):
            col[j] = rng.uniform(-1.0, 1.0)
    return g, rng


def copy_grid(g):
    h = macgrid.make_grid(g.nx, g.ny, g.dx)
    h.u = macgrid.copy_field(g.u)
    h.v = macgrid.copy_field(g.v)
    h.label = [list(col) for col in g.label]
    return h


def dense_solve(a, b):
    n = len(b)
    m = [list(row) + [b[k]] for k, row in enumerate(a)]
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            m[r] = [x - f * y for x, y in zip(m[r], m[c])]
    x = [0.0] * n
    for c in range(n - 1, -1, -1):
        x[c] = (m[c][n] - sum(m[c][k] * x[k] for k in range(c + 1, n))) / m[c][c]
    return x


def max_abs(*fields):
    return max(abs(t) for q in fields for col in q for t in col)


# ---- the parts against the helper ----

def test_interp_and_advect_match_helper():
    g, rng = random_grid(10, 8, 0.125, 1)
    macgrid.project(g, 0.1, 1.0)
    for _ in range(200):
        x, y = rng.uniform(-0.2, 1.4), rng.uniform(-0.2, 1.2)
        assert abs(sf.velocity(g, x, y)[0] - macgrid.u_at(g, x, y)) < 1e-14
        assert abs(sf.velocity(g, x, y)[1] - macgrid.v_at(g, x, y)) < 1e-14
        assert sf.trace_back(g, x, y, 0.3) == macgrid.backtrace(g, x, y, 0.3)
    q = [[rng.uniform(0.0, 2.0) for _ in range(8)] for _ in range(10)]
    a1, a2 = sf.advect(g, q, 0.4), macgrid.advect(g, q, 0.4)
    assert max(abs(a1[i][j] - a2[i][j]) for i in range(10) for j in range(8)) < 1e-14
    u1, v1 = sf.advect_velocity(g, 0.4)
    u2, v2 = macgrid.advect_velocity(g, 0.4)
    assert u1 == u2 and v1 == v2


def test_project_matches_helper_with_air_and_solid():
    g, _ = random_grid(12, 10, 0.1, 2)
    for i in range(12):
        for j in range(7, 10):
            g.label[i][j] = AIR
    g.label[5][3] = SOLID
    g.label[6][3] = SOLID
    h = copy_grid(g)
    sf.project(g, 0.05, 1000.0)
    macgrid.project(h, 0.05, 1000.0)
    pmax = max_abs(h.p)
    assert max(abs(g.p[i][j] - h.p[i][j]) for i in range(12) for j in range(10)) < 1e-9 * pmax
    assert max(abs(g.u[i][j] - h.u[i][j]) for i in range(13) for j in range(10)) < 1e-9
    assert max(abs(g.v[i][j] - h.v[i][j]) for i in range(12) for j in range(11)) < 1e-9
    assert macgrid.max_fluid_divergence(g) < 1e-8


def test_project_closed_box_32():
    g, _ = random_grid(32, 32, 1.0 / 32.0, 3)
    sf.set_walls(g)
    e0 = macgrid.kinetic_energy(g, 1000.0)
    it = sf.project(g, 1.0 / 60.0, 1000.0)
    assert it > 0
    assert macgrid.max_fluid_divergence(g) < 1e-8
    assert macgrid.kinetic_energy(g, 1000.0) <= e0
    assert abs(sum(map(sum, g.p))) < 1e-9 * 1024 * max_abs(g.p)


# ---- diffusion ----

def test_diffuse_matches_dense_solve_and_keeps_sum_and_bounds():
    rng = random.Random(4)
    na, nb, alpha = 5, 4, 2.5
    q = [[rng.uniform(-1.0, 3.0) for _ in range(nb)] for _ in range(na)]
    w, it = sf.diffuse(q, alpha)
    assert it > 0
    n = na * nb
    a = [[0.0] * n for _ in range(n)]
    for i in range(na):
        for j in range(nb):
            k = i * nb + j
            a[k][k] = 1.0
            for (i2, j2) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
                if 0 <= i2 < na and 0 <= j2 < nb:
                    a[k][k] += alpha
                    a[k][i2 * nb + j2] -= alpha
    x = dense_solve(a, [q[i][j] for i in range(na) for j in range(nb)])
    assert max(abs(w[i][j] - x[i * nb + j]) for i in range(na) for j in range(nb)) < 1e-10
    assert abs(sum(map(sum, w)) - sum(map(sum, q))) < 1e-10
    lo, hi = min(map(min, q)), max(map(max, q))
    assert all(lo - 1e-12 <= t <= hi + 1e-12 for col in w for t in col)
    assert sum(t * t for col in w for t in col) <= sum(t * t for col in q for t in col)


def test_diffuse_large_step_is_bounded_and_flattens():
    q = [[1.0 if (i + j) % 2 == 0 else 0.0 for j in range(8)] for i in range(8)]
    w, _ = sf.diffuse(q, 1000.0)
    assert all(abs(t - 0.5) < 1e-3 for col in w for t in col)
    w0, it = sf.diffuse(q, 0.0)
    assert w0 == q and it == 0


# ---- advection order and stability ----

def bump_error(nx, cfl=2.5, x0=0.34375, dist=0.3125, sigma=0.1):
    """Max error after moving a Gaussian bump by dist with u = 1, at the CFL number cfl."""
    g = macgrid.make_grid(nx, 2, 1.0 / nx)
    for col in g.u:
        col[0] = col[1] = 1.0

    def f(x):
        return math.exp(-(x - x0) ** 2 / (2.0 * sigma * sigma))

    s = [[f((a + 0.5) * g.dx)] * 2 for a in range(nx)]
    steps = round(dist / (cfl * g.dx))
    for _ in range(steps):
        s = sf.advect(g, s, dist / steps)
    return max(abs(s[a][0] - f((a + 0.5) * g.dx - dist)) for a in range(nx))


def test_advection_is_first_order_at_fixed_cfl():
    e8, e16, e32 = bump_error(8), bump_error(16), bump_error(32)
    assert e8 > e16 > e32
    order = math.log2(e16 / e32)
    assert 0.8 < order < 1.2
    assert 0.04 < e32 < 0.05


def test_constant_field_and_maximum_principle():
    g, rng = random_grid(12, 12, 1.0 / 12.0, 5)
    sf.project(g, 0.1, 1.0)
    const = [[2.5] * 12 for _ in range(12)]
    assert all(abs(t - 2.5) < 1e-14 for col in sf.advect(g, const, 0.7) for t in col)
    q = [[rng.uniform(0.0, 1.0) for _ in range(12)] for _ in range(12)]
    out = sf.advect(g, q, 0.7)
    assert 0.0 <= min(map(min, out)) and max(map(max, out)) <= 1.0


def test_large_step_stays_bounded():
    g, _ = random_grid(16, 16, 1.0 / 16.0, 11)
    sf.project(g, 0.01, 1.0)
    umax = max_abs(g.u, g.v)
    dt = 5.0 * g.dx / umax
    s = [[1.0 if 4 <= a < 8 and 4 <= b < 8 else 0.0 for b in range(16)] for a in range(16)]
    e = [macgrid.kinetic_energy(g, 1.0)]
    for _ in range(10):
        s = sf.step(g, dt, 1.0, scalars=[s])[0]
        e.append(macgrid.kinetic_energy(g, 1.0))
        assert macgrid.max_fluid_divergence(g) < 1e-8
    assert all(math.isfinite(t) for t in e)
    assert all(e[k + 1] <= e[k] for k in range(10))
    assert e[10] < 0.02 * e[0]
    assert 0.0 <= min(map(min, s)) and max(map(max, s)) <= 1.0


# ---- the full step ----

def test_step_with_force_viscosity_and_decay():
    g = macgrid.make_grid(12, 12, 1.0 / 12.0)
    s = [[1.0 if 5 <= a < 7 and 1 <= b < 3 else 0.0 for b in range(12)] for a in range(12)]

    def lift(x, y):
        return (0.0, 4.0 if 0.4 < x < 0.6 and y < 0.4 else 0.0)

    for _ in range(5):
        s = sf.step(g, 0.02, 1.0, nu=1e-3, force=lift, scalars=[s], kappa=1e-4, decay=0.5)[0]
        assert macgrid.max_fluid_divergence(g) < 1e-8
    assert max_abs(g.v) > 0.0
    assert all(t == 0.0 for t in g.v[3][:1] + g.v[3][12:])
    assert 0.0 <= min(map(min, s)) and max(map(max, s)) <= 1.0
    s1 = sf.step(macgrid.make_grid(4, 4, 0.25), 0.1, 1.0, scalars=[[[1.0] * 4 for _ in range(4)]], decay=2.0)[0]
    assert all(abs(t - 1.0 / 1.2) < 1e-15 for col in s1 for t in col)

History

Jos Stam presented stable fluids at SIGGRAPH 1999. Earlier animation solvers, such as the one of Foster and Metaxas (1996), were explicit and had to keep the step small. Stam made the advection semi-Lagrangian, a method known from weather prediction, made the diffusion implicit, and kept Chorin's projection. He showed that no part limits the step. In 2001, Fedkiw, Stam and Jensen moved the method to the staggered grid, added vorticity confinement, and used it for smoke. Later work kept the structure of the step and replaced the parts: higher order advection, particle velocities, and faster pressure solvers.

References

  1. Jos Stam, Stable fluids, Proceedings of SIGGRAPH 99, 121-128, 1999, the solver (add force, advect, diffuse, project), the stability argument, and the FFT solve on a periodic domain
  2. Ronald Fedkiw, Jos Stam and Henrik Wann Jensen, Visual simulation of smoke, SIGGRAPH 2001, 15-22, Section 4, the semi-Lagrangian solver on the staggered grid
  3. Robert Bridson, Fluid Simulation for Computer Graphics, second edition, CRC Press, 2015, the chapters Advection Algorithms and Making Fluids Incompressible

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.advect
  • a full proof of time.diffuse
  • a full proof of time.project
  • 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