Algorithm Search⌘K

Algorithmresearch

Divergence-free SPH

Also called DFSPH.

An SPH fluid solver with two Jacobi-like solvers in each step, one that keeps the density at the rest density and one that makes the velocity field divergence free.

Time
O(n + q) iterationO(k (n + q)) step
Space
O(n + q) extra
Where
k = the number of solver iterations in a step; n = the number of particles; q = the number of neighbor pairs
Properties
conserves angular momentumconserves linear momentumdeterministicnot exactiterative
Origin
Jan Bender, Dan Koschier, 2015

Divergence-free SPH (DFSPH) is an SPH fluid solver with two solvers in each step. The density solver changes the velocities until the predicted density of each particle is at most the rest density ρ0\rho_0, on average within a tolerance η\eta. After the particles move, the divergence solver changes the velocities until the rate of change of the density is near 0, so the velocity field is divergence free. Both solvers use one factor αi\alpha_i per particle that depends only on the positions, so it is computed once for each solver. The divergence solver is the main change from IISPH, and the paper reports that it allows larger steps with fewer iterations.

In plain words

Think of the water as many small balls. First every ball gets its speed from gravity. Then the method checks which balls would end up too crowded, and gives those balls a push away from their neighbors. It does this a few times, until almost no ball would be too crowded. Now the balls move. At the new places, the method checks if the balls are still coming closer to each other. If they are, it gives them a second kind of push, so they stop coming closer. This second step stops the crowding before it starts in the next step, so the next step needs less work.

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 tolerances η\eta and ηv\eta_v. The output is the state after one step. 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 density rate and the factor of the paper are

DρiDt=∑jmj(vi−vj)⋅∇Wij,αi=ρi∣∑jmj∇Wij∣2+∑j∣mj∇Wij∣2.\frac{D\rho_i}{Dt} = \sum_j m_j (v_i - v_j)\cdot\nabla W_{ij}, \qquad \alpha_i = \frac{\rho_i}{\left|\sum_j m_j\nabla W_{ij}\right|^2 + \sum_j\left|m_j\nabla W_{ij}\right|^2}.

A stiffness κi\kappa_i on each particle changes the velocities by

vi←vi−Δt∑jmj(κiρi+κjρj)∇Wij.v_i \leftarrow v_i - \Delta t\sum_j m_j\left(\frac{\kappa_i}{\rho_i} + \frac{\kappa_j}{\rho_j}\right)\nabla W_{ij}.

This is the symmetric SPH pressure force with the pressure pi=κiρip_i = \kappa_i\rho_i.

The algorithm

  1. DFSPH-STEP(x, v, Δt)
  2. 1P ← neighbor pairs; ∇Wᵢⱼ; ρᵢ; αᵢ at x
  3. 2for each i: v*ᵢ ← vᵢ + Δt g
  4. 3while iter < 2 or (err > η ρ₀ and iter < max) do
  5. 4for each i: eᵢ ← max(ρᵢ + Δt (Dρᵢ/Dt)(v*) - ρ₀, 0); err ← mean of eᵢ
  6. 5for each i: κᵢ ← eᵢ αᵢ / Δt²
  7. 6for each i: v*ᵢ ← v*ᵢ - Δt Σⱼ mⱼ (κᵢ/ρᵢ + κⱼ/ρⱼ) ∇Wᵢⱼ
  8. 7for each i: xᵢ ← xᵢ + Δt v*ᵢ, clamped to the walls
  9. 8P ← neighbor pairs; ∇Wᵢⱼ; ρᵢ; αᵢ at the new x
  10. 9while iter < 1 or (err > η_v ρ₀ and iter < max) do
  11. 10for each i: dᵢ ← max((Dρᵢ/Dt)(v*), 0); err ← Δt × mean of dᵢ
  12. 11for each i: κᵢ ← dᵢ αᵢ / Δt
  13. 12for each i: v*ᵢ ← v*ᵢ - Δt Σⱼ mⱼ (κᵢ/ρᵢ + κⱼ/ρⱼ) ∇Wᵢⱼ
  14. 13return x, v ← v*

Line L1 computes the pairs, the densities and the factors. In a full run they come from line L8 of the last step, as in the loop of the paper. Line L2 adds the non-pressure forces; the tests use gravity only. Lines L3 to L6 are the density solver. Line L4 predicts the density with the current velocities, and line L5 picks κi\kappa_i so that particle ii alone would remove its error exactly. Line L7 moves the particles with symplectic Euler. Line L8 finds the new neighbors and the new factors. Lines L9 to L12 are the divergence solver, with κi\kappa_i picked so that particle ii alone would make its density rate 0. The minimum of 2 density passes and 1 divergence pass is the rule of the paper. Both solvers here count only compression (ei>0e_i > 0 and di>0d_i > 0), so a particle at the free surface gets no pull. This is a choice of this page. The tolerance ηv\eta_v is a fraction of ρ0\rho_0 per step. The step size comes from a CFL condition Δt≤λ Δx/vmax\Delta t \le \lambda\,\Delta x / v_{max} with λ=0.4\lambda = 0.4 and a cap.

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. The table follows the predicted density ρ∗\rho^* of line L4 in the density solver.

pass mean error largest ρ∗\rho^* ρ∗\rho^* of the center compressed particles
1 3.124% 1109.56 1109.56 9 of 25
2 0% 934.50 757.72 0 of 25

Pass 1 starts from rest, so it sees the squeeze of the block: the 9 inner particles are above ρ0\rho_0. Line L5 gives each of them the stiffness that would remove its own error if it were alone. But all 9 push at the same time, so the center particle gets the pushes of its neighbors too, and its predicted density falls far below ρ0\rho_0. Pass 2 sees no compression, and the solver stops. In a running simulation the error of each step is small, and this overshoot is small too.

Correctness

The density solver and the divergence solver are Jacobi-like iterations without a proof of convergence in general. The tests check these facts, and the proof gives the arguments:

  • One particle. With equal masses, a stiffness κi\kappa_i from line L5 on particle ii alone moves its predicted density to exactly ρ0\rho_0. The stiffness of line L11 alone moves its density rate to exactly 0.
  • Jacobi with weight 1. With equal masses and without the max of line L4, one pass of lines L4 to L6 is one Jacobi pass with ω=1\omega = 1 on the pressure system of IISPH, with pi=ρiκip_i = \rho_i\kappa_i summed over the passes. IISPH uses ω=0.5\omega = 0.5; the weight 1 explains the overshoot of the example.
  • Exit conditions. If a solver stops before the cap, its mean error is at most its tolerance.
  • Momentum. The update of lines L6 and L12 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 κ\kappa.
Proof: The factor alpha, the link to Jacobi, the exit conditions and the momentum laws of DFSPHfull

We use the notation of the page. The arithmetic is exact real arithmetic. A sum over jj is over the neighbors of ii, the pairs and the gradients are those of line L1 (density solver) or line L8 (divergence solver), and they do not change inside a solver. The kernel is radial, so ∇Wij\nabla W_{ij} is parallel to xi−xjx_i - x_j and ∇Wji=−∇Wij\nabla W_{ji} = -\nabla W_{ij}. Write Gi=∑jmj∇WijG_i = \sum_j m_j\nabla W_{ij} and Si=∑jmj∣∇Wij∣2S_i = \sum_j m_j|\nabla W_{ij}|^2. DFSPH has no general proof that its solvers converge; the claims below hold for every run.

The effect of one stiffness

Lemma 1. Apply the update of line L6 with κi=c\kappa_i = c and κj=0\kappa_j = 0 for j≠ij \ne i. Then Dρi/DtD\rho_i/Dt changes by −Δt (c/ρi) (∣Gi∣2+miSi)-\Delta t\,(c/\rho_i)\,(|G_i|^2 + m_i S_i).

Proof. The update changes viv_i by −Δt (c/ρi) Gi-\Delta t\,(c/\rho_i)\,G_i. For a neighbor jj, only the term of ii in its sum has κi\kappa_i, so vjv_j changes by −Δt mi(c/ρi)∇Wji=Δt mi(c/ρi)∇Wij-\Delta t\,m_i(c/\rho_i)\nabla W_{ji} = \Delta t\,m_i(c/\rho_i)\nabla W_{ij}. Other particles do not change. Dρi/Dt=∑jmj(vi−vj)⋅∇WijD\rho_i/Dt = \sum_j m_j(v_i - v_j)\cdot\nabla W_{ij} is linear in the velocities, so it changes by

∑jmj(−ΔtcρiGi−Δt micρi∇Wij)⋅∇Wij=−Δtcρi(∣Gi∣2+miSi).  □\sum_j m_j\left(-\Delta t\frac{c}{\rho_i}G_i - \Delta t\,m_i\frac{c}{\rho_i}\nabla W_{ij}\right)\cdot\nabla W_{ij} = -\Delta t\frac{c}{\rho_i}\left(|G_i|^2 + m_i S_i\right). \;\square

Claim 2. Let all masses be equal and let the denominator of αi\alpha_i be positive. With κi=eiαi/Δt2\kappa_i = e_i\alpha_i/\Delta t^2 on ii alone, where ei=ρi+Δt Dρi/Dt−ρ0e_i = \rho_i + \Delta t\,D\rho_i/Dt - \rho_0, the new predicted density ρi+Δt Dρi/Dt\rho_i + \Delta t\,D\rho_i/Dt is ρ0\rho_0. With κi=(Dρi/Dt) αi/Δt\kappa_i = (D\rho_i/Dt)\,\alpha_i/\Delta t on ii alone, the new Dρi/DtD\rho_i/Dt is 0.

Proof. With equal masses mm, ∑j∣mj∇Wij∣2=mSi=miSi\sum_j|m_j\nabla W_{ij}|^2 = m S_i = m_i S_i, so αi=ρi/(∣Gi∣2+miSi)\alpha_i = \rho_i/(|G_i|^2 + m_i S_i). By Lemma 1 with c=eiαi/Δt2c = e_i\alpha_i/\Delta t^2, the predicted density changes by Δt⋅(−Δt (c/ρi)(∣Gi∣2+miSi))=−Δt2c/αi=−ei\Delta t \cdot(-\Delta t\,(c/\rho_i)(|G_i|^2 + m_i S_i)) = -\Delta t^2 c/\alpha_i = -e_i. By Lemma 1 with c=(Dρi/Dt)αi/Δtc = (D\rho_i/Dt)\alpha_i/\Delta t, the rate changes by −Δt c/αi=−Dρi/Dt-\Delta t\,c/\alpha_i = -D\rho_i/Dt. □\square

Let KiK_i be the sum of the stiffness values κi\kappa_i of the density passes so far, and pi=ρiKip_i = \rho_i K_i. The update of line L6 is linear in κ\kappa, so after the passes vi∗=viadv+Δt aipv^*_i = v^{adv}_i + \Delta t\,a^p_i with

aip=−∑jmj(Kiρi+Kjρj)∇Wij=−∑jmj(piρi2+pjρj2)∇Wij,a^p_i = -\sum_j m_j\left(\frac{K_i}{\rho_i} + \frac{K_j}{\rho_j}\right)\nabla W_{ij} = -\sum_j m_j\left(\frac{p_i}{\rho_i^2} + \frac{p_j}{\rho_j^2}\right)\nabla W_{ij},

the pressure acceleration of the IISPH page, and viadv=vi+Δt gv^{adv}_i = v_i + \Delta t\,g. So the predicted density of line L4 is ρi+Δt Dρi/Dt(vadv)+Δt2∑jmj(aip−ajp)⋅∇Wij=ρiadv+(Ap)i\rho_i + \Delta t\,D\rho_i/Dt(v^{adv}) + \Delta t^2\sum_j m_j(a^p_i - a^p_j)\cdot\nabla W_{ij} = \rho^{adv}_i + (Ap)_i in the notation of IISPH, and ρi∗−ρ0=(Ap)i−si\rho^*_i - \rho_0 = (Ap)_i - s_i.

Claim 3. With equal masses and without the max of line L4, one density pass changes pip_i by (si−(Ap)i)/aii(s_i - (Ap)_i)/a_{ii}, where aii=−(Δt2/ρi2)(∣Gi∣2+miSi)a_{ii} = -(\Delta t^2/\rho_i^2)(|G_i|^2 + m_i S_i) is the IISPH diagonal. This is one Jacobi pass with weight ω=1\omega = 1.

Proof. The pass adds κi=(ρi∗−ρ0)αi/Δt2\kappa_i = (\rho^*_i - \rho_0)\alpha_i/\Delta t^2 to KiK_i, so it adds ρiκi\rho_i\kappa_i to pip_i. With equal masses, ρiαi/Δt2=ρi2/(Δt2(∣Gi∣2+miSi))=−1/aii\rho_i\alpha_i/\Delta t^2 = \rho_i^2/(\Delta t^2(|G_i|^2 + m_i S_i)) = -1/a_{ii}. So pip_i changes by −(ρi∗−ρ0)/aii=(si−(Ap)i)/aii-(\rho^*_i - \rho_0)/a_{ii} = (s_i - (Ap)_i)/a_{ii}. □\square

Exit conditions

Claim 4. If the density solver stops before the cap, the mean of max⁡(ρi∗−ρ0,0)\max(\rho^*_i - \rho_0, 0) in its last pass is at most ηρ0\eta\rho_0. If the divergence solver stops before the cap, Δt\Delta t times the mean of max⁡(Dρi/Dt,0)\max(D\rho_i/Dt, 0) in its last pass is at most ηvρ0\eta_v\rho_0.

Proof. After the minimum number of passes and below the cap, the loops of lines L3 and L9 stop only when err is at most the tolerance times ρ0\rho_0, and err is the mean of line L4 or Δt\Delta t times the mean of line L10. □\square

Momentum

Claim 5. With g=0g = 0, no walls and any stiffness values, 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=κi/ρi+κj/ρj=cjic_{ij} = \kappa_i/\rho_i + \kappa_j/\rho_j = c_{ji}. In line L6 or L12, each pair changes mivim_i v_i by −Δt mimjcij∇Wij-\Delta t\,m_i m_j c_{ij}\nabla W_{ij} and mjvjm_j v_j by −Δt mjmicij∇Wji=+Δt mimjcij∇Wij-\Delta t\,m_j m_i c_{ij}\nabla W_{ji} = +\Delta t\,m_i m_j c_{ij}\nabla W_{ij}. The sum is 0, so every update keeps ∑imivi\sum_i m_i v_i. The change of the angular momentum at fixed positions is −Δt mimjcij(xi−xj)×∇Wij=0-\Delta t\,m_i m_j c_{ij}(x_i - x_j)\times\nabla W_{ij} = 0, because the two vectors are parallel. So the updates of the density solver keep ∑imixi×vi∗\sum_i m_i x_i \times v^*_i at the old positions, and the updates of the divergence solver keep it at the new positions. Line L7 gives xi′=xi+Δt vi∗x'_i = x_i + \Delta t\,v^*_i, so ∑imixi′×vi∗=∑imixi×vi∗\sum_i m_i x'_i \times v^*_i = \sum_i m_i x_i \times v^*_i, since vi∗×vi∗=0v^*_i \times v^*_i = 0. With g=0g = 0, line L2 does not change vv. So each part of the step keeps both sums. ■\blacksquare

Complexity

One pass of either solver costs O(n+q)O(n + q) time for qq pairs: one sweep over the pairs for the density rate and one for the update. A step with kk passes in total costs O(k(n+q))O(k(n + q)), and lines L1 and L8 add O(n+q)O(n + q) each. With a density near ρ0\rho_0, q=O(n)q = O(n). The memory is O(n+q)O(n + q). The number kk is a measurement. In the small dam break of the tests, 50 steps of 0.004 s with η=ηv=0.1%\eta = \eta_v = 0.1\% take 2 density passes and at most 4 divergence passes per step, and the measured mean compression stays below 0.7%.

Properties

  • Factor once per solver. αi\alpha_i depends only on the positions, so lines L1 and L8 compute it once, and each pass costs two sweeps over the pairs.
  • Two errors. The density solver removes the density error, and the divergence solver removes the rate at which it grows. Without the divergence solver, the density solver must remove the error that the velocity field builds up in each step.
  • Momentum. Linear and angular momentum are kept by both updates (proved).
  • Overshoot. With weight 1, a strongly squeezed block overshoots in one pass, as in the example.
  • Larger steps. The paper reports larger steps and less total work than IISPH and PCISPH on its scenes. These are measurements.

Variants and improvements

  • Warm start. The paper starts each solver with the stiffness values of the last step, which lowers the number of passes. The code here starts from zero.
  • Relaxation. A weight below 1 on line L5 lowers the overshoot and needs more passes, as in IISPH.
  • Boundary particles. Fixed particles on the walls take part in ρi\rho_i, αi\alpha_i and the update, and give smoother walls than the clamp of line L7.
  • Without the divergence solver. Lines L1 to L7 alone are a density solver of the IISPH kind; see IISPH and PCISPH.

When to use it

Use DFSPH for SPH liquids with a small density error at large steps, in particular in deep or fast scenes, where the divergence solver saves passes in the density solver. For small scenes, IISPH is simpler. For a solver on positions, see position based fluids.

Pitfalls

  • Old factors in the divergence solver. Line L8 must compute αi\alpha_i at the new positions. Factors of line L1 belong to the old neighbors.
  • Small denominator. A particle with no neighbors has a denominator 0 in αi\alpha_i. Clamp the denominator at a small value, as the code does with 10−610^{-6}, or skip the particle.
  • Different powers of the step. Line L5 divides by Δt2\Delta t^2 and line L11 by Δt\Delta t. With the same power in both, one solver is off by a factor Δt\Delta t.
  • Divergence of the wrong velocities. Line L10 uses the velocities after line L7, at the new positions. Using the velocities of line L2 repeats the density solve.
  • Surface pull. Without the max of lines L4 and L10, particles at the free surface get a negative stiffness and the surface clumps.

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.

divergence_free_sph.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/divergence-free-sph/. The authors are listed in prov/9VJ2XT.jsonl.
"""Divergence-free SPH (DFSPH) in 2D, after Bender and Koschier (2015).

Each step runs two solvers that share the factor

    alpha_i = rho_i / (|sum_j m_j grad W_ij|^2 + sum_j |m_j grad W_ij|^2).

The density solver uses kappa_i = (rho*_i - rho0) alpha_i / dt^2 with the
predicted density rho*_i = rho_i + dt sum_j m_j (v_i - v_j) . grad W_ij. The
divergence solver uses kappa_i = (D rho_i / Dt) alpha_i / dt. Both apply

    v_i <- v_i - dt sum_j m_j (kappa_i / rho_i + kappa_j / rho_j) grad W_ij.

This file counts only compression (rho* > rho0, D rho / Dt > 0) and has no
warm start; both are choices of this file.
"""

import math

from sph import density, grad_w, neighbor_pairs

GRAVITY = (0.0, -9.81)
ALPHA_EPS = 1e-6


class Neighborhood:
    """The pairs, their gradients, the densities and the factors alpha_i."""

    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
        self.alpha = alpha_factors(self)


def alpha_factors(nb):
    """alpha_i = rho_i / (|sum_j m_j grad W_ij|^2 + sum_j |m_j grad W_ij|^2), denominator at least 1e-6."""
    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] * m[j] * g2
        sq[j] += m[i] * m[i] * g2
    return [nb.rho[i] / max(sx[i] ** 2 + sy[i] ** 2 + sq[i], ALPHA_EPS) for i in range(nb.n)]


def density_rate(nb, vel):
    """D rho_i / Dt = sum_j m_j (v_i - v_j) . grad W_ij."""
    out = [0.0] * nb.n
    m = nb.m
    for (i, j), (gx, gy) in zip(nb.pairs, nb.grads):
        d = (vel[i][0] - vel[j][0]) * gx + (vel[i][1] - vel[j][1]) * gy
        out[i] += m[j] * d
        out[j] += m[i] * d
    return out


def apply_kappa(nb, vel, kappa, dt):
    """v_i <- v_i - dt sum_j m_j (kappa_i / rho_i + kappa_j / rho_j) grad W_ij."""
    vx = [v[0] for v in vel]
    vy = [v[1] for v in vel]
    rho, m = nb.rho, nb.m
    for (i, j), (gx, gy) in zip(nb.pairs, nb.grads):
        s = kappa[i] / rho[i] + kappa[j] / rho[j]
        vx[i] -= dt * m[j] * s * gx
        vy[i] -= dt * m[j] * s * gy
        vx[j] += dt * m[i] * s * gx
        vy[j] += dt * m[i] * s * gy
    return list(zip(vx, vy))


def density_solver(nb, vel, dt, rho0, eta=0.001, min_iter=2, max_iter=100):
    """Make the predicted density at most rho0 on average. Returns (vel, iterations, mean error / rho0)."""
    it = 0
    err = float("inf")
    while it < min_iter or (err > eta * rho0 and it < max_iter):  # @line L3
        rate = density_rate(nb, vel)
        e = [max(nb.rho[i] + dt * rate[i] - rho0, 0.0) for i in range(nb.n)]  # @line L4
        err = sum(e) / nb.n
        kappa = [e[i] * nb.alpha[i] / (dt * dt) for i in range(nb.n)]  # @line L5
        vel = apply_kappa(nb, vel, kappa, dt)  # @line L6
        it += 1
    return vel, it, err / rho0


def divergence_solver(nb, vel, dt, rho0, eta_v=0.001, min_iter=1, max_iter=100):
    """Make the positive density rate small. Returns (vel, iterations, mean dt rate / rho0)."""
    it = 0
    err = float("inf")
    while it < min_iter or (err > eta_v * rho0 and it < max_iter):  # @line L9
        rate = [max(r, 0.0) for r in density_rate(nb, vel)]  # @line L10
        err = dt * sum(rate) / nb.n
        kappa = [rate[i] * nb.alpha[i] / dt for i in range(nb.n)]  # @line L11
        vel = apply_kappa(nb, vel, kappa, dt)  # @line L12
        it += 1
    return vel, it, err / rho0


def clamp_box(pos, vel, box):
    x0, y0, x1, y1 = box
    out_p, out_v = [], []
    for (x, y), (u, v) in zip(pos, vel):
        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
        out_p.append((x, y))
        out_v.append((u, v))
    return out_p, out_v


def step(pos, vel, masses, dt, h, rho0, gravity=GRAVITY, eta=0.001, eta_v=0.001,
         max_iter=100, box=None):
    """One DFSPH step. Returns (pos, vel, (density iterations, density error, divergence iterations, divergence error))."""
    nb = Neighborhood(pos, masses, h)  # @line L1
    vel = [(v[0] + dt * gravity[0], v[1] + dt * gravity[1]) for v in vel]  # @line L2
    vel, it_d, err_d = density_solver(nb, vel, dt, rho0, eta, 2, max_iter)
    pos = [(pos[i][0] + dt * vel[i][0], pos[i][1] + dt * vel[i][1]) for i in range(nb.n)]  # @line L7
    if box is not None:
        pos, vel = clamp_box(pos, vel, box)
    nb = Neighborhood(pos, masses, h)  # @line L8
    vel, it_v, err_v = divergence_solver(nb, vel, dt, rho0, eta_v, 1, max_iter)
    return pos, vel, (it_d, err_d, it_v, err_v)  # @line L13


def cfl_step(dx, v_max, lam=0.4, dt_max=0.005):
    """dt = min(lam dx / v_max, dt_max)."""
    if v_max <= 0.0:
        return dt_max
    return min(lam * dx / v_max, dt_max)


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 max_speed(vel):
    return max((math.hypot(v[0], v[1]) for v in vel), default=0.0)
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_divergence_free_sph.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/divergence-free-sph/. The authors are listed in prov/9VJ2XT.jsonl.

import random

import divergence_free_sph as df

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 jittered(rng, n_side, spacing):
    return [(x + rng.uniform(-0.1, 0.1) * DX, y + rng.uniform(-0.1, 0.1) * DX) for x, y in lattice(n_side, spacing)]


def test_alpha_matches_a_direct_sum() -> None:
    rng = random.Random(1)
    pos = jittered(rng, 5, 0.9 * DX)
    ms = [M * rng.uniform(0.9, 1.1) for _ in pos]
    nb = df.Neighborhood(pos, ms, H)
    for i in range(nb.n):
        gx = gy = sq = 0.0
        for j in range(nb.n):
            if j != i:
                g = df.grad_w((pos[i][0] - pos[j][0], pos[i][1] - pos[j][1]), H)
                gx += ms[j] * g[0]
                gy += ms[j] * g[1]
                sq += (ms[j] * g[0]) ** 2 + (ms[j] * g[1]) ** 2
        assert abs(nb.alpha[i] - nb.rho[i] / (gx * gx + gy * gy + sq)) < 1e-12 * nb.alpha[i]


def test_one_kappa_removes_its_own_density_error() -> None:
    # With equal masses, kappa on particle i alone moves the predicted density
    # rho_i + dt D rho_i / Dt exactly to rho0, because the prediction is linear in v.
    rng = random.Random(2)
    pos = jittered(rng, 5, 0.9 * DX)
    ms = [M] * len(pos)
    nb = df.Neighborhood(pos, ms, H)
    dt = 0.003
    vel = [(rng.uniform(-0.2, 0.2), rng.uniform(-0.2, 0.2)) for _ in pos]
    rate = df.density_rate(nb, vel)
    for i in (0, 7, 12):
        e = nb.rho[i] + dt * rate[i] - RHO0
        kappa = [0.0] * nb.n
        kappa[i] = e * nb.alpha[i] / (dt * dt)
        new_rate = df.density_rate(nb, df.apply_kappa(nb, vel, kappa, dt))
        assert abs(nb.rho[i] + dt * new_rate[i] - RHO0) < 1e-9 * RHO0
        # The same for the divergence form: D rho_i / Dt goes to 0.
        kappa[i] = rate[i] * nb.alpha[i] / dt
        new_rate = df.density_rate(nb, df.apply_kappa(nb, vel, kappa, dt))
        assert abs(new_rate[i]) < 1e-9 * abs(rate[i])


def test_momentum_is_conserved_without_walls_and_gravity() -> None:
    rng = random.Random(3)
    pos = jittered(rng, 6, 0.85 * DX)
    ms = [M * rng.uniform(0.9, 1.1) for _ in pos]
    vel = [(rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)) for _ in pos]
    p0 = df.momentum(vel, ms)
    l0 = df.angular_momentum(pos, vel, ms)
    for _ in range(6):
        pos, vel, _ = df.step(pos, vel, ms, 0.002, H, RHO0, gravity=(0.0, 0.0))
    p1 = df.momentum(vel, ms)
    l1 = df.angular_momentum(pos, vel, ms)
    scale = sum(m * (abs(v[0]) + abs(v[1])) 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_both_tolerances() -> 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)
    worst = 0.0
    t = 0.0
    while t < 0.2:
        dt = df.cfl_step(DX, df.max_speed(vel), 0.4, 0.004)
        pos, vel, (it_d, err_d, it_v, err_v) = df.step(pos, vel, ms, dt, H, RHO0, eta=0.001, eta_v=0.001, box=box)
        t += dt
        assert 2 <= it_d < 100 and err_d <= 0.001
        assert 1 <= it_v < 100 and err_v <= 0.001
        worst = max(worst, df.mean_compression(pos, ms, H, RHO0))
    assert worst < 0.01
    assert max(x for x, _ in pos) > n_side * DX + 0.1


def test_cfl_step() -> None:
    assert df.cfl_step(0.02, 0.0) == 0.005
    assert abs(df.cfl_step(0.02, 4.0) - 0.002) < 1e-15
    assert df.cfl_step(0.02, 0.1) == 0.005

History

PCISPH (Solenthaler and Pajarola 2009) and IISPH (Ihmsen et al. 2014) solve for a pressure that keeps the density near ρ0\rho_0. Bender and Koschier (2015) added a second solver for the velocity divergence, with one factor αi\alpha_i for both solvers. Their open source library SPlisHSPlasH and the tutorial of Koschier, Bender, Solenthaler and Teschner (2019) put DFSPH next to the other pressure solvers.

References

  1. Jan Bender and Dan Koschier, Divergence-free smoothed particle hydrodynamics, Symposium on Computer Animation 2015, 147-155, the factor alpha, the two solvers, the simulation loop 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
  3. 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 whole paper (the density system that the density solver of DFSPH also solves)

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