Algorithm Search⌘K

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.

Time
Θ(I M) worst
Space
Θ(M) extra
Where
I = the number of pseudo-time iterations; M = the number of grid cells
Properties
deterministicdivergence free at convergenceexplicitnot needs poisson solvesteady state
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, pτ+c2∇⋅u=0p_\tau + c^2\nabla\cdot\mathbf{u} = 0, with an artificial sound speed cc. The resulting system behaves like a slightly compressible fluid: pressure waves carry the information that the constraint ∇⋅u=0\nabla\cdot\mathbf{u} = 0 is violated, and viscosity damps them. The method marches this system in pseudo time τ\tau 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 cc. 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

(u⋅∇)u=−∇p+νΔu+f,∇⋅u=0,(\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. Artificial compressibility replaces it by the pseudo-time system

uτ+(u⋅∇)u=−∇p+νΔu+f,pτ+c2∇⋅u=0,\mathbf{u}_\tau + (\mathbf{u}\cdot\nabla)\mathbf{u} = -\nabla p + \nu\Delta\mathbf{u} + \mathbf{f}, \qquad p_\tau + c^2\nabla\cdot\mathbf{u} = 0,

and looks for its steady state. This page discretizes it on the periodic MAC grid with MM cells: central differences for advection, the 5-point Laplacian for viscosity, DD the divergence at the cell centers and GG the gradient at the faces. The cost is counted in real arithmetic operations and in pseudo-time iterations II.

The algorithm

  1. ARTIFICIAL-COMPRESSIBILITY(u, v, p, Δτ, c, ν, f, tol)
  2. 1repeat
  3. 2R ← -(u·∇)u + ν Δ_h u - G p + f ▷ momentum residual at the faces
  4. 3(u, v) ← (u, v) + Δτ R
  5. 4p ← p - Δτ c² D(u, v) ▷ uses the new velocity
  6. 5until max|R| ≤ tol and max|D(u, v)| ≤ tol
  7. 6return (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 Δτ\Delta\tau is chosen from the sharp condition proved on this page for the linear Stokes problem, Δτ2c2μmax⁡+2Δτνμmax⁡<4\Delta\tau^2c^2\mu_{\max} + 2\Delta\tau\nu\mu_{\max} < 4 with μmax⁡=4/Δx2+4/Δy2\mu_{\max} = 4/\Delta x^2 + 4/\Delta y^2, times a safety factor 0.80.8, and from the rule of thumb Δτ≤2ν/∣u∣max⁡2\Delta\tau \le 2\nu/|\mathbf{u}|_{\max}^2 for central advection. The safety factor and cc 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 Δx=1\Delta x = 1, ν=0\nu = 0, zero start, force (1,0,0,0)(1, 0, 0, 0) on the uu faces, Δτ=12\Delta\tau = \tfrac12 and c=1c = 1. Line L3 gives u=(12,0,0,0)u = (\tfrac12, 0, 0, 0). The divergence is Du=(−12,0,0,12)Du = (-\tfrac12, 0, 0, \tfrac12): face 0 is the left face of cell 0 and the right face of cell 3, and u>0u > 0 there carries fluid from cell 3 into cell 0. Line L4 gives p=−12⋅Du=(14,0,0,−14)p = -\tfrac12 \cdot Du = (\tfrac14, 0, 0, -\tfrac14): 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 [0,2π]2[0, 2\pi]^2 the field u=−cos⁡xsin⁡yu = -\cos x \sin y, v=sin⁡xcos⁡yv = \sin x \cos y, p=−14(cos⁡2x+cos⁡2y)p = -\tfrac14(\cos 2x + \cos 2y) is a steady solution with the force f=2νu\mathbf{f} = 2\nu\mathbf{u}, which balances viscous decay. With ν=0.5\nu = 0.5, c=1c = 1, a zero start and a stopping tolerance of 10−1010^{-10}:

cells Δτ\Delta\tau iterations velocity error order pressure error
8×88 \times 8 0.198 137 4.899e-2 1.993e-2
12×1212 \times 12 0.0977 296 2.237e-2 1.93 1.168e-2
16×1616 \times 16 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 8×88 \times 8 grid the number of iterations to reach 10−1110^{-11} depends on cc: 1151 for c=0.25c = 0.25, 313 for c=0.5c = 0.5, 151 for c=1c = 1, 160 for c=1.5c = 1.5, 183 for c=2c = 2 and 290 for c=4c = 4, and the converged fields agree to 10−910^{-9}. These are measurements from the implementation on this page. The best cc 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 c>0c > 0 and every Δτ\Delta\tau; 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 1−Δτνμ1 - \Delta\tau\nu\mu and trace 2−Δτνμ−Δτ2c2μ2 - \Delta\tau\nu\mu - \Delta\tau^2c^2\mu. The Jury conditions give convergence exactly when Δτ2c2μ+2Δτνμ<4\Delta\tau^2c^2\mu + 2\Delta\tau\nu\mu < 4 for every eigenvalue μ\mu of −DG-DG. 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 MM cells. DD is the divergence at the cell centers, GG the gradient at the faces, and A=−DGA = -DG, the periodic 5-point matrix, which is symmetric positive semidefinite with the constants as its null space (summation by parts gives GT=−DG^T = -D; see the proof on the Chorin projection method page). R(u,p)=−Nh(u)+νLhu−Gp+fR(\mathbf{u}, p) = -N_h(\mathbf{u}) + \nu L_h\mathbf{u} - Gp + \mathbf{f} is the momentum residual of line L2, with NhN_h the central advection term and LhL_h the 5-point Laplacian on each component. One iteration with step τ>0\tau > 0 and sound speed c>0c > 0 is

um+1=um+τR(um,pm),pm+1=pm−τc2Dum+1.\mathbf{u}^{m+1} = \mathbf{u}^m + \tau R(\mathbf{u}^m, p^m), \qquad p^{m+1} = p^m - \tau c^2 D\mathbf{u}^{m+1}.

Theorem 1 (fixed points). (u,p)(\mathbf{u}, p) is a fixed point of the iteration if and only if R(u,p)=0R(\mathbf{u}, p) = 0 and Du=0D\mathbf{u} = 0, that is, if and only if it solves the discrete steady incompressible equations. The set of fixed points does not depend on cc or on τ\tau.

Proof. If R(u,p)=0R(\mathbf{u}, p) = 0 and Du=0D\mathbf{u} = 0, then um+1=u\mathbf{u}^{m+1} = \mathbf{u} and pm+1=pp^{m+1} = p. Conversely, a fixed point has τR=0\tau R = 0, so R=0R = 0, and then um+1=u\mathbf{u}^{m+1} = \mathbf{u} and τc2Du=0\tau c^2 D\mathbf{u} = 0, so Du=0D\mathbf{u} = 0, because τc2>0\tau c^2 > 0. Neither condition contains cc or τ\tau. □\square

So if the iteration converges, the limit is a steady solution of the incompressible discrete equations, whatever cc was used. The stopping test of line L5 checks the two conditions of Theorem 1 directly: when it stops, max⁡∣R∣≤\max|R| \le tol and max⁡∣Du∣≤\max|D\mathbf{u}| \le 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 (Nh=0N_h = 0). Let μmax⁡=4/Δx2+4/Δy2\mu_{\max} = 4/\Delta x^2 + 4/\Delta y^2, which bounds every eigenvalue of AA and of −Lh-L_h. If

τ2c2μ+2τνμ<4for every eigenvalue μ of A, in particular if τ2c2μmax⁡+2τνμmax⁡<4,\tau^2 c^2\mu + 2\tau\nu\mu < 4 \quad \text{for every eigenvalue } \mu \text{ of } A, \text{ in particular if } \tau^2 c^2\mu_{\max} + 2\tau\nu\mu_{\max} < 4,

then the iteration converges, from any start, to a solution of νLhu−Gp+f=0\nu L_h\mathbf{u} - Gp + \mathbf{f} = 0, Du=0D\mathbf{u} = 0, provided f\mathbf{f} 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 μ\mu that AA has, the iteration diverges for some start.

Proof. The iteration is affine, so the errors (e,q)(\mathbf{e}, q) with respect to a solution obey the same update with f=0\mathbf{f} = 0. On the uniform periodic grid, LhL_h, DD and GG are shift invariant difference operators, so they commute in the sense LhG=GΔhL_h G = G\Delta_h and DLh=ΔhDDL_h = \Delta_h D, with Δh=−A\Delta_h = -A on cell fields. Split the error orthogonally (discrete Helmholtz-Hodge) as e=e0+Gs\mathbf{e} = \mathbf{e}_0 + Gs with De0=0D\mathbf{e}_0 = 0.

The divergence-free part. DLhe0=ΔhDe0=0D L_h\mathbf{e}_0 = \Delta_h D\mathbf{e}_0 = 0, so LhL_h maps divergence-free fields to divergence-free fields, and the update gives e0←(I+τνLh)e0\mathbf{e}_0 \leftarrow (I + \tau\nu L_h)\mathbf{e}_0, independent of qq, and the pressure update does not see e0\mathbf{e}_0. The eigenvalues of −Lh-L_h on this space lie in [0,μmax⁡][0, \mu_{\max}], so the factor 1−τνμ1 - \tau\nu\mu has modulus below 1 when 0<τνμ<20 < \tau\nu\mu < 2, which the condition implies. The eigenvalue 00 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 ss and qq in eigenvectors ϕ\phi of AA with Aϕ=μϕA\phi = \mu\phi, μ>0\mu > 0 (the constant eigenvector has Gϕ=0G\phi = 0 and does not affect the velocity). Write e=αGϕ\mathbf{e} = \alpha G\phi (plus divergence-free terms) and q=βϕq = \beta\phi. Then LhGϕ=GΔhϕ=−μGϕL_hG\phi = G\Delta_h\phi = -\mu G\phi and DGϕ=−μϕDG\phi = -\mu\phi, so

α′=(1−s)α−τβ,β′=β−τc2D(α′Gϕ)/ϕ=β+τc2μα′,s=τνμ.\alpha' = (1 - s)\alpha - \tau\beta, \qquad \beta' = \beta - \tau c^2 D(\alpha' G\phi)/\phi = \beta + \tau c^2\mu\alpha', \qquad s = \tau\nu\mu.

The matrix of this map is (1−s−ττc2μ(1−s)1−r)\begin{pmatrix} 1 - s & -\tau \\ \tau c^2\mu(1 - s) & 1 - r\end{pmatrix} with r=τ2c2μr = \tau^2c^2\mu. Its determinant is (1−s)(1−r)+r(1−s)=1−s(1 - s)(1 - r) + r(1 - s) = 1 - s and its trace is 2−s−r2 - s - r. A real 2×22 \times 2 matrix has both eigenvalues inside the unit disk exactly when ∣det⁡∣<1|\det| < 1 and ∣tr∣<1+det⁡|\mathrm{tr}| < 1 + \det (the Schur-Cohn or Jury conditions). Here they read 0<s<20 < s < 2 and ∣2−s−r∣<2−s|2 - s - r| < 2 - s, that is r>0r > 0 and r+2s<4r + 2s < 4. Since r>0r > 0 always, and r+2s<4r + 2s < 4 implies s<2s < 2, the condition of the theorem is exactly the condition that every mode with μ>0\mu > 0 decays. If r+2s≥4r + 2s \ge 4 for some eigenvalue that AA has, that mode has an eigenvalue of modulus at least 1 and does not decay; with r+2s>4r + 2s > 4 it grows. Both functions of μ\mu are increasing, so the condition at μmax⁡\mu_{\max} covers all μ\mu. □\square

For even nxn_x and nyn_y the checkerboard (−1)i+j(-1)^{i+j} is an eigenvector of AA with μ=μmax⁡\mu = \mu_{\max}, so the bound is sharp. The tests check it: a small checkerboard pressure decays with 0.980.98 times the limiting step and grows with 1.021.02 times it. The implementation solves τ2c2μmax⁡+2τνμmax⁡=4\tau^2c^2\mu_{\max} + 2\tau\nu\mu_{\max} = 4 for τ\tau and multiplies by a safety factor 0.80.8, which is a choice. With the advection term the step must also satisfy the rule of thumb τ≤2ν/∣u∣max⁡2\tau \le 2\nu/|\mathbf{u}|_{\max}^2 for central differences with forward Euler; that part is not proved here.

Termination. Each iteration costs O(M)O(M) 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 O(log⁡(1/tol))O(\log(1/\text{tol})) iterations times a factor that depends on the spectral radius; for the nonlinear problem the iteration count is a measurement.

Complexity

One iteration costs Θ(M)\Theta(M) operations and Θ(M)\Theta(M) memory, with no linear solve. The number of iterations is the cost driver. With Δτ∼Δx2/ν\Delta\tau \sim \Delta x^2/\nu from the viscous part of the step limit, the slowest smooth modes decay at a rate of order ν\nu per unit pseudo time, so I=O(Δx−2log⁡(1/tol))I = O(\Delta x^{-2}\log(1/\text{tol})) and the total cost on a square grid is O(M2log⁡(1/tol))O(M^2\log(1/\text{tol})). The measured counts above grow by about 2.2 and 1.7 from grid to grid, close to the Δx−2\Delta x^{-2} growth. Implicit pseudo-time stepping, local time steps, preconditioning and multigrid reduce the count in practice.

Properties

  • The steady state does not depend on cc or Δτ\Delta\tau; 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 ∇⋅u=0\nabla\cdot\mathbf{u} = 0 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 cc makes the pressure respond slowly and the iteration crawl; too large a cc makes the system stiff and forces a small Δτ\Delta\tau. A rule of thumb takes cc 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 Δτ2c2μ+2Δτνμ<4\Delta\tau^2c^2\mu + 2\Delta\tau\nu\mu < 4, not two independent conditions. On the 8×88 \times 8 grid above, a step at 0.8 of each separate limit diverges for c=1.5c = 1.5.
  • Stopping on the change between iterates instead of the residuals can stop early when the iteration is slow. Check max⁡∣Du∣\max|D\mathbf{u}| 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.

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

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

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