Algorithm Search⌘K

Algorithmadvanced

PISO algorithm

Also called pressure-implicit with splitting of operators.

A non-iterative pressure-velocity coupling for transient flow with one predictor and two corrector steps in each time step.

Time
Θ(N M K) worst
Space
Θ(M) extra
Where
K = the number of conjugate gradient iterations per pressure solve; M = the number of grid cells; N = the number of time steps
Properties
deterministicdivergence free after each correctorimplicitneeds poisson solvenot outer iterationstime accurate
Origin
Raad I. Issa, 1986

PISO, Pressure-Implicit with Splitting of Operators, computes one implicit time step of incompressible flow without outer iterations. The implicit step couples the velocity and the pressure in one large system. SIMPLE would iterate on that system with under-relaxation until it converges. PISO instead does one momentum predictor with the old pressure and then a fixed number of pressure corrections, usually two. Each corrector solves a Poisson equation for the pressure and leaves a divergence-free velocity. The second corrector repairs the neighbor terms that the first one ignored. When the time step is small, the remaining difference from the fully coupled step shrinks with a high power of the time step and is smaller than the error of the time discretization itself, so the extra iterations of SIMPLE buy nothing.

In plain words

Each time step must find a new flow and a new pressure that fit together. The careful way is to adjust both again and again until they agree. PISO notices that over a short time step the flow changes only a little, so a few well-chosen adjustments are enough. First it moves the fluid using the old pressure. Then it fixes the pressure so that no cell gains or loses fluid, assuming each face reacts only to its own two cells. Then it does the same fix once more, now counting the push from the neighboring faces too. After these two fixes the answer is so close to the careful one that more work would not improve the result.

The problem

Advance 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,

with pp the pressure divided by the density and ν\nu the kinematic viscosity, by NN steps of the backward Euler method. This page uses the periodic MAC grid with MM cells and central differences, with the advecting velocity frozen at the old time level. One step then asks for the solution of the coupled linear system

aPu−∑nbanbunb=unΔt+f−Gp,Du=0,a_P\mathbf{u} - \sum_{nb} a_{nb}\mathbf{u}_{nb} = \frac{\mathbf{u}^n}{\Delta t} + \mathbf{f} - Gp, \qquad D\mathbf{u} = 0,

with aP=1/Δt+2ν/Δx2+2ν/Δy2a_P = 1/\Delta t + 2\nu/\Delta x^2 + 2\nu/\Delta y^2, DD the divergence and GG the gradient. The cost is counted in real arithmetic operations.

The algorithm

  1. PISO-STEP(u^n, p^n, ν, Δt, f, m)
  2. 1compute a_P, a_nb from u^n; b ← u^n/Δt + f
  3. 2u* ← solve a_P u* - Σ a_nb u*_nb = b - G p^n ▷ momentum predictor
  4. 3for k ← 1 to m ▷ m = 2 in standard PISO
  5. 4h ← (b + Σ a_nb u^(k-1)_nb) / a_P ▷ u^(0) = u*
  6. 5solve -D G p = -a_P D h for p ▷ pressure equation
  7. 6u^(k) ← h - G p / a_P ▷ divergence free
  8. 7return (u^(m), p)

Line L2 solves the momentum equations with the old pressure; this page uses Gauss-Seidel sweeps to a tolerance of 10−1310^{-13}. Line L4 uses the neighbor values of the latest velocity, so the kk-th corrector differs from the first only through the neighbor sum. The first corrector is the SIMPLE correction u(1)=u∗−G(p−pn)/aP\mathbf{u}^{(1)} = \mathbf{u}^* - G(p - p^n)/a_P, written for the full pressure instead of the increment p′=p−pnp' = p - p^n. Finite volume codes write line L4 with face fluxes, and on general grids aPa_P varies, so line L5 has variable coefficients 1/aP1/a_P. Here aPa_P is constant and line L5 is the periodic 5-point Poisson equation, solved with conjugate gradients.

Example

The first corrector by hand. In line L2, aPu∗=b+Nu∗−Gpna_P\mathbf{u}^* = \mathbf{b} + N\mathbf{u}^* - Gp^n, where NN holds the anba_{nb}. So line L4 for k=1k = 1 gives h=u∗+Gpn/aP\mathbf{h} = \mathbf{u}^* + Gp^n/a_P, and line L6 gives u(1)=u∗−G(p−pn)/aP\mathbf{u}^{(1)} = \mathbf{u}^* - G(p - p^n)/a_P: the old pressure gradient is taken out and the new one put in, with the face weight 1/aP1/a_P. Nothing in this step accounts for N(u(1)−u∗)N(\mathbf{u}^{(1)} - \mathbf{u}^*), the change in the neighbor terms. The second corrector puts that change into h\mathbf{h} and projects again.

Taylor-Green vortex. On [0,2π]2[0, 2\pi]^2 the field u=sin⁡xcos⁡y Fu = \sin x\cos y\,F, v=−cos⁡xsin⁡y Fv = -\cos x\sin y\,F, p=14(cos⁡2x+cos⁡2y)F2p = \tfrac14(\cos 2x + \cos 2y)F^2 with F=e−2νtF = e^{-2\nu t} solves the equations with f=0\mathbf{f} = 0. With ν=0.1\nu = 0.1 on 8×88 \times 8 cells, start from a pressure consistent with the scheme (one coupled step first), and compare one PISO step with mm correctors against the coupled step:

Δt\Delta t m=1m = 1 m=2m = 2 m=3m = 3
0.1 8.336e-5 3.575e-6 1.546e-7
0.05 1.107e-5 2.447e-7 5.457e-9
0.025 1.425e-6 1.600e-8 1.814e-10

The observed orders are about 2.9, 3.9 and 4.9, in line with the bound O(Δtm+2)O(\Delta t^{m+2}) proved for a consistent pressure. Over many steps to T=0.4T = 0.4 with m=2m = 2, the differences between runs with Δt=0.1,0.05,0.025,0.0125\Delta t = 0.1, 0.05, 0.025, 0.0125 are 3.196e-4, 1.553e-4 and 7.716e-5, which is first order in time (orders 1.04 and 1.01), the order of backward Euler. On 16×1616 \times 16 cells the orders are 1.18 and 1.06 with m=2m = 2, and 0.99 and 0.99 with m=40m = 40, which is the coupled step. These are measurements from the implementation on this page.

Correctness

The proof is in proofs/correctness.md. Because GT=−DG^T = -D on the MAC grid, each corrector is the orthogonal projection of h\mathbf{h} onto the divergence-free fields, so every corrector ends with Du=0D\mathbf{u} = 0 exactly, whatever the predictor. Repeating the corrector is a fixed-point iteration w↦P((b+Nw)/aP)\mathbf{w} \mapsto P((\mathbf{b} + N\mathbf{w})/a_P). The neighbor matrix has norm at most S=2ν/Δx2+2ν/Δy2+U/Δx+V/ΔyS = 2\nu/\Delta x^2 + 2\nu/\Delta y^2 + U/\Delta x + V/\Delta y, so when the Courant number C=Δt(U/Δx+V/Δy)C = \Delta t(U/\Delta x + V/\Delta y) is below 1 the map is a contraction with factor q=S/aP≤Δt Sq = S/a_P \le \Delta t\,S, the coupled step has a unique solution, and mm correctors miss it by at most qmΔt∥G(p−pn)∥/(1−C)q^m\Delta t\|G(p - p^n)\|/(1 - C). On a fixed grid this is O(Δtm+1)O(\Delta t^{m+1}), and O(Δtm+2)O(\Delta t^{m+2}) when the old pressure is consistent. Two correctors thus stay below the O(Δt2)O(\Delta t^2) local error of backward Euler. The step always ends after a fixed amount of work.

Proof: Every PISO corrector ends divergence free, and the correctors converge geometrically to the coupled implicit step, with a splitting error of order Δt^(m+1) after m of themfull

Setting. The grid is the periodic MAC grid of the main page with MM cells. DD is the divergence at the cell centers and GG the gradient at the faces. Summation by parts gives GT=−DG^T = -D, and −DG-DG is the periodic 5-point matrix, symmetric positive semidefinite with the constants as its null space (proved on the Chorin projection method page). One time step has the coefficients aP=1/Δt+2ν/Δx2+2ν/Δy2a_P = 1/\Delta t + 2\nu/\Delta x^2 + 2\nu/\Delta y^2, the same on every face, and the neighbor coefficients anba_{nb} of central differences, computed from un\mathbf{u}^n. Write NN for the matrix of the anba_{nb} and b=un/Δt+f\mathbf{b} = \mathbf{u}^n/\Delta t + \mathbf{f}. The coupled implicit step that PISO approximates is

aPu−Nu=b−Gp,Du=0.(C)a_P\mathbf{u} - N\mathbf{u} = \mathbf{b} - Gp, \qquad D\mathbf{u} = 0. \tag{C}

PISO computes the predictor u(0)=u∗\mathbf{u}^{(0)} = \mathbf{u}^* from (aP−N)u∗=b−Gpn(a_P - N)\mathbf{u}^* = \mathbf{b} - Gp^n (line L2) and then, for k=1,…,mk = 1, \dots, m, h=(b+Nu(k−1))/aP\mathbf{h} = (\mathbf{b} + N\mathbf{u}^{(k-1)})/a_P, p(k)p^{(k)} from −DGp(k)=−aPDh-DGp^{(k)} = -a_P D\mathbf{h}, and u(k)=h−Gp(k)/aP\mathbf{u}^{(k)} = \mathbf{h} - Gp^{(k)}/a_P (lines L4 to L6). The first corrector is Issa's form with p′=p(1)−pnp' = p^{(1)} - p^n: from the predictor equation h=u∗+Gpn/aP\mathbf{h} = \mathbf{u}^* + Gp^n/a_P, so u(1)=u∗−G(p(1)−pn)/aP\mathbf{u}^{(1)} = \mathbf{u}^* - G(p^{(1)} - p^n)/a_P.

Let U=max⁡∣un∣U = \max|u^n|, V=max⁡∣vn∣V = \max|v^n|, S=2ν/Δx2+2ν/Δy2+U/Δx+V/ΔyS = 2\nu/\Delta x^2 + 2\nu/\Delta y^2 + U/\Delta x + V/\Delta y, q=S/aPq = S/a_P, and the Courant number C=Δt(U/Δx+V/Δy)C = \Delta t(U/\Delta x + V/\Delta y). Norms are Euclidean.

Lemma 1 (the corrector is an orthogonal projection). Let PP be the orthogonal projection onto the face vectors with Dw=0D\mathbf{w} = 0. Each corrector gives u(k)=Ph\mathbf{u}^{(k)} = P\mathbf{h}.

Proof. The equation −DGp=−aPDh-DGp = -a_P D\mathbf{h} is solvable because ∑c(Dh)c=0\sum_c (D\mathbf{h})_c = 0 on the periodic grid, so the right side is in the range of −DG-DG. Then Du(k)=Dh−DGp/aP=0D\mathbf{u}^{(k)} = D\mathbf{h} - DGp/a_P = 0. Also u(k)−h=−Gp/aP\mathbf{u}^{(k)} - \mathbf{h} = -Gp/a_P is in the range of GG, and for every w\mathbf{w} with Dw=0D\mathbf{w} = 0, wTGp=(GTw)Tp=−(Dw)Tp=0\mathbf{w}^TGp = (G^T\mathbf{w})^Tp = -(D\mathbf{w})^Tp = 0. So u(k)\mathbf{u}^{(k)} is divergence free and h−u(k)\mathbf{h} - \mathbf{u}^{(k)} is orthogonal to the divergence-free vectors, which is the definition of PhP\mathbf{h}. □\square

Theorem 1 (mass conservation after every corrector). Du(k)=0D\mathbf{u}^{(k)} = 0 for every k≥1k \ge 1, whatever the predictor and Δt\Delta t are.

Proof. This is the first part of the proof of Lemma 1. □\square

The test file checks max⁡∣Du(k)∣<10−10\max|D\mathbf{u}^{(k)}| < 10^{-10} after each of three correctors, from a start that is not divergence free.

Lemma 2 (size of the neighbor matrix). ∥N∥≤S\|N\| \le S.

Proof. A row of NN has the four entries ν/Δx2∓uˉ/(2Δx)\nu/\Delta x^2 \mp \bar u/(2\Delta x) and ν/Δy2∓vˉ/(2Δy)\nu/\Delta y^2 \mp \bar v/(2\Delta y), where uˉ\bar u and vˉ\bar v are values or averages of un\mathbf{u}^n, so ∣uˉ∣≤U|\bar u| \le U and ∣vˉ∣≤V|\bar v| \le V. So every row has absolute sum at most SS. A column receives one entry from each of four rows, the east, west, north and south neighbors, and the same bound on each entry gives column sums at most SS. Then ∥N∥2≤∥N∥1∥N∥∞≤S2\|N\|^2 \le \|N\|_1\|N\|_\infty \le S^2. □\square

Note that q<1q < 1 is the same as aP>Sa_P > S, which is 1/Δt>U/Δx+V/Δy1/\Delta t > U/\Delta x + V/\Delta y, that is C<1C < 1. Also aP≥1/Δta_P \ge 1/\Delta t, so q≤Δt Sq \le \Delta t\,S, and aP−S≥(1−C)/Δta_P - S \ge (1 - C)/\Delta t.

Theorem 2 (convergence of the correctors). Let C<1C < 1. Then (C) has exactly one velocity solution u\mathbf{u}, with a pressure pp unique up to a constant, and for every k≥1k \ge 1

∥u(k)−u∥≤q ∥u(k−1)−u∥,∥u∗−u∥≤Δt1−C ∥G(p−pn)∥.\|\mathbf{u}^{(k)} - \mathbf{u}\| \le q\,\|\mathbf{u}^{(k-1)} - \mathbf{u}\|, \qquad \|\mathbf{u}^* - \mathbf{u}\| \le \frac{\Delta t}{1 - C}\,\|G(p - p^n)\|.

So ∥u(m)−u∥≤qmΔt1−C∥G(p−pn)∥≤(Δt S)m Δt1−C∥G(p−pn)∥\|\mathbf{u}^{(m)} - \mathbf{u}\| \le q^m\frac{\Delta t}{1 - C}\|G(p - p^n)\| \le \frac{(\Delta t\,S)^m\,\Delta t}{1 - C}\|G(p - p^n)\|.

Proof. Let T(w)=P((b+Nw)/aP)T(\mathbf{w}) = P((\mathbf{b} + N\mathbf{w})/a_P), so that u(k)=T(u(k−1))\mathbf{u}^{(k)} = T(\mathbf{u}^{(k-1)}) by Lemma 1. Since ∥P∥≤1\|P\| \le 1 and by Lemma 2, ∥T(w)−T(w′)∥≤∥N∥∥w−w′∥/aP≤q∥w−w′∥\|T(\mathbf{w}) - T(\mathbf{w}')\| \le \|N\|\|\mathbf{w} - \mathbf{w}'\|/a_P \le q\|\mathbf{w} - \mathbf{w}'\|, so TT is a contraction and has exactly one fixed point u\mathbf{u}. The fixed point solves (C): u=Ph\mathbf{u} = P\mathbf{h} with h=(b+Nu)/aP\mathbf{h} = (\mathbf{b} + N\mathbf{u})/a_P gives Du=0D\mathbf{u} = 0 and h−u=Gφ\mathbf{h} - \mathbf{u} = G\varphi for some φ\varphi (the orthogonal complement of the divergence-free vectors is the range of GG, because GT=−DG^T = -D). With p=aPφp = a_P\varphi this is aPu−Nu=b−Gpa_P\mathbf{u} - N\mathbf{u} = \mathbf{b} - Gp. Conversely every velocity solution of (C) is a fixed point of TT by Lemma 1, so it is u\mathbf{u}; GpGp is then fixed by (C), and pp is fixed up to the null space of GG, the constants.

For the first inequality, u(k)−u=T(u(k−1))−T(u)\mathbf{u}^{(k)} - \mathbf{u} = T(\mathbf{u}^{(k-1)}) - T(\mathbf{u}). For the second, subtract (C) from the predictor equation: (aP−N)(u∗−u)=G(p−pn)(a_P - N)(\mathbf{u}^* - \mathbf{u}) = G(p - p^n). For any w\mathbf{w}, ∥(aP−N)w∥≥(aP−S)∥w∥≥(1−C)∥w∥/Δt\|(a_P - N)\mathbf{w}\| \ge (a_P - S)\|\mathbf{w}\| \ge (1 - C)\|\mathbf{w}\|/\Delta t, which gives the bound. □\square

Corollary (splitting error). On a fixed grid, as Δt→0\Delta t \to 0, the difference between mm correctors and the coupled step is O(Δtm+1)O(\Delta t^{m+1}) in general, and O(Δtm+2)O(\Delta t^{m+2}) when pnp^n comes from the previous step of a smooth solution, so that p−pn=O(Δt)p - p^n = O(\Delta t). The coupled backward Euler step has a local error of order Δt2\Delta t^2. So already one corrector with a consistent pressure, and two in general, keep the splitting error below the local time error, and PISO is first order in time like backward Euler.

The test file confirms the contraction with the proved factor (q=0.53q = 0.53 on its 8×88 \times 8 case, where the observed ratios are about 0.08, so the bound is far from tight), measures splitting error orders of about 2.9 and 3.9 for m=1m = 1 and m=2m = 2 with a consistent pressure, and measures first order in time over many steps.

Termination. Line L2 runs at most a fixed number of Gauss-Seidel sweeps (it stops earlier when the update is below 10−1310^{-13}; the sweeps converge when C<1C < 1, because then aP>Sa_P > S makes the momentum matrix strictly diagonally dominant). The loop of line L3 runs exactly mm times, and each conjugate gradient solve stops after at most its iteration limit. So a PISO step always ends, after a fixed amount of work bounded in advance. There is no outer iteration.

What is not proved. The bounds are for one step with the coefficients frozen at un\mathbf{u}^n. Stability over many steps and the effect of the frozen advection coefficients are not proved here; the condition C<1C < 1 is sufficient for the bounds, not necessary for the method to work.

Complexity

The predictor costs Θ(M)\Theta(M) per Gauss-Seidel sweep, and the number of sweeps for a fixed tolerance is bounded when CC is bounded away from 1, because the momentum matrix is then strictly diagonally dominant. Each corrector costs Θ(M)\Theta(M) plus one Poisson solve of KK conjugate gradient iterations of Θ(M)\Theta(M) each. With a fixed number mm of correctors one step costs Θ(MK)\Theta(M K) and NN steps cost Θ(NMK)\Theta(N M K), with Θ(M)\Theta(M) memory. KK grows like M\sqrt{M} on a square grid; multigrid or a fast Poisson solver removes that factor. Compared with SIMPLE applied to each time step, PISO replaces an outer iteration of unknown length by a fixed number of solves.

Properties

  • Non-iterative: a fixed number of linear solves per time step, so the cost of a step is known in advance.
  • Every corrector leaves a discretely divergence-free velocity.
  • No under-relaxation is needed: the time step plays the role that under-relaxation plays in SIMPLE.
  • Time accurate to the order of the underlying implicit scheme when Δt\Delta t is small enough that the splitting error is smaller than the time error.
  • For large time steps the splitting error grows, and PISO no longer approximates the implicit step well.

Variants and improvements

  • More correctors. Each extra corrector multiplies the splitting error by at most qq (by about 0.08 in the test case, where q=0.53q = 0.53); three or more are used for stiff cases.
  • PIMPLE, the name used in OpenFOAM, wraps PISO correctors in a few SIMPLE-like outer iterations per time step, which allows larger time steps.
  • Non-orthogonal correctors. On skewed grids, extra solves of the pressure equation inside each corrector treat the non-orthogonal part of the Laplacian explicitly.
  • Collocated grids use Rhie-Chow interpolation for the face velocities in line L5.
  • Projection methods. A projection method with an incremental pressure is closely related: one predictor and one projection per step, with the splitting error analyzed in terms of the pressure update.

When to use it

Use PISO for unsteady incompressible flow with an implicit momentum equation and time steps at Courant numbers around 1 or below, where time accuracy matters and SIMPLE iterations per step would be wasted. For steady flow, use SIMPLE. For large time steps, use outer iterations (PIMPLE) or a fully coupled solver.

Pitfalls

  • Large Courant numbers. The contraction bound needs C<1C < 1. Above that the splitting error is no longer small, the result drifts from the implicit step, and the method may become unstable, although on a 16×1616 \times 16 Taylor-Green case the correctors still converged for C=5C = 5 to 20, only slowly.
  • Inconsistent pressure at the start. If pnp^n does not fit the scheme, as with an exact pressure sampled on a coarse grid, the first step loses one order: on 16×1616 \times 16 cells the measured one-corrector error fell like Δt2\Delta t^2 instead of Δt3\Delta t^3.
  • Inner solves that are too loose. The proof assumes the pressure equation is solved exactly; a pressure solve stopped early leaves a divergence error of the size of its residual.
  • Frozen advection coefficients. PISO linearizes advection at the old velocity. This is part of the first-order time error; a second order scheme needs a different predictor and more care.

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.

piso_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/piso-algorithm/. The authors are listed in prov/8SFP8G.jsonl.

"""PISO (Issa 1986) for the unsteady 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).
Staggered (MAC) grid: 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), v[k] at the bottom face ((i + 1/2) dx, j dy), k = i + nx j.

One time step is backward Euler with the advecting velocity frozen at u^n:
    a_P u_P - sum a_nb u_nb = u^n_P / dt + f_P - (G p)_P,   D u = 0,
with a_P = 1/dt + 2 nu/dx^2 + 2 nu/dy^2 and central differences. PISO does not solve
this coupled system. It does one momentum predictor with the old pressure and then a
fixed number of pressure corrections. Corrector m computes
    h = (b + sum a_nb u^(m-1)_nb) / a_P,  solves  -D (d G p) = -D h  with d = 1 / a_P,
    and sets u^(m) = h - d G p,
so each corrector ends with a divergence-free velocity.
"""

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.n = n
        self.e = [(k % nx + 1) % nx + nx * (k // nx) for k in range(n)]
        self.w = [(k % nx - 1) % nx + nx * (k // nx) for k in range(n)]
        self.nn = [k % nx + nx * ((k // nx + 1) % ny) for k in range(n)]
        self.s = [k % nx + nx * ((k // nx - 1) % ny) for k in range(n)]

    def points(self, where):
        sx = 0.0 if where == "u" else 0.5
        sy = 0.0 if where == "v" else 0.5
        return [((k % self.nx + sx) * self.dx, (k // self.nx + sy) * self.dy) for k in range(self.n)]


def divergence(g, u, v):
    return [(u[g.e[k]] - u[k]) / g.dx + (v[g.nn[k]] - v[k]) / g.dy for k in range(g.n)]


def gradient(g, p):
    return ([(p[k] - p[g.w[k]]) / g.dx for k in range(g.n)], [(p[k] - p[g.s[k]]) / g.dy for k in range(g.n)])


def coefficients(g, u, v, nu, dt):
    """a_P (the same on every face) and the neighbor coefficients of the u and v equations,
    with the advecting velocity taken from (u, v). Each neighbor list is (index, a_nb)."""
    dx, dy = g.dx, g.dy
    ap = 1 / dt + 2 * nu / dx**2 + 2 * nu / dy**2
    nbu, nbv = [], []
    for k in range(g.n):
        ub = u[k]
        vb = 0.25 * (v[k] + v[g.w[k]] + v[g.nn[k]] + v[g.w[g.nn[k]]])
        nbu.append(((g.e[k], nu / dx**2 - ub / (2 * dx)), (g.w[k], nu / dx**2 + ub / (2 * dx)),
                    (g.nn[k], nu / dy**2 - vb / (2 * dy)), (g.s[k], nu / dy**2 + vb / (2 * dy))))
        ub = 0.25 * (u[k] + u[g.e[k]] + u[g.s[k]] + u[g.e[g.s[k]]])
        vb = v[k]
        nbv.append(((g.e[k], nu / dx**2 - ub / (2 * dx)), (g.w[k], nu / dx**2 + ub / (2 * dx)),
                    (g.nn[k], nu / dy**2 - vb / (2 * dy)), (g.s[k], nu / dy**2 + vb / (2 * dy))))
    return ap, nbu, nbv


def _hbya(ap, nb, b, x):
    return [(b[k] + sum(a * x[m] for m, a in nb[k])) / ap for k in range(len(b))]


def _momentum_solve(ap, nb, b, x0, tol=1e-13, maxsweeps=500):
    """Solve a_P x - sum a_nb x_nb = b by Gauss-Seidel sweeps until the update is below tol."""
    x = list(x0)
    for _ in range(maxsweeps):
        change = 0.0
        for k in range(len(b)):
            new = (b[k] + sum(a * x[m] for m, a in nb[k])) / ap
            change = max(change, abs(new - x[k]))
            x[k] = new
        if change <= tol:
            break
    return x


def piso_step(g, u, v, p, nu, dt, fu, fv, correctors=2, check=None):
    """One PISO time step. Returns (u, v, p) at the new time level. check(m, u, v) is called
    after corrector m (for tests)."""
    A = scisparse.poisson2d(g.nx, g.ny, g.dx, g.dy, bc="periodic")  # -D G; d = 1/a_P is constant
    ap, nbu, nbv = coefficients(g, u, v, nu, dt)  # @line L1
    bu = [u[k] / dt + fu[k] for k in range(g.n)]
    bv = [v[k] / dt + fv[k] for k in range(g.n)]
    gx, gy = gradient(g, p)
    us = _momentum_solve(ap, nbu, [bu[k] - gx[k] for k in range(g.n)], u)  # @line L2
    vs = _momentum_solve(ap, nbv, [bv[k] - gy[k] for k in range(g.n)], v)  # @line L2
    for m in range(1, correctors + 1):  # @line L3
        hu, hv = _hbya(ap, nbu, bu, us), _hbya(ap, nbv, bv, vs)  # @line L4
        rhs = [-ap * x for x in divergence(g, hu, hv)]  # -D G p = -a_P D h  @line L5
        mean = sum(rhs) / g.n
        p, _ = scisparse.cg(A, [x - mean for x in rhs], tol=1e-13, x0=p)  # @line L5
        gx, gy = gradient(g, p)
        us = [hu[k] - gx[k] / ap for k in range(g.n)]  # @line L6
        vs = [hv[k] - gy[k] / ap for k in range(g.n)]  # @line L6
        if check:
            check(m, us, vs)
    return us, vs, p  # @line L7


def coupled_step(g, u, v, p, nu, dt, fu, fv, correctors=40):
    """The coupled backward Euler step that PISO approximates. Repeated correctors converge
    to it when a_P dominates the neighbor sum (proved on the page); 40 is plenty for the
    tests, which check it."""
    return piso_step(g, u, v, p, nu, dt, fu, fv, correctors=correctors)


def momentum_residual(g, u0, v0, u, v, p, nu, dt, fu, fv):
    """Residual of a_P u - sum a_nb u_nb - u0/dt - f + G p, coefficients from (u0, v0)."""
    ap, nbu, nbv = coefficients(g, u0, v0, nu, dt)
    gx, gy = gradient(g, p)
    ru = [ap * u[k] - sum(a * u[m] for m, a in nbu[k]) - u0[k] / dt - fu[k] + gx[k] for k in range(g.n)]
    rv = [ap * v[k] - sum(a * v[m] for m, a in nbv[k]) - v0[k] / dt - fv[k] + gy[k] for k in range(g.n)]
    return ru, rv


def taylor_green(g, nu, t):
    """u = sin x cos y F, v = -cos x sin y F, p = (cos 2x + cos 2y) F^2 / 4, F = exp(-2 nu t):
    an exact solution with f = 0 on [0, 2 pi)^2."""
    F = math.exp(-2 * nu * t)
    u = [math.sin(x) * math.cos(y) * F for x, y in g.points("u")]
    v = [-math.cos(x) * math.sin(y) * F for x, y in g.points("v")]
    p = [(math.cos(2 * x) + math.cos(2 * y)) * F * F / 4 for x, y in g.points("p")]
    return u, v, p
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_piso_algorithm.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/piso-algorithm/. The authors are listed in prov/8SFP8G.jsonl.

import math
import random

from piso_algorithm import Grid, coupled_step, divergence, momentum_residual, piso_step, taylor_green

NU = 0.1


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


def _gap2(a, b):
    return math.sqrt(sum((a[0][k] - b[0][k]) ** 2 + (a[1][k] - b[1][k]) ** 2 for k in range(len(a[0]))))


def _start(n):
    g = Grid(n, n)
    return g, [0.0] * g.n, taylor_green(g, NU, 0.0)


def test_every_corrector_ends_divergence_free():
    g, z, (u, v, p) = _start(8)
    rng = random.Random(4)
    u = [x + 0.05 * rng.uniform(-1, 1) for x in u]  # not divergence free at the start
    seen = []

    def check(m, us, vs):
        seen.append((m, max(abs(x) for x in divergence(g, us, vs))))

    piso_step(g, u, v, p, NU, 0.1, z, z, correctors=3, check=check)
    assert [m for m, _ in seen] == [1, 2, 3]
    assert all(d < 1e-10 for _, d in seen)


def test_many_correctors_solve_the_coupled_implicit_step():
    g, z, (u, v, p) = _start(8)
    dt = 0.1
    un, vn, pn = coupled_step(g, u, v, p, NU, dt, z, z)
    ru, rv = momentum_residual(g, u, v, un, vn, pn, NU, dt, z, z)
    assert max(max(map(abs, ru)), max(map(abs, rv))) < 1e-11
    assert max(abs(x) for x in divergence(g, un, vn)) < 1e-11


def test_corrector_error_contracts_by_the_proved_factor():
    # ||u^(m+1) - u|| <= q ||u^(m) - u|| with q = S / a_P, S = 2 nu/dx^2 + 2 nu/dy^2 + U/dx + V/dy.
    g, z, (u, v, p) = _start(8)
    dt = 0.2
    U, V = max(map(abs, u)), max(map(abs, v))
    ap = 1 / dt + 2 * NU / g.dx**2 + 2 * NU / g.dy**2
    q = (2 * NU / g.dx**2 + 2 * NU / g.dy**2 + U / g.dx + V / g.dy) / ap
    assert q < 1
    ref = coupled_step(g, u, v, p, NU, dt, z, z)
    errs = [_gap2(piso_step(g, u, v, p, NU, dt, z, z, correctors=m), ref) for m in (1, 2, 3, 4)]
    for a, b in zip(errs, errs[1:]):
        assert b <= q * a


def test_splitting_error_of_one_step_is_order_m_plus_2():
    # Start from a pressure consistent with the scheme (one coupled step first). Measured
    # orders on 8 x 8: about 3 for one corrector and 4 for two.
    g, z, (u, v, p) = _start(8)
    errs = {1: [], 2: []}
    for dt in (0.1, 0.05, 0.025):
        s1 = coupled_step(g, u, v, p, NU, dt, z, z)
        ref = coupled_step(g, *s1, NU, dt, z, z)
        for m in (1, 2):
            errs[m].append(_gap(piso_step(g, *s1, NU, dt, z, z, correctors=m), ref))
    for m, lo in ((1, 2.6), (2, 3.5)):
        e = errs[m]
        orders = [math.log2(e[i] / e[i + 1]) for i in range(2)]
        assert all(o > lo for o in orders), (m, orders)


def test_two_correctors_are_first_order_in_time_like_backward_euler():
    g, z, (u, v, p) = _start(8)
    T = 0.4
    sols = []
    for dt in (0.1, 0.05, 0.025, 0.0125):
        s = (u, v, p)
        for _ in range(round(T / dt)):
            s = piso_step(g, *s, NU, dt, z, z, correctors=2)
        sols.append(s)
    d = [_gap(sols[i], sols[i + 1]) for i in range(3)]
    orders = [math.log2(d[i] / d[i + 1]) for i in range(2)]
    assert all(0.9 < o < 1.15 for o in orders), orders
    eu, ev, _ = taylor_green(g, NU, T)
    assert _gap(sols[-1], (eu, ev)) < 0.05  # the 8 x 8 grid error dominates

History

Issa (1986) introduced PISO as a way to solve the implicitly discretized flow equations by operator splitting, with one predictor and a sequence of correctors in each time step, and analyzed the splitting error. It grew out of the pressure correction idea of SIMPLE (Patankar and Spalding 1972, and Patankar 1980), applied without outer iterations. PISO became one of the standard transient solvers of finite volume codes.

References

  1. R. I. Issa, Solution of the implicitly discretised fluid flow equations by operator-splitting, Journal of Computational Physics 62(1) (1986) 40-65, the predictor and corrector steps and the analysis of the splitting error
  2. Joel H. Ferziger, Milovan Peric and Robert L. Street, Computational Methods for Fluid Dynamics, fourth edition, Springer, 2020, Chapter 7 (pressure correction methods, PISO)
  3. Suhas V. Patankar, Numerical Heat Transfer and Fluid Flow, Hemisphere and McGraw-Hill, 1980, Sections 6.5 to 6.7 (the pressure and velocity corrections of SIMPLE that PISO repeats)

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