Algorithm Search⌘K

Algorithmcore

Marker-and-cell method

Also called MAC method.

Solves incompressible flow on a staggered grid, with pressures at cell centers and velocities on faces, and tracks the free surface with marker particles.

Time
Θ(N (M K + P)) worst
Space
Θ(M + P) extra
Where
K = the pressure solver iterations per step; M = the number of grid cells; N = the number of time steps; P = the number of marker particles
Properties
deterministicdivergence freeexplicitstaggered
Origin
Francis H. Harlow, J. Eddie Welch, 1965

The marker-and-cell (MAC) method computes time-dependent incompressible flow on a staggered grid. Pressure lives at cell centers, and each velocity component lives on the cell faces normal to it. Each time step updates the velocity from advection, viscosity and gravity, then solves a Poisson equation for the pressure that makes the new velocity divergence free in every cell. Massless marker particles move with the flow; the cells that hold markers are the fluid, and the empty cells are air, which lets the method follow a free surface. Graphics readers know the grid as the MAC grid and the step as the pressure projection of stable fluids. The MAC method as a CFD scheme adds central, consistent differences for advection and viscosity, a time step set by accuracy and stability limits, and wall conditions for each velocity component, so that the error falls at a measured second order rate in space.

In plain words

Divide the box into square cells. Keep one pressure value in the middle of each cell. Keep the flow through each wall between two cells as one number on that wall. Then the amount that leaves a cell is easy to count: add up the four walls. Each step has three moves. First, let the flow carry itself along and feel friction and gravity. Second, find the pressures that make each cell lose exactly as much as it gains, and push the flow with them. Third, move a cloud of tiny tracer dots with the flow. The dots show where the water is, so cells with dots are wet and cells without dots are dry. Because pressures and wall flows sit at different places, the pressures cannot form a hidden zigzag pattern that the flow does not feel.

The problem

Solve the incompressible Navier-Stokes equations ut+(u⋅∇)u=−∇p+νΔu+g\mathbf{u}_t + (\mathbf{u}\cdot\nabla)\mathbf{u} = -\nabla p + \nu\Delta\mathbf{u} + \mathbf{g}, ∇⋅u=0\nabla\cdot\mathbf{u} = 0 in a rectangular box, with pp the pressure divided by the density and ν\nu the kinematic viscosity, up to a time TT. At the walls the normal velocity is zero. The tangential velocity is either free (free slip, zero shear) or set (no slip, with a moving lid as a special case). The cost is counted in real arithmetic operations and pressure solver iterations on M=nxnyM = n_x n_y cells.

The grid places pi,jp_{i,j} at the cell center ((i+12)Δx,(j+12)Δy)((i + \tfrac12)\Delta x, (j + \tfrac12)\Delta y), ui,ju_{i,j} at (iΔx,(j+12)Δy)(i\Delta x, (j + \tfrac12)\Delta y) for i=0,…,nxi = 0, \dots, n_x, and vi,jv_{i,j} at ((i+12)Δx,jΔy)((i + \tfrac12)\Delta x, j\Delta y) for j=0,…,nyj = 0, \dots, n_y. The wall faces hold the normal velocity, which is zero. DD is the divergence at the centers, GG the gradient at the interior faces, and A=−DGA = -DG.

The algorithm

  1. MAC(u, v, markers, Δt, ν, g, N)
  2. 1for n ← 0 to N - 1 do
  3. 2fill the ghost values from the wall conditions, and form -(u·∇)u + ν Δ_h u
  4. 3(u*, v*) ← (u, v) + Δt (-(u·∇)u + ν Δ_h u + g) ▷ interior faces only
  5. 4solve A p = -D(u*, v*) / Δt ▷ ∂p/∂n = 0 at the walls
  6. 5(u, v) ← (u*, v*) - Δt G p ▷ interior faces only
  7. 6move every marker with the interpolated velocity
  8. 7flag the cells that hold a marker as fluid
  9. 8return (u, v, p, markers, fluid cells)

The tangential velocity at a wall enters only through ghost values outside the box. For free slip the ghost is a mirror copy of the first interior value. For no slip with wall speed UU it is 2U2U minus the interior value, so that the average on the wall is UU. The wall faces are never changed, and GG is zero there, which gives the pressure equation the homogeneous Neumann condition. The advection term uses central differences with the other component averaged from its four nearest faces. Markers move by a midpoint step with bilinear interpolation of each component.

The implementation on this page handles confined flow, where all cells are fluid. For a free surface, Harlow and Welch (1965) set the pressure in surface cells from the normal stress condition, set the velocities on faces between fluid and empty cells so that the surface cells are divergence free, and leave empty cells out of the pressure solve.

Example

Why the staggering matters, by hand. Take the checkerboard pressure pi,j=(−1)i+jp_{i,j} = (-1)^{i+j} on a 4×44 \times 4 grid with Δx=14\Delta x = \tfrac14. A collocated central gradient (pi+1,j−pi−1,j)/(2Δx)(p_{i+1,j} - p_{i-1,j})/(2\Delta x) is zero at every interior point, because both neighbors have the same sign. A solver that uses it cannot see or remove this pressure. The MAC gradient (pi,j−pi−1,j)/Δx(p_{i,j} - p_{i-1,j})/\Delta x is ±8\pm 8 on every interior face, so the checkerboard is not in the null space. On the MAC grid, −DG-DG is exactly the 5-point Neumann matrix, and the only pressures it ignores are the constants. For a 3×23 \times 2 grid with Δx=1\Delta x = 1, Δy=12\Delta y = \tfrac12 the corner cell's row is (1+4,−1,−4)(1 + 4, -1, -4) for itself, its east neighbor and its north neighbor; the test file checks every column of this matrix in exact rational arithmetic.

Free-slip Taylor-Green vortex. In the box [0,π]2[0, \pi]^2 the field u=sin⁡xcos⁡y e−2νtu = \sin x \cos y\, e^{-2\nu t}, v=−cos⁡xsin⁡y e−2νtv = -\cos x \sin y\, e^{-2\nu t}, p=14(cos⁡2x+cos⁡2y) e−4νtp = \tfrac14(\cos 2x + \cos 2y)\, e^{-4\nu t} is an exact solution with zero normal velocity and zero shear at the walls. With ν=0.1\nu = 0.1, T=0.2T = 0.2 and Δt≈0.4 Δx2\Delta t \approx 0.4\,\Delta x^2, the maximum errors at TT (pressure with the mean removed) are:

cells steps velocity error order pressure error order
8×88 \times 8 3 2.349e-4 7.184e-3
16×1616 \times 16 13 6.414e-5 1.87 1.736e-3 2.05
32×3232 \times 32 52 1.607e-5 2.00 4.441e-4 1.97

The divergence after each step is below 10−1310^{-13}. In the same vortex, frozen in time on a 16×1616 \times 16 grid, four markers moved for 100 midpoint steps of Δt=0.05\Delta t = 0.05 keep the stream function sin⁡xsin⁡y\sin x \sin y constant to 1.9×10−41.9 \times 10^{-4}, so they stay on their streamlines. In a no-slip cavity of 8×88 \times 8 cells with the lid moving at speed 1 and ν=0.01\nu = 0.01, 60 steps of Δt=0.01\Delta t = 0.01 give the start of the primary vortex: the top row moves right with the lid and the fluid below it returns to the left. These are measurements from the implementation on this page.

Correctness

The proof is in proofs/correctness.md. For velocity fields with zero normal velocity on the walls, summation by parts gives ⟨u,Gp⟩=−(Du,p)\langle\mathbf{u}, Gp\rangle = -(D\mathbf{u}, p). So A=−DGA = -DG is the symmetric Neumann 5-point matrix, its null space is the constants, and the right side of the pressure equation has zero sum because nothing flows through the walls. The pressure equation then has a solution, the new velocity has zero divergence in every cell, and it is the orthogonal projection of the predicted velocity onto the divergence-free fields, so the projection never adds kinetic energy. The same lemma shows that only constant pressures have zero MAC gradient, so there is no checkerboard mode. The proof also shows that marker interpolation is exact for linear fields. The second order spatial accuracy is a measurement, not a theorem proved here.

Proof: The MAC pressure step in a closed box gives an exactly divergence-free velocity, and the MAC gradient has no checkerboard null spacefull

Setting. The box has nx×ny=Mn_x \times n_y = M cells of size Δx×Δy\Delta x \times \Delta y. A face field u=(u,v)\mathbf{u} = (u, v) has ui,ju_{i,j} on the vertical faces, i=0,…,nxi = 0, \dots, n_x, and vi,jv_{i,j} on the horizontal faces, j=0,…,nyj = 0, \dots, n_y. Let WW be the face fields with zero values on the wall faces (u0,j=unx,j=0u_{0,j} = u_{n_x,j} = 0 and vi,0=vi,ny=0v_{i,0} = v_{i,n_y} = 0); every iterate of the method is in WW, because lines L3 and L5 change only interior faces. For a cell field pp,

(Du)i,j=ui+1,j−ui,jΔx+vi,j+1−vi,jΔy,(Gp)i,jx=pi,j−pi−1,jΔx (0<i<nx),(Gp)i,jy=pi,j−pi,j−1Δy (0<j<ny),(D\mathbf{u})_{i,j} = \frac{u_{i+1,j} - u_{i,j}}{\Delta x} + \frac{v_{i,j+1} - v_{i,j}}{\Delta y}, \qquad (Gp)^x_{i,j} = \frac{p_{i,j} - p_{i-1,j}}{\Delta x} \ (0 < i < n_x), \qquad (Gp)^y_{i,j} = \frac{p_{i,j} - p_{i,j-1}}{\Delta y} \ (0 < j < n_y),

and GG is zero on the wall faces, so Gp∈WGp \in W. The inner products are the plain sums ⟨u,w⟩\langle \mathbf{u}, \mathbf{w}\rangle over faces and (p,q)(p, q) over cells.

Lemma 1 (summation by parts). For u∈W\mathbf{u} \in W and every cell field pp, ⟨u,Gp⟩=−(Du,p)\langle \mathbf{u}, Gp\rangle = -(D\mathbf{u}, p).

Proof. Fix a row jj. With u0,j=unx,j=0u_{0,j} = u_{n_x,j} = 0,

∑i=0nx−1pi,j(ui+1,j−ui,j)=∑i=1nxpi−1,jui,j−∑i=0nx−1pi,jui,j=−∑i=1nx−1ui,j(pi,j−pi−1,j),\sum_{i=0}^{n_x - 1} p_{i,j}(u_{i+1,j} - u_{i,j}) = \sum_{i=1}^{n_x} p_{i-1,j}u_{i,j} - \sum_{i=0}^{n_x-1} p_{i,j}u_{i,j} = -\sum_{i=1}^{n_x - 1} u_{i,j}(p_{i,j} - p_{i-1,j}),

because the terms with i=0i = 0 and i=nxi = n_x vanish. Dividing by Δx\Delta x and summing over jj gives the xx part, and the columns give the yy part. □\square

Lemma 2 (−DG-DG is the Neumann 5-point matrix). A:=−DGA := -DG is the matrix of minus the 5-point Laplacian in which a missing neighbor across a wall drops out of the stencil, which is poisson2d(..., bc="neumann"). It is symmetric positive semidefinite, and Ap=0Ap = 0 exactly when Gp=0Gp = 0, exactly when pp is constant.

Proof. At an interior cell, (DGp)i,j=(pi+1,j−2pi,j+pi−1,j)/Δx2+(… )/Δy2(DGp)_{i,j} = (p_{i+1,j} - 2p_{i,j} + p_{i-1,j})/\Delta x^2 + (\dots)/\Delta y^2. At a cell next to the wall i=0i = 0, the face (0,j)(0, j) carries (Gp)x=0(Gp)^x = 0, so the xx part is (p1,j−p0,j)/Δx2(p_{1,j} - p_{0,j})/\Delta x^2: the west neighbor drops out, which is the discrete condition ∂p/∂n=0\partial p/\partial n = 0. By Lemma 1 with u=Gq∈W\mathbf{u} = Gq \in W, (Ap,q)=⟨Gp,Gq⟩(Ap, q) = \langle Gp, Gq\rangle, so AA is symmetric and (Ap,p)=∥Gp∥2≥0(Ap, p) = \|Gp\|^2 \ge 0. If Gp=0Gp = 0 then pi,j=pi−1,jp_{i,j} = p_{i-1,j} and pi,j=pi,j−1p_{i,j} = p_{i,j-1} across every interior face, and the cells are connected through interior faces, so pp is constant. □\square

The test file checks Lemma 2 column by column in exact rational arithmetic.

Corollary (no checkerboard mode). The only pressures with zero MAC gradient are the constants. The checkerboard pi,j=(−1)i+jp_{i,j} = (-1)^{i+j} has ∣Gp∣=2/Δx|Gp| = 2/\Delta x or 2/Δy2/\Delta y on every interior face, so the projection sees it and removes it. With the collocated central gradient (pi+1,j−pi−1,j)/(2Δx)(p_{i+1,j} - p_{i-1,j})/(2\Delta x) the checkerboard has zero gradient at every interior point, and a pressure solve with that gradient cannot control it.

Theorem (the pressure step). Let u∗∈W\mathbf{u}^* \in W and b=−Du∗/Δtb = -D\mathbf{u}^*/\Delta t. Then ∑b=0\sum b = 0, Ap=bAp = b has a solution, unique up to a constant, and u=u∗−Δt Gp\mathbf{u} = \mathbf{u}^* - \Delta t\, Gp satisfies

  1. u∈W\mathbf{u} \in W and Du=0D\mathbf{u} = 0;
  2. u\mathbf{u} is the orthogonal projection of u∗\mathbf{u}^* onto V={w∈W:Dw=0}V = \{\mathbf{w} \in W : D\mathbf{w} = 0\}, and ∥u∥≤∥u∗∥\|\mathbf{u}\| \le \|\mathbf{u}^*\|.

Proof. Lemma 1 with p≡1p \equiv 1 gives ∑Du∗=−⟨u∗,G1⟩=0\sum D\mathbf{u}^* = -\langle \mathbf{u}^*, G1\rangle = 0: what enters the box leaves it, because no flow crosses the walls. AA is symmetric, so its range is the orthogonal complement of its null space, the constants (Lemma 2), and bb is in the range. Then Du=Du∗+Δt Ap=0D\mathbf{u} = D\mathbf{u}^* + \Delta t\, Ap = 0, and u∈W\mathbf{u} \in W because Gp∈WGp \in W. For any w∈V\mathbf{w} \in V, Lemma 1 gives ⟨w,Gp⟩=−(Dw,p)=0\langle \mathbf{w}, Gp\rangle = -(D\mathbf{w}, p) = 0, so u∗−u=Δt Gp\mathbf{u}^* - \mathbf{u} = \Delta t\, Gp is orthogonal to VV while u∈V\mathbf{u} \in V. This characterizes the orthogonal projection, and Pythagoras gives the norm bound. □\square

This is the discrete form of the Helmholtz-Hodge decomposition with the boundary condition u⋅n=0\mathbf{u}\cdot\mathbf{n} = 0.

Lemma 3 (marker interpolation). Away from the walls (at least half a cell), the interpolated velocity is the bilinear interpolant of the four nearest unknowns of each component, so it reproduces every velocity field whose components are linear in xx and yy exactly. Each marker step is a midpoint (second order Runge-Kutta) step of x˙=uh(x)\dot{\mathbf{x}} = \mathbf{u}_h(\mathbf{x}).

Proof. The weights (1−a)(1−c)(1-a)(1-c), a(1−c)a(1-c), (1−a)c(1-a)c and acac sum to 1 and reproduce xx and yy on a rectangle. □\square

Termination. The loop runs NN times. Lines L2, L3, L5 and L7 cost O(M)O(M) each, and line L6 costs O(1)O(1) per marker. Line L4 is a CG solve of a symmetric positive semidefinite system with a right side in the range; in exact arithmetic its iterates stay in the range, where AA is positive definite, so it ends in at most M−1M - 1 iterations, and in floating point the implementation stops at its tolerance or at 10M10M iterations.

What is not proved here. The order of accuracy (second order in space for smooth flow, first order in time) is measured in the tests on the free-slip Taylor-Green vortex. The no-slip ghost value 2uwall−uinner2u_{\text{wall}} - u_{\text{inner}} is a linear extrapolation, and the viscous term next to a no-slip wall is only first order accurate locally.

Complexity

One step costs Θ(M)\Theta(M) for the momentum update, the divergence and the gradient, O(1)O(1) per marker, and one Poisson solve. CG needs O(nx)O(n_x) iterations on general data for a fixed tolerance, so a step costs O(M3/2)O(M^{3/2}) on a square grid with CG and O(M)O(M) with multigrid. Memory is Θ(M+P)\Theta(M + P). The explicit step must satisfy the viscous limit Δt≤1/(2ν(Δx−2+Δy−2))\Delta t \le 1/\big(2\nu(\Delta x^{-2} + \Delta y^{-2})\big) and the advective limits. The number of markers per cell is a choice.

Properties

  • Exact discrete mass conservation in every cell, up to the solver tolerance.
  • No spurious pressure modes: the null space of −DG-DG is the constants.
  • Second order in space for smooth confined flow on a uniform grid (measured above), first order in time with forward Euler.
  • The projection is orthogonal in the discrete L2L^2 inner product and never increases the kinetic energy.
  • The markers carry no mass and do not affect the flow; they only mark fluid cells.

Variants and improvements

  • SMAC (simplified MAC) by Amsden and Harlow (1970) solves for a pressure correction, which is the projection method form used today.
  • Implicit diffusion and second order time stepping (Adams-Bashforth, Crank-Nicolson) on the same grid.
  • Surface tracking. Volume of fluid and level set methods replaced markers for the free surface in most codes, because they give the surface position and the curvature more cleanly.
  • Particle methods on the MAC grid. PIC and FLIP keep markers that carry velocity; this is the graphics branch that grew out of MAC.
  • Staggered grids in finite volume codes. SIMPLE and its relatives use the same staggering for steady flow; collocated codes replace it with Rhie-Chow interpolation.
  • Graphics. Foster and Metaxas (1996) used the MAC method for animating liquids, and Stam (1999) made the step unconditionally stable with semi-Lagrangian advection.

When to use it

Use the MAC method for incompressible flow on rectangular or nearly rectangular domains, in particular with a free surface: sloshing, dam breaks, splashing in animation, and flows driven by moving walls such as the lid-driven cavity. It is a good base for teaching and for codes where exact cell mass conservation matters. On complex geometry, unstructured finite volume or finite element methods fit the walls better, or an immersed boundary method brings the geometry onto the MAC grid.

Pitfalls

  • Index offsets. On a staggered grid ui,ju_{i,j}, vi,jv_{i,j} and pi,jp_{i,j} sit at three different points. Most bugs are half-cell offsets in the averages of the advection term or in the interpolation of markers; test interpolation on linear fields.
  • The no-slip ghost value is a linear extrapolation. The viscous term next to the wall is then only first order accurate locally; the global error is usually still second order, but wall shear stress needs care.
  • The singular pressure matrix. In a closed box the pressure is fixed only up to a constant. Keep the right side of the pressure equation at zero sum and fix the constant.
  • Marker gaps. Markers spread out in stretching flow and leave fluid cells with no markers, which are then flagged as empty by mistake. Add markers or use a surface tracking method.
  • Free surface boundary conditions need consistent velocities on faces next to empty cells; mistakes there show up as mass loss.
  • Explicit time step limits are hard limits. Central advection with forward Euler needs enough viscosity; at high Reynolds number use upwind or higher order time stepping.

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.

marker_and_cell_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/marker-and-cell-method/. The authors are listed in prov/B1FT13.jsonl.

"""The marker-and-cell (MAC) method in a closed 2D box [0, Lx] x [0, Ly].

Staggered grid with nx by ny cells:
  p[i + nx * j]        at the cell center ((i + 1/2) dx, (j + 1/2) dy)
  u[i + (nx + 1) * j]  at the vertical face (i dx, (j + 1/2) dy), i = 0..nx
  v[i + nx * j]        at the horizontal face ((i + 1/2) dx, j dy), j = 0..ny
p is the pressure divided by the density. The wall faces (i = 0, nx for u and
j = 0, ny for v) carry zero normal velocity. The tangential velocity at a wall
enters through ghost values: free slip mirrors the first interior value, no
slip sets ghost = 2 u_wall - interior. The pressure equation gets the
homogeneous Neumann condition, and -D G is exactly the matrix of
scisparse.poisson2d(..., bc="neumann").

Marker particles are moved with the interpolated velocity; the cells that
hold a marker are the fluid cells. This file handles confined flow (every
cell is fluid); the free surface conditions of Harlow and Welch are described
on the page but not implemented here.
"""

import scisparse


class Box:
    def __init__(self, nx, ny, lx, ly, slip="free", lid=0.0):
        self.nx, self.ny, self.lx, self.ly = nx, ny, lx, ly
        self.dx, self.dy = lx / nx, ly / ny
        self.slip, self.lid = slip, lid  # lid: tangential wall speed of the top wall
        self.A = scisparse.poisson2d(nx, ny, self.dx, self.dy, bc="neumann")

    def iu(self, i, j):
        return i + (self.nx + 1) * j

    def iv(self, i, j):
        return i + self.nx * j

    def zeros(self):
        return [0.0] * ((self.nx + 1) * self.ny), [0.0] * (self.nx * (self.ny + 1)), [0.0] * (self.nx * self.ny)

    def sample(self, fu, fv):
        """Face values of a velocity field given by two functions of (x, y)."""
        u = [fu(i * self.dx, (j + 0.5) * self.dy) for j in range(self.ny) for i in range(self.nx + 1)]
        v = [fv((i + 0.5) * self.dx, j * self.dy) for j in range(self.ny + 1) for i in range(self.nx)]
        return u, v

    def sample_p(self, fp):
        return [fp((i + 0.5) * self.dx, (j + 0.5) * self.dy) for j in range(self.ny) for i in range(self.nx)]


def u_at(b, u, i, j):
    """u at face (i, j), with ghost rows j = -1 and j = ny from the wall condition."""
    if 0 <= j < b.ny:
        return u[b.iu(i, j)]
    inner = u[b.iu(i, 0 if j < 0 else b.ny - 1)]
    if b.slip == "free":
        return inner
    wall = b.lid if j >= b.ny else 0.0
    return 2 * wall - inner


def v_at(b, v, i, j):
    """v at face (i, j), with ghost columns i = -1 and i = nx from the wall condition."""
    if 0 <= i < b.nx:
        return v[b.iv(i, j)]
    inner = v[b.iv(0 if i < 0 else b.nx - 1, j)]
    return inner if b.slip == "free" else -inner


def divergence(b, u, v):
    nx, dx, dy = b.nx, b.dx, b.dy
    return [(u[b.iu(i + 1, j)] - u[b.iu(i, j)]) / dx + (v[b.iv(i, j + 1)] - v[b.iv(i, j)]) / dy
            for j in range(b.ny) for i in range(nx)]


def gradient(b, p):
    """G p on the interior faces; zero on the wall faces, which the projection does not change."""
    nx, ny = b.nx, b.ny
    gx = [0.0] * ((nx + 1) * ny)
    gy = [0.0] * (nx * (ny + 1))
    for j in range(ny):
        for i in range(1, nx):
            gx[b.iu(i, j)] = (p[i + nx * j] - p[i - 1 + nx * j]) / b.dx
    for j in range(1, ny):
        for i in range(nx):
            gy[b.iv(i, j)] = (p[i + nx * j] - p[i + nx * (j - 1)]) / b.dy
    return gx, gy


def momentum_rhs(b, u, v, nu):
    """-(u . grad) u + nu Laplacian u on the interior faces, central differences."""
    nx, ny, dx, dy = b.nx, b.ny, b.dx, b.dy
    ru = [0.0] * len(u)
    rv = [0.0] * len(v)
    for j in range(ny):
        for i in range(1, nx):
            c = u[b.iu(i, j)]
            e, w = u[b.iu(i + 1, j)], u[b.iu(i - 1, j)]
            n, s = u_at(b, u, i, j + 1), u_at(b, u, i, j - 1)
            vb = 0.25 * (v[b.iv(i - 1, j)] + v[b.iv(i, j)] + v[b.iv(i - 1, j + 1)] + v[b.iv(i, j + 1)])
            adv = c * (e - w) / (2 * dx) + vb * (n - s) / (2 * dy)
            lap = (e - 2 * c + w) / (dx * dx) + (n - 2 * c + s) / (dy * dy)
            ru[b.iu(i, j)] = nu * lap - adv
    for j in range(1, ny):
        for i in range(nx):
            c = v[b.iv(i, j)]
            e, w = v_at(b, v, i + 1, j), v_at(b, v, i - 1, j)
            n, s = v[b.iv(i, j + 1)], v[b.iv(i, j - 1)]
            ub = 0.25 * (u[b.iu(i, j - 1)] + u[b.iu(i + 1, j - 1)] + u[b.iu(i, j)] + u[b.iu(i + 1, j)])
            adv = ub * (e - w) / (2 * dx) + c * (n - s) / (2 * dy)
            lap = (e - 2 * c + w) / (dx * dx) + (n - 2 * c + s) / (dy * dy)
            rv[b.iv(i, j)] = nu * lap - adv
    return ru, rv


def project(b, us, vs, dt, p0=None, tol=1e-12):
    """Solve -D G p = -D u* / dt with the Neumann matrix, then u = u* - dt G p."""
    rhs = [-x / dt for x in divergence(b, us, vs)]
    mean = sum(rhs) / len(rhs)
    rhs = [x - mean for x in rhs]  # zero in exact arithmetic: the wall faces carry no flux
    p, its = scisparse.cg(b.A, rhs, tol=tol, x0=p0)
    gx, gy = gradient(b, p)
    return [us[k] - dt * gx[k] for k in range(len(us))], [vs[k] - dt * gy[k] for k in range(len(vs))], p, its


def interpolate(b, u, v, x, y):
    """Bilinear interpolation of (u, v) at (x, y); needs nx, ny >= 2. Points closer to a
    wall than half a cell use the nearest row (u) or column (v) of unknowns."""
    nx, ny, dx, dy = b.nx, b.ny, b.dx, b.dy

    def bilinear(field, idx, gx, gy, mi, mj):
        i = min(max(int(gx), 0), mi - 1)
        j = min(max(int(gy), 0), mj - 1)
        a, c = gx - i, gy - j
        return ((1 - a) * (1 - c) * field[idx(i, j)] + a * (1 - c) * field[idx(i + 1, j)]
                + (1 - a) * c * field[idx(i, j + 1)] + a * c * field[idx(i + 1, j + 1)])

    gy_u = min(max(y / dy - 0.5, 0.0), ny - 1.0)
    gx_v = min(max(x / dx - 0.5, 0.0), nx - 1.0)
    return bilinear(u, b.iu, x / dx, gy_u, nx, ny - 1), bilinear(v, b.iv, gx_v, y / dy, nx - 1, ny)


def move_markers(b, u, v, markers, dt):
    """One midpoint (RK2) step for every marker; markers are kept inside the box."""
    out = []
    for x, y in markers:
        u1, v1 = interpolate(b, u, v, x, y)
        u2, v2 = interpolate(b, u, v, x + 0.5 * dt * u1, y + 0.5 * dt * v1)
        out.append((min(max(x + dt * u2, 0.0), b.lx), min(max(y + dt * v2, 0.0), b.ly)))
    return out


def fluid_cells(b, markers):
    """The set of cells that hold at least one marker."""
    return {min(int(x / b.dx), b.nx - 1) + b.nx * min(int(y / b.dy), b.ny - 1) for x, y in markers}


def mac(b, u, v, dt, nu, steps, markers=(), gravity=(0.0, 0.0), p=None):
    """Run MAC-STEP a number of times. Returns (u, v, p, markers, fluid cells)."""
    markers = list(markers)
    cells = fluid_cells(b, markers)
    for n in range(steps):  # @line L1
        ru, rv = momentum_rhs(b, u, v, nu)  # @line L2
        us = [u[k] + dt * (ru[k] + gravity[0]) if 0 < k % (b.nx + 1) < b.nx else u[k] for k in range(len(u))]  # @line L3
        vs = [v[k] + dt * (rv[k] + gravity[1]) if 0 < k // b.nx < b.ny else v[k] for k in range(len(v))]  # @line L3
        u, v, p, _ = project(b, us, vs, dt, p0=p)  # @line L4 @line L5
        markers = move_markers(b, u, v, markers, dt)  # @line L6
        cells = fluid_cells(b, markers)  # @line L7
    return u, v, p, markers, cells  # @line L8
scisparse.py 189 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Tridiagonal solvers, sparse matrices and simple iterative solvers.

A vector is a list. A sparse matrix is a list of rows, and each row is a
dict that maps a column index to a value. Entries may be int, float or
fractions.Fraction. thomas, thomas_periodic, spmatvec, from_dense and
to_dense keep Fraction entries exact. cg takes square roots and works in
float.

API (fixed; other pages copy this file byte for byte):
    thomas(a, b, c, d)             solve a tridiagonal system. Row i reads
                                   a[i] x[i-1] + b[i] x[i] + c[i] x[i+1] = d[i];
                                   a[0] and c[n-1] are not used.
    thomas_periodic(a, b, c, d)    solve a cyclic tridiagonal system: as
                                   thomas, but a[0] multiplies x[n-1] and
                                   c[n-1] multiplies x[0]. Uses the
                                   Sherman-Morrison formula. n >= 3.
    from_dense(A)                  sparse copy of a dense matrix (drops zeros)
    to_dense(A, ncols=None)        dense copy of a sparse matrix
    spmatvec(A, x)                 A times x
    poisson2d(nx, ny, dx, dy, bc="dirichlet")
                                   the matrix of MINUS the 5-point Laplacian
                                   on nx by ny unknowns, numbered
                                   k = i + nx * j (i along x, j along y).
                                   bc = "dirichlet": unknowns at the interior
                                   nodes ((i + 1) dx, (j + 1) dy) with zero
                                   values outside; the matrix is symmetric
                                   positive definite.
                                   bc = "periodic": the grid wraps around in
                                   both directions; the matrix is symmetric
                                   positive semidefinite, and its null space
                                   is the constant vectors.
                                   bc = "neumann": unknowns at cell centers,
                                   zero normal derivative at the walls (a
                                   missing neighbor drops out of the
                                   stencil); null space as for "periodic".
    cg(A, b, tol=1e-10, maxit=None, x0=None)
                                   conjugate gradient for a symmetric
                                   positive (semi)definite A. Stops when
                                   ||b - A x||_2 <= tol * ||b||_2. Returns
                                   (x, iterations). For a singular A, b must
                                   be in the range of A (for the Poisson
                                   matrices above: sum(b) = 0).
    gauss_seidel(A, b, iters, x0=None)
                                   iters forward Gauss-Seidel sweeps; every
                                   row needs a nonzero diagonal entry.
"""

import math


def thomas(a, b, c, d):
    n = len(d)
    if n == 0:
        return []
    cp = [0] * n
    dp = [0] * n
    cp[0] = c[0] / b[0] if n > 1 else 0
    dp[0] = d[0] / b[0]
    for i in range(1, n):
        m = b[i] - a[i] * cp[i - 1]
        if i < n - 1:
            cp[i] = c[i] / m
        dp[i] = (d[i] - a[i] * dp[i - 1]) / m
    x = [0] * n
    x[n - 1] = dp[n - 1]
    for i in range(n - 2, -1, -1):
        x[i] = dp[i] - cp[i] * x[i + 1]
    return x


def thomas_periodic(a, b, c, d):
    """Cyclic tridiagonal solve. A = T + u v^T with u = (gamma, 0, .., 0, c[n-1])
    and v = (1, 0, .., 0, a[0] / gamma), so T is tridiagonal."""
    n = len(d)
    if n < 3:
        raise ValueError("thomas_periodic needs n >= 3")
    gamma = -b[0]
    bb = list(b)
    bb[0] = b[0] - gamma
    bb[n - 1] = b[n - 1] - c[n - 1] * a[0] / gamma
    y = thomas(a, bb, c, d)
    u = [0] * n
    u[0] = gamma
    u[n - 1] = c[n - 1]
    z = thomas(a, bb, c, u)
    vy = y[0] + a[0] * y[n - 1] / gamma
    vz = z[0] + a[0] * z[n - 1] / gamma
    f = vy / (1 + vz)
    return [y[i] - f * z[i] for i in range(n)]


def from_dense(A):
    return [{j: v for j, v in enumerate(row) if v != 0} for row in A]


def to_dense(A, ncols=None):
    if ncols is None:
        ncols = len(A)
    out = []
    for row in A:
        r = [0] * ncols
        for j, v in row.items():
            r[j] = v
        out.append(r)
    return out


def spmatvec(A, x):
    return [sum(v * x[j] for j, v in row.items()) for row in A]


def poisson2d(nx, ny, dx, dy, bc="dirichlet"):
    if bc not in ("dirichlet", "periodic", "neumann"):
        raise ValueError("bc must be dirichlet, periodic or neumann")
    cx = 1 / (dx * dx)
    cy = 1 / (dy * dy)
    A = []
    for j in range(ny):
        for i in range(nx):
            row = {}
            k = i + nx * j
            for (ii, jj, w) in ((i - 1, j, cx), (i + 1, j, cx), (i, j - 1, cy), (i, j + 1, cy)):
                inside = 0 <= ii < nx and 0 <= jj < ny
                if bc == "periodic":
                    ii %= nx
                    jj %= ny
                    inside = True
                if bc == "neumann" and not inside:
                    continue
                row[k] = row.get(k, 0) + w
                if inside:
                    m = ii + nx * jj
                    row[m] = row.get(m, 0) - w
            A.append({m: v for m, v in row.items() if v != 0})
    return A


def cg(A, b, tol=1e-10, maxit=None, x0=None):
    n = len(b)
    if maxit is None:
        maxit = 10 * n
    x = [0.0] * n if x0 is None else [float(v) for v in x0]
    if x0 is None:
        r = [float(v) for v in b]
    else:
        ax = spmatvec(A, x)
        r = [b[i] - ax[i] for i in range(n)]
    bnorm = math.sqrt(sum(float(v) * float(v) for v in b))
    stop = tol * bnorm
    rr = sum(v * v for v in r)
    if math.sqrt(rr) <= stop:
        return x, 0
    p = list(r)
    for it in range(1, maxit + 1):
        ap = spmatvec(A, p)
        pap = sum(p[i] * ap[i] for i in range(n))
        if pap <= 0:
            return x, it
        alpha = rr / pap
        for i in range(n):
            x[i] += alpha * p[i]
            r[i] -= alpha * ap[i]
        rr_new = sum(v * v for v in r)
        if math.sqrt(rr_new) <= stop:
            return x, it
        beta = rr_new / rr
        rr = rr_new
        p = [r[i] + beta * p[i] for i in range(n)]
    return x, maxit


def gauss_seidel(A, b, iters, x0=None):
    n = len(b)
    x = [0] * n if x0 is None else list(x0)
    for _ in range(iters):
        for i in range(n):
            row = A[i]
            s = b[i]
            diag = 0
            for j, v in row.items():
                if j == i:
                    diag = v
                else:
                    s -= v * x[j]
            x[i] = s / diag
    return x
test_marker_and_cell_method.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/marker-and-cell-method/. The authors are listed in prov/B1FT13.jsonl.

import math
import random
from fractions import Fraction as Fr

import scisparse as sp
from marker_and_cell_method import Box, divergence, gradient, interpolate, mac, move_markers, project


def _err(a, b):
    return max(abs(a[k] - b[k]) for k in range(len(a)))


def test_minus_div_grad_is_the_neumann_5_point_matrix_exactly():
    b = Box(3, 2, Fr(3), Fr(1))  # dx = 1, dy = 1/2
    A = sp.poisson2d(3, 2, Fr(1), Fr(1, 2), bc="neumann")
    for m in range(6):
        e = [Fr(int(k == m)) for k in range(6)]
        gx, gy = gradient(b, e)
        col = [-x for x in divergence(b, gx, gy)]
        assert col == [A[k].get(m, 0) for k in range(6)]


def test_no_checkerboard_mode():
    # G p = 0 only for constant p; the checkerboard has a nonzero MAC gradient
    b = Box(4, 4, 1.0, 1.0)
    cb = [(-1) ** (i + j) for j in range(4) for i in range(4)]
    gx, gy = gradient(b, cb)
    assert max(abs(x) for x in gx + gy) == 8.0
    # a collocated central gradient (p[i+1] - p[i-1]) / (2 dx) of the checkerboard is zero
    assert all(cb[i + 1 + 4 * j] - cb[i - 1 + 4 * j] == 0 for j in range(4) for i in range(1, 3))
    gx, gy = gradient(b, [2.5] * 16)
    assert max(abs(x) for x in gx + gy) == 0


def test_projection_on_random_data():
    rng = random.Random(5)
    b = Box(6, 5, 1.0, 1.2)
    us = [rng.uniform(-1, 1) if 0 < k % 7 < 6 else 0.0 for k in range(7 * 5)]
    vs = [rng.uniform(-1, 1) if 0 < k // 6 < 5 else 0.0 for k in range(6 * 6)]
    u, v, _, _ = project(b, us, vs, 0.1)
    assert max(abs(x) for x in divergence(b, u, v)) < 1e-10
    u2, v2, _, _ = project(b, u, v, 0.1)
    assert _err(u, u2) < 1e-10 and _err(v, v2) < 1e-10
    inner = sum((us[k] - u[k]) * u[k] for k in range(len(u))) + sum((vs[k] - v[k]) * v[k] for k in range(len(v)))
    assert abs(inner) < 1e-10


def test_free_slip_taylor_green_order():
    # u = sin x cos y, v = -cos x sin y, p = (cos 2x + cos 2y) / 4 times e^(-2 nu t), e^(-4 nu t) on [0, pi]^2
    nu, T = 0.1, 0.2
    eu, ep = [], []
    for n in (8, 16, 32):
        b = Box(n, n, math.pi, math.pi)
        u, v = b.sample(lambda x, y: math.sin(x) * math.cos(y), lambda x, y: -math.cos(x) * math.sin(y))
        steps = max(1, round(T / (0.4 * b.dx**2)))
        u, v, p, _, _ = mac(b, u, v, T / steps, nu, steps)
        assert max(abs(x) for x in divergence(b, u, v)) < 1e-10
        a = math.exp(-2 * nu * T)
        ue, ve = b.sample(lambda x, y: math.sin(x) * math.cos(y) * a, lambda x, y: -math.cos(x) * math.sin(y) * a)
        pe = b.sample_p(lambda x, y: (math.cos(2 * x) + math.cos(2 * y)) / 4 * a * a)
        m, me = sum(p) / len(p), sum(pe) / len(pe)
        eu.append(max(_err(u, ue), _err(v, ve)))
        ep.append(max(abs(p[k] - m - pe[k] + me) for k in range(len(p))))
    for e in (eu, ep):
        assert all(abs(math.log2(e[i] / e[i + 1]) - 2) < 0.2 for i in range(2)), e
    assert abs(eu[0] - 2.349e-4) < 1e-6  # 8 by 8 cells, 3 steps of dt = 1/15


def test_bilinear_interpolation_is_exact_for_linear_fields():
    b = Box(5, 4, 1.0, 2.0)
    u, v = b.sample(lambda x, y: 1 + 2 * x - 3 * y, lambda x, y: -0.5 + x + 4 * y)
    rng = random.Random(9)
    for _ in range(50):
        # stay at least half a cell from the walls, where both fields have unknowns on both sides
        x, y = rng.uniform(0.1, 0.9), rng.uniform(0.25, 1.75)
        uu, vv = interpolate(b, u, v, x, y)
        assert abs(uu - (1 + 2 * x - 3 * y)) < 1e-12 and abs(vv - (-0.5 + x + 4 * y)) < 1e-12


def test_markers_follow_streamlines():
    # in the frozen free-slip vortex the stream function sin x sin y is constant along paths
    b = Box(16, 16, math.pi, math.pi)
    u, v = b.sample(lambda x, y: math.sin(x) * math.cos(y), lambda x, y: -math.cos(x) * math.sin(y))
    start = [(0.8, 1.0), (1.5, 0.6), (2.2, 2.0), (1.2, 2.5)]
    pts = list(start)
    for _ in range(100):
        pts = move_markers(b, u, v, pts, 0.05)
    drift = max(abs(math.sin(x) * math.sin(y) - math.sin(x0) * math.sin(y0)) for (x, y), (x0, y0) in zip(pts, start))
    assert drift < 1e-3, drift  # measured 1.9e-4
    assert all(0 < x < math.pi and 0 < y < math.pi for x, y in pts)


def test_lid_driven_cavity_runs_divergence_free():
    # no-slip box with a lid moving at speed 1, Re = 1 / nu = 100, a short start-up run
    b = Box(8, 8, 1.0, 1.0, slip="no", lid=1.0)
    u, v, _ = b.zeros()
    rng = random.Random(2)
    markers = [(rng.uniform(0, 1), rng.uniform(0, 1)) for _ in range(40)]
    u, v, p, markers, cells = mac(b, u, v, 0.01, 0.01, 60, markers=markers)
    assert max(abs(x) for x in divergence(b, u, v)) < 1e-10
    assert all(0 <= x <= 1 and 0 <= y <= 1 for x, y in markers)
    assert cells <= set(range(64))
    # the lid drags the top row of fluid to the right, and the return flow below goes left
    assert min(u[b.iu(i, 7)] for i in range(1, 8)) > 0
    assert min(u[b.iu(4, j)] for j in range(8)) < 0

History

Harlow and Welch (1965) published the MAC method in Physics of Fluids for time-dependent viscous incompressible flow with a free surface, with the staggered grid, a Poisson equation for the pressure at each step and marker particles. Chorin (1968) gave the projection form of the pressure step, and Amsden and Harlow (1970) simplified the method as SMAC. Patankar (1980) made the staggered grid standard in steady finite volume solvers. Foster and Metaxas (1996) brought the method into computer graphics, where the grid is now called the MAC grid.

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 staggered grid, the pressure Poisson equation, marker particles and the free surface conditions
  2. Joel H. Ferziger, Milovan Peric and Robert L. Street, Computational Methods for Fluid Dynamics, fourth edition, Springer, 2020, Chapter 7 (staggered grids, the pressure equation and fractional step methods)
  3. Suhas V. Patankar, Numerical Heat Transfer and Fluid Flow, Hemisphere, 1980, Section 6.3 (the staggered grid and why it removes the checkerboard pressure)
  4. Alexandre J. Chorin, Numerical solution of the Navier-Stokes equations, Mathematics of Computation 22(104) (1968) 745-762, the projection step in the form used by later MAC codes

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