Algorithmcore
Chorin projection method
Also called Chorin-Temam projection method.
Advances the velocity without pressure, then solves a pressure Poisson equation and subtracts its gradient so the velocity is divergence free. First order in time.
- Solves
- Navier-Stokes equations
- Time
- Θ(N M K) worst
- Space
- Θ(M) extra
- Where
- K = the pressure solver iterations per step; M = the number of grid cells; N = the number of time steps
- Model
- Real RAM
- Properties
- deterministicdivergence freeexplicit
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alexandre J. Chorin, Roger Temam, 1968
Chorin's projection method advances incompressible flow in time in two parts per step. First it updates the velocity with advection, viscosity and body forces but without pressure. This intermediate velocity is not divergence free. Then it solves a Poisson equation for the pressure and subtracts the pressure gradient, which removes exactly the part of the velocity that is not divergence free. The second part is the discrete Helmholtz-Hodge decomposition: it is an orthogonal projection onto divergence-free fields. Graphics readers know this step from stable fluids, which uses the same projection on the same MAC grid. What the CFD form adds is a consistent advection term and a time step chosen for accuracy, so that the error falls at a known rate when the grid and the step are refined. The basic method is first order in time.
In plain words
Water cannot be squeezed. If you push it into a region, the same amount must leave that region at once. The method moves the fluid forward in two moves. In the first move it lets the fluid carry itself along, slow down by friction and feel gravity, as if squeezing were allowed. After this move, some cells have more fluid coming in than going out. In the second move it finds the pressure that pushes the fluid out of the crowded cells and into the empty ones, just enough that each cell has the same inflow and outflow again. Finding this pressure means solving one large set of linked equations, one equation per cell. Then it applies the push. The second move changes only the part of the flow that broke the rule and leaves the rest alone.
The problem
Solve the incompressible Navier-Stokes equations
for the velocity and the pressure up to a time , from a divergence-free initial velocity. Here is the pressure divided by the constant density and is the kinematic viscosity. The pressure has no evolution equation. It is the Lagrange multiplier of the constraint , and it is fixed only up to a constant.
This page uses a periodic box with cells on a staggered MAC grid: at cell centers, on the left face and on the bottom face of each cell. is the discrete divergence at the centers and the discrete gradient at the faces, both by central differences over one cell. On this grid is the 5-point matrix of minus the Laplacian. The cost is counted in arithmetic operations on reals and in iterations of the pressure solver.
The algorithm
CHORIN-PROJECTION(u, v, Δt, ν, f, N)- 1
for n ← 0 to N - 1 do - 2
(u*, v*) ← (u, v) + Δt (-(u·∇)u + ν Δ_h u + f) ▷ no pressure term - 3
b ← -D(u*, v*) / Δt - 4
solve A p = b ▷ A = -D G, the 5-point matrix - 5
(u, v) ← (u*, v*) - Δt G p - 6
return (u, v, p)
Line L2 is one forward Euler step of the momentum equation without . The implementation computes the advection term in advective form with central differences, averaging to the faces and to the faces, and the viscous term with the 5-point Laplacian on each velocity component. Lines L3 to L5 project: of the new velocity is . The periodic matrix is singular, with the constants as null space, and has zero sum, so exists and is unique up to a constant. The implementation solves line L4 by conjugate gradient, warm started from the previous pressure. A multigrid solver or, on a periodic box, a fast Fourier transform solve can replace it.
With walls, the normal velocity on a wall face is set to the wall value and is not changed by the projection, and the pressure equation gets the homogeneous Neumann condition at the wall. The marker and cell method page works out this case.
Example
A projection by hand. Take a periodic row of 4 cells with , , , and on the 4 faces, so face 0 carries one unit of flow into cell 0 from cell 3. The divergence is , so . The matrix is the periodic second difference with rows and its shifts. The solution with zero mean is ; for example row 0 gives . The face gradients are , and
In one periodic dimension a divergence-free field is a constant, and the projection keeps the mean flow and removes the rest, which is a gradient. The test file checks these numbers.
Taylor-Green vortex. On the periodic square the field , , is an exact solution with . With , and (so that the first order time error also scales like ), the maximum velocity error at is:
| cells | steps | max error | observed order | |
|---|---|---|---|---|
| 2 | 0.25 | 2.266e-3 | ||
| 8 | 0.0625 | 5.898e-4 | 1.94 | |
| 32 | 0.015625 | 1.489e-4 | 1.99 |
The discrete divergence after every projection is about . For the order in time, fix the grid, set , and compare runs with 10, 20, 40 and 80 steps. The differences between successive runs are 7.99e-4, 3.96e-4 and 1.97e-4, an observed order of 1.01, as expected for a first order method. These are measurements from the implementation on this page.
Correctness
The proof is in proofs/correctness.md. On the periodic MAC grid, summation by parts gives , so is symmetric positive semidefinite with the constants as its null space, and every divergence has zero sum. So the pressure equation has a solution, the new velocity has zero discrete divergence, and it is the orthogonal projection of onto the discretely divergence-free fields. From this, one Chorin step is exactly one forward Euler step for the projected system , which is the method-of-lines form of the discrete Navier-Stokes equations. This gives first order convergence in time on a fixed periodic grid (a theorem, with Lipschitz on bounded sets). The spatial order 2 is a measurement on this page. For the continuous problem, Temam (1969) proved convergence of the fractional step method.
Proof: One step of Chorin's projection method on the periodic MAC grid is a discrete orthogonal projection, and the method is forward Euler for the projected equationsfull
Setting. The grid is the periodic MAC grid of the main page with cells of size . A velocity field has one value on the left face and one value on the bottom face of each cell , and a pressure has one value per cell center. With the east, west, north and south neighbors of cell (with wrap around),
The inner products are on face fields and on cell fields; a common factor does not change any statement below. is the discrete right side of line L2, , any function from face fields to face fields. is the space of discretely divergence-free fields.
Lemma 1 (summation by parts). for every face field and cell field . So , and is symmetric positive semidefinite.
Proof. . The map is a bijection with inverse , so the second sum is . Hence . The terms are the same with and . Adding gives the identity. With it gives , which is symmetric in and and nonnegative for . Writing out shows that it is the matrix of minus the 5-point Laplacian with periodic wrap around.
Lemma 2 (null space and range). if and only if is constant. So the null space of is the constants, and has a solution if and only if ; the solution is unique up to an additive constant, and is unique.
Proof. If then and for all ; walking west and south reaches every cell, so is constant. , so implies ; the converse is clear. is symmetric, so its range is the orthogonal complement of its null space, the vectors with zero sum. Two solutions differ by a null vector, a constant, which maps to .
Lemma 3 (the right side is in the range). for every face field.
Proof. Take in Lemma 1: .
So in exact arithmetic (line L3) has zero sum, line L4 has a solution, and in line L5 is well defined. The implementation subtracts the mean of before calling CG; in exact arithmetic the mean is , and in floating point this removes the rounding part that is outside the range.
Theorem 1 (the step is the orthogonal projection onto ). Let with . Then
- ;
- for every cell field , so is an orthogonal splitting, and ;
- , where is the orthogonal projector onto ; it depends on only, not on and not on which solution is chosen.
Proof. (1) . (2) By Lemma 1 and (1), ; Pythagoras gives the norm identity. (3) By Lemma 1, the orthogonal complement of is the range of , the discrete gradients. By (1) and (2), and is orthogonal to . The orthogonal decomposition of into a part in and a part in is unique, so .
This is the discrete form of the Helmholtz-Hodge decomposition on a periodic domain. The tests check (1) to , the orthogonality in (2) and on random data.
Theorem 2 (equivalence with forward Euler). Let . Then the iterates of CHORIN-PROJECTION satisfy , which is the forward Euler method for the system of ordinary differential equations on . This system is the method-of-lines form of the discrete Navier-Stokes equations , .
Proof. Line L2 gives , and Theorem 1 gives because is linear. By induction , so . For the second claim, apply to : because gradients are orthogonal to , and because . Conversely, a solution of in solves the pair with , which is a gradient by Lemma 1.
Corollary (first order in time). For a fixed grid, is a polynomial in the face values, so it is Lipschitz on bounded sets, and has norm . If the exact solution of stays bounded on , the standard convergence theorem for forward Euler gives as . On the periodic grid the projection adds no splitting error of its own. The pressure of line L4 equals of the semi-discrete system evaluated at up to , because .
The spatial error, second order on the MAC grid for smooth solutions, is not proved here; the tests measure it on the Taylor-Green vortex. With walls and an implicit viscous term, Theorem 2 no longer holds as stated, because then satisfies a boundary condition that changes; this is the splitting error discussed on the main page.
Termination. The outer loop (line L1) runs times. Each step does arithmetic outside the pressure solve. CG on the symmetric positive semidefinite system of Lemma 2 with a right side in the range ends in at most iterations in exact arithmetic, because its iterates stay in the range, where is positive definite. In floating point the implementation stops at the residual tolerance or at a fixed iteration cap of , so each step ends.
Complexity
One step costs operations for lines L2, L3 and L5, plus the pressure solve. CG on the 5-point matrix has condition number , so it needs iterations for a fixed tolerance on general data, and one step costs on a square grid. Multigrid solves it in and an FFT in . Memory is . On the Taylor-Green vortex, whose data lie in a few eigenvectors, warm-started CG needed 2.0, 4.1 and 8.9 iterations per step on the three grids above (a measurement).
The explicit update limits the time step. The viscous term needs , and central advection with forward Euler needs the viscous term to damp it, about , together with the advective CFL condition. With , a run to time takes steps. Implicit diffusion removes the viscous limit at the price of one more linear solve per velocity component per step.
Properties
- Exact discrete incompressibility: up to the pressure solver tolerance, at every step.
- The projection is orthogonal, so it never increases the discrete kinetic energy: .
- First order in time, both for the velocity and for the pressure on a periodic domain. Second order in space on the MAC grid for smooth flow (measured here).
- The pressure is not a state variable. It is recomputed at each step and needs no initial value.
- One elliptic solve per step, with a constant matrix, so a factorization or a multigrid hierarchy is set up once.
Variants and improvements
- Incremental pressure correction. Keep the old pressure gradient in the predictor, , and solve for the increment . This is the form used with second order time stepping (Goda 1979, van Kan 1986). In its rotational form the pressure error near walls drops (Guermond, Minev and Shen 2006).
- Implicit diffusion. Treat by backward Euler or Crank-Nicolson, so the time step is limited only by advection.
- Stable fluids. Semi-Lagrangian advection makes the step stable for any , at the cost of strong numerical dissipation; see stable fluids.
- PISO. Several pressure corrections per step with an implicit momentum equation; the first corrector is close to a projection.
- Velocity correction schemes swap the roles: the viscous term is corrected after the pressure step.
- Approximate projections on collocated or adaptive grids give a field that is only approximately divergence free, in exchange for simpler data structures.
When to use it
Use the projection method for time-accurate incompressible flow when one Poisson solve per step is affordable: direct simulation of transitional and turbulent flow, flows in boxes and channels, and as the fluid solver inside the immersed boundary method. On periodic domains with an FFT pressure solve, it is hard to beat. For steady flow, where time accuracy does not matter, SIMPLE or artificial compressibility go to the steady state with larger effective steps.
Pitfalls
- Collocated grids. If and sit at the same points and and are wide central differences, has a checkerboard null space and the pressure oscillates. Use a staggered grid, or add Rhie-Chow interpolation.
- The artificial pressure boundary condition. With walls and implicit viscosity, satisfies the wall condition but the projection changes its tangential part, and the pressure gets , which the true pressure does not satisfy. This splitting error creates a numerical boundary layer. For the basic non-incremental scheme the velocity is first order in but the pressure only of order ; the incremental form recovers first order (Guermond, Minev and Shen 2006).
- The singular pressure matrix. On a periodic domain or with only Neumann walls, fix the constant (zero mean, or one value) and keep in the range of , or CG drifts.
- Too loose a pressure tolerance leaves a divergence that accumulates over many steps. Measure after the projection, not only the solver residual.
- The time step. The explicit viscous and advective limits above are hard limits; central advection with forward Euler is unstable without viscosity.
- Initial data that are not divergence free are projected in the first step. That is harmless, but the first pressure then has no physical meaning.
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/chorin-projection-method/. The authors are listed in prov/MYD986.jsonl.
"""Chorin's projection method for the 2D incompressible Navier-Stokes equations.
u_t + (u . grad) u = -grad p + nu Laplacian u + f, div u = 0,
with p the pressure divided by the density, on the periodic box
[0, Lx) x [0, Ly). The grid is staggered (MAC): p[k] at the cell center
((i + 1/2) dx, (j + 1/2) dy), u[k] at the left face (i dx, (j + 1/2) dy) and
v[k] at the bottom face ((i + 1/2) dx, j dy), with k = i + nx * j.
One step (Chorin 1968, first order in time):
1. u* = u^n + dt (-(u^n . grad) u^n + nu Laplacian u^n + f) (no pressure)
2. solve -D G p = -D u* / dt (pressure Poisson)
3. u^{n+1} = u* - dt G p (projection)
D is the discrete divergence and G the discrete gradient. On the MAC grid
-D G is the 5-point matrix of scisparse.poisson2d(..., bc="periodic").
"""
import math
import scisparse
class Grid:
def __init__(self, nx, ny, lx=2 * math.pi, ly=2 * math.pi):
self.nx, self.ny = nx, ny
self.dx, self.dy = lx / nx, ly / ny
n = nx * ny
self.e = [(k % nx + 1) % nx + nx * (k // nx) for k in range(n)] # east neighbor
self.w = [(k % nx - 1) % nx + nx * (k // nx) for k in range(n)] # west neighbor
self.nn = [k % nx + nx * ((k // nx + 1) % ny) for k in range(n)] # north neighbor
self.s = [k % nx + nx * ((k // nx - 1) % ny) for k in range(n)] # south neighbor
self.A = scisparse.poisson2d(nx, ny, self.dx, self.dy, bc="periodic")
def points(self, where):
"""Coordinates of the unknowns: where is 'p', 'u' or 'v'."""
ox = 0.5 if where in ("p", "v") else 0.0
oy = 0.5 if where in ("p", "u") else 0.0
return [((k % self.nx + ox) * self.dx, (k // self.nx + oy) * self.dy) for k in range(self.nx * self.ny)]
def divergence(g, u, v):
"""D(u, v) at the cell centers."""
e, nn = g.e, g.nn
return [(u[e[k]] - u[k]) / g.dx + (v[nn[k]] - v[k]) / g.dy for k in range(len(u))]
def gradient(g, p):
"""G p: the x part at the u faces and the y part at the v faces."""
w, s = g.w, g.s
return [(p[k] - p[w[k]]) / g.dx for k in range(len(p))], [(p[k] - p[s[k]]) / g.dy for k in range(len(p))]
def momentum_rhs(g, u, v, nu):
"""-(u . grad) u + nu Laplacian u at the faces, by central differences."""
e, w, nn, s = g.e, g.w, g.nn, g.s
dx, dy = g.dx, g.dy
cx, cy = nu / (dx * dx), nu / (dy * dy)
ru, rv = [], []
for k in range(len(u)):
# u face (i, j): v is the mean of the four v faces around it
vb = 0.25 * (v[k] + v[w[k]] + v[nn[k]] + v[w[nn[k]]])
adv = u[k] * (u[e[k]] - u[w[k]]) / (2 * dx) + vb * (u[nn[k]] - u[s[k]]) / (2 * dy)
lap = cx * (u[e[k]] - 2 * u[k] + u[w[k]]) + cy * (u[nn[k]] - 2 * u[k] + u[s[k]])
ru.append(lap - adv)
# v face (i, j): u is the mean of the four u faces around it
ub = 0.25 * (u[k] + u[e[k]] + u[s[k]] + u[e[s[k]]])
adv = ub * (v[e[k]] - v[w[k]]) / (2 * dx) + v[k] * (v[nn[k]] - v[s[k]]) / (2 * dy)
lap = cx * (v[e[k]] - 2 * v[k] + v[w[k]]) + cy * (v[nn[k]] - 2 * v[k] + v[s[k]])
rv.append(lap - adv)
return ru, rv
def project(g, us, vs, dt, p0=None, tol=1e-12):
"""Steps 2 and 3: returns the projected (u, v), the pressure p and the CG iterations."""
d = divergence(g, us, vs)
b = [-x / dt for x in d]
mean = sum(b) / len(b)
b = [x - mean for x in b] # the periodic matrix is singular: keep b in its range
p, its = scisparse.cg(g.A, b, tol=tol, x0=p0)
gx, gy = gradient(g, 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 chorin(g, u, v, dt, nu, steps, force=None, p=None):
"""Run CHORIN-PROJECTION for a number of steps. force(t) returns (fu, fv) at the faces."""
t = 0.0
cg_its = 0
for n in range(steps): # @line L1
ru, rv = momentum_rhs(g, u, v, nu)
fu, fv = force(t) if force else (None, None)
us = [u[k] + dt * (ru[k] + (fu[k] if fu else 0.0)) for k in range(len(u))] # @line L2
vs = [v[k] + dt * (rv[k] + (fv[k] if fv else 0.0)) for k in range(len(v))] # @line L2
u, v, p, its = project(g, us, vs, dt, p0=p) # @line L3 @line L4 @line L5
cg_its += its
t += dt
return u, v, p, cg_its # @line L6
# ---------------------------------------------------------------- the Taylor-Green vortex
def taylor_green(g, nu, t):
"""Exact solution on [0, 2 pi]^2: u, v at their faces and p (pressure / density) at centers."""
a = math.exp(-2 * nu * t)
u = [-math.cos(x) * math.sin(y) * a for x, y in g.points("u")]
v = [math.sin(x) * math.cos(y) * a for x, y in g.points("v")]
p = [-(math.cos(2 * x) + math.cos(2 * y)) / 4 * a * a for x, y in g.points("p")]
return u, v, p
def max_err(a, b):
return max(abs(a[k] - b[k]) for k in range(len(a)))
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_chorin_projection_method.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chorin-projection-method/. The authors are listed in prov/MYD986.jsonl.
import math
import random
from fractions import Fraction as Fr
import scisparse as sp
from chorin_projection_method import Grid, chorin, divergence, max_err, project, taylor_green
# ---------------------------------------------------------------- the projection method
def test_projection_hand_example():
# 4 by 1 periodic cells, dx = dy = 1, dt = 1, u* = (1, 0, 0, 0): the projection keeps the mean 1/4
g = Grid(4, 1, 4.0, 1.0)
u, v, p, _ = project(g, [1.0, 0.0, 0.0, 0.0], [0.0] * 4, 1.0)
assert max(abs(x - 0.25) for x in u) < 1e-12
assert max(abs(p[k] - q) for k, q in enumerate([0.375, 0.125, -0.125, -0.375])) < 1e-12
def test_projection_is_an_orthogonal_projector():
rng = random.Random(3)
g = Grid(6, 5, 1.0, 1.0)
us = [rng.uniform(-1, 1) for _ in range(30)]
vs = [rng.uniform(-1, 1) for _ in range(30)]
u, v, _, _ = project(g, us, vs, 0.5)
assert max(abs(x) for x in divergence(g, u, v)) < 1e-10
u2, v2, _, _ = project(g, u, v, 0.5)
assert max_err(u, u2) < 1e-10 and max_err(v, v2) < 1e-10
inner = sum((us[k] - u[k]) * u[k] + (vs[k] - v[k]) * v[k] for k in range(30))
assert abs(inner) < 1e-10
def test_taylor_green_space_order_and_divergence():
nu, T = 0.1, 0.5
errs = []
for n in (8, 16, 32):
g = Grid(n, n)
u, v, _ = taylor_green(g, nu, 0.0)
steps = max(1, round(T / (0.4 * g.dx**2))) # dt proportional to dx^2
u, v, p, _ = chorin(g, u, v, T / steps, nu, steps)
assert max(abs(x) for x in divergence(g, u, v)) < 1e-10
ue, ve, _ = taylor_green(g, nu, T)
errs.append(max(max_err(u, ue), max_err(v, ve)))
orders = [math.log2(errs[i] / errs[i + 1]) for i in range(2)]
assert all(abs(q - 2) < 0.2 for q in orders), orders
assert abs(errs[0] - 2.266e-3) < 1e-5 # N = 8: 2 steps of dt = 0.25
def test_taylor_green_time_order():
nu, T = 0.1, 1.0
g = Grid(16, 16)
runs = []
for steps in (10, 20, 40):
u, v, _ = taylor_green(g, nu, 0.0)
u, v, _, _ = chorin(g, u, v, T / steps, nu, steps)
runs.append((u, v))
d1 = max(max_err(runs[0][0], runs[1][0]), max_err(runs[0][1], runs[1][1]))
d2 = max(max_err(runs[1][0], runs[2][0]), max_err(runs[1][1], runs[2][1]))
assert abs(math.log2(d1 / d2) - 1) < 0.2
# ---------------------------------------------------------------- the shared helper scisparse
def test_thomas_hand_system():
# tridiag(-1, 2, -1) x = (1, 0, 0, 1) has the solution x = (1, 1, 1, 1)
a = [Fr(0), Fr(-1), Fr(-1), Fr(-1)]
b = [Fr(2)] * 4
c = [Fr(-1), Fr(-1), Fr(-1), Fr(0)]
assert sp.thomas(a, b, c, [Fr(1), Fr(0), Fr(0), Fr(1)]) == [1, 1, 1, 1]
def test_thomas_periodic_hand_system():
# cyclic tridiag(-1, 3, -1); for x = (1, 2, 3, 4) the right side is (-3, 2, 3, 8)
a = [Fr(-1)] * 4
b = [Fr(3)] * 4
c = [Fr(-1)] * 4
assert sp.thomas_periodic(a, b, c, [Fr(-3), Fr(2), Fr(3), Fr(8)]) == [1, 2, 3, 4]
def test_thomas_random_exact_residual():
rng = random.Random(7)
for n in (1, 2, 5, 9):
a = [Fr(rng.randint(-3, 3), rng.randint(1, 4)) for _ in range(n)]
c = [Fr(rng.randint(-3, 3), rng.randint(1, 4)) for _ in range(n)]
b = [abs(a[i]) + abs(c[i]) + Fr(1, rng.randint(1, 5)) for i in range(n)]
d = [Fr(rng.randint(-9, 9)) for _ in range(n)]
x = sp.thomas(a, b, c, d)
for i in range(n):
s = b[i] * x[i]
if i > 0:
s += a[i] * x[i - 1]
if i < n - 1:
s += c[i] * x[i + 1]
assert s == d[i]
def test_thomas_periodic_random_exact_residual():
rng = random.Random(11)
for n in (3, 4, 7):
a = [Fr(rng.randint(-3, 3), rng.randint(1, 4)) for _ in range(n)]
c = [Fr(rng.randint(-3, 3), rng.randint(1, 4)) for _ in range(n)]
b = [abs(a[i]) + abs(c[i]) + 1 for i in range(n)]
d = [Fr(rng.randint(-9, 9)) for _ in range(n)]
x = sp.thomas_periodic(a, b, c, d)
for i in range(n):
assert a[i] * x[(i - 1) % n] + b[i] * x[i] + c[i] * x[(i + 1) % n] == d[i]
def test_cg_hand_system():
A = sp.from_dense([[4, 1, 0, 0], [1, 4, 1, 0], [0, 1, 4, 1], [0, 0, 1, 4]])
x, it = sp.cg(A, [5, 6, 6, 5], tol=1e-14)
assert it <= 4
assert max(abs(v - 1) for v in x) < 1e-12
assert sp.to_dense(A)[1] == [1, 4, 1, 0]
def test_gauss_seidel_hand_system():
A = sp.from_dense([[4, 1, 0, 0], [1, 4, 1, 0], [0, 1, 4, 1], [0, 0, 1, 4]])
x = sp.gauss_seidel(A, [5.0, 6.0, 6.0, 5.0], 40)
assert max(abs(v - 1) for v in x) < 1e-12
def _sym(A):
return all(A[j].get(i, 0) == v for i, row in enumerate(A) for j, v in row.items())
def test_poisson_dirichlet_eigenfunction():
nx, ny, p, q = 7, 5, 2, 3
dx, dy = 1 / (nx + 1), 1 / (ny + 1)
A = sp.poisson2d(nx, ny, dx, dy)
assert _sym(A)
v = [math.sin(p * math.pi * (i + 1) * dx) * math.sin(q * math.pi * (j + 1) * dy) for j in range(ny) for i in range(nx)]
lam = 4 / dx**2 * math.sin(p * math.pi * dx / 2) ** 2 + 4 / dy**2 * math.sin(q * math.pi * dy / 2) ** 2
av = sp.spmatvec(A, v)
assert max(abs(av[k] - lam * v[k]) for k in range(nx * ny)) < 1e-9
x, _ = sp.cg(A, [lam * t for t in v], tol=1e-13)
assert max(abs(x[k] - v[k]) for k in range(nx * ny)) < 1e-10
def test_poisson_periodic_eigenfunction():
nx, ny = 8, 6
dx, dy = 1 / nx, 1 / ny
A = sp.poisson2d(nx, ny, dx, dy, bc="periodic")
assert _sym(A)
assert max(abs(s) for s in sp.spmatvec(A, [1.0] * (nx * ny))) == 0
v = [math.cos(2 * math.pi * i * dx) * math.sin(4 * math.pi * j * dy) for j in range(ny) for i in range(nx)]
lam = 4 / dx**2 * math.sin(math.pi * dx) ** 2 + 4 / dy**2 * math.sin(2 * math.pi * dy) ** 2
x, _ = sp.cg(A, [lam * t for t in v], tol=1e-13)
assert max(abs(x[k] - v[k]) for k in range(nx * ny)) < 1e-10
def test_poisson_neumann_eigenfunction():
nx, ny = 6, 5
dx, dy = 1 / nx, 1 / ny
A = sp.poisson2d(nx, ny, dx, dy, bc="neumann")
assert _sym(A)
assert max(abs(s) for s in sp.spmatvec(A, [1.0] * (nx * ny))) < 1e-12
assert sum(sp.spmatvec(sp.poisson2d(4, 3, Fr(1, 4), Fr(1, 3), bc="neumann"), [Fr(1)] * 12), Fr(0)) == 0
v = [math.cos(math.pi * (i + 0.5) * dx) * math.cos(2 * math.pi * (j + 0.5) * dy) for j in range(ny) for i in range(nx)]
lam = 4 / dx**2 * math.sin(math.pi * dx / 2) ** 2 + 4 / dy**2 * math.sin(math.pi * dy) ** 2
x, _ = sp.cg(A, [lam * t for t in v], tol=1e-13)
assert max(abs(x[k] - v[k]) for k in range(nx * ny)) < 1e-10
def test_poisson_exact_fraction_stencil():
A = sp.poisson2d(3, 3, Fr(1, 2), Fr(1, 3))
# center unknown k = 4: 2/dx^2 + 2/dy^2 = 8 + 18, and -4, -9 to the neighbors
assert A[4] == {4: 26, 3: -4, 5: -4, 1: -9, 7: -9}
History
Chorin (1968) proposed the method in Mathematics of Computation. Temam (1969) analyzed the same idea, which he called the method of fractional steps, and proved its convergence. The method builds on the staggered grid of Harlow and Welch (1965). Incremental forms (Goda 1979, van Kan 1986) and the analysis of the splitting error near walls followed; Guermond, Minev and Shen (2006) survey the family. Stam's stable fluids (1999) brought the same projection into computer graphics.
References
- Alexandre J. Chorin, Numerical solution of the Navier-Stokes equations, Mathematics of Computation 22(104) (1968) 745-762, the fractional step method, velocity update without pressure followed by projection
- Roger Temam, Sur l'approximation de la solution des equations de Navier-Stokes par la methode des pas fractionnaires (II), Archive for Rational Mechanics and Analysis 33 (1969) 377-385, convergence of the fractional step (projection) method
- J. L. Guermond, P. Minev and Jie Shen, An overview of projection methods for incompressible flows, Computer Methods in Applied Mechanics and Engineering 195(44-47) (2006) 6011-6045, pressure-correction schemes, the non-incremental and incremental forms, the artificial pressure boundary condition and its error
- Joel H. Ferziger, Milovan Peric and Robert L. Street, Computational Methods for Fluid Dynamics, fourth edition, Springer, 2020, Chapter 7 (solution of the Navier-Stokes equations, fractional step methods)
- 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 that the projection uses here
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 MYD986 Edit this page History Report an error Markdown