Algorithm Search⌘K

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.

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
Properties
deterministicdivergence freeexplicit
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

ut+(u⋅∇)u=−∇p+νΔu+f,∇⋅u=0,\mathbf{u}_t + (\mathbf{u}\cdot\nabla)\mathbf{u} = -\nabla p + \nu\Delta\mathbf{u} + \mathbf{f}, \qquad \nabla\cdot\mathbf{u} = 0,

for the velocity u=(u,v)\mathbf{u} = (u, v) and the pressure pp up to a time TT, from a divergence-free initial velocity. Here pp is the pressure divided by the constant density and ν\nu is the kinematic viscosity. The pressure has no evolution equation. It is the Lagrange multiplier of the constraint ∇⋅u=0\nabla\cdot\mathbf{u} = 0, and it is fixed only up to a constant.

This page uses a periodic box with M=nxnyM = n_x n_y cells on a staggered MAC grid: pp at cell centers, uu on the left face and vv on the bottom face of each cell. DD is the discrete divergence at the centers and GG the discrete gradient at the faces, both by central differences over one cell. On this grid A=−DGA = -DG 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

  1. CHORIN-PROJECTION(u, v, Δt, ν, f, N)
  2. 1for n ← 0 to N - 1 do
  3. 2(u*, v*) ← (u, v) + Δt (-(u·∇)u + ν Δ_h u + f) ▷ no pressure term
  4. 3b ← -D(u*, v*) / Δt
  5. 4solve A p = b ▷ A = -D G, the 5-point matrix
  6. 5(u, v) ← (u*, v*) - Δt G p
  7. 6return (u, v, p)

Line L2 is one forward Euler step of the momentum equation without ∇p\nabla p. The implementation computes the advection term in advective form with central differences, averaging vv to the uu faces and uu to the vv faces, and the viscous term with the 5-point Laplacian on each velocity component. Lines L3 to L5 project: DD of the new velocity is Du∗−Δt DGp=Du∗+Δt Ap=0D\mathbf{u}^* - \Delta t\, DGp = D\mathbf{u}^* + \Delta t\, Ap = 0. The periodic matrix AA is singular, with the constants as null space, and bb has zero sum, so pp 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 ∂p/∂n=0\partial p/\partial n = 0 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 Δx=1\Delta x = 1, Δt=1\Delta t = 1, v∗=0v^* = 0, and u∗=(1,0,0,0)u^* = (1, 0, 0, 0) on the 4 faces, so face 0 carries one unit of flow into cell 0 from cell 3. The divergence is Du∗=(−1,0,0,1)D u^* = (-1, 0, 0, 1), so b=(1,0,0,−1)b = (1, 0, 0, -1). The matrix AA is the periodic second difference with rows (2,−1,0,−1)(2, -1, 0, -1) and its shifts. The solution with zero mean is p=(38,18,−18,−38)p = (\tfrac38, \tfrac18, -\tfrac18, -\tfrac38); for example row 0 gives 2⋅38−18+38=12 \cdot \tfrac38 - \tfrac18 + \tfrac38 = 1. The face gradients are Gp=(p0−p3,p1−p0,p2−p1,p3−p2)=(34,−14,−14,−14)Gp = (p_0 - p_3, p_1 - p_0, p_2 - p_1, p_3 - p_2) = (\tfrac34, -\tfrac14, -\tfrac14, -\tfrac14), and

u=u∗−Gp=(14,14,14,14).u = u^* - Gp = (\tfrac14, \tfrac14, \tfrac14, \tfrac14).

In one periodic dimension a divergence-free field is a constant, and the projection keeps the mean flow 14\tfrac14 and removes the rest, which is a gradient. The test file checks these numbers.

Taylor-Green vortex. On the periodic square [0,2π]2[0, 2\pi]^2 the field u=−cos⁡xsin⁡y e−2νtu = -\cos x \sin y\, e^{-2\nu t}, v=sin⁡xcos⁡y e−2νtv = \sin x \cos 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 f=0\mathbf{f} = 0. With ν=0.1\nu = 0.1, T=0.5T = 0.5 and Δt≈0.4 Δx2\Delta t \approx 0.4\,\Delta x^2 (so that the first order time error also scales like Δx2\Delta x^2), the maximum velocity error at TT is:

N×NN \times N cells steps Δt\Delta t max error observed order
8×88 \times 8 2 0.25 2.266e-3
16×1616 \times 16 8 0.0625 5.898e-4 1.94
32×3232 \times 32 32 0.015625 1.489e-4 1.99

The discrete divergence after every projection is about 10−1410^{-14}. For the order in time, fix the 16×1616 \times 16 grid, set T=1T = 1, 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 GT=−DG^T = -D, so A=−DGA = -DG is symmetric positive semidefinite with the constants as its null space, and every divergence Du∗D\mathbf{u}^* has zero sum. So the pressure equation has a solution, the new velocity has zero discrete divergence, and it is the orthogonal projection of u∗\mathbf{u}^* onto the discretely divergence-free fields. From this, one Chorin step is exactly one forward Euler step for the projected system u′=PhFh(u)\mathbf{u}' = P_h F_h(\mathbf{u}), 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 FhF_h 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 nx×ny=Mn_x \times n_y = M cells of size Δx×Δy\Delta x \times \Delta y. A velocity field u=(u,v)\mathbf{u} = (u, v) has one value uku_k on the left face and one value vkv_k on the bottom face of each cell kk, and a pressure pp has one value per cell center. With e(k),w(k),n(k),s(k)e(k), w(k), n(k), s(k) the east, west, north and south neighbors of cell kk (with wrap around),

(Du)k=ue(k)−ukΔx+vn(k)−vkΔy,(Gp)kx=pk−pw(k)Δx,(Gp)ky=pk−ps(k)Δy.(D\mathbf{u})_k = \frac{u_{e(k)} - u_k}{\Delta x} + \frac{v_{n(k)} - v_k}{\Delta y}, \qquad (Gp)^x_k = \frac{p_k - p_{w(k)}}{\Delta x}, \qquad (Gp)^y_k = \frac{p_k - p_{s(k)}}{\Delta y}.

The inner products are ⟨u,w⟩=∑k(ukwkx+vkwky)\langle \mathbf{u}, \mathbf{w}\rangle = \sum_k (u_k w^x_k + v_k w^y_k) on face fields and (p,q)=∑kpkqk(p, q) = \sum_k p_k q_k on cell fields; a common factor ΔxΔy\Delta x \Delta y does not change any statement below. Fh(u)F_h(\mathbf{u}) is the discrete right side of line L2, −(u⋅∇)u+νΔhu+f-(\mathbf{u}\cdot\nabla)\mathbf{u} + \nu\Delta_h\mathbf{u} + \mathbf{f}, any function from face fields to face fields. Vh={u:Du=0}V_h = \{\mathbf{u} : D\mathbf{u} = 0\} is the space of discretely divergence-free fields.

Lemma 1 (summation by parts). ⟨u,Gp⟩=−(Du,p)\langle \mathbf{u}, Gp\rangle = -(D\mathbf{u}, p) for every face field u\mathbf{u} and cell field pp. So GT=−DG^{T} = -D, and A:=−DGA := -DG is symmetric positive semidefinite.

Proof. ∑kuk(pk−pw(k))=∑kukpk−∑kukpw(k)\sum_k u_k (p_k - p_{w(k)}) = \sum_k u_k p_k - \sum_k u_k p_{w(k)}. The map k↦w(k)k \mapsto w(k) is a bijection with inverse ee, so the second sum is ∑jue(j)pj\sum_j u_{e(j)} p_j. Hence ∑kuk(pk−pw(k))/Δx=−∑kpk(ue(k)−uk)/Δx\sum_k u_k (p_k - p_{w(k)})/\Delta x = -\sum_k p_k (u_{e(k)} - u_k)/\Delta x. The yy terms are the same with nn and ss. Adding gives the identity. With u=Gq\mathbf{u} = Gq it gives (Ap,q)=−(DGp,q)=⟨Gp,Gq⟩(Ap, q) = -(DGp, q) = \langle Gp, Gq\rangle, which is symmetric in pp and qq and nonnegative for q=pq = p. Writing out AA shows that it is the matrix of minus the 5-point Laplacian with periodic wrap around. □\square

Lemma 2 (null space and range). Gp=0Gp = 0 if and only if pp is constant. So the null space of AA is the constants, and Ap=bAp = b has a solution if and only if ∑kbk=0\sum_k b_k = 0; the solution is unique up to an additive constant, and GpGp is unique.

Proof. If Gp=0Gp = 0 then pk=pw(k)p_k = p_{w(k)} and pk=ps(k)p_k = p_{s(k)} for all kk; walking west and south reaches every cell, so pp is constant. (Ap,p)=∥Gp∥2(Ap, p) = \|Gp\|^2, so Ap=0Ap = 0 implies Gp=0Gp = 0; the converse is clear. AA 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 GG maps to 00. □\square

Lemma 3 (the right side is in the range). ∑k(Du)k=0\sum_k (D\mathbf{u})_k = 0 for every face field.

Proof. Take p≡1p \equiv 1 in Lemma 1: ∑k(Du)k=−⟨u,G1⟩=0\sum_k (D\mathbf{u})_k = -\langle \mathbf{u}, G1\rangle = 0. □\square

So in exact arithmetic b=−Du∗/Δtb = -D\mathbf{u}^*/\Delta t (line L3) has zero sum, line L4 has a solution, and GpGp in line L5 is well defined. The implementation subtracts the mean of bb before calling CG; in exact arithmetic the mean is 00, and in floating point this removes the rounding part that is outside the range.

Theorem 1 (the step is the orthogonal projection onto VhV_h). Let un+1=u∗−Δt Gp\mathbf{u}^{n+1} = \mathbf{u}^* - \Delta t\, Gp with Ap=−Du∗/ΔtAp = -D\mathbf{u}^*/\Delta t. Then

  1. Dun+1=0D\mathbf{u}^{n+1} = 0;
  2. ⟨un+1,Gq⟩=0\langle \mathbf{u}^{n+1}, Gq\rangle = 0 for every cell field qq, so u∗=un+1+Δt Gp\mathbf{u}^* = \mathbf{u}^{n+1} + \Delta t\, Gp is an orthogonal splitting, and ∥un+1∥2+Δt2∥Gp∥2=∥u∗∥2\|\mathbf{u}^{n+1}\|^2 + \Delta t^2\|Gp\|^2 = \|\mathbf{u}^*\|^2;
  3. un+1=Phu∗\mathbf{u}^{n+1} = P_h\mathbf{u}^*, where PhP_h is the orthogonal projector onto VhV_h; it depends on u∗\mathbf{u}^* only, not on Δt\Delta t and not on which solution pp is chosen.

Proof. (1) Dun+1=Du∗−Δt DGp=Du∗+Δt Ap=Du∗−Du∗=0D\mathbf{u}^{n+1} = D\mathbf{u}^* - \Delta t\, DGp = D\mathbf{u}^* + \Delta t\, Ap = D\mathbf{u}^* - D\mathbf{u}^* = 0. (2) By Lemma 1 and (1), ⟨un+1,Gq⟩=−(Dun+1,q)=0\langle \mathbf{u}^{n+1}, Gq\rangle = -(D\mathbf{u}^{n+1}, q) = 0; Pythagoras gives the norm identity. (3) By Lemma 1, the orthogonal complement of Vh=ker⁡DV_h = \ker D is the range of DT=−GD^T = -G, the discrete gradients. By (1) and (2), un+1∈Vh\mathbf{u}^{n+1} \in V_h and u∗−un+1=Δt Gp\mathbf{u}^* - \mathbf{u}^{n+1} = \Delta t\, Gp is orthogonal to VhV_h. The orthogonal decomposition of u∗\mathbf{u}^* into a part in VhV_h and a part in Vh⊥V_h^\perp is unique, so un+1=Phu∗\mathbf{u}^{n+1} = P_h\mathbf{u}^*. □\square

This is the discrete form of the Helmholtz-Hodge decomposition on a periodic domain. The tests check (1) to 10−1010^{-10}, the orthogonality in (2) and Ph2=PhP_h^2 = P_h on random data.

Theorem 2 (equivalence with forward Euler). Let u0∈Vh\mathbf{u}^0 \in V_h. Then the iterates of CHORIN-PROJECTION satisfy un+1=un+Δt PhFh(un)\mathbf{u}^{n+1} = \mathbf{u}^n + \Delta t\, P_h F_h(\mathbf{u}^n), which is the forward Euler method for the system of ordinary differential equations u′=PhFh(u)\mathbf{u}' = P_h F_h(\mathbf{u}) on VhV_h. This system is the method-of-lines form of the discrete Navier-Stokes equations u′=Fh(u)−Gp\mathbf{u}' = F_h(\mathbf{u}) - Gp, Du=0D\mathbf{u} = 0.

Proof. Line L2 gives u∗=un+Δt Fh(un)\mathbf{u}^* = \mathbf{u}^n + \Delta t\, F_h(\mathbf{u}^n), and Theorem 1 gives un+1=Phu∗=Phun+Δt PhFh(un)\mathbf{u}^{n+1} = P_h\mathbf{u}^* = P_h\mathbf{u}^n + \Delta t\, P_h F_h(\mathbf{u}^n) because PhP_h is linear. By induction un∈Vh\mathbf{u}^n \in V_h, so Phun=unP_h\mathbf{u}^n = \mathbf{u}^n. For the second claim, apply PhP_h to u′=Fh(u)−Gp\mathbf{u}' = F_h(\mathbf{u}) - Gp: PhGp=0P_h G p = 0 because gradients are orthogonal to VhV_h, and Phu′=u′P_h\mathbf{u}' = \mathbf{u}' because Du′=(Du)′=0D\mathbf{u}' = (D\mathbf{u})' = 0. Conversely, a solution of u′=PhFh(u)\mathbf{u}' = P_hF_h(\mathbf{u}) in VhV_h solves the pair with Gp=(I−Ph)Fh(u)Gp = (I - P_h)F_h(\mathbf{u}), which is a gradient by Lemma 1. □\square

Corollary (first order in time). For a fixed grid, FhF_h is a polynomial in the face values, so it is Lipschitz on bounded sets, and PhP_h has norm 11. If the exact solution of u′=PhFh(u)\mathbf{u}' = P_hF_h(\mathbf{u}) stays bounded on [0,T][0, T], the standard convergence theorem for forward Euler gives max⁡nΔt≤T∥un−u(nΔt)∥=O(Δt)\max_{n\Delta t \le T}\|\mathbf{u}^n - \mathbf{u}(n\Delta t)\| = O(\Delta t) as Δt→0\Delta t \to 0. On the periodic grid the projection adds no splitting error of its own. The pressure pp of line L4 equals pp of the semi-discrete system evaluated at un\mathbf{u}^n up to O(Δt)O(\Delta t), because Gp=(I−Ph)u∗/Δt=(I−Ph)Fh(un)Gp = (I - P_h)\mathbf{u}^*/\Delta t = (I - P_h)F_h(\mathbf{u}^n).

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 u∗\mathbf{u}^* then satisfies a boundary condition that PhP_h changes; this is the splitting error discussed on the main page.

Termination. The outer loop (line L1) runs NN times. Each step does O(M)O(M) 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 M−1M - 1 iterations in exact arithmetic, because its iterates stay in the range, where AA is positive definite. In floating point the implementation stops at the residual tolerance or at a fixed iteration cap of 10M10M, so each step ends.

Complexity

One step costs Θ(M)\Theta(M) operations for lines L2, L3 and L5, plus the pressure solve. CG on the 5-point matrix has condition number O(Δx−2)O(\Delta x^{-2}), so it needs O(nx)O(n_x) iterations for a fixed tolerance on general data, and one step costs O(M3/2)O(M^{3/2}) on a square grid. Multigrid solves it in O(M)O(M) and an FFT in O(Mlog⁡M)O(M\log M). Memory is Θ(M)\Theta(M). 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 Δt≤1/(2ν(Δx−2+Δy−2))\Delta t \le 1/\big(2\nu(\Delta x^{-2} + \Delta y^{-2})\big), and central advection with forward Euler needs the viscous term to damp it, about Δt≤2ν/∣u∣max⁡2\Delta t \le 2\nu/|\mathbf{u}|_{\max}^2, together with the advective CFL condition. With Δt∼Δx2/ν\Delta t \sim \Delta x^2/\nu, a run to time TT takes N=Θ(Tν/Δx2)N = \Theta(T\nu/\Delta x^2) steps. Implicit diffusion removes the viscous limit at the price of one more linear solve per velocity component per step.

Properties

  • Exact discrete incompressibility: Dun+1=0D\mathbf{u}^{n+1} = 0 up to the pressure solver tolerance, at every step.
  • The projection is orthogonal, so it never increases the discrete kinetic energy: ∥un+1∥≤∥u∗∥\|\mathbf{u}^{n+1}\| \le \|\mathbf{u}^*\|.
  • 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, u∗=⋯−Δt Gpn\mathbf{u}^* = \dots - \Delta t\,Gp^n, and solve for the increment pn+1−pnp^{n+1} - p^n. 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 νΔu\nu\Delta\mathbf{u} 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 Δt\Delta t, 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 pp and u\mathbf{u} sit at the same points and DD and GG are wide central differences, DGDG 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, u∗\mathbf{u}^* satisfies the wall condition but the projection changes its tangential part, and the pressure gets ∂p/∂n=0\partial p/\partial n = 0, 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 L2L^2 but the pressure only of order Δt1/2\Delta t^{1/2}; 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 bb in the range of AA, or CG drifts.
  • Too loose a pressure tolerance leaves a divergence that accumulates over many steps. Measure max⁡∣Du∣\max|D\mathbf{u}| 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.

chorin_projection_method.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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)
  5. 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.

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