Algorithm Search⌘K

Algorithmadvanced

Position based fluids

Also called PBF.

A particle fluid solver that keeps the SPH density of each particle near the rest density as a constraint on positions, solved by a few Jacobi passes of position based dynamics.

Time
O(n + q) passO(k (n + q)) step
Space
O(n + q) extra
Where
k = the number of solver passes; n = the number of particles; q = the number of neighbor pairs
Properties
not conserves angular momentumconserves linear momentumdeterministicnot exactiterative
Origin
Miles Macklin, Matthias Müller, 2013

Position based fluids (PBF) is a particle fluid solver in the frame of position based dynamics. Each particle has one constraint: its SPH density, computed at the predicted positions, must equal the rest density ρ0\rho_0. A few passes move the predicted positions to satisfy these constraints, all particles at once, like a Jacobi step. The velocity is then the change of position divided by the step. An artificial pressure term keeps particles from clumping, and XSPH viscosity smooths the velocities. The method is stable at the large steps of real time graphics, at the cost of a fixed and inexact number of passes.

In plain words

Think of the water as many small balls. First every ball moves with gravity alone, to a guessed place. At the guessed places, the method counts how crowded each ball is. Where a ball is too crowded, it and its neighbors are pushed apart by a small amount, all at the same time. After a few rounds of pushes, the balls are close to the right crowding. The speed of each ball is then the distance it went in this step, divided by the time. A small extra push keeps balls from sticking together, and a small blend of the speeds of neighbors makes the flow smooth.

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 kernel radius hh, gravity g=(0,−9.81)g = (0, -9.81) m/s², the step Δt\Delta t and the number of passes kk. The output is the state after one step. This is one method for fluid simulation for animation. PBF uses two kernels of the paper of Müller, Charypar and Gross (2003), both with support hh. In 2D,

Wpoly6(r)=4πh8(h2−r2)3,Wspiky(r)=10πh5(h−r)3,W_{poly6}(r) = \frac{4}{\pi h^8}(h^2 - r^2)^3, \qquad W_{spiky}(r) = \frac{10}{\pi h^5}(h - r)^3,

for r<hr < h, so 4/π=1.2732404/\pi = 1.273240 and 10/π=3.18309910/\pi = 3.183099. The density uses poly6, ρi=∑jm Wpoly6(∣xi−xj∣)\rho_i = \sum_j m\,W_{poly6}(|x_i - x_j|) with j=ij = i included, and the gradients use spiky, ∇Wij=∇Wspiky(xi−xj)\nabla W_{ij} = \nabla W_{spiky}(x_i - x_j). The constraint and its gradients are

Ci=ρiρ0−1,∇xiCi=mρ0∑j∇Wij,∇xjCi=−mρ0∇Wij.C_i = \frac{\rho_i}{\rho_0} - 1, \qquad \nabla_{x_i} C_i = \frac{m}{\rho_0}\sum_j \nabla W_{ij}, \qquad \nabla_{x_j} C_i = -\frac{m}{\rho_0}\nabla W_{ij}.

The algorithm

  1. PBF-STEP(x, v, Δt)
  2. 1for each i: vᵢ ← vᵢ + Δt g; x*ᵢ ← xᵢ + Δt vᵢ, clamped to the walls
  3. 2P ← neighbor pairs of x* within h
  4. 3repeat k times
  5. 4for each i: Cᵢ ← ρᵢ(x*) / ρ₀ - 1, or max(0, ρᵢ(x*) / ρ₀ - 1)
  6. 5for each i: λᵢ ← -Cᵢ / (Σₖ |∇ₖ Cᵢ|² + ε)
  7. 6for each i: Δxᵢ ← (m/ρ₀) Σⱼ (λᵢ + λⱼ + s_corr,ᵢⱼ) ∇Wᵢⱼ
  8. 7for each i: x*ᵢ ← x*ᵢ + Δxᵢ, clamped to the walls
  9. 8for each i: vᵢ ← (x*ᵢ - xᵢ) / Δt
  10. 9for each i: vᵢ ← vᵢ + c Σⱼ (m/ρ₀) (vⱼ - vᵢ) W_poly6(|x*ᵢ - x*ⱼ|)
  11. 10for each i: xᵢ ← x*ᵢ

Line L1 is the prediction of position based dynamics. Line L2 finds the neighbors once per step, as in the paper; pairs that come within hh during the passes are missed until the next step. Line L5 is the Newton step for one constraint, Ci+∇Ci⋅Δx=0C_i + \nabla C_i\cdot\Delta x = 0 with Δx\Delta x along ∇Ci\nabla C_i, softened by the relaxation ε\varepsilon. Without ε\varepsilon, a particle with few neighbors has a denominator near 0 and a huge λi\lambda_i. Line L6 adds the corrections of the constraint of ii and of the constraints of its neighbors. The artificial pressure of the paper is

scorr,ij=−ks(Wpoly6(∣xi−xj∣)Wpoly6(Δq))ns,s_{corr,ij} = -k_s\left(\frac{W_{poly6}(|x_i - x_j|)}{W_{poly6}(\Delta q)}\right)^{n_s},

with ks=0.1k_s = 0.1, ns=4n_s = 4 and ∣Δq∣|\Delta q| from 0.1h0.1h to 0.3h0.3h in the paper. These are tuning values. It is a small push between close pairs, and it makes the flow less likely to clump at the free surface. Line L8 is the velocity of position based dynamics. Line L9 is XSPH viscosity, which pulls the velocity of each particle toward the mean of its neighbors. The paper then adds vorticity confinement to put back rotation lost to damping; the code here does not.

Line L4 gives two forms. The paper uses Ci=ρi/ρ0−1C_i = \rho_i/\rho_0 - 1 for all particles. The code also has the one-sided form max⁡(0,Ci)\max(0, C_i), which pushes only where the fluid is compressed, and the tests use it. In the units of this page λ\lambda has the unit m², so the code scales ε\varepsilon and ksk_s by the denominator D0=∑k∣∇kCi∣2D_0 = \sum_k|\nabla_k C_i|^2 of a particle in a full lattice: ε=0.01D0\varepsilon = 0.01 D_0 and ks=0.1/D0k_s = 0.1/D_0. This scaling and c=0.01c = 0.01 are tuning choices of this page.

Example

Take Δx=0.02\Delta x = 0.02 m, h=1.8Δxh = 1.8\Delta x, ρ0=1000\rho_0 = 1000 kg/m² and m=ρ0Δx2=0.4m = \rho_0\Delta x^2 = 0.4 kg. A particle in a full lattice of spacing Δx\Delta x then has the density 1000.53 kg/m² and D0=1102.68D_0 = 1102.68 m⁻². Put 25 particles at rest on a 5 by 5 lattice with spacing 0.95Δx0.95\Delta x, and set g=0g = 0, Δt=0.004\Delta t = 0.004 s, ε=0.01D0\varepsilon = 0.01D_0 and no artificial pressure. The table gives the mean of max⁡(0,Ci)\max(0, C_i) at line L4 of each pass, for the one-sided and the two-sided form.

pass one-sided mean one-sided largest two-sided mean
1 4.313% 11.98% 4.313%
2 0.520% 3.251% 8.319%
3 0.173% 1.084% 3.531%
4 0.058% 0.365% 8.304%
5 0.020% 0.124% 3.731%
6 0.007% 0.042% 6.778%

The one-sided form lowers the error by about a factor of 3 in each pass. In the two-sided form, the particles on the edge of the small block have a low density, so their constraints pull them inward, and the error goes up and down. In a large body of water most particles are inside, and the paper uses the artificial pressure against this pull.

Correctness

PBF is an inexact solver with a fixed number of passes, and it has no proof of convergence. These things hold, and the proof gives the arguments:

  • The Newton step. For one constraint alone and ε=0\varepsilon = 0, the move Δxk=λi∇kCi\Delta x_k = \lambda_i\nabla_k C_i of line L5 makes the linear model of CiC_i zero. It is the shortest such move.
  • Linear momentum. Each pair term of lines L6 and L9 is opposite on ii and jj. So without walls and gravity, the step keeps ∑imvi\sum_i m v_i exactly, for any kk, ε\varepsilon and scorrs_{corr}.
  • Angular momentum. It is not kept exactly. The pair moves of line L6 are along xi∗−xj∗x^*_i - x^*_j, and the angular momentum of line L8 is measured about the old positions xix_i; the difference is of order Δt\Delta t times the moves.

The tests check the kernels, the value of λ\lambda, the drop of the error over the passes, the momentum law and a small dam break.

Proof: The Newton step of one constraint and the linear momentum law of PBFfull

We use the notation of the page. All particles have the mass m>0m > 0, and the arithmetic is exact real arithmetic. The pairs PP of line L2 are unordered and fixed during the step. The spiky kernel is radial, so ∇Wij\nabla W_{ij} is parallel to xi∗−xj∗x^*_i - x^*_j and ∇Wji=−∇Wij\nabla W_{ji} = -\nabla W_{ij}. PBF runs a fixed number of passes and has no proof of convergence; the claims below hold for every run.

The Newton step of one constraint

Claim 1. Let ε=0\varepsilon = 0 and let the gradient ∇Ci=(∇xkCi)k\nabla C_i = (\nabla_{x_k} C_i)_k be nonzero. Among all moves Δx=(Δxk)k\Delta x = (\Delta x_k)_k with Ci+∇Ci⋅Δx=0C_i + \nabla C_i\cdot\Delta x = 0, the shortest is Δxk=λi∇xkCi\Delta x_k = \lambda_i\nabla_{x_k} C_i with λi=−Ci/∑k∣∇xkCi∣2\lambda_i = -C_i/\sum_k|\nabla_{x_k} C_i|^2.

Proof. The set of moves with Ci+∇Ci⋅Δx=0C_i + \nabla C_i\cdot\Delta x = 0 is an affine hyperplane with normal ∇Ci\nabla C_i. The point of a hyperplane closest to the origin lies along its normal, so Δx=λ∇Ci\Delta x = \lambda\nabla C_i for a scalar λ\lambda. Then Ci+λ∣∇Ci∣2=0C_i + \lambda|\nabla C_i|^2 = 0 gives λ=λi\lambda = \lambda_i. □\square

With ε>0\varepsilon > 0, the same move with λi=−Ci/(∣∇Ci∣2+ε)\lambda_i = -C_i/(|\nabla C_i|^2 + \varepsilon) leaves the linear model at Ci ε/(∣∇Ci∣2+ε)C_i\,\varepsilon/(|\nabla C_i|^2 + \varepsilon), a fraction of CiC_i.

Claim 2. The move of line L6 is the sum over constraints of these moves: Δxi=λi∇xiCi+∑jλj∇xiCj\Delta x_i = \lambda_i\nabla_{x_i} C_i + \sum_j \lambda_j\nabla_{x_i} C_j, plus the artificial pressure term.

Proof. By the gradients of the page, λi∇xiCi=(m/ρ0)∑jλi∇Wij\lambda_i\nabla_{x_i} C_i = (m/\rho_0)\sum_j \lambda_i\nabla W_{ij}. For a neighbor jj, ∇xiCj=−(m/ρ0)∇Wji=(m/ρ0)∇Wij\nabla_{x_i} C_j = -(m/\rho_0)\nabla W_{ji} = (m/\rho_0)\nabla W_{ij}. The sum is (m/ρ0)∑j(λi+λj)∇Wij(m/\rho_0)\sum_j(\lambda_i + \lambda_j)\nabla W_{ij}, which is line L6 without scorrs_{corr}. □\square

In the one-sided form, a constraint with Ci≤0C_i \le 0 has λi=0\lambda_i = 0 and adds no move.

Linear momentum

Claim 3. With g=0g = 0 and no walls, one step keeps ∑imvi\sum_i m v_i, for any number of passes, any ε≥0\varepsilon \ge 0, any scorrs_{corr}, either form of line L4 and any cc.

Proof. Let X=∑imxi∗X = \sum_i m x^*_i. In line L6 the pair {i,j}\{i, j\} adds (m/ρ0)s ∇Wij(m/\rho_0)s\,\nabla W_{ij} to Δxi\Delta x_i and (m/ρ0)s ∇Wji=−(m/ρ0)s ∇Wij(m/\rho_0)s\,\nabla W_{ji} = -(m/\rho_0)s\,\nabla W_{ij} to Δxj\Delta x_j, with the same scalar s=λi+λj+scorr,ijs = \lambda_i + \lambda_j + s_{corr,ij}, because scorrs_{corr} depends only on ∣xi∗−xj∗∣|x^*_i - x^*_j|. So ∑imΔxi=0\sum_i m\Delta x_i = 0, and line L7 does not change XX. After line L1, X=∑im(xi+Δt vi)X = \sum_i m(x_i + \Delta t\,v_i). By line L8, ∑imvi′=(X−∑imxi)/Δt=∑imvi\sum_i m v_i' = (X - \sum_i m x_i)/\Delta t = \sum_i m v_i, the momentum after line L1, which equals the momentum before the step since g=0g = 0. In line L9, the pair adds c(m/ρ0)W(vj−vi)c(m/\rho_0)W(v_j - v_i) to viv_i and c(m/ρ0)W(vi−vj)c(m/\rho_0)W(v_i - v_j) to vjv_j, with the same WW for both, and the sum is 0. □\square

Angular momentum

The angular momentum is not kept exactly. With g=0g = 0, no walls and c=0c = 0, the angular momentum after the step is L′=∑im xi′×vi′L' = \sum_i m\,x'_i\times v'_i with xi′=xi∗x'_i = x^*_i and vi′=(xi∗−xi)/Δtv'_i = (x^*_i - x_i)/\Delta t, so L′=∑im xi×xi∗/ΔtL' = \sum_i m\,x_i\times x^*_i/\Delta t. Before the passes, the same formula with the predicted positions of line L1 gives LL. The difference is ∑im xi×(sum of the moves of i)/Δt\sum_i m\,x_i\times(\text{sum of the moves of }i)/\Delta t. A pair adds (m/ρ0)s m (xi−xj)×∇Wij/Δt(m/\rho_0)s\,m\,(x_i - x_j)\times\nabla W_{ij}/\Delta t, and ∇Wij\nabla W_{ij} is parallel to xi∗−xj∗=xi−xj+Δt(vi−vj)x^*_i - x^*_j = x_i - x_j + \Delta t(v_i - v_j), so the term is −(m/ρ0)s m (vi−vj)×∇Wij-(m/\rho_0)s\,m\,(v_i - v_j)\times\nabla W_{ij} and is not 0 in general. ■\blacksquare

Complexity

One pass costs O(n+q)O(n + q) time for qq pairs: line L4 is one sweep over the pairs for the densities, line L5 one sweep for the gradients and line L6 one sweep for the moves. A step costs O(k(n+q))O(k(n + q)), and the neighbor search adds O(n+q)O(n + q). With a density near ρ0\rho_0, q=O(n)q = O(n). The memory is O(n+q)O(n + q). In the small dam break of the tests, 4 passes per step at Δt=0.004\Delta t = 0.004 s keep the measured mean compression below 0.2% (a measurement).

Properties

  • Stable at large steps. The passes move positions by bounded amounts, and the velocity is derived from them, so there is no stiff force. This is a heuristic; the paper shows it on its scenes.
  • Inexact. A fixed number of passes leaves an error. Jacobi passes remove local errors fast and smooth errors slowly, so the error grows with the depth of the fluid (a heuristic).
  • Parallel. Each pass is a Jacobi step, with no order between particles, so it runs well on a GPU.
  • Momentum. Linear momentum is kept (proved); angular momentum is not kept exactly.
  • Damping. Position based velocities and XSPH lose energy, which is why the paper adds vorticity confinement.

Variants and improvements

  • Vorticity confinement. The paper computes the vorticity ωi=∑j(vj−vi)×∇Wij\omega_i = \sum_j (v_j - v_i)\times\nabla W_{ij} and adds a force along the gradient of ∣ω∣|\omega|; see vorticity confinement.
  • One-sided constraints. max⁡(0,Ci)\max(0, C_i), as in line L4, avoids the inward pull at a free surface.
  • Gauss-Seidel order. Projecting the constraints one at a time converges faster per pass but is hard to run in parallel.
  • Unified solvers. The same loop can hold cloth, rigid and granular constraints next to the fluid ones, in the position based dynamics frame.
  • Pressure solvers. PCISPH, IISPH and DFSPH iterate on pressures until a tolerance, instead of a fixed number of passes on positions.

When to use it

Use PBF for real time particle fluids, for example in games, where a fixed cost per step and stability matter more than an exact density. For offline work with a tolerance on the density error, use IISPH or DFSPH.

Pitfalls

  • No relaxation. With ε=0\varepsilon = 0 in line L5, a particle with one neighbor gets a very large λ\lambda and the step explodes.
  • Kernel support. Poly6 and spiky here have support hh, not 2h2h as the cubic spline. Line L2 must search with radius hh.
  • Gradient of poly6. Line L6 uses the spiky gradient. The poly6 gradient is 0 at r=0r = 0 and gives almost no push between very close particles.
  • Velocity before the walls. Line L7 clamps the positions, and line L8 then gives the velocity. Clamping only the velocity leaves particles in the walls.
  • Units of the tuning values. ε\varepsilon and ksk_s of lines L5 and L6 have the unit of λ\lambda. Values from the paper change meaning when mm, ρ0\rho_0 or hh change.

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.

position_based_fluids.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/position-based-fluids/. The authors are listed in prov/XH6YNA.jsonl.
"""Position based fluids (PBF) in 2D, after Macklin and Mueller (2013).

The density constraint of particle i is C_i = rho_i / rho0 - 1 with
rho_i = sum_j m W_poly6(x_i - x_j). Each solver pass computes

    lambda_i = -C_i / (sum_k |grad_k C_i|^2 + eps),
    dx_i = (m / rho0) sum_j (lambda_i + lambda_j + s_corr_ij) grad W_spiky(x_i - x_j),
    s_corr_ij = -k (W_poly6(x_i - x_j) / W_poly6(dq))^n,

and moves the predicted positions by dx. Both kernels have support h. All
particles have the same mass m. The 2D kernels are

    W_poly6(r) = 4 / (pi h^8) (h^2 - r^2)^3,  W_spiky(r) = 10 / (pi h^5) (h - r)^3.

The values of eps, k and the XSPH weight c are tuning constants; the defaults
here are scaled by the denominator D0 of a particle in a full lattice.
"""

import math

from sph import neighbor_pairs

GRAVITY = (0.0, -9.81)
POLY6_2D = 4.0 / math.pi  # times 1 / h^8
SPIKY_2D = 10.0 / math.pi  # times 1 / h^5


def w_poly6(r2, h):
    """W_poly6 as a function of r^2, support h."""
    if r2 >= h * h:
        return 0.0
    return POLY6_2D / h ** 8 * (h * h - r2) ** 3


def w_spiky(r, h):
    if r >= h:
        return 0.0
    return SPIKY_2D / h ** 5 * (h - r) ** 3


def grad_spiky(dx, dy, h):
    """Gradient of W_spiky(|x|) at x = (dx, dy); (0, 0) at x = 0."""
    r = math.hypot(dx, dy)
    if r == 0.0 or r >= h:
        return (0.0, 0.0)
    s = -3.0 * SPIKY_2D / h ** 5 * (h - r) ** 2 / r
    return (s * dx, s * dy)


def densities(pos, pairs, m, h):
    rho = [m * w_poly6(0.0, h)] * len(pos)
    for i, j in pairs:
        w = m * w_poly6((pos[i][0] - pos[j][0]) ** 2 + (pos[i][1] - pos[j][1]) ** 2, h)
        rho[i] += w
        rho[j] += w
    return rho


def full_lattice_denominator(dx, h, m, rho0):
    """D0 = sum_k |grad_k C_i|^2 for a particle in a full square lattice of spacing dx."""
    s = 0.0
    n = int(h / dx) + 1
    for a in range(-n, n + 1):
        for b in range(-n, n + 1):
            g = grad_spiky(a * dx, b * dx, h)
            s += g[0] * g[0] + g[1] * g[1]
    return (m / rho0) ** 2 * s


def lambdas(pos, pairs, m, h, rho0, eps, one_sided=False):
    """lambda_i = -C_i / (sum_k |grad_k C_i|^2 + eps). Returns (lambda, C)."""
    n = len(pos)
    rho = densities(pos, pairs, m, h)
    c = [r / rho0 - 1.0 for r in rho]  # @line L4
    if one_sided:
        c = [max(t, 0.0) for t in c]
    gx = [0.0] * n
    gy = [0.0] * n
    sq = [0.0] * n
    f = m / rho0
    for i, j in pairs:
        g = grad_spiky(pos[i][0] - pos[j][0], pos[i][1] - pos[j][1], h)
        gx[i] += f * g[0]
        gy[i] += f * g[1]
        gx[j] -= f * g[0]
        gy[j] -= f * g[1]
        g2 = f * f * (g[0] * g[0] + g[1] * g[1])
        sq[i] += g2
        sq[j] += g2
    lam = [-c[i] / (gx[i] ** 2 + gy[i] ** 2 + sq[i] + eps) for i in range(n)]  # @line L5
    return lam, c


def corrections(pos, pairs, lam, m, h, rho0, k=0.0, dq=0.2, power=4):
    """dx_i = (m / rho0) sum_j (lambda_i + lambda_j + s_corr_ij) grad W_spiky(x_i - x_j)."""
    n = len(pos)
    out_x = [0.0] * n
    out_y = [0.0] * n
    f = m / rho0
    w_dq = w_poly6((dq * h) ** 2, h)
    for i, j in pairs:
        ddx = pos[i][0] - pos[j][0]
        ddy = pos[i][1] - pos[j][1]
        s = lam[i] + lam[j]
        if k != 0.0:
            s -= k * (w_poly6(ddx * ddx + ddy * ddy, h) / w_dq) ** power
        g = grad_spiky(ddx, ddy, h)
        out_x[i] += f * s * g[0]
        out_y[i] += f * s * g[1]
        out_x[j] -= f * s * g[0]
        out_y[j] -= f * s * g[1]
    return list(zip(out_x, out_y))


def clamp_box(pos, box):
    x0, y0, x1, y1 = box
    return [(min(max(x, x0), x1), min(max(y, y0), y1)) for x, y in pos]


def xsph(pos, vel, pairs, m, h, rho0, c):
    """v_i <- v_i + c sum_j (m / rho0) (v_j - v_i) W_poly6(x_i - x_j)."""
    vx = [v[0] for v in vel]
    vy = [v[1] for v in vel]
    f = c * m / rho0
    for i, j in pairs:
        w = f * w_poly6((pos[i][0] - pos[j][0]) ** 2 + (pos[i][1] - pos[j][1]) ** 2, h)
        du = vel[j][0] - vel[i][0]
        dv = vel[j][1] - vel[i][1]
        vx[i] += w * du
        vy[i] += w * dv
        vx[j] -= w * du
        vy[j] -= w * dv
    return list(zip(vx, vy))


def step(pos, vel, m, dt, h, rho0, eps, iterations=4, k=0.0, dq=0.2, power=4, c_xsph=0.01,
         gravity=GRAVITY, box=None, one_sided=False):
    """One PBF step. Returns (pos, vel, constraint errors C of each pass before its correction)."""
    n = len(pos)
    vel = [(v[0] + dt * gravity[0], v[1] + dt * gravity[1]) for v in vel]  # @line L1
    pred = [(pos[i][0] + dt * vel[i][0], pos[i][1] + dt * vel[i][1]) for i in range(n)]
    if box is not None:
        pred = clamp_box(pred, box)
    pairs = neighbor_pairs(pred, h)  # @line L2
    history = []
    for _ in range(iterations):  # @line L3
        lam, c = lambdas(pred, pairs, m, h, rho0, eps, one_sided)
        history.append(c)
        dp = corrections(pred, pairs, lam, m, h, rho0, k, dq, power)  # @line L6
        pred = [(pred[i][0] + dp[i][0], pred[i][1] + dp[i][1]) for i in range(n)]  # @line L7
        if box is not None:
            pred = clamp_box(pred, box)
    vel = [((pred[i][0] - pos[i][0]) / dt, (pred[i][1] - pos[i][1]) / dt) for i in range(n)]  # @line L8
    if c_xsph != 0.0:
        vel = xsph(pred, vel, pairs, m, h, rho0, c_xsph)  # @line L9
    return pred, vel, history  # @line L10


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


def mean_abs(c):
    return sum(abs(t) for t in c) / len(c)


def mean_positive(c):
    return sum(max(t, 0.0) for t in c) / len(c)
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_position_based_fluids.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/position-based-fluids/. The authors are listed in prov/XH6YNA.jsonl.

import math
import random

import position_based_fluids as pb

DX = 0.02
H = 1.8 * DX
RHO0 = 1000.0
M = RHO0 * DX * DX
D0 = pb.full_lattice_denominator(DX, H, M, RHO0)


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 radial_integral(f, h, n=2000):
    # Simpson rule for the integral of f(r) 2 pi r dr over [0, h].
    s = 0.0
    for k in range(n + 1):
        r = h * k / n
        w = 1 if k in (0, n) else (4 if k % 2 else 2)
        s += w * f(r) * 2.0 * math.pi * r
    return s * h / (3 * n)


def test_kernels_integrate_to_one() -> None:
    assert abs(pb.POLY6_2D - 1.273240) < 1e-6
    assert abs(pb.SPIKY_2D - 3.183099) < 1e-6
    for h in (0.5, H):
        assert abs(radial_integral(lambda r: pb.w_poly6(r * r, h), h) - 1.0) < 1e-9
        assert abs(radial_integral(lambda r: pb.w_spiky(r, h), h) - 1.0) < 1e-9


def test_spiky_gradient_matches_finite_differences() -> None:
    rng = random.Random(1)
    e = 1e-7
    for _ in range(20):
        x, y = rng.uniform(-H, H), rng.uniform(-H, H)
        if not 0.05 * H < math.hypot(x, y) < 0.95 * H:
            continue
        g = pb.grad_spiky(x, y, H)
        fx = (pb.w_spiky(math.hypot(x + e, y), H) - pb.w_spiky(math.hypot(x - e, y), H)) / (2 * e)
        fy = (pb.w_spiky(math.hypot(x, y + e), H) - pb.w_spiky(math.hypot(x, y - e), H)) / (2 * e)
        scale = abs(g[0]) + abs(g[1])
        assert abs(g[0] - fx) < 1e-6 * scale and abs(g[1] - fy) < 1e-6 * scale


def test_lambda_matches_a_direct_sum() -> None:
    rng = random.Random(2)
    pos = [(x + rng.uniform(-0.2, 0.2) * DX, y + rng.uniform(-0.2, 0.2) * DX) for x, y in lattice(5, 0.9 * DX)]
    pairs = pb.neighbor_pairs(pos, H)
    eps = 0.01 * D0
    lam, c = pb.lambdas(pos, pairs, M, H, RHO0, eps)
    f = M / RHO0
    for i in range(len(pos)):
        rho = sum(M * pb.w_poly6((pos[i][0] - q[0]) ** 2 + (pos[i][1] - q[1]) ** 2, H) for q in pos)
        gi = [0.0, 0.0]
        sq = 0.0
        for j, q in enumerate(pos):
            if j != i:
                g = pb.grad_spiky(pos[i][0] - q[0], pos[i][1] - q[1], H)
                gi[0] += f * g[0]
                gi[1] += f * g[1]
                sq += f * f * (g[0] ** 2 + g[1] ** 2)
        ci = rho / RHO0 - 1.0
        assert abs(c[i] - ci) < 1e-12
        assert abs(lam[i] - (-ci / (gi[0] ** 2 + gi[1] ** 2 + sq + eps))) < 1e-9 * abs(lam[i]) + 1e-18


def test_passes_lower_the_constraint_error_of_a_squeezed_block() -> None:
    rng = random.Random(3)
    pos = [(x + rng.uniform(-0.05, 0.05) * DX, y + rng.uniform(-0.05, 0.05) * DX) for x, y in lattice(10, 0.93 * DX)]
    vel = [(0.0, 0.0)] * len(pos)
    _, _, hist = pb.step(pos, vel, M, 0.004, H, RHO0, 0.01 * D0, iterations=6, gravity=(0.0, 0.0), c_xsph=0.0,
                         one_sided=True)
    errs = [pb.mean_positive(c) for c in hist]
    assert errs[0] > 0.02
    for a, b in zip(errs, errs[1:]):
        assert b < a
    assert errs[-1] < 0.2 * errs[0]


def test_linear_momentum_is_conserved_without_walls_and_gravity() -> None:
    rng = random.Random(4)
    pos = [(x + rng.uniform(-0.2, 0.2) * DX, y + rng.uniform(-0.2, 0.2) * DX) for x, y in lattice(7, 0.85 * DX)]
    vel = [(rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)) for _ in pos]
    p0 = pb.momentum(vel, M)
    for one_sided in (False, True):
        for _ in range(5):
            pos, vel, _ = pb.step(pos, vel, M, 0.003, H, RHO0, 0.01 * D0, iterations=4, k=0.1 / D0,
                                  gravity=(0.0, 0.0), one_sided=one_sided)
    p1 = pb.momentum(vel, M)
    scale = M * sum(abs(v[0]) + abs(v[1]) for v in vel)
    assert abs(p1[0] - p0[0]) < 1e-10 * scale and abs(p1[1] - p0[1]) < 1e-10 * scale


def test_small_dam_break_keeps_a_low_density_error() -> None:
    n_side = 8
    pos = lattice(n_side, DX)
    vel = [(0.0, 0.0)] * len(pos)
    box = (0.0, 0.0, 0.4, 0.4)
    worst = 0.0
    for _ in range(60):
        pos, vel, _ = pb.step(pos, vel, M, 0.004, H, RHO0, 0.01 * D0, iterations=4, k=0.1 / D0, box=box,
                              one_sided=True)
        rho = pb.densities(pos, pb.neighbor_pairs(pos, H), M, H)
        worst = max(worst, sum(max(r / RHO0 - 1.0, 0.0) for r in rho) / len(rho))
        assert all(0.0 <= x <= 0.4 and 0.0 <= y <= 0.4 for x, y in pos)
    assert worst < 0.01
    assert max(x for x, _ in pos) > n_side * DX + 0.1

History

Position based dynamics (Müller, Heidelberger, Hennix and Ratcliff 2007) moves positions to satisfy constraints and derives velocities from the moves. Macklin and Müller (2013) added the SPH density as a constraint, with the poly6 and spiky kernels of Müller, Charypar and Gross (2003), XSPH viscosity of Monaghan (1989) and vorticity confinement. The method ran fluids with large steps in real time on a GPU, and the same loop became part of unified particle solvers for games.

References

  1. Miles Macklin and Matthias Müller, Position based fluids, ACM Transactions on Graphics 32(4), article 104, 2013, the density constraint, the relaxation eps, the artificial pressure s_corr with k = 0.1 and n = 4, XSPH viscosity, vorticity confinement and the simulation loop
  2. Matthias Müller, Bruno Heidelberger, Marcus Hennix and John Ratcliff, Position based dynamics, Journal of Visual Communication and Image Representation 18(2), 109-118, 2007, the whole paper (the position based loop and the constraint projection)
  3. Matthias Müller, David Charypar and Markus Gross, Particle-based fluid simulation for interactive applications, Symposium on Computer Animation 2003, 154-159, the poly6 and spiky kernels
  4. Joe J. Monaghan, On the problem of penetration in particle methods, Journal of Computational Physics 82(1), 1-15, 1989, the whole paper (the XSPH velocity correction)

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.pass
  • 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