Algorithm Search⌘K

Algorithmadvanced

Weakly compressible SPH

Also called WCSPH.

An SPH fluid solver that computes pressure from density with a stiff Tait equation of state, so the fluid compresses by about 1% and needs no pressure solve, at the cost of small time steps.

Time
O(n + q) stepΘ(c / h) steps_per_unit_time
Space
O(n + q) extra
Where
c = the numerical speed of sound; h = the smoothing length; n = the number of particles; q = the number of neighbor pairs
Properties
conserves angular momentumconserves linear momentumdeterministicnot exactnot implicit
Origin
Joe J. Monaghan, Markus Becker, Matthias Teschner, 1994

Weakly compressible SPH (WCSPH) moves a fluid as a set of particles and computes the pressure of each particle directly from its density. It uses the stiff Tait equation of state p=B((ρ/ρ0)7−1)p = B((\rho/\rho_0)^7 - 1), so a small compression gives a large pressure that pushes the particles apart. With a numerical speed of sound cc about ten times the largest flow speed, the density stays within about 1% of the rest density ρ0\rho_0. There is no linear system to solve, but the time step must shrink as cc grows, and this is the main cost of the method.

In plain words

Think of the water as many small balls. Each ball looks at the balls near it and counts how crowded its place is. That count is its density. If the place is more crowded than water at rest, the ball gets a high pressure. High pressure pushes the neighbors away, and the push between two balls is equal and opposite. Gravity pulls all balls down. Then each ball changes its speed and moves a short distance, and the loop starts again. The pressure rule is very stiff, so water is squeezed only a little. A stiff rule needs very short steps, or the balls fly apart. So the method is simple to write, but it takes many steps for each second of motion.

The problem

The input is a set of nn particles with positions xix_i, velocities viv_i and masses mim_i, a rest density ρ0\rho_0, the smoothing length hh, gravity g=(0,−9.81)g = (0, -9.81) m/s², and a time step Δt\Delta t. The output is the state after one step. The particles carry the smoothed particle hydrodynamics approximation of the Euler equations of a fluid with a free surface, as one method for fluid simulation for animation. The page works in 2D, where a density is in kg/m².

The kernel is the cubic spline of Monaghan with support 2h2h and the 2D constant σ=10/(7π)\sigma = 10/(7\pi), so W(0,h)=0.454728/h2W(0, h) = 0.454728/h^2 (see SPH smoothing kernel). We write Wij=W(∣xi−xj∣,h)W_{ij} = W(|x_i - x_j|, h) and ∇Wij\nabla W_{ij} for its gradient with respect to xix_i. This gradient is antisymmetric: ∇Wji=−∇Wij\nabla W_{ji} = -\nabla W_{ij}, and it points along xi−xjx_i - x_j.

The algorithm

  1. WCSPH-STEP(x, v, m, Δt) ▷ one step, 2D
  2. 1P ← all pairs (i, j), i < j, with |xᵢ - xⱼ| < 2h ▷ uniform grid search
  3. 2for each i: ρᵢ ← Σⱼ mⱼ Wᵢⱼ ▷ j = i included
  4. 3for each i: pᵢ ← B ((ρᵢ / ρ₀)^γ - 1), B = ρ₀ c² / γ ▷ γ = 7
  5. 4for each i: aᵢ ← g
  6. 5for each pair (i, j) in P do
  7. 6s ← pᵢ / ρᵢ² + pⱼ / ρⱼ²
  8. 7if (vᵢ - vⱼ)·(xᵢ - xⱼ) < 0 then s ← s + Πᵢⱼ ▷ artificial viscosity
  9. 8aᵢ ← aᵢ - mⱼ s ∇Wᵢⱼ; aⱼ ← aⱼ + mᵢ s ∇Wᵢⱼ
  10. 9for each i: vᵢ ← vᵢ + Δt aᵢ ▷ symplectic Euler
  11. 10for each i: xᵢ ← xᵢ + Δt vᵢ ▷ uses the new velocity
  12. 11apply the walls

Line L1 puts the particles in a uniform grid with cells of side 2h2h and tests only the 3 by 3 block of cells around each particle. Line L2 is the SPH density sum, and line L3 is the Tait equation of state with γ=7\gamma = 7. Lines L5 to L8 add the pressure force of each pair once, with opposite signs on the two particles. The term in line L6 is the symmetric form of the pressure gradient −∇p/ρ-\nabla p / \rho. Line L7 adds the artificial viscosity of Monaghan, Πij=−αcμij/ρˉij\Pi_{ij} = -\alpha c \mu_{ij} / \bar\rho_{ij} with μij=h (vi−vj)⋅(xi−xj)/(∣xi−xj∣2+0.01h2)\mu_{ij} = h\,(v_i - v_j)\cdot(x_i - x_j) / (|x_i - x_j|^2 + 0.01 h^2) and ρˉij=(ρi+ρj)/2\bar\rho_{ij} = (\rho_i + \rho_j)/2. It acts only on pairs that approach each other, and α\alpha is a tuning constant (the tests use 0.1). Lines L9 and L10 are symplectic Euler: the position update uses the velocity of the new step. Line L11 is a simple wall model, outside the method: it clamps each particle into the box and removes the velocity into the wall. Better wall models use fixed boundary particles that add to the density.

The constants come from two rules. The speed of sound is c≈10 vmax⁡c \approx 10\,v_{\max}, where vmax⁡v_{\max} is the largest expected speed, for example (2gH)1/2(2 g H)^{1/2} for a column of height HH. The step obeys Δt≤λh/(c+vmax⁡)\Delta t \le \lambda h / (c + v_{\max}) with λ≈0.4\lambda \approx 0.4. Both are heuristics.

Example

Take two particles of mass 1 at x1=(0,0)x_1 = (0, 0) and x2=(1,0)x_2 = (1, 0), at rest, with h=1h = 1, ρ0=0.5\rho_0 = 0.5, c=1c = 1, no gravity and Δt=0.1\Delta t = 0.1. Then W(0)=0.454728W(0) = 0.454728 and W(1)=0.113682W(1) = 0.113682, so line L2 gives ρ1=ρ2=0.568411\rho_1 = \rho_2 = 0.568411. This is above ρ0\rho_0, so line L3 gives a positive pressure. At r=1r = 1 the kernel slope is dW/dr=−0.341046dW/dr = -0.341046, and ∇W12=(0.341046,0)\nabla W_{12} = (0.341046, 0). Line L8 pushes particle 1 to the left and particle 2 to the right with equal and opposite accelerations.

step x1x_1 v1v_1 ρ1\rho_1 p1p_1 a1a_1
0 (0,0)(0, 0) (0,0)(0, 0) 0.568411 0.103845 (−0.219233,0)(-0.219233, 0)
1 (−0.002192,0)(-0.002192, 0) (−0.021923,0)(-0.021923, 0) 0.566922 0.100657 (−0.211750,0)(-0.211750, 0)
2 (−0.006502,0)(-0.006502, 0) (−0.043098,0)(-0.043098, 0) 0.564033 0.094611 (−0.197610,0)(-0.197610, 0)

Particle 2 is the mirror image: x2=(1,0)−x1x_2 = (1, 0) - x_1 and v2=−v1v_2 = -v_1 in each row. The particles move apart, the density drops toward ρ0\rho_0, and the pressure falls. The sum m1v1+m2v2m_1 v_1 + m_2 v_2 stays 0.

Correctness

WCSPH does not solve the incompressible equations exactly. It solves a slightly compressible fluid, and the stiff equation of state keeps the compression small. Three things are exact for the discrete method.

  • Linear momentum. Without walls and gravity, each pair in line L8 adds −mimjs∇Wij-m_i m_j s\nabla W_{ij} to the momentum of ii and +mimjs∇Wij+m_i m_j s\nabla W_{ij} to that of jj. The sum is 0, so ∑imivi\sum_i m_i v_i does not change in line L9. This is a proved property.
  • Angular momentum. The pair force is parallel to xi−xjx_i - x_j, because ∇Wij\nabla W_{ij} is. So the internal torques cancel, and under symplectic Euler ∑imi xi×vi\sum_i m_i\, x_i \times v_i is the same after the step. This is a proved property.
  • Rest state. A particle with a density of exactly ρ0\rho_0 has p=0p = 0.

The size of the compression is an estimate, not a theorem. For a small relative compression ee, p≈ρ0c2ep \approx \rho_0 c^2 e. The pressure needed to turn a flow of speed vv is of order ρ0v2\rho_0 v^2, so ee is of order (v/c)2(v/c)^2, and c=10 vmax⁡c = 10\,v_{\max} gives about 1% (Monaghan 1994). The proof gives the momentum arguments in full.

Proof: The WCSPH step conserves linear and angular momentumfull

We use the notation of the page. The step has no walls (line L11 is skipped) and no gravity (g=0g = 0). The arithmetic is exact real arithmetic; in floating point the same identities hold up to rounding. The masses are positive and constant.

The pair term

Lemma 1. For i≠ji \ne j, ∇Wji=−∇Wij\nabla W_{ji} = -\nabla W_{ij}, and ∇Wij=f(rij) (xi−xj)\nabla W_{ij} = f(r_{ij})\,(x_i - x_j) for a scalar f(rij)f(r_{ij}) with rij=∣xi−xj∣r_{ij} = |x_i - x_j|.

Proof. Wij=W(rij,h)W_{ij} = W(r_{ij}, h) depends on xix_i only through rijr_{ij}. The chain rule gives ∇xiWij=W′(rij) (xi−xj)/rij\nabla_{x_i} W_{ij} = W'(r_{ij})\,(x_i - x_j)/r_{ij} for rij>0r_{ij} > 0, so f=W′/rf = W'/r. Swapping ii and jj changes the sign of xi−xjx_i - x_j and leaves rijr_{ij} fixed. At rij=0r_{ij} = 0 the gradient is 0, since the cubic spline has a smooth maximum there. □\square

Lemma 2. The scalar ss of lines L6 and L7 is symmetric in ii and jj.

Proof. pi/ρi2+pj/ρj2p_i/\rho_i^2 + p_j/\rho_j^2 is symmetric. In Πij\Pi_{ij}, the product (vi−vj)⋅(xi−xj)(v_i - v_j)\cdot(x_i - x_j) does not change when ii and jj swap, because both factors change sign. The same holds for ∣xi−xj∣2|x_i - x_j|^2 and ρˉij=(ρi+ρj)/2\bar\rho_{ij} = (\rho_i + \rho_j)/2. □\square

So the code may compute ss once per pair, as lines L5 to L8 do.

Linear momentum

Claim 1. Let P=∑imiviP = \sum_i m_i v_i. After lines L4 to L9, PP has the same value as before.

Proof. With g=0g = 0, line L4 sets every aia_i to 0. Each pair (i,j)(i, j) in line L8 adds −mjs∇Wij-m_j s \nabla W_{ij} to aia_i and +mis∇Wij+m_i s \nabla W_{ij} to aja_j. Its contribution to ∑kmkak\sum_k m_k a_k is −mimjs∇Wij+mjmis∇Wij=0-m_i m_j s\nabla W_{ij} + m_j m_i s \nabla W_{ij} = 0. So ∑kmkak=0\sum_k m_k a_k = 0 after line L8. Line L9 changes PP by Δt∑kmkak=0\Delta t \sum_k m_k a_k = 0. □\square

Angular momentum

In 2D the cross product of a=(ax,ay)a = (a_x, a_y) and b=(bx,by)b = (b_x, b_y) is the scalar a×b=axby−aybxa \times b = a_x b_y - a_y b_x. It is bilinear and a×a=0a \times a = 0.

Claim 2. The total torque ∑kxk×mkak\sum_k x_k \times m_k a_k of the forces of line L8 is 0.

Proof. The pair (i,j)(i, j) adds mimjsm_i m_j s times

−xi×∇Wij+xj×∇Wij=−(xi−xj)×∇Wij.-x_i \times \nabla W_{ij} + x_j \times \nabla W_{ij} = -(x_i - x_j)\times \nabla W_{ij}.

By Lemma 1, ∇Wij=f (xi−xj)\nabla W_{ij} = f\,(x_i - x_j), so this is −f (xi−xj)×(xi−xj)=0-f\,(x_i - x_j)\times(x_i - x_j) = 0. □\square

Claim 3. Let L=∑kmk xk×vkL = \sum_k m_k\, x_k \times v_k. After lines L9 and L10, LL has the same value as before.

Proof. Write x,vx, v for the old state and x′,v′x', v' for the new state, with v′=v+Δt av' = v + \Delta t\, a and x′=x+Δt v′x' = x + \Delta t\, v'. Then

∑kmk xk′×vk′=∑kmk xk×vk′+Δt∑kmk vk′×vk′=∑kmk xk×vk′,\sum_k m_k\, x'_k \times v'_k = \sum_k m_k\, x_k \times v'_k + \Delta t \sum_k m_k\, v'_k \times v'_k = \sum_k m_k\, x_k \times v'_k,

since vk′×vk′=0v'_k \times v'_k = 0. Next,

∑kmk xk×vk′=∑kmk xk×vk+Δt∑kxk×mkak=L,\sum_k m_k\, x_k \times v'_k = \sum_k m_k\, x_k \times v_k + \Delta t \sum_k x_k \times m_k a_k = L,

by Claim 2. □\square

Claim 3 uses the order of lines L9 and L10. The position update must use the new velocity; with the explicit Euler order (x′=x+Δt vx' = x + \Delta t\, v, then v′=v+Δtav' = v + \Delta t a) the term Δt2∑kmk vk×ak\Delta t^2 \sum_k m_k\, v_k \times a_k is left over, and LL drifts.

Consistency of the state equation

Claim 4. For ρ>0\rho > 0, the Tait pressure is 0 if and only if ρ=ρ0\rho = \rho_0, it is increasing in ρ\rho, and its derivative at ρ0\rho_0 is c2c^2.

Proof. p(ρ)=B((ρ/ρ0)γ−1)p(\rho) = B((\rho/\rho_0)^\gamma - 1) with B>0B > 0 and γ=7\gamma = 7 is 0 exactly at ρ=ρ0\rho = \rho_0. Its derivative is p′(ρ)=Bγργ−1/ρ0γ>0p'(\rho) = B\gamma\rho^{\gamma - 1}/\rho_0^\gamma > 0. At ρ0\rho_0 it is Bγ/ρ0=c2B\gamma/\rho_0 = c^2, since B=ρ0c2/γB = \rho_0 c^2/\gamma. □\square

So cc is the speed of sound of the discrete fluid near rest, and a compression e=(ρ−ρ0)/ρ0e = (\rho - \rho_0)/\rho_0 gives p=ρ0c2e+O(e2)p = \rho_0 c^2 e + O(e^2).

Claims 1 and 3 hold for any positions, velocities, masses and step size, and for any α≥0\alpha \ge 0. They are the momentum laws of a closed system, kept exactly by the discrete step. ■\blacksquare

Complexity

One step costs O(n+q)O(n + q) time for qq neighbor pairs: the grid search in line L1 visits each particle and its candidate pairs, and lines L2 to L10 do constant work per particle and per pair. If the density stays near ρ0\rho_0, each particle has a bounded number of neighbors in its disk of radius 2h2h, so q=O(n)q = O(n) and the step costs O(n)O(n). A test of all pairs would cost Θ(n2)\Theta(n^2). The memory is O(n+q)O(n + q) for the grid and the pair list.

The time step is the real cost. The step limit is proportional to h/ch/c, so a simulated time TT needs Θ(Tc/h)\Theta(T c / h) steps. Halving the density error needs about 2\sqrt{2} times larger cc, so about 2\sqrt{2} times more steps.

Properties

  • Explicit. No linear system and no iteration. Each step is one pass over the pairs.
  • Momentum. Linear and angular momentum are conserved by the internal forces (proved above). The walls of line L11 do not conserve them.
  • Compressible. The density error is of order (v/c)2(v/c)^2 and is not bounded by a user tolerance. The incompressible solvers PCISPH, IISPH and DFSPH iterate to a stated tolerance instead.
  • Stiff. The step limit falls as 1/c1/c. In a measured comparison, PCISPH took steps 35 times larger at the same 1% density error (Solenthaler and Pajarola 2009).
  • Tensile instability. Negative pressures at the free surface pull particles into clumps. Clamping pp at 0 removes the pull but makes the surface less smooth.

Variants and improvements

  • Clamped pressure. Set pi=max⁡(pi,0)p_i = \max(p_i, 0) in line L3. The tests use this for the dam break, so the free surface does not clump.
  • Other equations of state. The linear law p=c2(ρ−ρ0)p = c^2(\rho - \rho_0) is less stiff and allows larger steps for the same cc, but compresses more under the same load.
  • Physical viscosity. Replace Πij\Pi_{ij} by a Laplacian form for a given kinematic viscosity, as in smoothed particle hydrodynamics.
  • Incompressible solvers. PCISPH predicts and corrects the pressure, and IISPH and DFSPH solve a pressure equation. Incompressible SPH in engineering uses a projection.
  • Position based fluids. PBF enforces the density as a constraint on positions and takes large steps.

When to use it

Use WCSPH for small scenes, for teaching, and as a reference to test other SPH solvers. It is short to write, it runs on GPUs with one pass per step, and its forces conserve momentum. For large scenes with deep water, the stiff step limit makes it slow; use an incompressible solver. For a surface to render, add a surfacing step.

Pitfalls

  • Too small c. If cc is close to the flow speed, line L3 gives too little pressure and the fluid compresses by much more than 1%.
  • Too large step. A step above λh/(c+vmax⁡)\lambda h/(c + v_{\max}) makes lines L9 and L10 unstable, and the particles explode.
  • Missing neighbors at walls. With the clamp walls of line L11, particles near a wall have fewer neighbors, so line L2 gives a low density there. Boundary particles fix this.
  • One-sided pair update. Line L8 must change both particles by the same pair term. A loop over each particle with its own form of the term loses momentum conservation.
  • Wrong cell size. The grid of line L1 needs a cell side at least 2h2h, the kernel support. A smaller cell misses neighbors.

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.

sph.pyI0RawGitHub
# 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
weakly_compressible_sph.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weakly-compressible-sph/. The authors are listed in prov/XB7CYE.jsonl.
"""Weakly compressible SPH (WCSPH) in 2D with the Tait equation of state.

One step (Monaghan 1994; Becker and Teschner 2007):
1. find the neighbor pairs at a distance below 2h,
2. rho_i = sum_j m_j W_ij (j = i included),
3. p_i = B ((rho_i / rho0)^gamma - 1) with B = rho0 c^2 / gamma,
4. a_i = g - sum_j m_j (p_i / rho_i^2 + p_j / rho_j^2 + Pi_ij) grad W_ij,
   with the artificial viscosity Pi_ij of Monaghan,
5. symplectic Euler: v += dt a, then x += dt v.

The kernel, the neighbor search and the density come from the shared helper
sph.py. Each pair force is applied with opposite signs to i and j, so the
internal forces conserve linear and angular momentum.
"""

import math

from sph import density, grad_w, neighbor_pairs

GRAVITY = (0.0, -9.81)


def tait_b(rho0, c, gamma=7.0):
    """The stiffness B = rho0 c^2 / gamma of the Tait equation (Pa)."""
    return rho0 * c * c / gamma


def tait_pressure(rho, rho0, c, gamma=7.0, clamp=False):
    """p = B ((rho / rho0)^gamma - 1). With clamp, a negative p is set to 0."""
    p = tait_b(rho0, c, gamma) * ((rho / rho0) ** gamma - 1.0)
    if clamp and p < 0.0:
        return 0.0
    return p


def time_step_limit(h, c, v_max, lam=0.4):
    """The CFL type limit dt <= lam h / (c + v_max) (a heuristic, lam about 0.4)."""
    return lam * h / (c + v_max)


def accelerations(pos, vel, masses, h, rho0, c, gravity=GRAVITY, alpha=0.0,
                  gamma=7.0, clamp=False):
    """Return (acc, rho, p) for the particles. Cost O(n + q) for q pairs."""
    n = len(pos)
    pairs = neighbor_pairs(pos, 2.0 * h)  # @line L1
    rho = density(pos, masses, h)  # @line L2
    p = [tait_pressure(r, rho0, c, gamma, clamp) for r in rho]  # @line L3
    ax = [gravity[0]] * n  # @line L4
    ay = [gravity[1]] * n
    eps = 0.01 * h * h
    for i, j in pairs:  # @line L5
        dx = pos[i][0] - pos[j][0]
        dy = pos[i][1] - pos[j][1]
        gx, gy = grad_w((dx, dy), h)
        s = p[i] / (rho[i] * rho[i]) + p[j] / (rho[j] * rho[j])  # @line L6
        if alpha > 0.0:
            vx = vel[i][0] - vel[j][0]
            vy = vel[i][1] - vel[j][1]
            vr = vx * dx + vy * dy
            if vr < 0.0:  # @line L7
                mu = h * vr / (dx * dx + dy * dy + eps)
                s += -alpha * c * mu / (0.5 * (rho[i] + rho[j]))
        ax[i] -= masses[j] * s * gx  # @line L8
        ay[i] -= masses[j] * s * gy
        ax[j] += masses[i] * s * gx
        ay[j] += masses[i] * s * gy
    return list(zip(ax, ay)), rho, p


def apply_box(pos, vel, box, restitution=0.0):
    """Clamp the particles into box = (x0, y0, x1, y1) and reflect the normal velocity.

    This is a simple wall model (a heuristic), not part of WCSPH itself.
    """
    x0, y0, x1, y1 = box
    out_p, out_v = [], []
    for (x, y), (u, v) in zip(pos, vel):
        if x < x0:
            x, u = x0, -restitution * u if u < 0.0 else u
        elif x > x1:
            x, u = x1, -restitution * u if u > 0.0 else u
        if y < y0:
            y, v = y0, -restitution * v if v < 0.0 else v
        elif y > y1:
            y, v = y1, -restitution * v if v > 0.0 else v
        out_p.append((x, y))
        out_v.append((u, v))
    return out_p, out_v


def step(pos, vel, masses, dt, h, rho0, c, gravity=GRAVITY, alpha=0.0,
         gamma=7.0, clamp=False, box=None):
    """Advance one step of WCSPH. Returns (pos, vel, rho) with rho at the start."""
    acc, rho, _ = accelerations(pos, vel, masses, h, rho0, c, gravity, alpha,
                                gamma, clamp)
    vel = [(v[0] + dt * a[0], v[1] + dt * a[1]) for v, a in zip(vel, acc)]  # @line L9
    pos = [(x[0] + dt * v[0], x[1] + dt * v[1]) for x, v in zip(pos, vel)]  # @line L10
    if box is not None:  # @line L11
        pos, vel = apply_box(pos, vel, box)
    return pos, vel, rho


def momentum(vel, masses):
    """The total linear momentum sum_i m_i v_i."""
    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):
    """The total angular momentum sum_i m_i (x_i v_i,y - y_i v_i,x) about the origin."""
    return sum(m * (x[0] * v[1] - x[1] * v[0]) for m, x, v in zip(masses, pos, vel))


def max_speed(vel):
    """The largest particle speed."""
    return max((math.hypot(v[0], v[1]) for v in vel), default=0.0)
test_weakly_compressible_sph.py 234 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weakly-compressible-sph/. The authors are listed in prov/XB7CYE.jsonl.

import math
import random

import sph
import weakly_compressible_sph as wc

# ---------------------------------------------------------------- the shared helper sph.py


def brute_pairs(pos, radius):
    out = []
    for i in range(len(pos)):
        for j in range(i + 1, len(pos)):
            if (pos[i][0] - pos[j][0]) ** 2 + (pos[i][1] - pos[j][1]) ** 2 < radius * radius:
                out.append((i, j))
    return out


def test_kernel_check_value() -> None:
    assert abs(sph.SIGMA_2D - 0.454728) < 1e-6
    assert abs(sph.w_cubic(0.0, 1.0) - 0.454728) < 1e-6
    assert abs(sph.w_cubic(0.0, 0.5) - 0.454728 / 0.25) < 1e-5
    assert sph.w_cubic(2.0, 1.0) == 0.0
    assert sph.w_cubic(3.0, 1.0) == 0.0


def test_kernel_integrates_to_one() -> None:
    for h in (1.0, 0.05, 0.3):
        # Simpson's rule on [0, h] and [h, 2h] of W(r) 2 pi r dr.
        total = 0.0
        n = 200
        for a in (0.0, h):
            step = h / n
            s = 0.0
            for k in range(n + 1):
                r = a + k * step
                f = sph.w_cubic(r, h) * 2.0 * math.pi * r
                wgt = 1 if k in (0, n) else (4 if k % 2 else 2)
                s += wgt * f
            total += s * step / 3.0
        assert abs(total - 1.0) < 1e-3


def test_kernel_is_continuous_and_derivative_matches() -> None:
    h = 0.7
    for q in (1.0, 2.0):
        r = q * h
        assert abs(sph.w_cubic(r - 1e-9, h) - sph.w_cubic(r + 1e-9, h)) < 1e-7
    for q in (0.1, 0.5, 0.9, 1.1, 1.5, 1.9):
        r = q * h
        e = 1e-6
        num = (sph.w_cubic(r + e, h) - sph.w_cubic(r - e, h)) / (2 * e)
        assert abs(num - sph.dw_cubic(r, h)) < 1e-6 * max(1.0, abs(num))


def test_gradient_is_antisymmetric_and_numeric() -> None:
    rng = random.Random(7)
    h = 0.2
    assert sph.grad_w((0.0, 0.0), h) == (0.0, 0.0)
    for _ in range(200):
        d = (rng.uniform(-0.45, 0.45), rng.uniform(-0.45, 0.45))
        g = sph.grad_w(d, h)
        gm = sph.grad_w((-d[0], -d[1]), h)
        assert abs(g[0] + gm[0]) < 1e-12 and abs(g[1] + gm[1]) < 1e-12
        e = 1e-7
        for c in range(2):
            dp = list(d)
            dm = list(d)
            dp[c] += e
            dm[c] -= e
            num = (sph.w_cubic(math.hypot(*dp), h) - sph.w_cubic(math.hypot(*dm), h)) / (2 * e)
            assert abs(num - g[c]) < 1e-5 * max(1.0, abs(num))


def test_neighbor_pairs_equal_brute_force() -> None:
    rng = random.Random(2024)
    for radius in (0.05, 0.1, 0.25):
        pos = [(rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)) for _ in range(200)]
        assert sph.neighbor_pairs(pos, radius) == brute_pairs(pos, radius)
    # Points on cell borders and at exactly the radius.
    pos = [(0.0, 0.0), (0.1, 0.0), (0.2, 0.0), (0.1, 0.1), (-0.1, -0.1), (0.05, 0.05)]
    assert sph.neighbor_pairs(pos, 0.1) == brute_pairs(pos, 0.1)
    assert sph.neighbor_pairs([], 0.1) == []
    assert sph.neighbor_pairs([(0.3, 0.3)], 0.1) == []
    lists = sph.neighbor_lists(pos, 0.1)
    for i, nb in enumerate(lists):
        assert nb == [j for j in range(len(pos)) if j != i and ((pos[i][0] - pos[j][0]) ** 2 + (pos[i][1] - pos[j][1]) ** 2) < 0.01]


def test_density_equals_brute_force_sum() -> None:
    rng = random.Random(11)
    h = 0.06
    pos = [(rng.uniform(0, 0.6), rng.uniform(0, 0.6)) for _ in range(200)]
    ms = [rng.uniform(0.5, 1.5) for _ in pos]
    rho = sph.density(pos, ms, h)
    for i in range(len(pos)):
        ref = sum(ms[j] * sph.w_cubic(math.hypot(pos[i][0] - pos[j][0], pos[i][1] - pos[j][1]), h) for j in range(len(pos)))
        assert abs(rho[i] - ref) < 1e-9 * ref


def test_density_on_a_lattice_is_near_rest_density() -> None:
    dx = 0.02
    rho0 = 1000.0
    h = 1.3 * dx
    n = 15
    pos = [(i * dx, j * dx) for i in range(n) for j in range(n)]
    ms = [rho0 * dx * dx] * len(pos)
    rho = sph.density(pos, ms, h)
    for k, p in enumerate(pos):
        i, j = round(p[0] / dx), round(p[1] / dx)
        if 3 <= i < n - 3 and 3 <= j < n - 3:
            assert abs(rho[k] - rho0) < 0.01 * rho0


# ---------------------------------------------------------------- WCSPH


def random_blob(rng, n, dx, rho0):
    side = int(math.ceil(math.sqrt(n)))
    pos = []
    for k in range(n):
        i, j = k % side, k // side
        pos.append((i * dx + rng.uniform(-0.2, 0.2) * dx, j * dx + rng.uniform(-0.2, 0.2) * dx))
    vel = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
    ms = [rho0 * dx * dx * rng.uniform(0.8, 1.2) for _ in range(n)]
    return pos, vel, ms


def brute_accelerations(pos, vel, ms, h, rho0, c, gravity, alpha):
    n = len(pos)
    rho = [sum(ms[j] * sph.w_cubic(math.hypot(pos[i][0] - pos[j][0], pos[i][1] - pos[j][1]), h) for j in range(n)) for i in range(n)]
    b = rho0 * c * c / 7.0
    p = [b * ((r / rho0) ** 7 - 1.0) for r in rho]
    acc = []
    for i in range(n):
        ax, ay = gravity
        for j in range(n):
            if j == i:
                continue
            d = (pos[i][0] - pos[j][0], pos[i][1] - pos[j][1])
            g = sph.grad_w(d, h)
            s = p[i] / rho[i] ** 2 + p[j] / rho[j] ** 2
            vr = (vel[i][0] - vel[j][0]) * d[0] + (vel[i][1] - vel[j][1]) * d[1]
            if alpha > 0 and vr < 0:
                mu = h * vr / (d[0] ** 2 + d[1] ** 2 + 0.01 * h * h)
                s += -alpha * c * mu / (0.5 * (rho[i] + rho[j]))
            ax -= ms[j] * s * g[0]
            ay -= ms[j] * s * g[1]
        acc.append((ax, ay))
    return acc


def test_tait_check_values() -> None:
    assert abs(wc.tait_b(1000.0, 10.0) - 14285.714285714286) < 1e-9
    assert wc.tait_pressure(1000.0, 1000.0, 10.0) == 0.0
    p = wc.tait_pressure(1010.0, 1000.0, 10.0)
    assert abs(p - 14285.714285714286 * (1.01 ** 7 - 1.0)) < 1e-9
    assert abs(p - 1030.505030) < 1e-5
    # For a small compression e, p is close to c^2 rho0 e.
    assert abs(wc.tait_pressure(1000.1, 1000.0, 10.0) - 100.0 * 0.1) < 0.01
    assert wc.tait_pressure(990.0, 1000.0, 10.0) < 0.0
    assert wc.tait_pressure(990.0, 1000.0, 10.0, clamp=True) == 0.0
    assert abs(wc.time_step_limit(0.026, 18.0, 2.0) - 0.4 * 0.026 / 20.0) < 1e-15


def test_accelerations_equal_brute_force() -> None:
    rng = random.Random(5)
    dx = 0.02
    pos, vel, ms = random_blob(rng, 49, dx, 1000.0)
    h = 1.3 * dx
    for alpha in (0.0, 0.2):
        acc, _, _ = wc.accelerations(pos, vel, ms, h, 1000.0, 15.0, (0.0, -9.81), alpha)
        ref = brute_accelerations(pos, vel, ms, h, 1000.0, 15.0, (0.0, -9.81), alpha)
        for a, r in zip(acc, ref):
            scale = max(1.0, abs(r[0]), abs(r[1]))
            assert abs(a[0] - r[0]) < 1e-9 * scale and abs(a[1] - r[1]) < 1e-9 * scale


def test_momentum_is_conserved_without_walls_and_gravity() -> None:
    rng = random.Random(9)
    dx = 0.02
    pos, vel, ms = random_blob(rng, 64, dx, 1000.0)
    h = 1.3 * dx
    c = 15.0
    dt = wc.time_step_limit(h, c, 2.0)
    p0 = wc.momentum(vel, ms)
    l0 = wc.angular_momentum(pos, vel, ms)
    scale = sum(m * math.hypot(*v) for m, v in zip(ms, vel))
    lscale = sum(m * math.hypot(*x) * math.hypot(*v) for m, x, v in zip(ms, pos, vel))
    for _ in range(60):
        pos, vel, _ = wc.step(pos, vel, ms, dt, h, 1000.0, c, (0.0, 0.0), alpha=0.1)
    p1 = wc.momentum(vel, ms)
    l1 = wc.angular_momentum(pos, vel, ms)
    assert abs(p1[0] - p0[0]) < 1e-10 * scale and abs(p1[1] - p0[1]) < 1e-10 * scale
    assert abs(l1 - l0) < 1e-10 * lscale


def test_gravity_alone_gives_free_fall() -> None:
    pos = [(0.0, 0.0), (1.0, 0.0)]
    vel = [(0.0, 0.0), (0.0, 0.0)]
    ms = [1.0, 1.0]
    dt = 0.01
    for _ in range(10):
        pos, vel, _ = wc.step(pos, vel, ms, dt, 0.1, 1000.0, 10.0)
    # Symplectic Euler: v_n = n g dt and y_n = g dt^2 n (n + 1) / 2.
    assert abs(vel[0][1] + 9.81 * 0.1) < 1e-12
    assert abs(pos[1][1] + 9.81 * dt * dt * 55) < 1e-12


def test_small_dam_break_keeps_the_density_error_near_one_percent() -> None:
    dx = 0.02
    rho0 = 1000.0
    h = 1.3 * dx
    n_side = 8
    v_max = math.sqrt(2 * 9.81 * n_side * dx)
    c = 10.0 * v_max
    pos = [((i + 0.5) * dx, (j + 0.5) * dx) for i in range(n_side) for j in range(n_side)]
    vel = [(0.0, 0.0)] * len(pos)
    ms = [rho0 * dx * dx] * len(pos)
    dt = wc.time_step_limit(h, c, v_max)
    box = (0.0, 0.0, 0.4, 0.4)
    worst_mean = 0.0
    for _ in range(280):
        pos, vel, rho = wc.step(pos, vel, ms, dt, h, rho0, c, alpha=0.1, clamp=True, box=box)
        worst_mean = max(worst_mean, sum(max(r - rho0, 0.0) for r in rho) / (rho0 * len(rho)))
    assert worst_mean < 0.01
    assert wc.max_speed(vel) < 1.2 * v_max
    # The column has collapsed: the front moved to the right.
    assert max(x for x, _ in pos) > n_side * dx + 0.05
    for x, y in pos:
        assert 0.0 <= x <= 0.4 and 0.0 <= y <= 0.4

History

Lucy (1977) and Gingold and Monaghan (1977) introduced SPH for astrophysics. Monaghan (1992) reviewed the method, with the cubic spline kernel and the artificial viscosity. Monaghan (1994) used the Tait equation of state to simulate free surface flows with a small compression. Becker and Teschner (2007) used the weakly compressible form with γ=7\gamma = 7 for fluids in computer graphics. Later solvers in graphics, such as PCISPH (2009), IISPH (2014) and DFSPH (2015), keep the SPH sums but replace the equation of state by a pressure iteration.

References

  1. Joe J. Monaghan, Simulating free surface flows with SPH, Journal of Computational Physics 110(2), 399-406, 1994, the whole paper (the Tait equation of state and the choice of the speed of sound)
  2. Markus Becker and Matthias Teschner, Weakly compressible SPH for free surface flows, Symposium on Computer Animation 2007, 209-217, the whole paper (the Tait equation with gamma = 7 for graphics fluids)
  3. Joe J. Monaghan, Smoothed particle hydrodynamics, Annual Review of Astronomy and Astrophysics 30, 543-574, 1992, the whole paper (the cubic spline kernel, the symmetric pressure term and the artificial viscosity)
  4. 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 sections on the state equation and on time stepping

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.step
  • a full proof of time.steps_per_unit_time
  • 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