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.
- Solves
- Navier-Stokes equations
- 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
- Model
- Real RAM
- Properties
- deterministicdivergence freeexplicitstaggered
- Evidence
- Proof sketchCode in 1 languages
- 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 , in a rectangular box, with the pressure divided by the density and the kinematic viscosity, up to a time . 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 cells.
The grid places at the cell center , at for , and at for . The wall faces hold the normal velocity, which is zero. is the divergence at the centers, the gradient at the interior faces, and .
The algorithm
MAC(u, v, markers, Δt, ν, g, N)- 1
for n ← 0 to N - 1 do - 2
fill the ghost values from the wall conditions, and form -(u·∇)u + ν Δ_h u - 3
(u*, v*) ← (u, v) + Δt (-(u·∇)u + ν Δ_h u + g) ▷ interior faces only - 4
solve A p = -D(u*, v*) / Δt ▷ ∂p/∂n = 0 at the walls - 5
(u, v) ← (u*, v*) - Δt G p ▷ interior faces only - 6
move every marker with the interpolated velocity - 7
flag the cells that hold a marker as fluid - 8
return (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 it is minus the interior value, so that the average on the wall is . The wall faces are never changed, and 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 on a grid with . A collocated central gradient 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 is on every interior face, so the checkerboard is not in the null space. On the MAC grid, is exactly the 5-point Neumann matrix, and the only pressures it ignores are the constants. For a grid with , the corner cell's row is 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 the field , , is an exact solution with zero normal velocity and zero shear at the walls. With , and , the maximum errors at (pressure with the mean removed) are:
| cells | steps | velocity error | order | pressure error | order |
|---|---|---|---|---|---|
| 3 | 2.349e-4 | 7.184e-3 | |||
| 13 | 6.414e-5 | 1.87 | 1.736e-3 | 2.05 | |
| 52 | 1.607e-5 | 2.00 | 4.441e-4 | 1.97 |
The divergence after each step is below . In the same vortex, frozen in time on a grid, four markers moved for 100 midpoint steps of keep the stream function constant to , so they stay on their streamlines. In a no-slip cavity of cells with the lid moving at speed 1 and , 60 steps of 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 . So 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 cells of size . A face field has on the vertical faces, , and on the horizontal faces, . Let be the face fields with zero values on the wall faces ( and ); every iterate of the method is in , because lines L3 and L5 change only interior faces. For a cell field ,
and is zero on the wall faces, so . The inner products are the plain sums over faces and over cells.
Lemma 1 (summation by parts). For and every cell field , .
Proof. Fix a row . With ,
because the terms with and vanish. Dividing by and summing over gives the part, and the columns give the part.
Lemma 2 ( is the Neumann 5-point matrix). 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 exactly when , exactly when is constant.
Proof. At an interior cell, . At a cell next to the wall , the face carries , so the part is : the west neighbor drops out, which is the discrete condition . By Lemma 1 with , , so is symmetric and . If then and across every interior face, and the cells are connected through interior faces, so is constant.
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 has or on every interior face, so the projection sees it and removes it. With the collocated central gradient the checkerboard has zero gradient at every interior point, and a pressure solve with that gradient cannot control it.
Theorem (the pressure step). Let and . Then , has a solution, unique up to a constant, and satisfies
- and ;
- is the orthogonal projection of onto , and .
Proof. Lemma 1 with gives : what enters the box leaves it, because no flow crosses the walls. is symmetric, so its range is the orthogonal complement of its null space, the constants (Lemma 2), and is in the range. Then , and because . For any , Lemma 1 gives , so is orthogonal to while . This characterizes the orthogonal projection, and Pythagoras gives the norm bound.
This is the discrete form of the Helmholtz-Hodge decomposition with the boundary condition .
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 and exactly. Each marker step is a midpoint (second order Runge-Kutta) step of .
Proof. The weights , , and sum to 1 and reproduce and on a rectangle.
Termination. The loop runs times. Lines L2, L3, L5 and L7 cost each, and line L6 costs 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 is positive definite, so it ends in at most iterations, and in floating point the implementation stops at its tolerance or at 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 is a linear extrapolation, and the viscous term next to a no-slip wall is only first order accurate locally.
Complexity
One step costs for the momentum update, the divergence and the gradient, per marker, and one Poisson solve. CG needs iterations on general data for a fixed tolerance, so a step costs on a square grid with CG and with multigrid. Memory is . The explicit step must satisfy the viscous limit 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 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 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 , and 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.
# 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
- 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
- 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)
- Suhas V. Patankar, Numerical Heat Transfer and Fluid Flow, Hemisphere, 1980, Section 6.3 (the staggered grid and why it removes the checkerboard pressure)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag B1FT13 Edit this page History Report an error Markdown