Algorithm Search⌘K

Algorithmadvanced

Predictive-corrective incompressible SPH

Also called PCISPH.

An SPH fluid solver that finds each pressure by a loop that predicts the next positions and densities and corrects the pressure by a fixed factor times the predicted density error.

Time
O(n + q) iterationO(k (n + q)) step
Space
O(n + q) extra
Where
k = the number of correction iterations; n = the number of particles; q = the number of neighbor pairs
Properties
conserves angular momentumconserves linear momentumdeterministicnot exactiterative
Origin
Barbara Solenthaler, Renato Pajarola, 2009

Predictive-corrective incompressible SPH (PCISPH) is an SPH fluid solver that does not use an equation of state. Each step starts with zero pressure and runs a loop: predict where the particles go with the current pressure force, compute the densities there, and raise the pressure of each particle by a fixed factor δ\delta times its predicted density error. The loop stops when the largest predicted compression is below a tolerance η\eta, for example 1% of the rest density. The time step can be much larger than in weakly compressible SPH, because the pressure is no longer a stiff function of the density.

In plain words

Think of the water as many small balls. Before the balls move, the method makes a guess of where they would go in this step. At the guessed places it counts how crowded each ball is. Where a ball is too crowded, its pressure goes up a little. With the new pressures it makes a better guess, and counts again. After a few rounds, no ball is too crowded, and the balls move for real. The size of each pressure change comes from one sample ball with a full ring of neighbors, worked out once before the run. The guesses cost time, but the steps can be much longer than in the simple method, so the total work is often smaller.

The problem

The input is a set of nn particles of equal mass mm with positions xix_i and velocities viv_i, the rest density ρ0\rho_0, the smoothing length hh, gravity g=(0,−9.81)g = (0, -9.81) m/s², the step Δt\Delta t and the tolerance η\eta. The output is the state after one step, in which the predicted density of each particle is at most (1+η)ρ0(1 + \eta)\rho_0. This is the SPH form of an incompressible fluid with a free surface, one method for fluid simulation for animation. The kernel WW is the 2D cubic spline with support 2h2h, as on WCSPH, and ∇Wij\nabla W_{ij} is its gradient with respect to xix_i.

The algorithm

Before the run, compute the factor δ\delta on a prototype particle with a full neighborhood on a square lattice of spacing Δx\Delta x:

β=2(Δt mρ0)2,δ=1β(∣∑j∇Wij∣2+∑j∣∇Wij∣2).\beta = 2\left(\frac{\Delta t\, m}{\rho_0}\right)^2, \qquad \delta = \frac{1}{\beta\left(\left|\sum_j \nabla W_{ij}\right|^2 + \sum_j |\nabla W_{ij}|^2\right)}.
  1. PCISPH-STEP(x, v, Δt)
  2. 1P ← neighbor pairs at time t; store ∇Wᵢⱼ for each pair
  3. 2for each i: fᵢ ← g + other non-pressure accelerations
  4. 3for each i: pᵢ ← 0; aᵖᵢ ← 0
  5. 4while iter < 3 or (max error > η ρ₀ and iter < max) do
  6. 5for each i: v*ᵢ ← vᵢ + Δt (fᵢ + aᵖᵢ)
  7. 6for each i: x*ᵢ ← xᵢ + Δt v*ᵢ, clamped to the walls
  8. 7for each i: ρ*ᵢ ← m W(0) + Σ over pairs of m W(|x*ᵢ - x*ⱼ|)
  9. 8for each i: eᵢ ← ρ*ᵢ - ρ₀
  10. 9for each i: pᵢ ← max(0, pᵢ + δ eᵢ)
  11. 10for each i: aᵖᵢ ← -m Σⱼ (pᵢ + pⱼ) / ρ₀² ∇Wᵢⱼ
  12. 11for each i: vᵢ ← vᵢ + Δt (fᵢ + aᵖᵢ)
  13. 12for each i: xᵢ ← xᵢ + Δt vᵢ, clamped to the walls

Line L1 finds the pairs with the grid search and keeps them for the whole loop, as Section 2.4.1 of the paper does. Line L2 holds gravity and any viscosity or external force; the tests use gravity only. Lines L5 to L7 predict the state with the current pressure. Line L8 is the predicted density error, and line L9 corrects the pressure. The clamp at 0 in line L9 is the choice of this page: at the free surface a particle has fewer neighbors and a low density, and a negative pressure there would pull the surface into clumps. Line L10 is the symmetric pressure force with ρ0\rho_0 in place of ρi\rho_i and ρj\rho_j, the same approximation that gives δ\delta. The loop runs at least 3 times, as in the paper, and stops when max⁡iei≤ηρ0\max_i e_i \le \eta\rho_0. Lines L11 and L12 are symplectic Euler with the final pressure force.

The formula for δ\delta comes from a linear guess. A pressure p~\tilde p on particle ii, with the same pressure on its neighbors, moves ii by −Δt2m(2p~/ρ02)∑j∇Wij-\Delta t^2 m (2\tilde p/\rho_0^2)\sum_j \nabla W_{ij} and moves each neighbor jj by Δt2m(2p~/ρ02)∇Wij\Delta t^2 m (2\tilde p/\rho_0^2)\nabla W_{ij}. To first order this lowers ρi\rho_i by p~ β (∣∑j∇Wij∣2+∑j∣∇Wij∣2)\tilde p\,\beta\,(|\sum_j \nabla W_{ij}|^2 + \sum_j|\nabla W_{ij}|^2). Setting the drop equal to the error eie_i gives p~=δei\tilde p = \delta e_i. On a full symmetric lattice ∑j∇Wij=0\sum_j \nabla W_{ij} = 0, so only the second term is left.

Example

Take Δx=0.02\Delta x = 0.02 m, h=1.3Δxh = 1.3\Delta x, ρ0=1000\rho_0 = 1000 kg/m², m=ρ0Δx2=0.4m = \rho_0\Delta x^2 = 0.4 kg and Δt=0.004\Delta t = 0.004 s. The prototype gives δ=53.05\delta = 53.05 m²/s². Put 25 particles at rest on a 5 by 5 lattice with spacing 0.95Δx0.95\Delta x, so the block is squeezed, and set g=0g = 0 and η=0.01\eta = 0.01. The table gives the largest predicted compression max⁡iei/ρ0\max_i e_i/\rho_0 of line L8 in each pass of the loop.

pass max error
1 10.96%
2 0.62%
3 1.57%
4 0.99%

The first pass has no pressure, so it sees the squeeze of the block. The second pass already has a small error, but the loop runs at least 3 times. The third pass overshoots at some particles, because δ\delta comes from a full neighborhood and the block has edges. The fourth pass is below 1%, so the loop stops.

Correctness

PCISPH is a fixed point iteration on the pressure, and it has no proof of convergence in general. The paper states it with a linear model of one particle and reports that it converges in practice; the tests here check it on a small dam break. These things are exact:

  • Exit condition. If the loop stops before the cap, every predicted density of line L7 is at most (1+η)ρ0(1 + \eta)\rho_0.
  • Momentum. The pressure force of line L10 is a sum of pair terms with opposite signs on ii and jj, parallel to xi−xjx_i - x_j. So without walls and gravity, the step keeps the total linear and angular momentum, by the argument of WCSPH.
  • First order. For a small error ee on the prototype particle, the pressure δe\delta e lowers its predicted density by e+O(e2)e + O(e^2).

The final positions of line L12 use the pressure after the last correction, so the real density error is usually a little smaller than the last measured one. The proof gives the three arguments.

Proof: The exit condition, the momentum laws and the first order meaning of delta in PCISPHfull

We use the notation of the page. All particles have the mass m>0m > 0. The arithmetic is exact real arithmetic. PCISPH has no general proof of convergence; the claims below are what holds for every run.

The exit condition

Claim 1. If the loop of line L4 ends with fewer than the maximum number of passes, then ρi∗≤(1+η)ρ0\rho^*_i \le (1 + \eta)\rho_0 for every particle, where ρ∗\rho^* is the density of line L7 in the last pass.

Proof. The loop ends only when its condition fails. After at least 3 passes and below the cap, the condition fails only if max⁡iei≤ηρ0\max_i e_i \le \eta\rho_0, with ei=ρi∗−ρ0e_i = \rho^*_i - \rho_0 from line L8 of the last pass. □\square

Momentum

Claim 2. With g=0g = 0, no other forces and no walls, one step keeps ∑imvi\sum_i m v_i and ∑im xi×vi\sum_i m\, x_i \times v_i.

Proof. By line L10, aip=∑(i,j)∈P−c (pi+pj)∇Wij+∑(j,i)∈Pc (pj+pi)∇Wjia^p_i = \sum_{(i,j) \in P} -c\,(p_i + p_j)\nabla W_{ij} + \sum_{(j,i) \in P} c\,(p_j + p_i)\nabla W_{ji} with c=m/ρ02c = m/\rho_0^2: each stored pair adds −c(pi+pj)∇Wij-c(p_i + p_j)\nabla W_{ij} to aipa^p_i and the negative of it to ajpa^p_j. So ∑im aip=0\sum_i m\, a^p_i = 0, and line L11 keeps ∑imvi\sum_i m v_i. Each pair term is a scalar times ∇Wij\nabla W_{ij}, which is parallel to xi−xjx_i - x_j (the gradient of a radial kernel). The torque of the pair is −c(pi+pj) m (xi−xj)×∇Wij=0-c(p_i + p_j)\,m\,(x_i - x_j)\times\nabla W_{ij} = 0, so ∑ixi×maip=0\sum_i x_i \times m a^p_i = 0. With v′=v+Δt apv' = v + \Delta t\,a^p and x′=x+Δt v′x' = x + \Delta t\,v',

∑im xi′×vi′=∑im xi×vi′=∑im xi×vi+Δt∑ixi×maip,\sum_i m\, x'_i \times v'_i = \sum_i m\, x_i \times v'_i = \sum_i m\, x_i \times v_i + \Delta t\sum_i x_i \times m a^p_i,

since vi′×vi′=0v'_i \times v'_i = 0, and the last sum is 0. □\square

The values of pp do not matter in Claim 2, so it holds for any number of passes and with the clamp of line L9.

The first order meaning of delta

Let ii be the prototype particle with neighbors jj, and let G=∑j∇WijG = \sum_j \nabla W_{ij}. Give ii and its neighbors the pressure p~\tilde p, and keep the gradients of time tt. Following the derivation of Section 2.3 of the paper, the pressure moves ii by Δxi=−Δt2m (2p~/ρ02) G\Delta x_i = -\Delta t^2 m\,(2\tilde p/\rho_0^2)\,G, and the pair force of ii on jj moves jj by Δxj=Δt2m (2p~/ρ02)∇Wij\Delta x_j = \Delta t^2 m\,(2\tilde p/\rho_0^2)\nabla W_{ij}.

Claim 3. To first order in the displacements, the density of ii changes by −p~ β (∣G∣2+∑j∣∇Wij∣2)-\tilde p\,\beta\,(|G|^2 + \sum_j|\nabla W_{ij}|^2). So p~=δe\tilde p = \delta e changes it by −e+O(e2)-e + O(e^2).

Proof. ρi=mW(0)+∑jmW(∣xi−xj∣)\rho_i = m W(0) + \sum_j m W(|x_i - x_j|). The first order change is ∑jm ∇Wij⋅(Δxi−Δxj)\sum_j m\,\nabla W_{ij}\cdot(\Delta x_i - \Delta x_j). Substituting,

∑jm∇Wij⋅Δxi=−2Δt2m2p~ρ02 G⋅G,∑jm∇Wij⋅Δxj=2Δt2m2p~ρ02∑j∣∇Wij∣2.\sum_j m\nabla W_{ij}\cdot\Delta x_i = -\frac{2\Delta t^2 m^2\tilde p}{\rho_0^2}\,G\cdot G, \qquad \sum_j m\nabla W_{ij}\cdot\Delta x_j = \frac{2\Delta t^2 m^2\tilde p}{\rho_0^2}\sum_j|\nabla W_{ij}|^2.

The change is the first sum minus the second, which is −p~ β (∣G∣2+∑j∣∇Wij∣2)-\tilde p\,\beta\,(|G|^2 + \sum_j|\nabla W_{ij}|^2) with β=2Δt2m2/ρ02\beta = 2\Delta t^2 m^2/\rho_0^2. With p~=δe\tilde p = \delta e and the definition of δ\delta, this is −e-e. The kernel is twice differentiable away from r=0r = 0 and r=2hr = 2h, so the rest of the Taylor expansion is O(∣Δx∣2)=O(e2)O(|\Delta x|^2) = O(e^2) for a lattice with no neighbor at exactly 2h2h. □\square

The test checks Claim 3 by a direct sum on a lattice: for e=10−3e = 10^{-3} and e=10−2e = 10^{-2} the density drop is within 5% of ee. Claim 3 is the reason for the factor in line L9; it is a statement about one particle in a full neighborhood, not a proof that the loop converges for the whole fluid. ■\blacksquare

Complexity

One pass of the loop costs O(n+q)O(n + q) time for qq pairs: lines L5 to L10 do constant work per particle and per pair. A step with kk passes costs O(k(n+q))O(k(n + q)), and the grid search of line L1 adds O(n+q)O(n + q) once. With a density near ρ0\rho_0, q=O(n)q = O(n). The number kk is a measurement, not a bound. In the small dam break of the tests, most steps need a few passes, and the steps where the front hits the wall need many more. The memory is O(n+q)O(n + q) for the pairs and their gradients.

Properties

  • Larger steps. The step is limited by the flow speed, not by a numerical speed of sound. The paper measured steps 35 times larger than WCSPH at η=1%\eta = 1\% and 151 times larger at 0.1%0.1\%, on its scenes.
  • Tolerance. The user sets the density error η\eta directly.
  • Momentum. Linear and angular momentum are kept by the pressure force (proved).
  • No convergence proof. The loop is a Jacobi-like iteration with one factor δ\delta for all particles. Particles with few neighbors get a δ\delta that is too large, so the error can overshoot, as in the example.
  • Fixed neighbors. The pairs of time tt are reused in the loop, so a pair that comes closer than 2h2h during the step is missed until the next step.

Variants and improvements

  • Local factor. Compute δi\delta_i per particle from its own neighbors instead of the prototype. This costs one more pass over the pairs.
  • Implicit incompressible SPH. IISPH writes the same density condition as a linear system in the pressures and solves it with relaxed Jacobi, with a per-particle diagonal.
  • Divergence-free SPH. DFSPH adds a second solver for the velocity divergence, which allows still larger steps.
  • Boundary particles. Fixed particles on the walls that add to the density and get a pressure give smoother walls than the clamped walls of lines L6 and L12.
  • Other methods. Position based fluids write the same density condition as a constraint on positions.

When to use it

Use PCISPH when WCSPH is too slow because of its small steps, and you want a solver that is still easy to write. It needs only the SPH sums and a loop, with no matrix. For large scenes, IISPH or DFSPH usually converge in fewer passes.

Pitfalls

  • Pressure not reset. Line L3 sets pi=0p_i = 0 at the start of each step. If the pressures of the last step are kept without care, the first pass overshoots.
  • Prototype too small. The lattice of the prototype must cover the full support 2h2h. A partial neighborhood gives a too large δ\delta and the loop of line L4 oscillates.
  • Unclamped surface pressure. Without the clamp of line L9, free surface particles get negative pressures and clump.
  • Error sign. Line L8 is ρ∗−ρ0\rho^* - \rho_0. With the opposite sign, line L9 lowers the pressure where the fluid is squeezed.
  • Gradients at the predicted positions. Line L10 uses the gradients of time tt, as in the derivation of δ\delta. Mixing predicted gradients with δ\delta from time tt breaks the linear model.

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.

pcisph.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pcisph/. The authors are listed in prov/Y0N4QC.jsonl.
"""Predictive-corrective incompressible SPH (PCISPH) in 2D.

The step follows Algorithm 2 of Solenthaler and Pajarola (2009). All particles
have the same mass m. The pressure starts at 0 and is corrected in a loop:
predict the velocities and positions with the current pressure force, predict
the densities, and add delta times the predicted density error to the
pressure. The loop runs at least min_iter times and stops when the largest
predicted compression is below eta * rho0.

delta comes from a prototype particle with a full neighborhood on a square
lattice (Section 2.3 of the paper):

    delta = 1 / (beta (|sum_j grad W_ij|^2 + sum_j |grad W_ij|^2)),
    beta = 2 (dt m / rho0)^2.

The pressure force uses rho0 in place of rho_i and rho_j, as in the
derivation of delta, and the gradients at the start of the step. The neighbor
pairs of the start of the step are reused in the loop (Section 2.4.1).
The page clamps the pressure at 0, so the free surface does not pull.
"""

import math

from sph import grad_w, neighbor_pairs, w_cubic

GRAVITY = (0.0, -9.81)


def prototype_delta(dx, h, m, rho0, dt):
    """delta of the paper for a particle in a full square lattice of spacing dx."""
    k = int(math.ceil(2.0 * h / dx)) + 1
    sx = sy = 0.0
    ss = 0.0
    for a in range(-k, k + 1):
        for b in range(-k, k + 1):
            if a == 0 and b == 0:
                continue
            g = grad_w((-a * dx, -b * dx), h)
            sx += g[0]
            sy += g[1]
            ss += g[0] * g[0] + g[1] * g[1]
    beta = 2.0 * (dt * m / rho0) ** 2
    return 1.0 / (beta * (sx * sx + sy * sy + ss))


def clamp_box(x, y, box):
    if box is None:
        return x, y
    x0, y0, x1, y1 = box
    return min(max(x, x0), x1), min(max(y, y0), y1)


def pressure_accelerations(grads, pairs, p, m, rho0, n):
    """a^p_i = -m sum_j (p_i + p_j) / rho0^2 grad W_ij, pair by pair."""
    ax = [0.0] * n
    ay = [0.0] * n
    c = m / (rho0 * rho0)
    for (i, j), (gx, gy) in zip(pairs, grads):
        s = c * (p[i] + p[j])
        ax[i] -= s * gx
        ay[i] -= s * gy
        ax[j] += s * gx
        ay[j] += s * gy
    return ax, ay


def step(pos, vel, m, dt, h, rho0, delta, gravity=GRAVITY, eta=0.01,
         min_iter=3, max_iter=50, box=None):
    """One PCISPH step. Returns (pos, vel, info) with info = (iterations, error)."""
    n = len(pos)
    pairs = neighbor_pairs(pos, 2.0 * h)  # @line L1
    grads = [grad_w((pos[i][0] - pos[j][0], pos[i][1] - pos[j][1]), h) for i, j in pairs]
    fx = [gravity[0]] * n  # @line L2
    fy = [gravity[1]] * n
    p = [0.0] * n  # @line L3
    apx = [0.0] * n
    apy = [0.0] * n
    w0 = w_cubic(0.0, h)
    it = 0
    err = float("inf")
    xs = pos
    while it < min_iter or (err > eta * rho0 and it < max_iter):  # @line L4
        vs = [(vel[i][0] + dt * (fx[i] + apx[i]), vel[i][1] + dt * (fy[i] + apy[i])) for i in range(n)]  # @line L5
        xs = [clamp_box(pos[i][0] + dt * vs[i][0], pos[i][1] + dt * vs[i][1], box) for i in range(n)]  # @line L6
        rho = [m * w0] * n  # @line L7
        for i, j in pairs:
            w = w_cubic(math.hypot(xs[i][0] - xs[j][0], xs[i][1] - xs[j][1]), h)
            rho[i] += m * w
            rho[j] += m * w
        err = 0.0
        for i in range(n):
            e = rho[i] - rho0  # @line L8
            err = max(err, e)
            p[i] = max(0.0, p[i] + delta * e)  # @line L9
        apx, apy = pressure_accelerations(grads, pairs, p, m, rho0, n)  # @line L10
        it += 1
    vel = [(vel[i][0] + dt * (fx[i] + apx[i]), vel[i][1] + dt * (fy[i] + apy[i])) for i in range(n)]  # @line L11
    new = []
    out_v = []
    for i in range(n):
        x, y = clamp_box(pos[i][0] + dt * vel[i][0], pos[i][1] + dt * vel[i][1], box)  # @line L12
        u, v = vel[i]
        if box is not None:
            if x != pos[i][0] + dt * u:
                u = 0.0
            if y != pos[i][1] + dt * v:
                v = 0.0
        new.append((x, y))
        out_v.append((u, v))
    return new, out_v, (it, max(err, 0.0) / rho0)


def momentum(vel, m):
    return (m * sum(v[0] for v in vel), m * sum(v[1] for v in vel))


def angular_momentum(pos, vel, m):
    return m * sum(x[0] * v[1] - x[1] * v[0] for x, v in zip(pos, vel))
sph.py 127 lines
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The 2D cubic spline kernel, a uniform grid neighbor search and the SPH density.

This file is copied byte for byte into each impl/python folder that needs it.
It holds no solver step of a page: no equation of state, no pressure force,
no pressure solve and no time integration. The method of each page lives in
its slug file.

Conventions (prompts/graphics-ext.md, "Particles and SPH"):
- Positions are 2D tuples (x, y) in meters. Masses are in kg; in 2D a
  density is in kg/m^2.
- h is the smoothing length. The cubic spline of Monaghan has support 2h:
  W(r, h) = 0 for r >= 2h.
- grad_w(xij, h) is the gradient of W(|x_i - x_j|, h) with respect to x_i,
  where xij = x_i - x_j. It is antisymmetric: grad_w(-xij) = -grad_w(xij).
- The density of particle i is rho_i = sum_j m_j W(|x_i - x_j|, h), with
  j = i included.
"""

import math

# The 2D normalization constant of the cubic spline: W(0, h) = SIGMA_2D / h^2.
SIGMA_2D = 10.0 / (7.0 * math.pi)


def w_cubic(r, h):
    """Return the 2D cubic spline kernel W(r, h) for a distance r >= 0.

    W = SIGMA_2D / h^2 * (1 - 1.5 q^2 + 0.75 q^3) for 0 <= q < 1,
    W = SIGMA_2D / h^2 * 0.25 (2 - q)^3 for 1 <= q < 2, and W = 0 for
    q >= 2, with q = r / h. Unit 1/m^2. Cost O(1).
    """
    q = r / h
    s = SIGMA_2D / (h * h)
    if q < 1.0:
        return s * (1.0 - 1.5 * q * q + 0.75 * q * q * q)
    if q < 2.0:
        t = 2.0 - q
        return s * 0.25 * t * t * t
    return 0.0


def dw_cubic(r, h):
    """Return the radial derivative dW/dr of the 2D cubic spline. Unit 1/m^3."""
    q = r / h
    s = SIGMA_2D / (h * h * h)
    if q < 1.0:
        return s * (-3.0 * q + 2.25 * q * q)
    if q < 2.0:
        t = 2.0 - q
        return s * (-0.75 * t * t)
    return 0.0


def grad_w(xij, h):
    """Return the gradient of W(|xij|, h) with respect to x_i, for xij = x_i - x_j.

    The gradient is dW/dr * xij / |xij|. It is (0, 0) at r = 0, where the
    kernel has a smooth maximum. Cost O(1).
    """
    r = math.hypot(xij[0], xij[1])
    if r == 0.0:
        return (0.0, 0.0)
    d = dw_cubic(r, h) / r
    return (d * xij[0], d * xij[1])


def neighbor_pairs(positions, radius):
    """Return the sorted list of pairs (i, j), i < j, with |x_i - x_j| < radius.

    The search puts the particles in a uniform grid of square cells of side
    radius, keyed by (floor(x / radius), floor(y / radius)). Two particles at
    a distance below radius are in the same cell or in adjacent cells, so
    the search looks only at the 3 by 3 block of cells around each particle.
    The result is the same as a test of all pairs. For the cubic spline,
    pass radius = 2h. Cost O(n + q') for q' candidate pairs in adjacent
    cells; this is O(n) when the number of particles per cell is bounded.
    """
    cells = {}
    keys = []
    for i, p in enumerate(positions):
        key = (math.floor(p[0] / radius), math.floor(p[1] / radius))
        keys.append(key)
        cells.setdefault(key, []).append(i)
    r2 = radius * radius
    pairs = []
    for i, p in enumerate(positions):
        cx, cy = keys[i]
        for dx in (-1, 0, 1):
            for dy in (-1, 0, 1):
                for j in cells.get((cx + dx, cy + dy), ()):
                    if j <= i:
                        continue
                    ex = p[0] - positions[j][0]
                    ey = p[1] - positions[j][1]
                    if ex * ex + ey * ey < r2:
                        pairs.append((i, j))
    pairs.sort()
    return pairs


def neighbor_lists(positions, radius):
    """Return, for each particle i, the sorted list of j != i with |x_i - x_j| < radius."""
    lists = [[] for _ in positions]
    for i, j in neighbor_pairs(positions, radius):
        lists[i].append(j)
        lists[j].append(i)
    for nb in lists:
        nb.sort()
    return lists


def density(positions, masses, h):
    """Return the list of SPH densities rho_i = sum_j m_j W(|x_i - x_j|, h), j = i included.

    The sum runs over the neighbor pairs at distances below 2h, found with
    the grid search. Cost O(n + q) for q neighbor pairs.
    """
    w0 = w_cubic(0.0, h)
    rho = [m * w0 for m in masses]
    for i, j in neighbor_pairs(positions, 2.0 * h):
        r = math.hypot(positions[i][0] - positions[j][0], positions[i][1] - positions[j][1])
        w = w_cubic(r, h)
        rho[i] += masses[j] * w
        rho[j] += masses[i] * w
    return rho
test_pcisph.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pcisph/. The authors are listed in prov/Y0N4QC.jsonl.

import math
import random

import pcisph
import sph

DX = 0.02
H = 1.3 * DX
RHO0 = 1000.0
M = RHO0 * DX * DX


def lattice(n_side):
    return [((i + 0.5) * DX, (j + 0.5) * DX) for i in range(n_side) for j in range(n_side)]


def test_prototype_delta_matches_its_formula() -> None:
    dt = 0.004
    d = pcisph.prototype_delta(DX, H, M, RHO0, dt)
    # Direct sum over a large lattice, written out again.
    ss = 0.0
    gx = gy = 0.0
    for a in range(-6, 7):
        for b in range(-6, 7):
            if (a, b) != (0, 0):
                r = math.hypot(a * DX, b * DX)
                dw = sph.dw_cubic(r, H)
                ss += dw * dw
                g = sph.grad_w((a * DX, b * DX), H)
                gx += g[0]
                gy += g[1]
    beta = 2.0 * dt * dt * M * M / (RHO0 * RHO0)
    assert abs(gx) < 1e-9 and abs(gy) < 1e-9  # the full lattice is symmetric
    assert abs(d - 1.0 / (beta * ss)) < 1e-9 * d
    # delta scales as 1 / dt^2.
    assert abs(pcisph.prototype_delta(DX, H, M, RHO0, 2 * dt) - d / 4.0) < 1e-9 * d


def test_delta_removes_a_small_density_error_to_first_order() -> None:
    # The derivation of delta: pressure p = delta e on the prototype particle c
    # moves each neighbor j by dt^2 m (2 p / rho0^2) grad W_cj, and this lowers
    # the density of c by e to first order.
    dt = 0.004
    d = pcisph.prototype_delta(DX, H, M, RHO0, dt)
    pos = [(a * DX, b * DX) for a in range(-5, 6) for b in range(-5, 6)]
    c = pos.index((0.0, 0.0))
    rho_c = sum(M * sph.w_cubic(math.hypot(*p), H) for p in pos)
    for e in (1e-3, 1e-2):
        p = d * e
        moved = []
        for k, x in enumerate(pos):
            if k == c:
                moved.append(x)
                continue
            g = sph.grad_w((0.0 - x[0], 0.0 - x[1]), H)  # grad W_cj with respect to x_c
            s = dt * dt * M * 2.0 * p / (RHO0 * RHO0)
            moved.append((x[0] + s * g[0], x[1] + s * g[1]))
        new_rho = sum(M * sph.w_cubic(math.hypot(*q), H) for q in moved)
        assert abs((rho_c - new_rho) - e) < 0.05 * e


def test_momentum_is_conserved_without_walls_and_gravity() -> None:
    rng = random.Random(3)
    pos = [(x + rng.uniform(-0.3, 0.3) * DX, y + rng.uniform(-0.3, 0.3) * DX) for x, y in lattice(7)]
    # Squeeze the blob so the pressure is not zero.
    pos = [(0.8 * x, 0.8 * y) for x, y in pos]
    vel = [(rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)) for _ in pos]
    dt = 0.002
    d = pcisph.prototype_delta(DX, H, M, RHO0, dt)
    p0 = pcisph.momentum(vel, M)
    l0 = pcisph.angular_momentum(pos, vel, M)
    for _ in range(10):
        pos, vel, (it, _) = pcisph.step(pos, vel, M, dt, H, RHO0, d, gravity=(0.0, 0.0))
        assert it >= 3
    p1 = pcisph.momentum(vel, M)
    l1 = pcisph.angular_momentum(pos, vel, M)
    scale = M * sum(math.hypot(*v) for v in vel)
    assert abs(p1[0] - p0[0]) < 1e-10 * scale and abs(p1[1] - p0[1]) < 1e-10 * scale
    assert abs(l1 - l0) < 1e-10 * scale


def test_small_dam_break_reaches_one_percent() -> None:
    n_side = 8
    pos = lattice(n_side)
    vel = [(0.0, 0.0)] * len(pos)
    dt = 0.004
    d = pcisph.prototype_delta(DX, H, M, RHO0, dt)
    box = (0.0, 0.0, 0.4, 0.4)
    worst = 0.0
    for _ in range(60):
        pos, vel, (it, err) = pcisph.step(pos, vel, M, dt, H, RHO0, d, eta=0.01, box=box)
        assert 3 <= it < 50
        assert err <= 0.01
        rho = sph.density(pos, [M] * len(pos), H)
        worst = max(worst, sum(max(r - RHO0, 0.0) for r in rho) / (RHO0 * len(rho)))
    assert worst < 0.01
    assert max(x for x, _ in pos) > n_side * DX + 0.05
    # The step is far above the WCSPH limit 0.4 h / (c + v) with c = 10 v.
    v = math.sqrt(2 * 9.81 * n_side * DX)
    assert dt > 5 * 0.4 * H / (11 * v)

History

Before PCISPH, graphics used WCSPH (Becker and Teschner 2007) or projection methods from engineering (incompressible SPH). WCSPH needs a stiff equation of state and small steps, and projection methods need a linear solve. Solenthaler and Pajarola (2009) took a middle path: a loop that predicts the density and corrects the pressure, with one precomputed factor. Ihmsen et al. (2014) then wrote the same condition as a linear system in IISPH, and Bender and Koschier (2015) added a divergence solver in DFSPH.

References

  1. Barbara Solenthaler and Renato Pajarola, Predictive-corrective incompressible SPH, ACM Transactions on Graphics 28(3), article 40, 2009, Section 2.3 (the pressure update and delta, equations 8 and 9), Section 2.4 (Algorithm 2, the reuse of neighbors and the minimum of 3 iterations) and Section 4 (results)
  2. Markus Becker and Matthias Teschner, Weakly compressible SPH for free surface flows, Symposium on Computer Animation 2007, 209-217, the whole paper (the WCSPH baseline)
  3. Dan Koschier, Jan Bender, Barbara Solenthaler and Matthias Teschner, Smoothed particle hydrodynamics techniques for the physics based simulation of fluids and solids, Eurographics tutorial, 2019, the section on pressure solvers

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.iteration
  • a full proof of time.step
  • 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