Algorithm Search⌘K

Data structurecore

MAC grid

Also called marker-and-cell grid, staggered grid.

A fluid grid with pressure at cell centers and each velocity component on the faces normal to it. Divergence and gradient become compact central differences with no checkerboard null space.

Time
Θ(g) divergence · gradient_update · poisson_buildO(g k) pressure_solveO(1) sample
Space
Θ(g) total
Where
g = the number of grid cells; k = the number of conjugate gradient iterations
Properties
not concurrentnot externalnot persistent
Origin
Francis H. Harlow, J. Eddie Welch, 1965

A MAC grid is the standard layout of a grid fluid solver in computer animation. Pressure and other scalars live at the centers of the cells. The x component of the velocity lives at the centers of the cell faces whose normal is x, and the y component at the centers of the faces whose normal is y. With this layout, the divergence of a cell and the pressure gradient across a face both use the two nearest values only. The discrete Laplacian that they make has no checkerboard null space, which is the main reason for the layout. This page fixes the layout for all grid fluid pages of the encyclopedia. The shared helper macgrid.py implements it, and the marker-and-cell method of 1965 is the full solver from which the name comes.

In plain words

Think of a tiled floor with water on it. Water crosses from tile to tile at the edges, so a MAC grid measures the flow on each edge. It keeps the pressure in the middle of each tile.

To find the net flow out of a tile, add its four edge values with signs. To find how pressure pushes water across an edge, take the difference of the two tiles on its sides.

If you kept all values in the tile centers, you would have to average neighbors to get edge values. Then a pressure that goes up and down from tile to tile, like a chessboard, gives no push at all, and the solver cannot see it. On a MAC grid that pattern pushes hard, so it cannot hide.

The abstract type

A MAC grid stores a discrete velocity field and the scalar fields of a fluid on a uniform grid, and gives these operations:

  • SAMPLE(q,x,y)(q, x, y): the value of a stored field at any point, by bilinear interpolation. The velocity at a point needs one sample of uu and one of vv.
  • DIVERGENCE: the net outflow of each cell divided by its area.
  • GRADIENT-UPDATE(p)(p): subtract Δtρ\frac{\Delta t}{\rho} times the discrete pressure gradient from the velocity on each face.
  • POISSON-SYSTEM: the sparse symmetric matrix AA and the right side bb of the pressure equation over the FLUID cells, so that the velocity after GRADIENT-UPDATE has zero divergence.

PROJECT is POISSON-SYSTEM, a linear solve and GRADIENT-UPDATE. ADVECT moves a field along the velocity; it is the subject of stable fluids and its relatives. The helper has both.

Representation

The grid has nxn_x by nyn_y square cells of side Δx\Delta x. The index ii counts in xx and jj counts in yy, so ii is not an image row.

  • p[i][j]p[i][j] is at ((i+12)Δx,(j+12)Δx)((i + \tfrac12)\Delta x, (j + \tfrac12)\Delta x) for 0≤i<nx0 \le i < n_x, 0≤j<ny0 \le j < n_y. Smoke density, temperature and other scalars use the same points.
  • u[i][j]u[i][j] is at (i Δx,(j+12)Δx)(i\,\Delta x, (j + \tfrac12)\Delta x) for 0≤i≤nx0 \le i \le n_x: the left face of cell (i,j)(i, j). There are (nx+1) ny(n_x + 1)\,n_y values.
  • v[i][j]v[i][j] is at ((i+12)Δx,j Δx)((i + \tfrac12)\Delta x, j\,\Delta x) for 0≤j≤ny0 \le j \le n_y: the bottom face of cell (i,j)(i, j). There are nx (ny+1)n_x\,(n_y + 1) values.
  • label[i][j]∈{FLUID,SOLID,AIR}label[i][j] \in \{\text{FLUID}, \text{SOLID}, \text{AIR}\}. A cell outside the grid counts as SOLID, so the border of the domain is a wall.

In 3D, add w[i][j][k]w[i][j][k] at ((i+12)Δx,(j+12)Δx,k Δx)((i + \tfrac12)\Delta x, (j + \tfrac12)\Delta x, k\,\Delta x). All the code here is 2D.

A uniform field with offsets (ox,oy)(o_x, o_y) has q[a][b]q[a][b] at ((a+ox)Δx,(b+oy)Δx)((a + o_x)\Delta x, (b + o_y)\Delta x). The offsets are (12,12)(\tfrac12, \tfrac12) for pp, (0,12)(0, \tfrac12) for uu and (12,0)(\tfrac12, 0) for vv. One sampling routine with the offsets as arguments serves all three, which removes a common source of half-cell bugs.

The boundary rules are part of the representation:

  • (S) Solid faces. On a face with a SOLID cell on at least one side, the velocity is the normal velocity of the solid there, which is zero for a fixed wall. The pressure update does not change it.
  • (A) Air cells. In an AIR cell, p=0p = 0. This is the free surface condition with the pressure measured from the air pressure.

The layout is one of several staggered layouts. In atmospheric modeling it is called the Arakawa C grid, while the B and E grids place the two components together at other points. "Marker-and-cell grid" names the layout after the method that introduced it; the method also moves marker particles, which the grid does not need.

Operations

  1. SAMPLE(q, x, y, ox, oy) ▷ q[a][b] at ((a + ox) dx, (b + oy) dx), size na by nb
  2. 1fx <- clamp(x/dx - ox, 0, na - 1); fy <- clamp(y/dx - oy, 0, nb - 1)
  3. 2a <- min(floor(fx), na - 2); b <- min(floor(fy), nb - 2); s <- fx - a; t <- fy - b
  4. 3return (1-s)(1-t) q[a][b] + (1-s) t q[a][b+1] + s (1-t) q[a+1][b] + s t q[a+1][b+1]
  5. DIVERGENCE(u, v)
  6. 4for each cell (i, j): d[i][j] <- (u[i+1][j] - u[i][j] + v[i][j+1] - v[i][j]) / dx
  7. GRADIENT-UPDATE(u, v, p, label, dt, rho) ▷ p = 0 in AIR cells
  8. 5for each inner u face (i, j), 1 <= i <= nx - 1, with no SOLID side and a FLUID side do
  9. 6u[i][j] <- u[i][j] - dt / (rho dx) (p[i][j] - p[i-1][j])
  10. 7the same for each inner v face (i, j), 1 <= j <= ny - 1, with p[i][j] - p[i][j-1]
  11. POISSON-ROW(i, j) ▷ cell (i, j) is FLUID; its row is k
  12. 8for each neighbor c of (i, j) that is not SOLID: A[k][k] <- A[k][k] + 1
  13. 9if c is FLUID then A[k][c] <- A[k][c] - 1
  14. 10b[k] <- -(rho dx / dt) (u[i+1][j] - u[i][j] + v[i][j+1] - v[i][j])

Lines L1 and L2 clamp the point to the box of the sample points, so a query outside the grid returns the value at the nearest border sample. The weights at line L3 are nonnegative and sum to 1.

Line L4 is the finite volume form of the divergence: the flux through each face of the cell, with the outward sign, over the cell area. In the interior it is also the central difference of uu and vv over one cell, which is second order accurate at the cell center.

Lines L5 to L7 update only faces between two cells that are not SOLID, with at least one FLUID side. Faces between two AIR cells keep their values, and faces on a solid keep the solid velocity, rule (S). The difference at line L6 is a central difference at the face center over one cell, again second order.

Lines L8 to L10 build the equations A p=bA\,p = b that make the updated divergence zero. A SOLID neighbor adds nothing, because rule (S) fixes its face. An AIR neighbor adds 1 to the diagonal only, because its pressure is 0. A FLUID neighbor adds 1 to the diagonal and −1-1 off the diagonal. With Δx=1\Delta x = 1 this is the 5-point Laplacian with a minus sign, with Neumann rows at walls and Dirichlet rows at air. Solve it by conjugate gradients (the helper), by multigrid, or by a dense method for small tests.

Example

Divergence. Take nx=2n_x = 2, ny=1n_y = 1, Δx=0.5\Delta x = 0.5 m, u=(0,1,3)u = (0, 1, 3) m/s on the three vertical faces and v[0]=(0,2)v[0] = (0, 2), v[1]=(1,1)v[1] = (1, 1) m/s on the bottom and top faces of the two cells. Line L4 gives

cell uu right minus left vv top minus bottom divergence (1/s)
(0, 0) 1 - 0 = 1 2 - 0 = 2 3 / 0.5 = 6
(1, 0) 3 - 1 = 2 1 - 1 = 0 2 / 0.5 = 4

One projection by hand. A 2 by 2 box with walls, Δx=Δt=ρ=1\Delta x = \Delta t = \rho = 1, and one nonzero face: u[1][0]=1u[1][0] = 1, the face between cells (0, 0) and (1, 0). The divergence is 11 in cell (0, 0) and −1-1 in cell (1, 0). Each cell has two walls and two FLUID neighbors, so each row of AA has 2 on the diagonal and −1-1 twice. In the cell order (0, 0), (0, 1), (1, 0), (1, 1),

A=(2−1−10−120−1−102−10−1−12),b=(−1,0,1,0).A = \begin{pmatrix} 2 & -1 & -1 & 0 \\ -1 & 2 & 0 & -1 \\ -1 & 0 & 2 & -1 \\ 0 & -1 & -1 & 2 \end{pmatrix}, \qquad b = (-1, 0, 1, 0).

AA is singular, because the box is closed: adding a constant to pp changes nothing. The entries of bb sum to zero, so the system is consistent. The solution with mean zero is p=(−38,−18,38,18)p = (-\tfrac38, -\tfrac18, \tfrac38, \tfrac18). Lines L5 to L7 then give

face before pressure difference after
u[1][0]u[1][0] 1 3/8 - (-3/8) = 3/4 1/4
u[1][1]u[1][1] 0 1/8 - (-1/8) = 1/4 -1/4
v[0][1]v[0][1] 0 -1/8 - (-3/8) = 1/4 -1/4
v[1][1]v[1][1] 0 1/8 - 3/8 = -1/4 1/4

Every cell now has zero divergence. The single jet became a loop that turns counterclockwise with speed 14\tfrac14 on each inner face. The kinetic energy 12∑\tfrac12 \sum (velocity squared) dropped from 12\tfrac12 to 18\tfrac18.

A larger box. The helper on a 16 by 16 box with Δx=1/16\Delta x = 1/16 m, Δt=0.01\Delta t = 0.01 s, ρ=1000\rho = 1000 kg/m^3 (per unit depth), and random face velocities in [−1,1][-1, 1] m/s from random.Random(4): the largest cell divergence goes from 55.40 1/s to 4.2×10−114.2 \times 10^{-11} 1/s after 74 conjugate gradient iterations with the tolerance 10−1210^{-12}, and the kinetic energy goes from 350.00 J to 161.63 J. On a 32 by 32 grid (Δx=1/32\Delta x = 1/32 m, seed 5) the solve takes 153 iterations, about twice as many for twice the side, as the condition number predicts. The iteration counts are measurements.

The checkerboard. On a periodic 4 by 4 grid, the MAC Laplacian has a null space of dimension 1: the constants. The Laplacian made from the central difference gradient and divergence on a collocated grid has a null space of dimension 4, and the checkerboard (−1)i+j(-1)^{i+j} is in it. The MAC Laplacian maps the checkerboard to −8-8 times itself, the eigenvalue of largest size, so the pressure solve sees this mode and removes the divergence it causes. The test file checks both counts by exact elimination for n=4n = 4 and n=6n = 6.

Correctness

The correctness claims are identities of the discrete operators. They hold exactly in rational arithmetic, and the tests check them with fractions.Fraction.

  1. SAMPLE reproduces every affine function exactly, and its value lies between the smallest and the largest of the four values it uses. The weights are products of numbers in [0,1][0, 1] that sum to 1.
  2. Let DD be DIVERGENCE and GG the gradient of lines L5 to L7 without the factor Δt/ρ\Delta t / \rho. Then −Δx2 D G=A-\Delta x^2\,D\,G = A on the FLUID cells, so after GRADIENT-UPDATE with the solution of A p=bA\,p = b the divergence of every FLUID cell is zero.
  3. AA is symmetric and positive semidefinite. Its null space is spanned by the indicator vectors of the connected FLUID regions that touch no AIR cell. For each such region, the system is consistent if and only if the sum of bb over the region is zero, which is the discrete compatibility condition: the net flux through the solid boundary of a closed region must be zero.
  4. With fixed walls, the projection is the orthogonal projection onto the divergence-free fields in the inner product ∑u2+∑v2\sum u^2 + \sum v^2. It never increases the kinetic energy.
  5. On a periodic nn by nn grid, the null space of the MAC Laplacian is the constants. For even nn, the collocated central difference Laplacian has a null space of dimension 4.

The proofs, by summation by parts and by discrete Fourier modes, are in proofs/correctness.md.

Proof: The MAC grid operators give a symmetric pressure system, an exact divergence-free projection and no checkerboard null spacefull

We use the layout and the line numbers of the page. All statements are about exact arithmetic. A cell outside the grid is SOLID. For a FLUID cell cc let N(c)N(c) be its four neighbors. A face is open if no side is SOLID and at least one side is FLUID; lines L5 to L7 change exactly the open inner faces. A face with a SOLID side is a solid face.

For a cell field qq with q=0q = 0 on AIR cells, define the face field GqG q by (Gq)f=(qhigh−qlow)/Δx(G q)_f = (q_{\text{high}} - q_{\text{low}}) / \Delta x on an open face ff, where high and low are the cells on the side of larger and smaller index, and (Gq)f=0(G q)_f = 0 on every other face. Define (Dw)c(D w)_c as line L4 computes it. Then line L6 and line L7 do w←w−ΔtρGpw \leftarrow w - \frac{\Delta t}{\rho} G p.

Lemma 1 (SAMPLE). If q[a][b]=α(a+ox)Δx+β(b+oy)Δx+γq[a][b] = \alpha (a + o_x)\Delta x + \beta (b + o_y) \Delta x + \gamma for all a,ba, b, then SAMPLE returns αx+βy+γ\alpha x + \beta y + \gamma at every point (x,y)(x, y) inside the box of the sample points. At any point, the result lies between the least and the largest of the four values used.

Proof. Inside the box, the clamps of line L1 do nothing, so x=(fx+ox)Δxx = (f_x + o_x)\Delta x and y=(fy+oy)Δxy = (f_y + o_y)\Delta x. Line L2 picks a≤fx≤a+1a \le f_x \le a + 1 and b≤fy≤b+1b \le f_y \le b + 1, so s,t∈[0,1]s, t \in [0, 1]. The four weights of line L3 are (1−s)(1−t)(1-s)(1-t), (1−s)t(1-s)t, s(1−t)s(1-t) and stst. They are nonnegative and sum to 11, which proves the second claim at any point. The weighted sum of the aa indices is (1−s)a+s(a+1)=a+s=fx(1-s)a + s(a+1) = a + s = f_x, and in the same way the weighted sum of the bb indices is fyf_y. An affine function of the indices commutes with a weighted sum whose weights sum to 1, so the result is α(fx+ox)Δx+β(fy+oy)Δx+γ=αx+βy+γ\alpha (f_x + o_x)\Delta x + \beta (f_y + o_y)\Delta x + \gamma = \alpha x + \beta y + \gamma. □\square

Lemma 2 (the pressure matrix). For each FLUID cell cc and each cell field pp with p=0p = 0 on AIR cells, −Δx2(DGp)c=(Ap)c-\Delta x^2 (D G p)_c = (A p)_c, where AA is the matrix of lines L8 and L9.

Proof. Each face of cc is either a solid face or an open face, because cc is FLUID. On a solid face (Gp)f=0(G p)_f = 0. On an open face toward the neighbor nn, the outward flux of GpG p is (pn−pc)/Δx(p_n - p_c)/\Delta x: if nn has the larger index this is (Gp)f(G p)_f with the sign ++, and if nn has the smaller index it is −(Gp)f=−(pc−pn)/Δx-(G p)_f = -(p_c - p_n)/\Delta x. So

(DGp)c=1Δx2∑n∈N(c), n not SOLID(pn−pc).(D G p)_c = \frac{1}{\Delta x^2} \sum_{n \in N(c),\ n \text{ not SOLID}} (p_n - p_c).

An AIR neighbor has pn=0p_n = 0 and adds −pc-p_c. A FLUID neighbor adds pn−pcp_n - p_c. Lines L8 and L9 put 11 on the diagonal for each non-SOLID neighbor and −1-1 in the column of each FLUID neighbor, so (Ap)c=∑n not SOLIDpc−∑n FLUIDpn(A p)_c = \sum_{n \text{ not SOLID}} p_c - \sum_{n \text{ FLUID}} p_n, which is −Δx2(DGp)c-\Delta x^2 (D G p)_c. □\square

Theorem 1 (zero divergence). If Ap=bA p = b with bb from line L10, then after GRADIENT-UPDATE every FLUID cell has zero divergence.

Proof. Line L10 is bc=−ρ Δx2Δt(Dw)cb_c = -\frac{\rho\,\Delta x^2}{\Delta t} (D w)_c for the old field ww. GRADIENT-UPDATE gives w′=w−ΔtρGpw' = w - \frac{\Delta t}{\rho} G p, and DD is linear, so by Lemma 2

(Dw′)c=(Dw)c−Δtρ(DGp)c=(Dw)c+ΔtρΔx2(Ap)c=(Dw)c+Δtρ Δx2bc=0.□(D w')_c = (D w)_c - \frac{\Delta t}{\rho} (D G p)_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. \qquad \square

Theorem 2 (the matrix). AA is symmetric and positive semidefinite. Its null space is spanned by the indicator vectors of the connected components of FLUID cells (under 4-neighbor adjacency) that have no AIR neighbor. Ap=bA p = b has a solution if and only if, for each such closed component KK, ∑c∈Kbc=0\sum_{c \in K} b_c = 0. For a closed component this sum is −ρ ΔxΔt-\frac{\rho\,\Delta x}{\Delta t} times the net outflow through the solid faces of KK, so with fixed walls the condition always holds.

Proof. The entry Acn=−1A_{cn} = -1 for two FLUID neighbors is the same in row cc and in row nn, so AA is symmetric. For a vector xx on the FLUID cells,

xTAx=∑{c,n} FLUID neighbors(xc−xn)2+∑c FLUID, n∈N(c) AIRxc2 ≥ 0,x^T A x = \sum_{\{c, n\} \text{ FLUID neighbors}} (x_c - x_n)^2 + \sum_{c \text{ FLUID},\ n \in N(c) \text{ AIR}} x_c^2 \ \ge\ 0,

which follows by collecting, for each pair of FLUID neighbors, the terms xc2−xcxnx_c^2 - x_c x_n from row cc and xn2−xnxcx_n^2 - x_n x_c from row nn, and for each AIR neighbor the term xc2x_c^2. So xTAx=0x^T A x = 0 if and only if xx is constant on each component and zero on each component with an AIR neighbor. For a positive semidefinite matrix, Ax=0A x = 0 if and only if xTAx=0x^T A x = 0, which gives the null space. A symmetric system is solvable if and only if bb is orthogonal to the null space, that is, the sum of bb over each closed component is zero.

For the last claim, sum Δx(Dw)c\Delta x (D w)_c over c∈Kc \in K. A face between two cells of KK appears twice with opposite signs. A face between a cell of KK and a cell outside KK is not toward a FLUID cell (else that cell would be in KK) and not toward AIR (since KK is closed), so it is a solid face. What remains is the net outflow through the solid faces of KK. With fixed walls, rule (S) makes every solid face zero. □\square

The helper removes the mean of bb on each closed component before the solve. This makes the system consistent when rounding or a moving solid gives a small nonzero sum, and it then removes the mean of pp on the component, which picks one solution.

Lemma 3 (summation by parts). Let ww be a face field that is zero on every solid face. For every cell field qq with q=0q = 0 on AIR cells,

∑faces f(Gq)f wf=−∑c FLUIDqc (Dw)c.\sum_{\text{faces } f} (G q)_f\, w_f = -\sum_{c \text{ FLUID}} q_c\, (D w)_c .

Proof. Only open faces have (Gq)f≠0(G q)_f \ne 0. Write (Gq)fwf=(qhighwf−qlowwf)/Δx(G q)_f w_f = (q_{\text{high}} w_f - q_{\text{low}} w_f)/\Delta x and give each term to its cell. Cell cc receives −qcwf/Δx-q_c w_f/\Delta x times the outward sign for each of its open faces: −1-1 for its right and top faces (it is the low cell) and +1+1 for its left and bottom faces. AIR cells have q=0q = 0, and a SOLID cell has no open face. For a FLUID cell, the faces that are not open are solid faces, where w=0w = 0, so the sum of the outward fluxes of its open faces is Δx(Dw)c\Delta x (D w)_c. Hence the total is −∑c FLUIDqc(Dw)c-\sum_{c \text{ FLUID}} q_c (D w)_c. □\square

Theorem 3 (energy). With fixed walls (zero velocity on solid faces), let w′=w−ΔtρGpw' = w - \frac{\Delta t}{\rho} G p with Ap=bA p = b. Then ∑fwf2=∑fwf′2+∑f(ΔtρGp)f2\sum_f w_f^2 = \sum_f w_f'^2 + \sum_f \left(\frac{\Delta t}{\rho} G p\right)_f^2. So the projection does not increase the kinetic energy 12ρΔx2∑fwf2\frac12 \rho \Delta x^2 \sum_f w_f^2, and w′w' is the closest field to ww in this norm among the fields with zero divergence on the FLUID cells, the same values on the faces that are not open, and zero on the solid faces.

Proof. w′w' is zero on solid faces, because GpG p is. By Theorem 1, Dw′=0D w' = 0 on FLUID cells, so Lemma 3 with q=Δtρpq = \frac{\Delta t}{\rho} p gives ∑f(Gq)fwf′=0\sum_f (G q)_f w'_f = 0. Expand ∑fwf2=∑f(wf′+(Gq)f)2\sum_f w_f^2 = \sum_f (w'_f + (G q)_f)^2; the cross term is zero. For the second claim, let zz be any field with these properties. Then z−w′z - w' is zero on all faces that are not open and has zero divergence on FLUID cells, so Lemma 3 gives ∑f(Gq)f(zf−wf′)=0\sum_f (G q)_f (z_f - w'_f) = 0, and ∑f(zf−wf)2=∑f(zf−wf′)2+∑f(Gq)f2≥∑f(wf′−wf)2\sum_f (z_f - w_f)^2 = \sum_f (z_f - w'_f)^2 + \sum_f (G q)_f^2 \ge \sum_f (w'_f - w_f)^2. □\square

With a moving solid, the solid faces carry the solid velocity, Lemma 3 gets a boundary term, and the kinetic energy of the fluid can grow: the solid does work on it.

Theorem 4 (no checkerboard on the MAC grid). On a periodic nn by nn grid with Δx=1\Delta x = 1, let LMAC=DGL_{\text{MAC}} = D G with the face differences of the MAC grid, and let Lcol=DcGcL_{\text{col}} = D_c G_c with Gcpi=(pi+1−pi−1)/2G_c p_i = (p_{i+1} - p_{i-1})/2 and Dcwi=(wi+1−wi−1)/2D_c w_i = (w_{i+1} - w_{i-1})/2 in each axis on a collocated grid. Then the null space of LMACL_{\text{MAC}} is the constants, and for even nn the null space of LcolL_{\text{col}} has dimension 4 and contains the checkerboard (−1)i+j(-1)^{i+j}.

Proof. On the MAC grid, (DGp)ij=pi+1,j+pi−1,j+pi,j+1+pi,j−1−4pij(D G p)_{ij} = p_{i+1,j} + p_{i-1,j} + p_{i,j+1} + p_{i,j-1} - 4 p_{ij}. On the collocated grid, (DcGcp)i=12(pi+2−pi2−pi−pi−22)=pi+2−2pi+pi−24(D_c G_c p)_i = \frac12 \left( \frac{p_{i+2} - p_i}{2} - \frac{p_i - p_{i-2}}{2} \right) = \frac{p_{i+2} - 2 p_i + p_{i-2}}{4} in each axis: the two central differences skip the direct neighbors. Both operators are circulant in each axis, so the n2n^2 Fourier modes ekl(i,j)=exp⁡(2πι(ki+lj)/n)e_{kl}(i, j) = \exp(2\pi\iota (k i + l j)/n), 0≤k,l<n0 \le k, l < n, which form a basis, are eigenvectors. The eigenvalues are

λMAC(k,l)=−4sin⁡2πkn−4sin⁡2πln,λcol(k,l)=−sin⁡22πkn−sin⁡22πln.\lambda_{\text{MAC}}(k, l) = -4 \sin^2\frac{\pi k}{n} - 4 \sin^2 \frac{\pi l}{n}, \qquad \lambda_{\text{col}}(k, l) = -\sin^2 \frac{2\pi k}{n} - \sin^2\frac{2 \pi l}{n}.

λMAC=0\lambda_{\text{MAC}} = 0 only for k=l=0k = l = 0, the constant mode. λcol=0\lambda_{\text{col}} = 0 when 2k/n2k/n and 2l/n2l/n are both integers, that is k,l∈{0,n/2}k, l \in \{0, n/2\} for even nn: four modes, which are real (±1\pm 1 patterns), and k=l=n/2k = l = n/2 is the checkerboard. The real null space has the same dimension as the complex one, because the operators are real. For the checkerboard on the MAC grid, λMAC(n/2,n/2)=−8\lambda_{\text{MAC}}(n/2, n/2) = -8. □\square

The test file checks Lemma 1 and Lemma 2 exactly with fractions.Fraction on a grid with SOLID and AIR cells, the symmetry of AA, the nullities 1 and 4 for n=4n = 4 and n=6n = 6 by exact elimination, and Theorems 1 to 3 in floating point through the helper.

Complexity

Let g=nxnyg = n_x n_y be the number of cells. The grid stores gg pressures, (nx+1)ny+nx(ny+1)=2g+nx+ny(n_x + 1) n_y + n_x (n_y + 1) = 2g + n_x + n_y face velocities and gg labels, so the space is Θ(g)\Theta(g), plus Θ(g)\Theta(g) per extra scalar field.

SAMPLE costs O(1)O(1). DIVERGENCE, GRADIENT-UPDATE and the assembly of AA and bb cost Θ(g)\Theta(g), because each cell and face does a constant amount of work. AA has at most 5 nonzeros per row.

The solve dominates. One conjugate gradient iteration costs Θ(g)\Theta(g). On an NN by NN grid the condition number of AA grows as N2N^2, so plain conjugate gradients need O(N)O(N) iterations for a fixed reduction of the error, which is O(g3/2)O(g^{3/2}) in total in 2D. Multigrid reaches a fixed reduction in O(g)O(g). The measured counts above (74 and 153) fit the O(N)O(N) estimate.

Variants

  • 3D. The same layout with a third component ww on the faces normal to zz. Every statement above holds with 7-point stencils.
  • Collocated grids. All components at cell centers. Simpler to advect, but the central difference projection has the checkerboard null space. Stam's stable fluids used a cell-centered grid, and computational fluid dynamics codes with collocated grids add a correction to the face fluxes (the Rhie-Chow interpolation) to remove the checkerboard.
  • Cut cells and fractional weights. Faces partly covered by a solid get a weight between 0 and 1 in the pressure equation. See variational solid-fluid coupling.
  • Free surface at sub-cell accuracy. The ghost fluid method puts p=0p = 0 at the interpolated surface position instead of the AIR cell center.
  • Sparse and adaptive grids. Store only tiles near the fluid, or refine with an octree. The face placement stays the same inside each tile or cell.
  • Particles on a MAC grid. Particle-in-cell, FLIP and APIC carry velocity on particles and use the MAC grid only for the projection.

When to use it

Use a MAC grid for any incompressible grid fluid with a pressure projection: smoke, fire, liquids with a level set or particles, and the grid part of hybrid particle methods. It gives the most compact and robust pressure equation, and the boundary conditions are simple to state on faces.

A collocated grid is easier when the main work is advection of many vector quantities, or when the code also runs other solvers that expect values at the same points. For compressible flow with shocks, the finite volume method with collocated cell averages and Riemann solvers is the usual choice.

Pitfalls

  • Off by half a cell. uu has nx+1n_x + 1 columns and vv has ny+1n_y + 1 rows. Sampling uu with the offsets of pp shifts the whole velocity field by half a cell. Use one sampling routine with explicit offsets.
  • Velocity at a cell center. It is the average of the two uu faces and the two vv faces. Do not take u[i][j]u[i][j] as the velocity of cell (i,j)(i, j).
  • Boundaries before the divergence. Set the solid face velocities, rule (S), before computing bb. Otherwise the right side contains flow through walls, and the closed system can become inconsistent.
  • The singular closed box. With walls on all sides, AA is singular. Remove the mean of bb over each closed region and fix the free constant of pp, for example by removing its mean. The helper does both. A floating point bb with a small nonzero sum makes plain conjugate gradients stall.
  • AIR is not SOLID. An AIR neighbor adds 1 to the diagonal; a SOLID neighbor adds nothing. Mixing them up gives a free surface that acts like a wall, or a wall that leaks.
  • Faces between AIR cells. The projection does not touch them, but advection reads them. Extrapolate the fluid velocity into a few layers of AIR faces before advection.
  • Units of bb. The right side at line L10 has the factor ρ Δx/Δt\rho\,\Delta x / \Delta t. Code that solves for p Δt/ρp\,\Delta t / \rho instead must use the same scale in GRADIENT-UPDATE.

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.

mac_grid.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mac-grid/. The authors are listed in prov/NKCN2S.jsonl.

"""The operations of a 2D MAC grid, written out on plain arrays.

The arrays follow the layout of 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). A cell outside
the grid is SOLID. The functions use only + - * / and comparisons, so they also run on
fractions.Fraction values, which lets the tests check the identities exactly.

The file also has the two periodic Laplacians of the page: the MAC (staggered) one and
the collocated one with central differences, to show the checkerboard null space.
"""

import math
from fractions import Fraction

from macgrid import AIR, FLUID, SOLID


def label_of(label, i, j):
    """The label of cell (i, j); a cell outside the grid is SOLID."""
    if 0 <= i < len(label) and 0 <= j < len(label[0]):
        return label[i][j]
    return SOLID


def sample(q, x, y, dx, ox, oy):
    """Bilinear sample at (x, y) of q, where q[a][b] is at ((a + ox) dx, (b + oy) dx)."""
    na, nb = len(q), len(q[0])
    if na < 2 or nb < 2:
        raise ValueError("sample needs at least 2 by 2 values")
    fx = min(max(x / dx - ox, 0), na - 1)  # @line L1
    fy = min(max(y / dx - oy, 0), nb - 1)
    a = min(int(math.floor(fx)), na - 2)  # @line L2
    b = min(int(math.floor(fy)), nb - 2)
    s, t = fx - a, fy - b
    return ((1 - s) * (1 - t) * q[a][b] + (1 - s) * t * q[a][b + 1]  # @line L3
            + s * (1 - t) * q[a + 1][b] + s * t * q[a + 1][b + 1])


def divergence(u, v, dx):
    """The divergence of every cell: (u[i+1][j] - u[i][j] + v[i][j+1] - v[i][j]) / dx."""
    nx, ny = len(v), len(u[0])
    return [[(u[i + 1][j] - u[i][j] + v[i][j + 1] - v[i][j]) / dx  # @line L4
             for j in range(ny)] for i in range(nx)]


def gradient_update(u, v, p, label, dt, rho, dx):
    """Subtract dt / (rho dx) times the pressure difference on each open face, in place.

    A face is open if no side is SOLID and at least one side is FLUID. AIR cells have p = 0.
    """
    nx, ny = len(p), len(p[0])
    s = dt / (rho * dx)

    def pr(i, j):
        return 0 if label[i][j] == AIR else p[i][j]

    for i in range(1, nx):  # @line L5
        for j in range(ny):
            a, c = label[i - 1][j], label[i][j]
            if a == SOLID or c == SOLID or (a != FLUID and c != FLUID):
                continue
            u[i][j] = u[i][j] - s * (pr(i, j) - pr(i - 1, j))  # @line L6
    for i in range(nx):  # @line L7
        for j in range(1, ny):
            a, c = label[i][j - 1], label[i][j]
            if a == SOLID or c == SOLID or (a != FLUID and c != FLUID):
                continue
            v[i][j] = v[i][j] - s * (pr(i, j) - pr(i, j - 1))


def poisson_system(u, v, label, dt, rho, dx):
    """The dense pressure system A p = b over the FLUID cells, in row-major cell order.

    Returns (cells, A, b). Row k of A has the number of non-SOLID neighbors on the
    diagonal and -1 for each FLUID neighbor. b = -(rho dx / dt) times the face flux sum.
    """
    nx, ny = len(label), len(label[0])
    cells = [(i, j) for i in range(nx) for j in range(ny) if label[i][j] == FLUID]
    idx = {c: k for k, c in enumerate(cells)}
    n = len(cells)
    a_mat = [[0] * n for _ in range(n)]
    b = [0] * n
    for k, (i, j) in enumerate(cells):
        for (a, c) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
            lab = label_of(label, a, c)
            if lab == SOLID:
                continue
            a_mat[k][k] += 1  # @line L8
            if lab == FLUID:
                a_mat[k][idx[(a, c)]] -= 1  # @line L9
        b[k] = -rho * dx / dt * (u[i + 1][j] - u[i][j] + v[i][j + 1] - v[i][j])  # @line L10
    return cells, a_mat, b


def periodic_mac_laplacian(n):
    """The matrix of D G on an n by n periodic MAC grid with dx = 1 (the 5-point Laplacian)."""
    m = n * n
    a = [[Fraction(0)] * m for _ in range(m)]
    for i in range(n):
        for j in range(n):
            k = i * n + j
            for (di, dj) in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                a[k][((i + di) % n) * n + (j + dj) % n] += 1
            a[k][k] -= 4
    return a


def periodic_collocated_laplacian(n):
    """The matrix of D G on an n by n periodic collocated grid, both by central differences.

    The gradient is (p[i+1] - p[i-1]) / 2, so D G reaches two cells away and skips the
    direct neighbors: the stencil is (p[i+2] - 2 p[i] + p[i-2]) / 4 in each axis.
    """
    m = n * n
    a = [[Fraction(0)] * m for _ in range(m)]
    q = Fraction(1, 4)
    for i in range(n):
        for j in range(n):
            k = i * n + j
            for (di, dj) in ((2, 0), (-2, 0), (0, 2), (0, -2)):
                a[k][((i + di) % n) * n + (j + dj) % n] += q
            a[k][k] -= 4 * q
    return a


def nullity(a):
    """The dimension of the null space of a square matrix of Fractions, by exact elimination."""
    m = [list(row) for row in a]
    n = len(m)
    rank = 0
    for col in range(n):
        piv = next((r for r in range(rank, n) if m[r][col] != 0), None)
        if piv is None:
            continue
        m[rank], m[piv] = m[piv], m[rank]
        for r in range(n):
            if r != rank and m[r][col] != 0:
                f = m[r][col] / m[rank][col]
                m[r] = [x - f * y for x, y in zip(m[r], m[rank])]
        rank += 1
    return n - rank
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_mac_grid.py 232 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mac-grid/. The authors are listed in prov/NKCN2S.jsonl.

"""Tests of the MAC grid page and of the shared helper macgrid.py."""

import random
from fractions import Fraction

import macgrid
from macgrid import AIR, FLUID, SOLID
from mac_grid import (
    divergence,
    gradient_update,
    nullity,
    periodic_collocated_laplacian,
    periodic_mac_laplacian,
    poisson_system,
    sample,
)


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 dense_solve(a, b):
    """Gaussian elimination with partial pivoting (works on floats and Fractions)."""
    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] * 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


# ---- the page: layout, sampling, divergence and the Poisson rows ----

def test_array_sizes():
    g = macgrid.make_grid(5, 3, 0.25)
    assert len(g.p) == 5 and len(g.p[0]) == 3
    assert len(g.u) == 6 and len(g.u[0]) == 3
    assert len(g.v) == 5 and len(g.v[0]) == 4
    assert macgrid.cell_center(g, 0, 0) == (0.125, 0.125)
    assert macgrid.cell_label(g, -1, 0) == SOLID and macgrid.cell_label(g, 0, 3) == SOLID


def test_sample_reproduces_affine_fields_exactly():
    dx = Fraction(1, 4)
    for ox, oy in ((0, Fraction(1, 2)), (Fraction(1, 2), 0), (Fraction(1, 2), Fraction(1, 2))):
        q = [[3 * (a + ox) * dx - 2 * (b + oy) * dx + 1 for b in range(5)] for a in range(6)]
        for (x, y) in ((Fraction(1, 3), Fraction(2, 5)), (Fraction(7, 8), Fraction(1, 2)), (Fraction(5, 7), Fraction(3, 4))):
            assert sample(q, x, y, dx, ox, oy) == 3 * x - 2 * y + 1


def test_sample_agrees_with_helper():
    g, rng = random_grid(6, 5, 0.2, 1)
    for _ in range(200):
        x, y = rng.uniform(-0.3, 1.5), rng.uniform(-0.3, 1.3)
        assert abs(sample(g.u, x, y, g.dx, 0.0, 0.5) - macgrid.u_at(g, x, y)) < 1e-14
        assert abs(sample(g.v, x, y, g.dx, 0.5, 0.0) - macgrid.v_at(g, x, y)) < 1e-14


def test_divergence_matches_helper_and_example():
    g, _ = random_grid(4, 4, 0.5, 2)
    d1 = divergence(g.u, g.v, g.dx)
    d2 = macgrid.divergence(g)
    assert all(abs(d1[i][j] - d2[i][j]) < 1e-14 for i in range(4) for j in range(4))
    u = [[Fraction(0)], [Fraction(1)], [Fraction(3)]]
    v = [[Fraction(0), Fraction(2)], [Fraction(1), Fraction(1)]]
    assert divergence(u, v, Fraction(1, 2)) == [[Fraction(6)], [Fraction(4)]]


def test_divergence_of_gradient_is_minus_poisson_matrix_exactly():
    rng = random.Random(3)
    nx, ny = 5, 4
    label = [[FLUID] * ny for _ in range(nx)]
    label[2][1] = SOLID
    label[0][3] = AIR
    label[4][3] = AIR
    dt, rho, dx = Fraction(1, 10), Fraction(1000), Fraction(1, 8)
    u = [[Fraction(0)] * ny for _ in range(nx + 1)]
    v = [[Fraction(0)] * (ny + 1) for _ in range(nx)]
    p = [[Fraction(rng.randint(-50, 50), 7) if label[i][j] == FLUID else Fraction(0) for j in range(ny)] for i in range(nx)]
    cells, a_mat, _ = poisson_system(u, v, label, dt, rho, dx)
    gradient_update(u, v, p, label, dt, rho, dx)
    d = divergence(u, v, dx)
    for k, (i, j) in enumerate(cells):
        ap = sum(a_mat[k][m] * p[c[0]][c[1]] for m, c in enumerate(cells))
        assert d[i][j] == dt / (rho * dx * dx) * ap


def test_poisson_matrix_is_symmetric_with_the_right_diagonal():
    label = [[FLUID, FLUID, AIR], [FLUID, SOLID, FLUID], [FLUID, FLUID, FLUID]]
    u = [[0] * 3 for _ in range(4)]
    v = [[0] * 4 for _ in range(3)]
    cells, a_mat, _ = poisson_system(u, v, label, 1, 1, 1)
    n = len(cells)
    assert all(a_mat[r][c] == a_mat[c][r] for r in range(n) for c in range(n))
    k = cells.index((0, 1))
    assert a_mat[k][k] == 2  # the wall on the left and the SOLID cell (1, 1) close two faces
    assert sum(a_mat[k]) == 1  # one FLUID neighbor, and the AIR neighbor adds only to the diagonal


def test_checkerboard_null_space():
    for n in (4, 6):
        assert nullity(periodic_mac_laplacian(n)) == 1
        assert nullity(periodic_collocated_laplacian(n)) == 4
    n = 4
    a = periodic_collocated_laplacian(n)
    check = [Fraction((-1) ** (i + j)) for i in range(n) for j in range(n)]
    assert all(sum(a[r][c] * check[c] for c in range(n * n)) == 0 for r in range(n * n))
    a = periodic_mac_laplacian(n)
    assert all(sum(a[r][c] * check[c] for c in range(n * n)) == -8 * check[r] for r in range(n * n))


# ---- the shared helper macgrid.py ----

def test_helper_project_box():
    g, _ = random_grid(16, 16, 1.0 / 16.0, 4)
    macgrid.set_solid_boundaries(g)
    e0 = macgrid.kinetic_energy(g, 1000.0)
    it = macgrid.project(g, 0.01, 1000.0)
    assert it > 0
    assert macgrid.max_fluid_divergence(g) < 1e-8
    assert macgrid.kinetic_energy(g, 1000.0) <= e0 * (1 + 1e-12)
    mean = sum(g.p[i][j] for i in range(16) for j in range(16)) / 256
    assert abs(mean) < 1e-9 * max(abs(g.p[i][j]) for i in range(16) for j in range(16))


def test_helper_project_32_grid():
    g, _ = random_grid(32, 32, 1.0 / 32.0, 5)
    e0 = macgrid.kinetic_energy(g, 1000.0)
    macgrid.project(g, 1.0 / 60.0, 1000.0)
    assert macgrid.max_fluid_divergence(g) < 1e-8
    assert macgrid.kinetic_energy(g, 1000.0) <= e0


def test_helper_project_with_air_and_solid():
    g, _ = random_grid(10, 10, 0.1, 6)
    for i in range(10):
        for j in range(7, 10):
            g.label[i][j] = AIR
    g.label[4][2] = SOLID
    g.label[5][2] = SOLID
    macgrid.set_solid_boundaries(g)
    e0 = macgrid.kinetic_energy(g, 1.0)
    macgrid.project(g, 0.05, 1.0)
    assert macgrid.max_fluid_divergence(g) < 1e-8
    assert macgrid.kinetic_energy(g, 1.0) <= e0 * (1 + 1e-12)
    assert all(g.p[i][j] == 0.0 for i in range(10) for j in range(7, 10))
    assert g.u[5][2] == 0.0 and g.u[4][2] == 0.0 and g.v[4][2] == 0.0


def test_helper_pressure_matches_dense_solve():
    g, _ = random_grid(5, 4, 0.25, 7)
    for i in range(5):
        g.label[i][3] = AIR
    g.label[2][1] = SOLID
    macgrid.set_solid_boundaries(g)
    cells, a_mat, b = poisson_system(g.u, g.v, g.label, 0.1, 2.0, g.dx)
    x = dense_solve(a_mat, b)
    macgrid.pressure_solve(g, 0.1, 2.0)
    assert all(abs(g.p[i][j] - x[k]) < 1e-9 * (1 + abs(x[k])) for k, (i, j) in enumerate(cells))


def test_helper_two_closed_components():
    g, _ = random_grid(6, 4, 0.5, 8)
    for j in range(4):
        g.label[3][j] = SOLID
    macgrid.project(g, 0.1, 1.0)
    assert macgrid.max_fluid_divergence(g) < 1e-8
    for rng_i in (range(0, 3), range(4, 6)):
        cells = [(i, j) for i in rng_i for j in range(4)]
        assert abs(sum(g.p[i][j] for (i, j) in cells)) < 1e-9


def test_helper_moving_solid_velocity():
    g = macgrid.make_grid(6, 6, 0.5)
    g.label[2][2] = SOLID
    macgrid.set_solid_boundaries(g, lambda x, y: (1.0, -2.0))
    assert g.u[2][2] == 1.0 and g.u[3][2] == 1.0 and g.v[2][2] == -2.0 and g.v[2][3] == -2.0
    assert g.u[0][2] == 0.0 and g.v[2][0] == 0.0
    macgrid.project(g, 0.1, 1.0, solid_velocity=lambda x, y: (1.0, -2.0))
    assert macgrid.max_fluid_divergence(g) < 1e-8


def test_helper_advect_constant_and_maximum_principle():
    g, rng = random_grid(12, 12, 1.0 / 12.0, 9)
    macgrid.project(g, 0.1, 1.0)
    const = [[2.5] * 12 for _ in range(12)]
    out = macgrid.advect(g, const, 0.3)
    assert all(abs(t - 2.5) < 1e-14 for col in out for t in col)
    q = [[rng.uniform(0.0, 1.0) for _ in range(12)] for _ in range(12)]
    dt = 0.4
    out = macgrid.advect(g, q, dt)
    dx = g.dx
    for a in range(12):
        for b in range(12):
            xb, yb = macgrid.backtrace(g, (a + 0.5) * dx, (b + 0.5) * dx, dt)
            fx = min(max(xb / dx - 0.5, 0.0), 11.0)
            fy = min(max(yb / dx - 0.5, 0.0), 11.0)
            i0, j0 = min(int(fx), 10), min(int(fy), 10)
            st = [q[i0][j0], q[i0 + 1][j0], q[i0][j0 + 1], q[i0 + 1][j0 + 1]]
            assert min(st) - 1e-14 <= out[a][b] <= max(st) + 1e-14


def test_helper_advect_uniform_flow_shifts_linear_field():
    g = macgrid.make_grid(10, 10, 0.1)
    for col in g.u:
        for j in range(10):
            col[j] = 0.5
    q = [[(a + 0.5) * 0.1 for b in range(10)] for a in range(10)]
    out = macgrid.advect(g, q, 0.2)
    for a in range(2, 10):
        assert abs(out[a][4] - (q[a][4] - 0.1)) < 1e-12
    nu, nv = macgrid.advect_velocity(g, 0.2)
    assert all(abs(t - 0.5) < 1e-14 for col in nu for t in col)
    assert all(t == 0.0 for col in nv for t in col)

History

Harlow and Welch (1965) introduced the layout at Los Alamos as the grid of their marker-and-cell method for incompressible flow with a free surface: pressure at cell centers, velocity components on the faces, and marker particles to track the liquid. In meteorology the same layout became known as the C grid in Arakawa's classification of staggered grids. Foster and Metaxas (1996) used it for the first liquid animations in computer graphics, with marker particles and an explicit solver. Stam (1999) used a cell-centered grid in stable fluids, and Fedkiw, Stam and Jensen (2001) went back to the staggered layout of Foster and Metaxas for smoke. Since then the MAC grid is the default of grid fluid solvers in animation, and Bridson's book builds every grid method on it.

References

  1. Francis H. Harlow and J. Eddie Welch, Numerical calculation of time-dependent viscous incompressible flow of fluid with free surface, Physics of Fluids 8(12), 1965, 2182-2189, the finite difference mesh with the pressure at cell centers and the velocity components on the cell faces
  2. Robert Bridson, Fluid Simulation for Computer Graphics, second edition, CRC Press, 2015, the chapter Overview of Numerical Simulation (section Grids) and the chapter Making Fluids Incompressible (the discrete pressure gradient, the discrete divergence, the pressure equations and the compatibility condition)
  3. Nick Foster and Dimitri Metaxas, Realistic animation of liquids, Graphical Models and Image Processing 58(5), 1996, 471-483, Section 3.1, the staggered velocities at face centers and the pressure at cell centers
  4. Ronald Fedkiw, Jos Stam and Henrik Wann Jensen, Visual simulation of smoke, SIGGRAPH 2001, 15-22, Section 4, the staggered grid and the sampling of the velocity at cell faces

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.divergence
  • a full proof of time.gradient_update
  • a full proof of time.poisson_build
  • a full proof of time.pressure_solve
  • a full proof of time.sample
  • a full proof of space.total
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)
WritingW4 complete
  • a review of the text: no review record reviews/NKCN2S/text.yaml