Algorithm Search⌘K

Algorithmadvanced

Implicit incompressible SPH

Also called IISPH.

An SPH fluid solver that finds the pressures from a linear system, a discrete pressure Poisson equation, solved by relaxed Jacobi iteration so that the predicted density is the rest density.

Time
O(n + q) iterationO(k (n + q)) step
Space
O(n + q) extra
Where
k = the number of Jacobi iterations; n = the number of particles; q = the number of neighbor pairs
Properties
conserves angular momentumconserves linear momentumdeterministicnot exactiterative
Origin
Markus Ihmsen, Jens Cornelis, Barbara Solenthaler, Christopher Horvath, Matthias Teschner, 2014

Implicit incompressible SPH (IISPH) is an SPH fluid solver that finds the pressures from a linear system. The system says that after the step, the density of each particle predicted to first order is the rest density ρ0\rho_0. It is a discrete form of the pressure Poisson equation, with one unknown pressure per particle. IISPH solves it with relaxed Jacobi iteration, with no matrix in memory, and stops when the mean predicted compression is below a tolerance η\eta such as 0.1%. Like PCISPH, it allows steps much larger than weakly compressible SPH.

In plain words

Think of the water as many small balls. First, every ball moves a little with gravity alone, and the method checks which balls would end up too crowded. Then it looks for pressures that push the balls apart just enough to remove the crowding. Each pressure has an effect on the neighbors too, so all the pressures are linked. The method guesses all the pressures, checks the crowding that they give, and improves each guess a little. After a few rounds the crowding is very small, and the balls move for real. The pressures of the last step are a good first guess for the next step.

The problem

The input is a set of nn particles with masses mim_i, 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 and the pressures pi≥0p_i \ge 0. This is one method for fluid simulation for animation. The kernel WW is the 2D cubic spline with support 2h2h, as on WCSPH, ∇Wij\nabla W_{ij} is its gradient with respect to xix_i, and ρi=∑jmjWij\rho_i = \sum_j m_j W_{ij} with j=ij = i included.

The pressure acceleration and the operator AA are

aip=−∑jmj(piρi2+pjρj2)∇Wij,(Ap)i=Δt2∑jmj (aip−ajp)⋅∇Wij.a^p_i = -\sum_j m_j\left(\frac{p_i}{\rho_i^2} + \frac{p_j}{\rho_j^2}\right)\nabla W_{ij}, \qquad (Ap)_i = \Delta t^2\sum_j m_j\,(a^p_i - a^p_j)\cdot\nabla W_{ij}.

With viadv=vi+Δt gv^{adv}_i = v_i + \Delta t\,g, the density after the step is ρiadv+(Ap)i\rho^{adv}_i + (Ap)_i to first order, where ρiadv=ρi+Δt∑jmj(viadv−vjadv)⋅∇Wij\rho^{adv}_i = \rho_i + \Delta t\sum_j m_j(v^{adv}_i - v^{adv}_j)\cdot\nabla W_{ij}. IISPH solves Ap=sAp = s with si=ρ0−ρiadvs_i = \rho_0 - \rho^{adv}_i. This operator form is the one of the tutorial of Koschier et al.; the paper writes the same system with displacement terms diid_{ii} and dijd_{ij}.

The algorithm

  1. IISPH-STEP(x, v, p_prev, Δt)
  2. 1P ← neighbor pairs; store ∇Wᵢⱼ; ρᵢ ← Σⱼ mⱼ Wᵢⱼ
  3. 2for each i: vᵃᵈᵛᵢ ← vᵢ + Δt g
  4. 3for each i: sᵢ ← ρ₀ - ρᵢ - Δt Σⱼ mⱼ (vᵃᵈᵛᵢ - vᵃᵈᵛⱼ)·∇Wᵢⱼ
  5. 4for each i: aᵢᵢ ← -(Δt²/ρᵢ²) (|Σⱼ mⱼ ∇Wᵢⱼ|² + mᵢ Σⱼ mⱼ |∇Wᵢⱼ|²)
  6. 5for each i: pᵢ ← 0.5 p_prevᵢ
  7. 6while iter < 2 or (err > η ρ₀ and iter < max) do
  8. 7compute aᵖ from p, then (Ap)ᵢ for each i
  9. 8for each i: pᵢ ← max(0, pᵢ + ω (sᵢ - (Ap)ᵢ) / aᵢᵢ)
  10. 9err ← mean over i of max((Ap)ᵢ - sᵢ, 0)
  11. 10for each i: vᵢ ← vᵃᵈᵛᵢ + Δt aᵖᵢ
  12. 11for each i: xᵢ ← xᵢ + Δt vᵢ, clamped to the walls

Line L1 finds the pairs with the grid search and keeps them for the step. Line L2 adds the non-pressure forces; the tests use gravity only. Line L3 is the right side: the density error that the advected velocities would give. Line L4 is the diagonal of AA, the coefficient of pip_i in (Ap)i(Ap)_i. It has two parts: pip_i pushes ii away from all neighbors, and it pushes each neighbor away from ii. Line L5 is the warm start of the paper, half the pressure of the last step. Lines L7 and L8 are one step of Jacobi with relaxation ω=0.5\omega = 0.5, the value of the paper. Line L8 also clamps each pressure at 0, so a particle at the free surface does not pull its neighbors. Line L9 measures the mean predicted compression ρiadv+(Ap)i−ρ0\rho^{adv}_i + (Ap)_i - \rho_0, counted only where it is positive. The loop runs at least 2 times, as in the paper. Lines L10 and L11 are symplectic Euler with the final pressure acceleration.

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², mi=ρ0Δx2=0.4m_i = \rho_0\Delta x^2 = 0.4 kg and Δt=0.004\Delta t = 0.004 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, pprev=0p_{prev} = 0 and η=0.05%\eta = 0.05\%. The table gives the error of line L9 in each pass, as a fraction of ρ0\rho_0, and the largest pressure after the pass.

pass mean error max pressure
1 3.124% 6389.0
2 0.079% 4273.3
3 0.398% 5205.6
4 0.161% 5739.7
5 0.163% 6198.9
6 0.095% 6515.5
7 0.063% 6724.9
8 0.054% 6903.4
9 0.048% 7061.8

Pass 1 starts from p=0p = 0, so its error is the squeeze of the block itself. The error does not fall in each pass: the clamp of line L8 changes the system as pressures reach 0, and the edge particles of the block have few neighbors. Pass 9 is below η\eta, so the loop stops. With η=0.1%\eta = 0.1\% the loop stops after pass 2.

Correctness

IISPH solves a linear system, but the clamp of line L8 makes the iteration nonlinear, and the paper gives no proof that the clamped loop converges. The tests check these facts, and the proof gives the arguments:

  • The system is the density condition. (Ap)i(Ap)_i is the first order change of ρi\rho_i when every particle jj moves by Δt2ajp\Delta t^2 a^p_j, which is what the pressure does to the positions in lines L10 and L11. So Ap=sAp = s means that the predicted density is ρ0\rho_0.
  • The diagonal. Line L4 is the coefficient of pip_i in (Ap)i(Ap)_i, and it is negative when ii has a neighbor.
  • Fixed points. Without the clamp, a fixed point of line L8 solves Ap=sAp = s. The tests compare the result with Gaussian elimination.
  • Exit condition. If the loop stops before the cap, the mean predicted compression is at most ηρ0\eta\rho_0.
  • Momentum. The pressure acceleration is a sum of pair terms, opposite on ii and jj and parallel to xi−xjx_i - x_j. So without walls and gravity, the step keeps the total linear and angular momentum, for any pp.

The predicted density is a first order model. The measured compression after the step is larger: in the squeezed block above it is 0.57% after the step with η=0.1%\eta = 0.1\%.

Proof: The density condition, the diagonal, the fixed points and the momentum laws of IISPHfull

We use the notation of the page. The arithmetic is exact real arithmetic. The pairs PP are the unordered pairs {i,j}\{i, j\} with ∣xi−xj∣<2h|x_i - x_j| < 2h, and a sum over jj is over the neighbors of ii. The kernel is radial, so ∇Wij=ϕij(xi−xj)\nabla W_{ij} = \phi_{ij}(x_i - x_j) for a scalar ϕij=ϕji\phi_{ij} = \phi_{ji}, and ∇Wji=−∇Wij\nabla W_{ji} = -\nabla W_{ij}. IISPH has no proof that the clamped loop converges; the claims below hold for every run.

The system is the density condition

Claim 1. Move every particle jj by Δt2ajp\Delta t^2 a^p_j, with the neighbors and densities of time tt. Then the first order change of ρi\rho_i is (Ap)i(Ap)_i.

Proof. ρi=∑jmjW(∣xi−xj∣)\rho_i = \sum_j m_j W(|x_i - x_j|), with the term j=ij = i constant. The first order change for the displacements uju_j is ∑jmj∇Wij⋅(ui−uj)\sum_j m_j\nabla W_{ij}\cdot(u_i - u_j). With uj=Δt2ajpu_j = \Delta t^2 a^p_j this is Δt2∑jmj(aip−ajp)⋅∇Wij=(Ap)i\Delta t^2\sum_j m_j(a^p_i - a^p_j)\cdot\nabla W_{ij} = (Ap)_i. □\square

In the step, lines L10 and L11 give xi′=xi+Δtviadv+Δt2aipx_i' = x_i + \Delta t v^{adv}_i + \Delta t^2 a^p_i. The same expansion for the displacement Δtviadv\Delta t v^{adv}_i gives ρiadv\rho^{adv}_i of line L3. So, to first order, the density after the step is ρiadv+(Ap)i\rho^{adv}_i + (Ap)_i, and Ap=sAp = s is the condition that it equals ρ0\rho_0.

The diagonal

Claim 2. The coefficient of pip_i in (Ap)i(Ap)_i is aiia_{ii} of line L4, and aii<0a_{ii} < 0 when ii has a neighbor with ∇Wij≠0\nabla W_{ij} \ne 0.

Proof. Set p=eip = e_i, the unit vector of particle ii. Then aip=−(1/ρi2)∑jmj∇Wij=−Gi/ρi2a^p_i = -(1/\rho_i^2)\sum_j m_j\nabla W_{ij} = -G_i/\rho_i^2 with Gi=∑jmj∇WijG_i = \sum_j m_j\nabla W_{ij}. For a neighbor jj, only the term of ii in the sum of ajpa^p_j has pip_i, so ajp=−mi(1/ρi2)∇Wji=mi∇Wij/ρi2a^p_j = -m_i(1/\rho_i^2)\nabla W_{ji} = m_i\nabla W_{ij}/\rho_i^2. Particles that are not neighbors of ii do not enter (Ap)i(Ap)_i through ajpa^p_j, because (Ap)i(Ap)_i sums over neighbors only. So

(Aei)i=Δt2(aip⋅Gi−∑jmjajp⋅∇Wij)=−Δt2ρi2(∣Gi∣2+mi∑jmj∣∇Wij∣2),(Ae_i)_i = \Delta t^2\left(a^p_i\cdot G_i - \sum_j m_j a^p_j\cdot\nabla W_{ij}\right) = -\frac{\Delta t^2}{\rho_i^2}\left(|G_i|^2 + m_i\sum_j m_j|\nabla W_{ij}|^2\right),

which is line L4. Both terms are at least 0, and the second is positive when some ∇Wij≠0\nabla W_{ij} \ne 0, since mi,mj>0m_i, m_j > 0. □\square

Fixed points

Claim 3. Without the clamp, if aii≠0a_{ii} \ne 0 for all ii, then pp is a fixed point of line L8 if and only if Ap=sAp = s.

Proof. Line L8 maps pip_i to pi+ω(si−(Ap)i)/aiip_i + \omega(s_i - (Ap)_i)/a_{ii} with ω=0.5≠0\omega = 0.5 \ne 0. This equals pip_i for all ii if and only if si−(Ap)i=0s_i - (Ap)_i = 0 for all ii. □\square

With the clamp, a fixed point has, for each ii, either pi>0p_i > 0 and (Ap)i=si(Ap)_i = s_i, or pi=0p_i = 0 and (si−(Ap)i)/aii≤0(s_i - (Ap)_i)/a_{ii} \le 0, that is (Ap)i≤si(Ap)_i \le s_i. So at a fixed point no particle is predicted to be compressed, and particles with a predicted low density have zero pressure.

Exit condition

Claim 4. If the loop of line L6 stops after fewer than the maximum number of passes, then the mean over ii of max⁡(ρiadv+(Ap)i−ρ0,0)\max(\rho^{adv}_i + (Ap)_i - \rho_0, 0) is at most ηρ0\eta\rho_0, where pp is the pressure at the start of the last pass.

Proof. ρiadv+(Ap)i−ρ0=(Ap)i−si\rho^{adv}_i + (Ap)_i - \rho_0 = (Ap)_i - s_i, and line L9 computes the mean of the positive parts. After at least 2 passes and below the cap, the loop stops only when this mean is at most ηρ0\eta\rho_0. □\square

Momentum

Claim 5. With g=0g = 0, no walls and any pressures pp, one step keeps ∑imivi\sum_i m_i v_i and ∑imi xi×vi\sum_i m_i\, x_i \times v_i.

Proof. Write cij=pi/ρi2+pj/ρj2=cjic_{ij} = p_i/\rho_i^2 + p_j/\rho_j^2 = c_{ji}. Each pair adds −mjcij∇Wij-m_j c_{ij}\nabla W_{ij} to aipa^p_i and −micij∇Wji=micij∇Wij-m_i c_{ij}\nabla W_{ji} = m_i c_{ij}\nabla W_{ij} to ajpa^p_j. So the pair adds −mimjcij∇Wij+mjmicij∇Wij=0-m_i m_j c_{ij}\nabla W_{ij} + m_j m_i c_{ij}\nabla W_{ij} = 0 to ∑imiaip\sum_i m_i a^p_i. Its torque is mimjcij (xj−xi)×∇Wij=0m_i m_j c_{ij}\,(x_j - x_i)\times\nabla W_{ij} = 0, because ∇Wij\nabla W_{ij} is parallel to xi−xjx_i - x_j. So ∑imiaip=0\sum_i m_i a^p_i = 0 and ∑ixi×miaip=0\sum_i x_i \times m_i a^p_i = 0. With g=0g = 0, v′=v+Δt apv' = v + \Delta t\,a^p by line L10, so the linear momentum is kept. With x′=x+Δt v′x' = x + \Delta t\,v' by line L11,

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

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

The claim does not use the values of pp, so it holds for any number of passes, with or without the clamp. The density ρi\rho_i of time tt is used in all the sums of a step, so the masses and densities do not change inside the step and the pair terms stay opposite. ■\blacksquare

Complexity

One pass costs O(n+q)O(n + q) time for qq pairs: line L7 is two sweeps over the pairs, and line L8 is one sweep over the particles. A step with kk passes costs O(k(n+q))O(k(n + q)), and lines L1 to L4 add O(n+q)O(n + q) once. With a density near ρ0\rho_0, q=O(n)q = O(n). The memory is O(n+q)O(n + q); the matrix AA is never stored. The number kk is a measurement, not a bound. The paper reports fewer passes and larger steps than PCISPH on its scenes, at η=0.1%\eta = 0.1\%.

Properties

  • Matrix free. Line L7 computes ApAp from the SPH sums, so the cost per pass is the cost of two SPH sums.
  • Per-particle diagonal. Each particle has its own aiia_{ii}, so a particle with few neighbors gets a smaller step than in PCISPH, where one factor δ\delta is used for all.
  • Not symmetric. With different masses or densities, AA is not symmetric, so the conjugate gradient method does not apply directly.
  • Momentum. Linear and angular momentum are kept by the pressure force (proved).
  • Slow smooth errors. Jacobi removes local errors fast and smooth errors over many particles slowly. So deep fluids need more passes (a heuristic). In the tests, the unclamped solve of 16 particles needs about 200 passes for a relative error of 10−510^{-5} (measured).

Variants and improvements

  • Displacement form. The paper computes the same system with the terms dii=−Δt2∑j(mj/ρi2)∇Wijd_{ii} = -\Delta t^2\sum_j (m_j/\rho_i^2)\nabla W_{ij} and ∑jdijpj\sum_j d_{ij}p_j, which are the pressure displacements.
  • Divergence-free SPH. DFSPH uses a density solver of the same kind and adds a second solver that makes the velocity field divergence free.
  • Boundary particles. Fixed particles on the walls take part in ρi\rho_i and in AA, and give smoother walls than the clamp of line L11.
  • Other solvers. Conjugate gradient or multigrid on a symmetric form of the system, as in projection methods of incompressible SPH in engineering.

When to use it

Use IISPH for SPH liquids with a small density error, such as 0.1%, at large steps. It is a good default when PCISPH needs too many passes, because the per-particle diagonal handles the free surface better. For deep or large scenes, add the divergence solver of DFSPH, or use a grid method such as FLIP.

Pitfalls

  • Sign of the diagonal. The diagonal of line L4 is negative. Line L8 divides by aiia_{ii}, so with a positive diagonal the pressure goes the wrong way.
  • Missing self term. Line L4 has the term mi∑jmj∣∇Wij∣2m_i\sum_j m_j|\nabla W_{ij}|^2, the push of pip_i on the neighbors. Without it, the diagonal is near 0 inside the fluid, where ∑j∇Wij≈0\sum_j \nabla W_{ij} \approx 0.
  • Error with the clamp. Line L9 counts only compression. If it also counts the low density at the free surface, the loop never reaches η\eta.
  • Predicted is not measured. The error of line L9 is a first order prediction. Do not report it as the density error of the result.
  • No minimum. Without the 2 passes of line L6, a warm start can stop the loop at once with a pressure from the last step.

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.

implicit_incompressible_sph.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/implicit-incompressible-sph/. The authors are listed in prov/V1STXV.jsonl.
"""Implicit incompressible SPH (IISPH) in 2D.

The pressure p solves the discrete pressure Poisson equation A p = s with

    a^p_i = -sum_j m_j (p_i / rho_i^2 + p_j / rho_j^2) grad W_ij,
    (A p)_i = dt^2 sum_j m_j (a^p_i - a^p_j) . grad W_ij,
    s_i = rho0 - rho^adv_i,
    rho^adv_i = rho_i + dt sum_j m_j (v^adv_i - v^adv_j) . grad W_ij,

so that the predicted density rho^adv_i + (A p)_i equals rho0. The solver is
relaxed Jacobi with omega = 0.5 and the diagonal

    a_ii = -(dt^2 / rho_i^2) (|sum_j m_j grad W_ij|^2 + m_i sum_j m_j |grad W_ij|^2),

with each pressure clamped at 0, in the operator form of the tutorial of
Koschier et al. (2019). Ihmsen et al. (2014) write the same system with the
displacement terms d_ii and d_ij. The solve stops when the mean predicted
compression is below eta rho0 and at least min_iter passes have run.
"""

import math

from sph import density, grad_w, neighbor_pairs

GRAVITY = (0.0, -9.81)


class Neighborhood:
    """The pairs, their gradients and the per-particle gradient sums of one step."""

    def __init__(self, pos, masses, h):
        self.n = len(pos)
        self.pairs = neighbor_pairs(pos, 2.0 * h)
        self.grads = [grad_w((pos[i][0] - pos[j][0], pos[i][1] - pos[j][1]), h) for i, j in self.pairs]
        self.rho = density(pos, masses, h)
        self.m = masses


def pressure_acc(nb, p):
    """a^p_i = -sum_j m_j (p_i / rho_i^2 + p_j / rho_j^2) grad W_ij."""
    ax = [0.0] * nb.n
    ay = [0.0] * nb.n
    rho, m = nb.rho, nb.m
    for (i, j), (gx, gy) in zip(nb.pairs, nb.grads):
        s = p[i] / (rho[i] * rho[i]) + p[j] / (rho[j] * rho[j])
        ax[i] -= m[j] * s * gx
        ay[i] -= m[j] * s * gy
        ax[j] += m[i] * s * gx
        ay[j] += m[i] * s * gy
    return ax, ay


def apply_a(nb, p, dt):
    """(A p)_i = dt^2 sum_j m_j (a^p_i - a^p_j) . grad W_ij."""
    ax, ay = pressure_acc(nb, p)
    out = [0.0] * nb.n
    m = nb.m
    for (i, j), (gx, gy) in zip(nb.pairs, nb.grads):
        d = (ax[i] - ax[j]) * gx + (ay[i] - ay[j]) * gy
        out[i] += m[j] * d
        out[j] += m[i] * d  # grad W_ji = -grad W_ij and a_j - a_i = -(a_i - a_j)
    return [dt * dt * t for t in out]


def diagonal(nb, dt):
    """a_ii = -(dt^2 / rho_i^2) (|sum_j m_j grad W_ij|^2 + m_i sum_j m_j |grad W_ij|^2)."""
    sx = [0.0] * nb.n
    sy = [0.0] * nb.n
    sq = [0.0] * nb.n
    m = nb.m
    for (i, j), (gx, gy) in zip(nb.pairs, nb.grads):
        sx[i] += m[j] * gx
        sy[i] += m[j] * gy
        sx[j] -= m[i] * gx
        sy[j] -= m[i] * gy
        g2 = gx * gx + gy * gy
        sq[i] += m[j] * g2
        sq[j] += m[i] * g2
    return [-(dt * dt) / (nb.rho[i] ** 2) * (sx[i] ** 2 + sy[i] ** 2 + m[i] * sq[i]) for i in range(nb.n)]


def source(nb, vel_adv, dt, rho0):
    """s_i = rho0 - rho^adv_i."""
    rho_adv = list(nb.rho)
    m = nb.m
    for (i, j), (gx, gy) in zip(nb.pairs, nb.grads):
        d = (vel_adv[i][0] - vel_adv[j][0]) * gx + (vel_adv[i][1] - vel_adv[j][1]) * gy
        rho_adv[i] += dt * m[j] * d
        rho_adv[j] += dt * m[i] * d
    return [rho0 - r for r in rho_adv]


def relaxed_jacobi(nb, s, diag, dt, rho0, p0, omega=0.5, eta=0.001, min_iter=2,
                   max_iter=100, clamp=True):
    """Solve A p = s by relaxed Jacobi. Returns (p, iterations, mean error / rho0)."""
    p = list(p0)
    it = 0
    err = float("inf")
    while it < min_iter or (err > eta * rho0 and it < max_iter):  # @line L6
        ap = apply_a(nb, p, dt)  # @line L7
        err = 0.0
        for i in range(nb.n):
            if diag[i] != 0.0:
                p[i] = p[i] + omega * (s[i] - ap[i]) / diag[i]  # @line L8
                if clamp and p[i] < 0.0:
                    p[i] = 0.0
            err += max(ap[i] - s[i], 0.0)  # @line L9
        err /= nb.n
        it += 1
    return p, it, err / rho0


def step(pos, vel, masses, dt, h, rho0, p_prev=None, gravity=GRAVITY,
         eta=0.001, min_iter=2, max_iter=100, box=None):
    """One IISPH step. Returns (pos, vel, p, info) with info = (iterations, error)."""
    nb = Neighborhood(pos, masses, h)  # @line L1
    vel_adv = [(v[0] + dt * gravity[0], v[1] + dt * gravity[1]) for v in vel]  # @line L2
    s = source(nb, vel_adv, dt, rho0)  # @line L3
    diag = diagonal(nb, dt)  # @line L4
    p0 = [0.5 * q for q in p_prev] if p_prev is not None else [0.0] * nb.n  # @line L5
    p, it, err = relaxed_jacobi(nb, s, diag, dt, rho0, p0, 0.5, eta, min_iter, max_iter)
    ax, ay = pressure_acc(nb, p)
    vel = [(vel_adv[i][0] + dt * ax[i], vel_adv[i][1] + dt * ay[i]) for i in range(nb.n)]  # @line L10
    new = [(pos[i][0] + dt * vel[i][0], pos[i][1] + dt * vel[i][1]) for i in range(nb.n)]  # @line L11
    if box is not None:
        x0, y0, x1, y1 = box
        for i in range(nb.n):
            x, y = new[i]
            u, v = vel[i]
            if x < x0 or x > x1:
                x, u = min(max(x, x0), x1), 0.0
            if y < y0 or y > y1:
                y, v = min(max(y, y0), y1), 0.0
            new[i] = (x, y)
            vel[i] = (u, v)
    return new, vel, p, (it, err)


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


def angular_momentum(pos, vel, masses):
    return sum(m * (x[0] * v[1] - x[1] * v[0]) for m, x, v in zip(masses, pos, vel))


def mean_compression(pos, masses, h, rho0):
    rho = density(pos, masses, h)
    return sum(max(r - rho0, 0.0) for r in rho) / (rho0 * len(rho))


def speed(v):
    return math.hypot(v[0], v[1])
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_implicit_incompressible_sph.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/implicit-incompressible-sph/. The authors are listed in prov/V1STXV.jsonl.

import random

import implicit_incompressible_sph as ii

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


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


def solve_dense(a, b):
    n = len(b)
    a = [row[:] + [b[k]] for k, row in enumerate(a)]
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(a[r][c]))
        a[c], a[piv] = a[piv], a[c]
        for r in range(c + 1, n):
            f = a[r][c] / a[c][c]
            for k in range(c, n + 1):
                a[r][k] -= f * a[c][k]
    x = [0.0] * n
    for r in range(n - 1, -1, -1):
        x[r] = (a[r][n] - sum(a[r][k] * x[k] for k in range(r + 1, n))) / a[r][r]
    return x


def squeezed_cluster(rng, n_side=5):
    pos = [(x + rng.uniform(-0.1, 0.1) * DX, y + rng.uniform(-0.1, 0.1) * DX) for x, y in lattice(n_side, 0.8 * DX)]
    ms = [M * rng.uniform(0.9, 1.1) for _ in pos]
    return pos, ms


def test_diagonal_equals_the_operator_on_unit_vectors() -> None:
    rng = random.Random(1)
    pos, ms = squeezed_cluster(rng)
    nb = ii.Neighborhood(pos, ms, H)
    dt = 0.003
    diag = ii.diagonal(nb, dt)
    for i in range(nb.n):
        e = [0.0] * nb.n
        e[i] = 1.0
        col = ii.apply_a(nb, e, dt)
        assert abs(col[i] - diag[i]) < 1e-10 * abs(diag[i])
        assert diag[i] < 0.0


def test_operator_is_the_predicted_density_change() -> None:
    # (A p)_i is the first order change of rho_i when the pressure acceleration
    # acts for one step dt: x_j moves by dt^2 a^p_j.
    rng = random.Random(2)
    pos, ms = squeezed_cluster(rng)
    nb = ii.Neighborhood(pos, ms, H)
    dt = 1e-4
    p = [rng.uniform(0.0, 50.0) for _ in pos]
    ax, ay = ii.pressure_acc(nb, p)
    ap = ii.apply_a(nb, p, dt)
    moved = [(x + dt * dt * ax[k], y + dt * dt * ay[k]) for k, (x, y) in enumerate(pos)]
    rho_new = ii.density(moved, ms, H)
    for i in range(nb.n):
        assert abs((rho_new[i] - nb.rho[i]) - ap[i]) < 1e-3 * max(abs(ap[i]), 1e-12) + 1e-12


def test_relaxed_jacobi_equals_gaussian_elimination() -> None:
    # Without the clamp, relaxed Jacobi converges to the exact solution of A p = s.
    rng = random.Random(3)
    pos, ms = squeezed_cluster(rng, 4)
    nb = ii.Neighborhood(pos, ms, H)
    dt = 0.003
    vel_adv = [(0.0, 0.0)] * nb.n
    s = ii.source(nb, vel_adv, dt, RHO0)
    diag = ii.diagonal(nb, dt)
    cols = [ii.apply_a(nb, [1.0 if k == c else 0.0 for k in range(nb.n)], dt) for c in range(nb.n)]
    a = [[cols[c][r] for c in range(nb.n)] for r in range(nb.n)]
    ref = solve_dense(a, s)
    p, it, err = ii.relaxed_jacobi(nb, s, diag, dt, RHO0, [0.0] * nb.n, eta=0.0, min_iter=500,
                                   max_iter=500, clamp=False)
    assert it == 500
    scale = max(abs(t) for t in ref)
    for x, y in zip(p, ref):
        assert abs(x - y) < 1e-9 * scale


def test_momentum_is_conserved_without_walls_and_gravity() -> None:
    rng = random.Random(4)
    pos, ms = squeezed_cluster(rng, 6)
    vel = [(rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)) for _ in pos]
    p0 = ii.momentum(vel, ms)
    l0 = ii.angular_momentum(pos, vel, ms)
    p = None
    for _ in range(8):
        pos, vel, p, _ = ii.step(pos, vel, ms, 0.002, H, RHO0, p, gravity=(0.0, 0.0))
    p1 = ii.momentum(vel, ms)
    l1 = ii.angular_momentum(pos, vel, ms)
    scale = sum(m * ii.speed(v) for m, v in zip(ms, 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_its_tolerance() -> None:
    n_side = 8
    pos = lattice(n_side, DX)
    ms = [M] * len(pos)
    vel = [(0.0, 0.0)] * len(pos)
    box = (0.0, 0.0, 0.4, 0.4)
    p = None
    worst = 0.0
    for _ in range(100):
        pos, vel, p, (it, err) = ii.step(pos, vel, ms, 0.002, H, RHO0, p, eta=0.001, box=box)
        assert 2 <= it < 100
        assert err <= 0.001
        worst = max(worst, ii.mean_compression(pos, ms, H, RHO0))
    # The solver bounds the predicted error; the measured compression after the
    # step is larger (first order prediction, wall clamp) but stays below 1%.
    assert worst < 0.01
    assert max(x for x, _ in pos) > n_side * DX + 0.1
    assert all(q >= 0.0 for q in p)

History

PCISPH (Solenthaler and Pajarola 2009) corrects the pressure with one factor from a prototype particle. Ihmsen, Cornelis, Solenthaler, Horvath and Teschner (2014) wrote the same density condition as a linear system with a per-particle diagonal and solved it with relaxed Jacobi. Bender and Koschier (2015) then added a divergence solver in DFSPH. The tutorial of Koschier, Bender, Solenthaler and Teschner (2019) writes the IISPH system in the operator form used here.

References

  1. Markus Ihmsen, Jens Cornelis, Barbara Solenthaler, Christopher Horvath and Matthias Teschner, Implicit incompressible SPH, IEEE Transactions on Visualization and Computer Graphics 20(3), 426-435, 2014, the derivation of the pressure system, the relaxed Jacobi solver with omega = 0.5 and the results
  2. 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 (the operator form of the IISPH system)
  3. Barbara Solenthaler and Renato Pajarola, Predictive-corrective incompressible SPH, ACM Transactions on Graphics 28(3), article 40, 2009, the whole paper (the density condition that IISPH writes as a linear system)

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