Algorithmcore
SIMPLE algorithm
Also called semi-implicit method for pressure-linked equations.
Couples pressure and velocity by guessing a pressure, solving momentum, then correcting both from a pressure correction equation, until converged.
- Solves
- Navier-Stokes equations
- Time
- Θ(I M K) worst
- Space
- Θ(M) extra
- Where
- I = the number of outer iterations; K = the number of conjugate gradient iterations per pressure correction; M = the number of grid cells
- Model
- Real RAM
- Properties
- deterministiciterativemass conserving iteratesneeds poisson solvesteady state
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Suhas V. Patankar, D. Brian Spalding, 1972
SIMPLE, the Semi-Implicit Method for Pressure-Linked Equations, is the classic iteration for steady incompressible flow in finite volume codes. The difficulty is that incompressible flow has no equation for the pressure: the pressure is whatever field makes the velocity divergence free. SIMPLE guesses a pressure, solves the momentum equations with it, and then asks how the pressure must change so that the new velocity conserves mass. An approximate answer to that question is a Poisson-like equation for a pressure correction . The velocity takes the full correction, so it conserves mass after every iteration, and the pressure takes only a fraction of . The iteration repeats until the momentum equations hold too. At convergence the answer does not depend on the approximations made in the correction or on the under-relaxation factors.
In plain words
Think of a network of pipes where the pump pressures are unknown. Guess the pressures and compute how the fluid would move with them. The result leaks: some junctions receive more fluid than they send out. For each junction, work out how much the pressure must go up or down to stop the leak, if each pipe reacts only to the pressures at its two ends. Correct the flows fully, so that nothing leaks now, but correct the pressures only part of the way, because the estimate of how pipes react was rough. Then compute the flows again with the new pressures and repeat. When nothing changes any more, the flows and the pressures fit each other exactly.
The problem
Find a steady solution of the incompressible Navier-Stokes equations
with the pressure divided by the density and the kinematic viscosity. This page uses the staggered MAC grid with cells, periodic in , and in either periodic or closed by no-slip walls. Central differences for advection and viscosity give, at each velocity face, the discrete momentum equation
with coefficients that depend on the velocity, and at each cell, where is the divergence and the pressure gradient. Finite volume codes have the same structure with fluxes through cell faces. The cost is counted in real arithmetic operations.
The algorithm
SIMPLE(u, p, ν, f, α_u, α_p, s, tol)- 1
repeat - 2
compute a_P, a_nb from the current u ▷ Picard linearization - 3
u* ← s Gauss-Seidel sweeps on (a_P/α_u) u* - Σ a_nb u*_nb = f - G p + (1 - α_u)(a_P/α_u) u - 4
d ← α_u / a_P ▷ on every velocity face - 5
solve -D(d G p') = -D u* for p' ▷ pressure correction equation - 6
p ← p + α_p p' - 7
u ← u* - d G p' - 8
until the momentum residual and |D u| are at most tol - 9
return (u, p)
Line L3 solves the momentum equations only roughly, with the old pressure and with momentum under-relaxation , which adds weight to the diagonal and pulls toward the previous iterate. The corrected velocity should satisfy for the corrections . SIMPLE drops the neighbor sum, which gives in line L7. Requiring then gives the correction equation of line L5. Its matrix is , a 5-point Poisson matrix with face weights ; a wall face has no correction, which is the Neumann condition for . This page solves it with conjugate gradients. Line L6 under-relaxes the pressure, because the dropped neighbor sum makes too large. The values , and in the implementation are rules of thumb.
Example
Channel flow by hand. Take a channel of height 1 with walls at and , a constant force along , and cells in with . The exact solution is , , constant. The discrete equation is with the ghost value for no slip, and the same at the top. A second difference is exact on a parabola, so with satisfies the interior equations for any constant . The ghost condition gives . So the discrete solution overshoots the exact one by exactly at every face, second order in . With and the shift is for and for . SIMPLE reaches it from a zero start in 70, 155 and 568 iterations for (tolerance ). The count grows roughly with here, because three Gauss-Seidel sweeps per iteration spread viscous effects slowly across the channel.
Under-relaxation. A second test uses a channel on with cells, , and a force chosen so that a given smooth field, divergence free on the grid, is the exact discrete solution. SIMPLE recovers that field to from a zero start, with after every iteration. The number of iterations to a residual of :
| sweeps | iterations | ||
|---|---|---|---|
| 0.7 | 0.1 | 3 | 297 |
| 0.7 | 0.3 | 3 | 153 |
| 0.7 | 0.5 | 3 | 156 |
| 0.7 | 0.7 | 3 | 157 |
| 0.7 | 1.0 | 3 | diverges |
| 0.8 | 0.2 | 3 | 155 |
| 0.5 | 0.5 | 3 | 288 |
| 0.5 | 1.0 | 3 | 292 |
| 0.7 | 0.3 | 1 | 301 |
| 0.7 | 0.3 | 10 | 111 |
The runs with , and were compared with the given field and agree with it to . With and the residual is 24 after 5 iterations and after 25. These are measurements from the implementation on this page, not general results.
Correctness
The proof is in proofs/correctness.md. Summation by parts gives on the staggered grid, so the correction matrix is symmetric positive semidefinite, with the constants as its null space and the zero-sum vectors as its range. The right side always sums to zero, so the correction equation is solvable, and the corrected velocity has exactly, at every iteration and for every under-relaxation factor. The second theorem shows that the fixed points of SIMPLE are exactly the solutions of the discrete steady equations, for every , and number of sweeps, provided that Gauss-Seidel converges on the relaxed momentum system. So the approximation in the velocity correction affects only the path, not the answer. Convergence itself is not proved; SIMPLE has no general convergence theorem.
Proof: Every SIMPLE iteration conserves mass exactly, and the fixed points of SIMPLE are the discrete steady solutions for every choice of under-relaxationfull
Setting. The grid is the staggered grid of the main page: periodic in , and in either periodic or closed by no-slip walls, where on the wall faces. The unknown faces are all faces and the faces that are not on a wall. maps face values to cell centers, with wall values zero, and maps cell values to the unknown faces, with or . The discrete steady equations are
where row of reads , the central difference form of with coefficients computed from itself. Write and . One SIMPLE iteration from , with , and sweeps, is:
- compute and from (line L2);
- , where is one Gauss-Seidel sweep on the relaxed system (line L3);
- on each unknown face (line L4);
- solve with (line L5);
- and (lines L6 and L7).
Assume on every unknown face; this holds when , because contains and the wall ghost terms add nonnegative amounts when the cell Péclet number is at most 2. Then .
Lemma 1 (summation by parts). For every face vector with zero wall values and every cell vector , , the sum over the unknown faces. As matrices, .
Proof. Collect the terms of the left side by faces. A face between the cells (left) and (right) appears with in cell and in cell , so it contributes . The faces are the same with . Periodicity makes every face have two cells. A wall face has and contributes nothing on either side.
Lemma 2 (the correction matrix). is symmetric positive semidefinite. Its null space is the constant vectors, and its range is the vectors with zero sum.
Proof. Lemma 1 gives , which is symmetric. For any , , with equality exactly when on every unknown face, because every . means that is equal across every unknown face; the cells and the unknown faces form a connected graph, so is constant. For a symmetric matrix the range is the orthogonal complement of the null space, which is the zero-sum vectors.
The test file checks , the symmetry and the zero row sums in exact rational arithmetic, with random .
Lemma 3 (solvability). For every face vector with zero wall values, . So the equation has a solution, unique up to a constant.
Proof. Lemma 1 with gives . By Lemma 2 the right side is in the range of , and two solutions differ by an element of the null space.
Theorem 1 (mass conservation at every iteration). If line L5 solves exactly, then after every iteration, whatever , , , and are.
Proof. .
The code solves line L5 with conjugate gradients to a relative residual of ; conjugate gradients from a zero start on a consistent symmetric positive semidefinite system stay in the range of , so they converge as on a definite system. The test file checks after every iteration of a full run. Theorem 1 does not use : the velocity correction uses all of , and only the pressure is under-relaxed. This is what makes every SIMPLE iterate mass conserving, unlike the iterates of artificial compressibility.
Lemma 4 (fixed points of Gauss-Seidel). Let have a nonzero diagonal and a unique solution . One sweep maps to itself. If the iteration matrix of has no eigenvalue with (true when Gauss-Seidel converges, so ), then implies .
Proof. In a sweep from , row sets with all other entries still equal to , which gives because satisfies row . For the second claim, , so means , and is invertible by the assumption.
The assumption holds, for example, when the relaxed matrix is strictly diagonally dominant. That is the case when and every (cell Péclet number ), because then .
Theorem 2 (fixed points). Assume the hypothesis of Lemma 4 for the relaxed system at . Then is a fixed point of the SIMPLE iteration if and only if and . The set of fixed points does not depend on , or .
Proof. Suppose solves the steady equations. The relaxed system at reads , which satisfies, because . By Lemma 4, . Then , line L5 returns (conjugate gradients from zero with a zero right side), and .
Conversely, let be a fixed point. From and we get , so , and Theorem 1 gives . Now equals , so by Lemma 4 solves the relaxed system: . Subtract from both sides to get . No step used the values of , or .
So if SIMPLE converges, the limit solves the discrete steady incompressible equations, and the under-relaxation factors change only the path. The coefficients in the correction are an approximation (SIMPLE drops the neighbor terms of the velocity correction), but Theorem 2 shows that this approximation does not reach the converged answer. On the staggered grid the converged answer also does not depend on through any interpolation; on a collocated grid with Rhie-Chow interpolation it can. Line L8 checks the residual of the full discrete equations (the momentum equations, evaluated by separate code, and ) directly, so a return from line L9 certifies tol.
Termination. The loop of line L1 runs at most maxit times. Each iteration does a fixed number of Gauss-Seidel sweeps and one conjugate gradient solve, which stops after at most its own iteration limit. So the procedure always ends. It ends at line L9 with a certified residual, or after maxit iterations without one.
What is not proved. Theorems 1 and 2 say nothing about convergence. SIMPLE has no general convergence theorem for the nonlinear equations, and the right under-relaxation factors are rules of thumb. The tests show a case where with diverges and converges. Theorem 2 also does not say that the discrete steady equations have a unique solution; on a fully periodic grid they do not fix the mean velocity, and the tests find two different converged states from two starts.
Complexity
One iteration assembles the coefficients and does Gauss-Seidel sweeps in operations, and solves the correction equation with conjugate gradient iterations of each. With outer iterations the total is for constant , and the memory is . Both and grow with the grid: grows like the square root of the condition number of the Poisson matrix, about on a square grid, and grew like in the channel example. A multigrid solver for the correction equation makes independent of the grid. Production codes also stop the inner solves early, since only the converged outer iterate matters.
Properties
- Every iterate conserves mass on the discrete grid (Theorem 1 of the proof); only the momentum residual is not yet zero.
- The converged answer does not depend on , or the inner solvers.
- The momentum equations are implicit, so SIMPLE has no time step limit of the CFL kind; under-relaxation plays the role of a pseudo time step.
- The pressure correction equation is the expensive part; it is a Poisson problem with variable coefficients .
- On the staggered grid there is no checkerboard pressure mode. On a collocated grid SIMPLE needs Rhie-Chow interpolation.
Variants and improvements
- SIMPLER (Patankar 1980, Section 6.8) solves a separate pressure equation from the momentum coefficients and uses only to correct the velocity, so the pressure needs no under-relaxation.
- SIMPLEC keeps part of the neighbor sum in the velocity correction, with in place of , which allows near 1.
- PISO (Issa 1986) applies two or more corrections per time step for unsteady flow, without outer iterations.
- Coupled solvers solve the momentum and continuity equations together with a block preconditioner, at a higher cost per iteration and with far fewer iterations.
- Collocated grids store all unknowns at cell centers and use Rhie-Chow interpolation for the face velocities in the continuity equation.
When to use it
Use SIMPLE or one of its variants for steady incompressible flow with implicit momentum equations, especially in finite volume codes on unstructured or body-fitted grids, where it is widely used. For unsteady flow with small time steps, PISO or a projection method avoids the outer iterations. For a simple explicit steady solver without a Poisson solve, artificial compressibility is an alternative.
Pitfalls
- Too much pressure correction diverges. The dropped neighbor sum makes too large, and with diverged in the example. A common rule of thumb is for SIMPLE.
- Too little under-relaxation is slow. Small or converges, but the count roughly doubles from to in the example.
- Stopping on the change between iterates. Heavy under-relaxation makes successive iterates close long before they converge. Stop on the residual of the full discrete equations, as line L8 does.
- Periodic boxes leave the mean velocity free. With no walls, the steady equations do not fix the mean flow. The tests start a forced Taylor-Green vortex with two different mean velocities and get two different converged states, both with a residual below . Prescribe the mean velocity, or a mass flow rate in a periodic channel.
- The pressure is fixed only up to a constant when no boundary prescribes it. The correction equation is singular; keep its right side at zero sum and fix the constant afterwards.
- Central advection at cell Péclet numbers above 2 loses diagonal dominance, and Gauss-Seidel on the momentum equations may stop converging. Production codes use upwind or deferred-correction schemes for advection.
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
# 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
simple_algorithm.py 201 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simple-algorithm/. The authors are listed in prov/61PTZG.jsonl.
"""SIMPLE (Patankar and Spalding 1972) for steady 2D incompressible flow.
Steady equations: (u . grad) u = -grad p + nu Laplacian u + f, div u = 0, with p the
pressure divided by the density. Staggered (MAC) grid with nx by ny cells on
[0, Lx) x [0, Ly], periodic in x. In y the grid is periodic, or it has no-slip
walls at y = 0 and y = Ly.
p[i + nx j] cell center ((i + 1/2) dx, (j + 1/2) dy)
u[i + nx j] left face (i dx, (j + 1/2) dy)
v[i + nx j] bottom face ((i + 1/2) dx, j dy); with walls j runs to ny and the
rows j = 0 and j = ny are the walls, where v = 0.
The momentum equations are finite differences with central advection, linearized
by Picard iteration (the advecting velocity is the current iterate). The
under-relaxation factors 0.7 (velocity) and 0.3 (pressure) and the number of
Gauss-Seidel sweeps are rules of thumb, not results.
"""
import scisparse
class Grid:
def __init__(self, nx, ny, lx, ly, walls=False):
self.nx, self.ny, self.lx, self.ly, self.walls = nx, ny, lx, ly, walls
self.dx, self.dy = lx / nx, ly / ny
self.nv = nx * (ny + 1) if walls else nx * ny
def ip(self, i, j):
return i % self.nx + self.nx * (j % self.ny)
def iv(self, i, j):
return i % self.nx + self.nx * (j if self.walls else j % self.ny)
def wall_v(self, k):
return self.walls and (k < self.nx or k >= self.nx * self.ny)
def sample(self, fu, fv):
u = [fu((k % self.nx) * self.dx, (k // self.nx + 0.5) * self.dy) for k in range(self.nx * self.ny)]
v = [0.0 if self.wall_v(k) else fv((k % self.nx + 0.5) * self.dx, (k // self.nx) * self.dy) for k in range(self.nv)]
return u, v
def sample_p(self, fp):
return [fp((k % self.nx + 0.5) * self.dx, (k // self.nx + 0.5) * self.dy) for k in range(self.nx * self.ny)]
def divergence(g, u, v):
out = []
for j in range(g.ny):
for i in range(g.nx):
out.append((u[g.ip(i + 1, j)] - u[g.ip(i, j)]) / g.dx + (v[g.iv(i, j + 1)] - v[g.iv(i, j)]) / g.dy)
return out
def u_coefficients(g, u, v, nu):
"""For each u face k: (aP, {neighbor: a_nb}) of aP u_k - sum a_nb u_nb = rhs, central
advection with the current velocity. A no-slip ghost (-u_P) moves a_N or a_S into aP."""
dx, dy = g.dx, g.dy
rows = []
for j in range(g.ny):
for i in range(g.nx):
k = g.ip(i, j)
ub = u[k]
vb = 0.25 * (v[g.iv(i - 1, j)] + v[g.iv(i, j)] + v[g.iv(i - 1, j + 1)] + v[g.iv(i, j + 1)])
ap = 2 * nu / dx**2 + 2 * nu / dy**2
nb = {}
for m, a in ((g.ip(i + 1, j), nu / dx**2 - ub / (2 * dx)), (g.ip(i - 1, j), nu / dx**2 + ub / (2 * dx))):
nb[m] = nb.get(m, 0.0) + a
for jj, a in ((j + 1, nu / dy**2 - vb / (2 * dy)), (j - 1, nu / dy**2 + vb / (2 * dy))):
if g.walls and not 0 <= jj < g.ny:
ap += a # ghost value -u_P
else:
m = g.ip(i, jj)
nb[m] = nb.get(m, 0.0) + a
rows.append((ap, nb))
return rows
def v_coefficients(g, u, v, nu):
"""As u_coefficients for the v faces; wall faces get the row 1 * v = 0."""
dx, dy = g.dx, g.dy
rows = []
for k in range(g.nv):
if g.wall_v(k):
rows.append((1.0, {}))
continue
i, j = k % g.nx, k // g.nx
vb = v[k]
ub = 0.25 * (u[g.ip(i, j - 1)] + u[g.ip(i + 1, j - 1)] + u[g.ip(i, j)] + u[g.ip(i + 1, j)])
ap = 2 * nu / dx**2 + 2 * nu / dy**2
nb = {}
for m, a in ((g.iv(i + 1, j), nu / dx**2 - ub / (2 * dx)), (g.iv(i - 1, j), nu / dx**2 + ub / (2 * dx)),
(g.iv(i, j + 1), nu / dy**2 - vb / (2 * dy)), (g.iv(i, j - 1), nu / dy**2 + vb / (2 * dy))):
if not g.wall_v(m): # a wall neighbor has v = 0 and drops out
nb[m] = nb.get(m, 0.0) + a
rows.append((ap, nb))
return rows
def pressure_gradient(g, p):
gx = [(p[g.ip(i, j)] - p[g.ip(i - 1, j)]) / g.dx for j in range(g.ny) for i in range(g.nx)]
gy = [0 if g.wall_v(k) else (p[g.ip(k % g.nx, k // g.nx)] - p[g.ip(k % g.nx, k // g.nx - 1)]) / g.dy for k in range(g.nv)]
return gx, gy
def correction_matrix(g, du, dv):
"""B = -D diag(d) G: symmetric positive semidefinite, constants in its null space.
A wall face has no correction, which gives the Neumann condition for p'."""
B = []
for j in range(g.ny):
for i in range(g.nx):
row = {}
k = g.ip(i, j)
faces = ((g.ip(i + 1, j), du[g.ip(i + 1, j)], g.dx), (g.ip(i - 1, j), du[k], g.dx))
vfaces = ((j + 1, g.iv(i, j + 1)), (j - 1, g.iv(i, j)))
for m, d, h in faces:
row[k] = row.get(k, 0) + d / h**2
row[m] = row.get(m, 0) - d / h**2
for jj, f in vfaces:
if g.wall_v(f):
continue
m = g.ip(i, jj)
row[k] = row.get(k, 0) + dv[f] / g.dy**2
row[m] = row.get(m, 0) - dv[f] / g.dy**2
B.append({m: a for m, a in row.items() if a != 0})
return B
def _relaxed_system(rows, x, rhs, alpha):
"""Sparse matrix and right side of (aP / alpha) x - sum a_nb x_nb = rhs + (1 - alpha) aP / alpha x_old."""
A, b = [], []
for k, (ap, nb) in enumerate(rows):
row = {m: -a for m, a in nb.items()}
row[k] = row.get(k, 0.0) + ap / alpha
A.append(row)
b.append(rhs[k] + (1 - alpha) * ap / alpha * x[k])
return A, b
def simple(g, u, v, p, nu, fu, fv, alpha_u=0.7, alpha_p=0.3, sweeps=3, tol=1e-10, maxit=20000, check=None):
"""Outer SIMPLE iterations until the steady residual and the divergence are below tol.
Returns (u, v, p, iterations). check(u, v) is called after each correction (for tests)."""
for it in range(1, maxit + 1): # @line L1
ru, rv = u_coefficients(g, u, v, nu), v_coefficients(g, u, v, nu) # @line L2
gx, gy = pressure_gradient(g, p)
bu = [fu[k] - gx[k] for k in range(len(u))]
bv = [0.0 if g.wall_v(k) else fv[k] - gy[k] for k in range(g.nv)]
Au, cu = _relaxed_system(ru, u, bu, alpha_u)
Av, cv = _relaxed_system(rv, v, bv, alpha_u)
us = scisparse.gauss_seidel(Au, cu, sweeps, x0=u) # @line L3
vs = scisparse.gauss_seidel(Av, cv, sweeps, x0=v) # @line L3
du = [alpha_u / ap for ap, _ in ru] # @line L4
dv = [0.0 if g.wall_v(k) else alpha_u / rv[k][0] for k in range(g.nv)] # @line L4
rhs = [-x for x in divergence(g, us, vs)]
mean = sum(rhs) / len(rhs)
pc, _ = scisparse.cg(correction_matrix(g, du, dv), [x - mean for x in rhs], tol=1e-12) # @line L5
p = [p[k] + alpha_p * pc[k] for k in range(len(p))] # @line L6
cx, cy = pressure_gradient(g, pc)
u = [us[k] - du[k] * cx[k] for k in range(len(u))] # @line L7
v = [vs[k] - dv[k] * cy[k] for k in range(g.nv)] # @line L7
if check:
check(u, v)
r = steady_residual(g, u, v, p, nu, fu, fv)
if max(abs(x) for x in r) <= tol: # @line L8
return u, v, p, it # @line L9
return u, v, p, maxit
def steady_residual(g, u, v, p, nu, fu, fv):
"""Residuals of the discrete steady equations, written out directly (independent of the
coefficient assembly above): -(u . grad) u + nu Laplacian u - G p + f on every unknown
face, then D u on every cell."""
dx, dy = g.dx, g.dy
def un(i, j, k):
if g.walls and not 0 <= j < g.ny:
return -u[k] # no-slip ghost
return u[g.ip(i, j)]
out = []
gx, gy = pressure_gradient(g, p)
for j in range(g.ny):
for i in range(g.nx):
k = g.ip(i, j)
n, s = un(i, j + 1, k), un(i, j - 1, k)
e, w = u[g.ip(i + 1, j)], u[g.ip(i - 1, j)]
vb = 0.25 * (v[g.iv(i - 1, j)] + v[g.iv(i, j)] + v[g.iv(i - 1, j + 1)] + v[g.iv(i, j + 1)])
adv = u[k] * (e - w) / (2 * dx) + vb * (n - s) / (2 * dy)
lap = (e - 2 * u[k] + w) / dx**2 + (n - 2 * u[k] + s) / dy**2
out.append(nu * lap - adv - gx[k] + fu[k])
for k in range(g.nv):
if g.wall_v(k):
continue
i, j = k % g.nx, k // g.nx
e, w = v[g.iv(i + 1, j)], v[g.iv(i - 1, j)]
n, s = v[g.iv(i, j + 1)], v[g.iv(i, j - 1)]
ub = 0.25 * (u[g.ip(i, j - 1)] + u[g.ip(i + 1, j - 1)] + u[g.ip(i, j)] + u[g.ip(i + 1, j)])
adv = ub * (e - w) / (2 * dx) + v[k] * (n - s) / (2 * dy)
lap = (e - 2 * v[k] + w) / dx**2 + (n - 2 * v[k] + s) / dy**2
out.append(nu * lap - adv - gy[k] + fv[k])
return out + divergence(g, u, v)
test_simple_algorithm.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simple-algorithm/. The authors are listed in prov/61PTZG.jsonl.
import math
import random
from fractions import Fraction as Fr
import scisparse as sp
from simple_algorithm import Grid, correction_matrix, divergence, pressure_gradient, simple, steady_residual
NU = 0.5
def _manufactured(nx=8, ny=8, amp=0.5):
"""Channel, periodic in x, no-slip walls at y = 0 and y = 1. The velocity comes from a
discrete streamfunction at the cell corners, so D u = 0 exactly. The force is chosen so
that this sampled field and p are an exact solution of the discrete steady equations."""
g = Grid(nx, ny, 2.0, 1.0, walls=True)
psi = lambda x, y: amp * math.sin(math.pi * x) * 16 * (y * (1 - y)) ** 2
u = [(psi(i * g.dx, (j + 1) * g.dy) - psi(i * g.dx, j * g.dy)) / g.dy for j in range(ny) for i in range(nx)]
v = [0.0 if g.wall_v(k) else -(psi((k % nx + 1) * g.dx, (k // nx) * g.dy) - psi((k % nx) * g.dx, (k // nx) * g.dy)) / g.dx
for k in range(g.nv)]
p = g.sample_p(lambda x, y: 0.2 * math.cos(math.pi * x) * (y - 0.5))
n = nx * ny
r = steady_residual(g, u, v, p, NU, [0.0] * n, [0.0] * g.nv)
fu = [-x for x in r[:n]]
fv, pos = [], n
for k in range(g.nv):
if g.wall_v(k):
fv.append(0.0)
else:
fv.append(-r[pos])
pos += 1
return g, u, v, p, fu, fv
def _gap(g, u, v, p, ue, ve, pe):
n = len(u)
eu = max(max(abs(u[k] - ue[k]) for k in range(n)), max(abs(v[k] - ve[k]) for k in range(g.nv)))
pm, qm = sum(p) / n, sum(pe) / n
return eu, max(abs(p[k] - pm - pe[k] + qm) for k in range(n))
def test_correction_matrix_is_minus_div_d_grad_exactly():
rng = random.Random(3)
g = Grid(3, 3, Fr(3), Fr(3, 2), walls=True)
du = [Fr(rng.randint(1, 9), 10) for _ in range(9)]
dv = [0 if g.wall_v(k) else Fr(rng.randint(1, 9), 10) for k in range(g.nv)]
B = correction_matrix(g, du, dv)
for m in range(9):
e = [Fr(int(k == m)) for k in range(9)]
gx, gy = pressure_gradient(g, e)
col = [-x for x in divergence(g, [du[k] * gx[k] for k in range(9)], [dv[k] * gy[k] for k in range(g.nv)])]
assert col == [B[k].get(m, 0) for k in range(9)]
assert all(B[k].get(m, 0) == B[m].get(k, 0) for k in range(9) for m in range(9))
assert all(sum(row.values()) == 0 for row in B) # constants are in the null space
def test_poiseuille_error_is_exactly_g_dy2_over_8_nu():
# The discrete solution is the exact parabola plus G dy^2 / (8 nu): second order.
G = 1.0
for ny in (4, 8):
g = Grid(2, ny, 1.0, 1.0, walls=True)
n = 2 * ny
u, v, p, it = simple(g, [0.0] * n, [0.0] * g.nv, [0.0] * n, NU, [G] * n, [0.0] * g.nv, tol=1e-11)
exact, _ = g.sample(lambda x, y: G / (2 * NU) * y * (1 - y), lambda x, y: 0.0)
shift = G * g.dy**2 / (8 * NU)
assert it < 20000
assert max(abs(u[k] - exact[k] - shift) for k in range(n)) < 1e-9
assert max(abs(x) for x in v) < 1e-12
def test_converges_to_the_discrete_solution_and_conserves_mass_every_iteration():
g, ue, ve, pe, fu, fv = _manufactured()
n = len(ue)
worst = [0.0]
def check(u, v):
worst[0] = max(worst[0], max(abs(x) for x in divergence(g, u, v)))
u, v, p, it = simple(g, [0.0] * n, [0.0] * g.nv, [0.0] * n, NU, fu, fv, tol=1e-10, check=check)
eu, ep = _gap(g, u, v, p, ue, ve, pe)
assert it < 400 # measured: 153
assert eu < 1e-9 and ep < 1e-9
assert worst[0] < 1e-10 # D u = 0 after every correction, not only at the end
def test_fixed_point_does_not_depend_on_under_relaxation():
g, ue, ve, pe, fu, fv = _manufactured()
n = len(ue)
u, v, p, it = simple(g, [0.0] * n, [0.0] * g.nv, [0.0] * n, NU, fu, fv, alpha_u=0.8, alpha_p=0.2, sweeps=2, tol=1e-10)
eu, ep = _gap(g, u, v, p, ue, ve, pe)
assert it < 400
assert eu < 1e-9 and ep < 1e-9
def test_full_pressure_correction_diverges_here():
# Measured on this problem: alpha_u = 0.7 with alpha_p = 1 blows up (rule of thumb:
# alpha_p near 1 - alpha_u), alpha_p = 0.3 converges.
g, ue, ve, pe, fu, fv = _manufactured()
n = len(ue)
for alpha_p, grows in ((1.0, True), (0.3, False)):
u, v, p, _ = simple(g, [0.0] * n, [0.0] * g.nv, [0.0] * n, NU, fu, fv, alpha_p=alpha_p, maxit=15)
r = max(abs(x) for x in steady_residual(g, u, v, p, NU, fu, fv))
assert (r > 10) == grows
def test_periodic_box_leaves_the_mean_velocity_free():
# Fully periodic: the steady equations do not fix the mean velocity. Two starts give two
# different converged states, both with a residual below 1e-10.
n = 8
L = 2 * math.pi
g = Grid(n, n, L, L)
U = lambda x, y: math.sin(x) * math.cos(y)
V = lambda x, y: -math.cos(x) * math.sin(y)
fu, fv = g.sample(lambda x, y: 2 * NU * U(x, y), lambda x, y: 2 * NU * V(x, y))
eu, ev = g.sample(U, V)
ep = g.sample_p(lambda x, y: 0.25 * (math.cos(2 * x) + math.cos(2 * y)))
means = []
for shift in (0.0, 0.1):
u, v, p, it = simple(g, [x + shift for x in eu], list(ev), list(ep), NU, fu, fv, tol=1e-10, maxit=1000)
assert it < 1000
assert max(abs(x) for x in steady_residual(g, u, v, p, NU, fu, fv)) < 1e-10
means.append(sum(u) / len(u))
assert abs(means[1] - means[0]) > 0.05
History
Patankar and Spalding (1972) introduced the pressure correction procedure in a paper on three-dimensional parabolic flows. Patankar's 1980 textbook gave the method on the staggered grid in its now standard form, with the discussion of the pressure correction equation, its boundary conditions and the relative nature of the pressure, and introduced SIMPLER. Collocated versions became possible with the interpolation of Rhie and Chow (1983), and Issa (1986) derived PISO for unsteady flow.
References
- S. V. Patankar and D. B. Spalding, A calculation procedure for heat, mass and momentum transfer in three-dimensional parabolic flows, International Journal of Heat and Mass Transfer 15(10) (1972) 1787-1806, the pressure correction procedure
- Suhas V. Patankar, Numerical Heat Transfer and Fluid Flow, Hemisphere and McGraw-Hill, 1980, Sections 6.3 to 6.8 (staggered grid, momentum equations, pressure and velocity corrections, the pressure correction equation, SIMPLE, SIMPLER)
- Joel H. Ferziger, Milovan Peric and Robert L. Street, Computational Methods for Fluid Dynamics, fourth edition, Springer, 2020, Chapter 7 (pressure correction methods for steady flow)
- R. I. Issa, Solution of the implicitly discretised fluid flow equations by operator-splitting, Journal of Computational Physics 62(1) (1986) 40-65, PISO, the non-iterative relative of SIMPLE for unsteady flow
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 61PTZG Edit this page History Report an error Markdown