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
- Model
- Real RAM
- Properties
- conserves angular momentumconserves linear momentumdeterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , on average within a tolerance . 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 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 particles with masses , positions and velocities , the rest density , the smoothing length , gravity m/s², the step and the tolerances and . The output is the state after one step. This is one method for fluid simulation for animation. The kernel is the 2D cubic spline with support , as on WCSPH, is its gradient with respect to , and with included.
The density rate and the factor of the paper are
A stiffness on each particle changes the velocities by
This is the symmetric SPH pressure force with the pressure .
The algorithm
DFSPH-STEP(x, v, Δt)- 1
P ← neighbor pairs; ∇Wᵢⱼ; ρᵢ; αᵢ at x - 2
for each i: v*ᵢ ← vᵢ + Δt g - 3
while iter < 2 or (err > η ρ₀ and iter < max) do - 4
for each i: eᵢ ← max(ρᵢ + Δt (Dρᵢ/Dt)(v*) - ρ₀, 0); err ← mean of eᵢ - 5
for each i: κᵢ ← eᵢ αᵢ / Δt² - 6
for each i: v*ᵢ ← v*ᵢ - Δt Σⱼ mⱼ (κᵢ/ρᵢ + κⱼ/ρⱼ) ∇Wᵢⱼ - 7
for each i: xᵢ ← xᵢ + Δt v*ᵢ, clamped to the walls - 8
P ← neighbor pairs; ∇Wᵢⱼ; ρᵢ; αᵢ at the new x - 9
while iter < 1 or (err > η_v ρ₀ and iter < max) do - 10
for each i: dᵢ ← max((Dρᵢ/Dt)(v*), 0); err ← Δt × mean of dᵢ - 11
for each i: κᵢ ← dᵢ αᵢ / Δt - 12
for each i: v*ᵢ ← v*ᵢ - Δt Σⱼ mⱼ (κᵢ/ρᵢ + κⱼ/ρⱼ) ∇Wᵢⱼ - 13
return 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 so that particle 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 picked so that particle 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 ( and ), so a particle at the free surface gets no pull. This is a choice of this page. The tolerance is a fraction of per step. The step size comes from a CFL condition with and a cap.
Example
Take m, , kg/m², kg and s. Put 25 particles at rest on a 5 by 5 lattice with spacing , so the block is squeezed, and set . The table follows the predicted density of line L4 in the density solver.
| pass | mean error | largest | 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 . 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 . 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 from line L5 on particle alone moves its predicted density to exactly . 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 on the pressure system of IISPH, with summed over the passes. IISPH uses ; 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 and and parallel to . So without walls and gravity, the step keeps the total linear and angular momentum, for any .
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 is over the neighbors of , 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 is parallel to and . Write and . 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 and for . Then changes by .
Proof. The update changes by . For a neighbor , only the term of in its sum has , so changes by . Other particles do not change. is linear in the velocities, so it changes by
Claim 2. Let all masses be equal and let the denominator of be positive. With on alone, where , the new predicted density is . With on alone, the new is 0.
Proof. With equal masses , , so . By Lemma 1 with , the predicted density changes by . By Lemma 1 with , the rate changes by .
The link to Jacobi
Let be the sum of the stiffness values of the density passes so far, and . The update of line L6 is linear in , so after the passes with
the pressure acceleration of the IISPH page, and . So the predicted density of line L4 is in the notation of IISPH, and .
Claim 3. With equal masses and without the max of line L4, one density pass changes by , where is the IISPH diagonal. This is one Jacobi pass with weight .
Proof. The pass adds to , so it adds to . With equal masses, . So changes by .
Exit conditions
Claim 4. If the density solver stops before the cap, the mean of in its last pass is at most . If the divergence solver stops before the cap, times the mean of in its last pass is at most .
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 , and err is the mean of line L4 or times the mean of line L10.
Momentum
Claim 5. With , no walls and any stiffness values, one step keeps and .
Proof. Write . In line L6 or L12, each pair changes by and by . The sum is 0, so every update keeps . The change of the angular momentum at fixed positions is , because the two vectors are parallel. So the updates of the density solver keep at the old positions, and the updates of the divergence solver keep it at the new positions. Line L7 gives , so , since . With , line L2 does not change . So each part of the step keeps both sums.
Complexity
One pass of either solver costs time for pairs: one sweep over the pairs for the density rate and one for the update. A step with passes in total costs , and lines L1 and L8 add each. With a density near , . The memory is . The number is a measurement. In the small dam break of the tests, 50 steps of 0.004 s with 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. 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 , 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 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 . Clamp the denominator at a small value, as the code does with , or skip the particle.
- Different powers of the step. Line L5 divides by and line L11 by . With the same power in both, one solver is off by a factor .
- 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.
# 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 . Bender and Koschier (2015) added a second solver for the velocity divergence, with one factor 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 9VJ2XT Edit this page History Report an error Markdown