Algorithmcore
Artificial compressibility method
Also called pseudo-compressibility method.
Replaces incompressibility by a pressure equation with an artificial sound speed and marches in pseudo-time to a divergence-free steady state.
- Solves
- Navier-Stokes equations
- Time
- Θ(I M) worst
- Space
- Θ(M) extra
- Where
- I = the number of pseudo-time iterations; M = the number of grid cells
- Model
- Real RAM
- Properties
- deterministicdivergence free at convergenceexplicitnot needs poisson solvesteady state
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alexandre J. Chorin, 1967
The artificial compressibility method finds steady incompressible flow without solving a pressure Poisson equation. It adds a fake time derivative of the pressure to the continuity equation, , with an artificial sound speed . The resulting system behaves like a slightly compressible fluid: pressure waves carry the information that the constraint is violated, and viscosity damps them. The method marches this system in pseudo time with simple explicit steps until nothing changes. At that steady state the time derivatives are zero, so the velocity is divergence free and the momentum equation holds, for any choice of . Each step is cheap and local, which made the method attractive for early computers and later for compressible-flow codes reused for incompressible flow. Intermediate pseudo-time states have no physical meaning.
In plain words
Real water cannot be squeezed, and that rule is hard to enforce directly, because every part of the flow must agree at once. This method relaxes the rule. It pretends the water can be squeezed a little, so that pushing water into a region raises its pressure, and the higher pressure then pushes the water out again. These pressure pulses move like sound and fade because of friction. The method lets the flow settle step by step, each step looking only at neighbors. When the flow stops changing, every region has exactly as much water leaving as entering, so the pretend squeezing is gone and the answer is the true steady flow. How fast it settles depends on the chosen fake sound speed.
The problem
Find a steady solution of the incompressible Navier-Stokes equations
with the pressure divided by the density and the kinematic viscosity. Artificial compressibility replaces it by the pseudo-time system
and looks for its steady state. This page discretizes it on the periodic MAC grid with cells: central differences for advection, the 5-point Laplacian for viscosity, the divergence at the cell centers and the gradient at the faces. The cost is counted in real arithmetic operations and in pseudo-time iterations .
The algorithm
ARTIFICIAL-COMPRESSIBILITY(u, v, p, Δτ, c, ν, f, tol)- 1
repeat - 2
R ← -(u·∇)u + ν Δ_h u - G p + f ▷ momentum residual at the faces - 3
(u, v) ← (u, v) + Δτ R - 4
p ← p - Δτ c² D(u, v) ▷ uses the new velocity - 5
until max|R| ≤ tol and max|D(u, v)| ≤ tol - 6
return (u, v, p)
Line L4 uses the velocity just computed in line L3. This makes the pressure-velocity part of the iteration a symplectic Euler step for the pseudo-acoustic waves, which allows a larger step than a fully explicit update. The step is chosen from the sharp condition proved on this page for the linear Stokes problem, with , times a safety factor , and from the rule of thumb for central advection. The safety factor and are choices.
For time-accurate flow, dual time stepping puts the whole pseudo-time iteration inside each physical time step: the physical time derivative becomes a source term, and the iteration converges to an implicit time step.
Example
One step by hand. Take a periodic row of 4 cells with , , zero start, force on the faces, and . Line L3 gives . The divergence is : face 0 is the left face of cell 0 and the right face of cell 3, and there carries fluid from cell 3 into cell 0. Line L4 gives : pressure rises where fluid gathers (cell 0) and falls where it leaves (cell 3). In the next step this pressure difference pushes back on face 0. The test file checks these numbers in exact rational arithmetic.
Forced steady Taylor-Green vortex. On the field , , is a steady solution with the force , which balances viscous decay. With , , a zero start and a stopping tolerance of :
| cells | iterations | velocity error | order | pressure error | |
|---|---|---|---|---|---|
| 0.198 | 137 | 4.899e-2 | 1.993e-2 | ||
| 0.0977 | 296 | 2.237e-2 | 1.93 | 1.168e-2 | |
| 0.0576 | 514 | 1.270e-2 | 1.97 | 7.189e-3 |
The velocity converges at second order; the pressure error ratios are still below that on these coarse grids. On the grid the number of iterations to reach depends on : 1151 for , 313 for , 151 for , 160 for , 183 for and 290 for , and the converged fields agree to . These are measurements from the implementation on this page. The best here is of the order of the flow speed, in line with the usual rule of thumb.
Correctness
The proof is in proofs/correctness.md. A fixed point of the iteration has zero momentum residual and zero discrete divergence, and conversely, so the limit, when the iteration converges, solves the discrete steady incompressible equations for every and every ; the stopping test checks both residuals directly. For the linear Stokes problem on the periodic MAC grid, the proof splits the error into a divergence-free part, which decays by viscosity alone, and gradient modes, each coupled to one pressure mode by a 2 by 2 matrix with determinant and trace . The Jury conditions give convergence exactly when for every eigenvalue of . The tests confirm that the bound is sharp on the checkerboard mode. Convergence for the nonlinear problem is not guaranteed; it is observed here.
Proof: The fixed points of artificial compressibility are the discrete steady incompressible solutions, and the linear Stokes iteration converges under a sharp step conditionfull
Setting. The grid is the periodic MAC grid of the main page with cells. is the divergence at the cell centers, the gradient at the faces, and , the periodic 5-point matrix, which is symmetric positive semidefinite with the constants as its null space (summation by parts gives ; see the proof on the Chorin projection method page). is the momentum residual of line L2, with the central advection term and the 5-point Laplacian on each component. One iteration with step and sound speed is
Theorem 1 (fixed points). is a fixed point of the iteration if and only if and , that is, if and only if it solves the discrete steady incompressible equations. The set of fixed points does not depend on or on .
Proof. If and , then and . Conversely, a fixed point has , so , and then and , so , because . Neither condition contains or .
So if the iteration converges, the limit is a steady solution of the incompressible discrete equations, whatever was used. The stopping test of line L5 checks the two conditions of Theorem 1 directly: when it stops, tol and tol. Theorem 1 does not say that the iteration converges; for the nonlinear problem that is not guaranteed.
Theorem 2 (linear Stokes iteration). Drop the advection term (). Let , which bounds every eigenvalue of and of . If
then the iteration converges, from any start, to a solution of , , provided has zero mean on each face set and the start has the same mean velocity as the solution sought. If the condition fails for an eigenvalue that has, the iteration diverges for some start.
Proof. The iteration is affine, so the errors with respect to a solution obey the same update with . On the uniform periodic grid, , and are shift invariant difference operators, so they commute in the sense and , with on cell fields. Split the error orthogonally (discrete Helmholtz-Hodge) as with .
The divergence-free part. , so maps divergence-free fields to divergence-free fields, and the update gives , independent of , and the pressure update does not see . The eigenvalues of on this space lie in , so the factor has modulus below 1 when , which the condition implies. The eigenvalue belongs to the constant fields, the mean velocity, which never changes; this is why the start must have the right mean.
The gradient part. Expand and in eigenvectors of with , (the constant eigenvector has and does not affect the velocity). Write (plus divergence-free terms) and . Then and , so
The matrix of this map is with . Its determinant is and its trace is . A real matrix has both eigenvalues inside the unit disk exactly when and (the Schur-Cohn or Jury conditions). Here they read and , that is and . Since always, and implies , the condition of the theorem is exactly the condition that every mode with decays. If for some eigenvalue that has, that mode has an eigenvalue of modulus at least 1 and does not decay; with it grows. Both functions of are increasing, so the condition at covers all .
For even and the checkerboard is an eigenvector of with , so the bound is sharp. The tests check it: a small checkerboard pressure decays with times the limiting step and grows with times it. The implementation solves for and multiplies by a safety factor , which is a choice. With the advection term the step must also satisfy the rule of thumb for central differences with forward Euler; that part is not proved here.
Termination. Each iteration costs operations, with no linear solve. The loop ends when the two residuals of Theorem 1 are below the tolerance, or after a fixed maximum number of iterations, so it always ends. Under the condition of Theorem 2 for the Stokes problem, the error decays geometrically, so the tolerance is reached after iterations times a factor that depends on the spectral radius; for the nonlinear problem the iteration count is a measurement.
Complexity
One iteration costs operations and memory, with no linear solve. The number of iterations is the cost driver. With from the viscous part of the step limit, the slowest smooth modes decay at a rate of order per unit pseudo time, so and the total cost on a square grid is . The measured counts above grow by about 2.2 and 1.7 from grid to grid, close to the growth. Implicit pseudo-time stepping, local time steps, preconditioning and multigrid reduce the count in practice.
Properties
- The steady state does not depend on or ; only the path to it does.
- No Poisson equation and no global solve: every step is local, so the method is easy to parallelize.
- The pseudo-time system is hyperbolic-parabolic, so methods for compressible flow (upwind fluxes, Riemann solvers, implicit schemes) can be reused.
- Intermediate iterates are not divergence free and have no physical meaning.
- The steady discrete equations are the same as those of the MAC method, so the result has the same second order spatial accuracy.
Variants and improvements
- Dual time stepping for unsteady flow: a pseudo-time iteration inside each physical step.
- Implicit and preconditioned pseudo time: implicit schemes and low-Mach preconditioning, which make the pseudo-acoustic and convective speeds comparable, cut the iteration count.
- Upwind and characteristic schemes for the pseudo-compressible system, used in collocated finite volume codes.
- Projection methods solve a Poisson equation instead and enforce at every step; Chorin proposed them a year later for time-accurate flow.
- Weakly compressible methods such as lattice Boltzmann and weakly compressible SPH also replace incompressibility by a stiff equation of state, but with a physical time and a small Mach number instead of a pseudo-time iteration.
When to use it
Use artificial compressibility for steady incompressible flow when a compressible-flow code or an explicit, local, easily parallel scheme is available and a Poisson solver is not. With dual time stepping it also serves unsteady flow. If a fast Poisson solver is at hand and time accuracy matters, the projection method is usually cheaper. For steady flow with implicit momentum equations, SIMPLE is the common alternative.
Pitfalls
- The artificial sound speed is a choice. Too small a makes the pressure respond slowly and the iteration crawl; too large a makes the system stiff and forces a small . A rule of thumb takes of the order of the flow speed; it is not a guarantee.
- Separate step limits are not enough. The viscous and acoustic limits interact: the condition is , not two independent conditions. On the grid above, a step at 0.8 of each separate limit diverges for .
- Stopping on the change between iterates instead of the residuals can stop early when the iteration is slow. Check and the momentum residual.
- Unsteady flow without dual time stepping. Plain pseudo time is not physical time; transients computed with it are wrong.
- Periodic and closed domains fix the pressure only up to a constant and the mean velocity only by the start; give the start the right mean flow.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/artificial-compressibility-method/. The authors are listed in prov/FZZC89.jsonl.
"""Chorin's artificial compressibility method for steady 2D incompressible flow.
The steady equations (u . grad) u = -grad p + nu Laplacian u + f, div u = 0
(p is the pressure divided by the density) are replaced by the pseudo-time system
u_tau + (u . grad) u = -grad p + nu Laplacian u + f
p_tau + c^2 div u = 0
with an artificial sound speed c. Its steady state, if it is reached, solves the
steady incompressible equations, for every c > 0. The grid is the periodic MAC
grid on [0, Lx) x [0, Ly): p[k] at the cell center, u[k] on the left face, v[k]
on the bottom face of cell k = i + nx * j. No Poisson equation is solved.
"""
import math
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)]
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):
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):
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 residual(g, u, v, p, nu, fu, fv):
"""Momentum residual -(u . grad) u + nu Laplacian u - G p + f at the faces."""
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)):
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 - (p[k] - p[w[k]]) / dx + fu[k])
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 - (p[k] - p[s[k]]) / dy + fv[k])
return ru, rv
def stable_step(g, nu, c, umax, safety=0.8):
"""A pseudo-time step. Without advection (the Stokes problem) the iteration converges
exactly when dtau^2 c^2 mu + 2 dtau nu mu < 4 for every eigenvalue mu of -D G (proved on
the page); mu_max = 4/dx^2 + 4/dy^2. Central advection adds the rule of thumb
dtau <= 2 nu / umax^2. The safety factor is a choice."""
mu = 4 / g.dx**2 + 4 / g.dy**2
limits = [(-nu * mu + math.sqrt((nu * mu) ** 2 + 4 * c * c * mu)) / (c * c * mu)]
if umax > 0:
limits.append(2 * nu / umax**2)
return safety * min(limits)
def artificial_compressibility(g, u, v, p, dtau, c, nu, fu, fv, tol, maxit=100000):
"""Iterate in pseudo time until the momentum residual and the divergence are below tol.
Returns (u, v, p, iterations)."""
c2 = c * c
for it in range(1, maxit + 1): # @line L1
ru, rv = residual(g, u, v, p, nu, fu, fv) # @line L2
u = [u[k] + dtau * ru[k] for k in range(len(u))] # @line L3
v = [v[k] + dtau * rv[k] for k in range(len(v))] # @line L3
d = divergence(g, u, v)
p = [p[k] - dtau * c2 * d[k] for k in range(len(p))] # @line L4
if max(max(abs(x) for x in ru), max(abs(x) for x in rv)) <= tol and max(abs(x) for x in d) <= tol: # @line L5
return u, v, p, it # @line L6
return u, v, p, maxit
# ---------------------------------------------------------------- the forced steady Taylor-Green vortex
def taylor_green_steady(g, nu):
"""u = -cos x sin y, v = sin x cos y, p = -(cos 2x + cos 2y) / 4 is a steady solution
with the force f = 2 nu (u, v), which balances the viscous decay."""
u = [-math.cos(x) * math.sin(y) for x, y in g.points("u")]
v = [math.sin(x) * math.cos(y) for x, y in g.points("v")]
p = [-(math.cos(2 * x) + math.cos(2 * y)) / 4 for x, y in g.points("p")]
return u, v, p, [2 * nu * t for t in u], [2 * nu * t for t in v]
test_artificial_compressibility_method.py 76 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/artificial-compressibility-method/. The authors are listed in prov/FZZC89.jsonl.
import math
from fractions import Fraction as Fr
from artificial_compressibility_method import (
Grid,
artificial_compressibility,
divergence,
residual,
stable_step,
taylor_green_steady,
)
NU = 0.5 # viscosity of the forced steady Taylor-Green tests
def _solve(n, c, tol=1e-11):
g = Grid(n, n)
u, v, p, fu, fv = taylor_green_steady(g, NU)
zero = [0.0] * (n * n)
uu, vv, pp, it = artificial_compressibility(g, zero, zero, zero, stable_step(g, NU, c, 1.0), c, NU, fu, fv, tol)
return g, (u, v, p, fu, fv), (uu, vv, pp), it
def test_one_step_by_hand():
# 4 by 1 periodic cells, dx = dy = 1, nu = 0, force (1, 0, 0, 0) on the u faces, dtau = 1/2, c = 1
g = Grid(4, 1, Fr(4), Fr(1))
z = [Fr(0)] * 4
u, v, p, it = artificial_compressibility(g, z, z, z, Fr(1, 2), 1, 0, [Fr(1), 0, 0, 0], z, 0, maxit=1)
assert it == 1
assert u == [Fr(1, 2), 0, 0, 0] and v == z
assert divergence(g, u, v) == [Fr(-1, 2), 0, 0, Fr(1, 2)]
assert p == [Fr(1, 4), 0, 0, Fr(-1, 4)]
def test_converged_state_is_divergence_free_and_steady():
g, (u, v, p, fu, fv), (uu, vv, pp), it = _solve(8, 1.0)
assert it < 1000 # measured: 151 iterations
assert max(abs(x) for x in divergence(g, uu, vv)) < 1e-10
ru, rv = residual(g, uu, vv, pp, NU, fu, fv)
assert max(abs(x) for x in ru + rv) < 1e-10
def test_steady_state_does_not_depend_on_the_sound_speed():
_, _, (u1, v1, p1), it1 = _solve(8, 1.0)
_, _, (u2, v2, p2), it2 = _solve(8, 0.5)
assert it2 > it1 # measured: 313 against 151 iterations
m1, m2 = sum(p1) / 64, sum(p2) / 64
assert max(abs(u1[k] - u2[k]) + abs(v1[k] - v2[k]) + abs(p1[k] - m1 - p2[k] + m2) for k in range(64)) < 1e-9
def test_stability_limit_on_the_checkerboard_mode():
# the checkerboard pressure is the eigenvector of -D G with the largest eigenvalue;
# with a tiny amplitude the advection term is negligible and the Stokes analysis applies
g = Grid(8, 8)
lim = stable_step(g, NU, 1.0, 0, safety=1.0)
z = [0.0] * 64
out = []
for f in (0.98, 1.02):
p = [1e-6 * (-1) ** (k % 8 + k // 8) for k in range(64)]
_, _, pp, _ = artificial_compressibility(g, z, z, p, f * lim, 1.0, NU, z, z, -1, maxit=300)
out.append(max(abs(x) for x in pp))
assert out[0] < 1e-12 and out[1] > 1e-3
def test_space_order_on_the_forced_taylor_green_vortex():
errs, hs = [], []
for n in (8, 12, 16):
g, (u, v, p, _, _), (uu, vv, pp), _ = _solve(n, 1.0, tol=1e-10)
errs.append(max(max(abs(uu[k] - u[k]) for k in range(n * n)), max(abs(vv[k] - v[k]) for k in range(n * n))))
hs.append(g.dx)
orders = [math.log(errs[i] / errs[i + 1]) / math.log(hs[i] / hs[i + 1]) for i in range(2)]
assert all(abs(q - 2) < 0.2 for q in orders), orders
assert abs(errs[0] - 0.048993) < 1e-5
History
Chorin (1967) introduced the method in the second volume of the Journal of Computational Physics, as a way to compute steady viscous incompressible flow by explicit marching. A year later Chorin (1968) proposed the projection method for time-accurate flow. Artificial compressibility returned in the 1980s in upwind and implicit form in collocated finite volume codes, often with dual time stepping for unsteady problems.
References
- Alexandre J. Chorin, A numerical method for solving incompressible viscous flow problems, Journal of Computational Physics 2(1) (1967) 12-26, the artificial compressibility equations and the explicit iteration to the steady state
- Joel H. Ferziger, Milovan Peric and Robert L. Street, Computational Methods for Fluid Dynamics, fourth edition, Springer, 2020, Chapter 7 (other methods for the pressure-velocity coupling, artificial compressibility)
- Alexandre J. Chorin, Numerical solution of the Navier-Stokes equations, Mathematics of Computation 22(104) (1968) 745-762, the projection method that Chorin proposed next for time-accurate flow
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 FZZC89 Edit this page History Report an error Markdown