Algorithmadvanced
Implicit incompressible SPH
Also called IISPH.
An SPH fluid solver that finds the pressures from a linear system, a discrete pressure Poisson equation, solved by relaxed Jacobi iteration so that the predicted density is the rest density.
- Time
- O(n + q) iterationO(k (n + q)) step
- Space
- O(n + q) extra
- Where
- k = the number of Jacobi iterations; n = the number of particles; q = the number of neighbor pairs
- Model
- Real RAM
- Properties
- conserves angular momentumconserves linear momentumdeterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Markus Ihmsen, Jens Cornelis, Barbara Solenthaler, Christopher Horvath, Matthias Teschner, 2014
Implicit incompressible SPH (IISPH) is an SPH fluid solver that finds the pressures from a linear system. The system says that after the step, the density of each particle predicted to first order is the rest density . It is a discrete form of the pressure Poisson equation, with one unknown pressure per particle. IISPH solves it with relaxed Jacobi iteration, with no matrix in memory, and stops when the mean predicted compression is below a tolerance such as 0.1%. Like PCISPH, it allows steps much larger than weakly compressible SPH.
In plain words
Think of the water as many small balls. First, every ball moves a little with gravity alone, and the method checks which balls would end up too crowded. Then it looks for pressures that push the balls apart just enough to remove the crowding. Each pressure has an effect on the neighbors too, so all the pressures are linked. The method guesses all the pressures, checks the crowding that they give, and improves each guess a little. After a few rounds the crowding is very small, and the balls move for real. The pressures of the last step are a good first guess for the next step.
The problem
The input is a set of particles with masses , positions and velocities , the rest density , the smoothing length , gravity m/s², the step and the tolerance . The output is the state after one step and the pressures . 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 pressure acceleration and the operator are
With , the density after the step is to first order, where . IISPH solves with . This operator form is the one of the tutorial of Koschier et al.; the paper writes the same system with displacement terms and .
The algorithm
IISPH-STEP(x, v, p_prev, Δt)- 1
P ← neighbor pairs; store ∇Wᵢⱼ; ρᵢ ← Σⱼ mⱼ Wᵢⱼ - 2
for each i: vᵃᵈᵛᵢ ← vᵢ + Δt g - 3
for each i: sᵢ ← ρ₀ - ρᵢ - Δt Σⱼ mⱼ (vᵃᵈᵛᵢ - vᵃᵈᵛⱼ)·∇Wᵢⱼ - 4
for each i: aᵢᵢ ← -(Δt²/ρᵢ²) (|Σⱼ mⱼ ∇Wᵢⱼ|² + mᵢ Σⱼ mⱼ |∇Wᵢⱼ|²) - 5
for each i: pᵢ ← 0.5 p_prevᵢ - 6
while iter < 2 or (err > η ρ₀ and iter < max) do - 7
compute aᵖ from p, then (Ap)ᵢ for each i - 8
for each i: pᵢ ← max(0, pᵢ + ω (sᵢ - (Ap)ᵢ) / aᵢᵢ) - 9
err ← mean over i of max((Ap)ᵢ - sᵢ, 0) - 10
for each i: vᵢ ← vᵃᵈᵛᵢ + Δt aᵖᵢ - 11
for each i: xᵢ ← xᵢ + Δt vᵢ, clamped to the walls
Line L1 finds the pairs with the grid search and keeps them for the step. Line L2 adds the non-pressure forces; the tests use gravity only. Line L3 is the right side: the density error that the advected velocities would give. Line L4 is the diagonal of , the coefficient of in . It has two parts: pushes away from all neighbors, and it pushes each neighbor away from . Line L5 is the warm start of the paper, half the pressure of the last step. Lines L7 and L8 are one step of Jacobi with relaxation , the value of the paper. Line L8 also clamps each pressure at 0, so a particle at the free surface does not pull its neighbors. Line L9 measures the mean predicted compression , counted only where it is positive. The loop runs at least 2 times, as in the paper. Lines L10 and L11 are symplectic Euler with the final pressure acceleration.
Example
Take 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 , and . The table gives the error of line L9 in each pass, as a fraction of , and the largest pressure after the pass.
| pass | mean error | max pressure |
|---|---|---|
| 1 | 3.124% | 6389.0 |
| 2 | 0.079% | 4273.3 |
| 3 | 0.398% | 5205.6 |
| 4 | 0.161% | 5739.7 |
| 5 | 0.163% | 6198.9 |
| 6 | 0.095% | 6515.5 |
| 7 | 0.063% | 6724.9 |
| 8 | 0.054% | 6903.4 |
| 9 | 0.048% | 7061.8 |
Pass 1 starts from , so its error is the squeeze of the block itself. The error does not fall in each pass: the clamp of line L8 changes the system as pressures reach 0, and the edge particles of the block have few neighbors. Pass 9 is below , so the loop stops. With the loop stops after pass 2.
Correctness
IISPH solves a linear system, but the clamp of line L8 makes the iteration nonlinear, and the paper gives no proof that the clamped loop converges. The tests check these facts, and the proof gives the arguments:
- The system is the density condition. is the first order change of when every particle moves by , which is what the pressure does to the positions in lines L10 and L11. So means that the predicted density is .
- The diagonal. Line L4 is the coefficient of in , and it is negative when has a neighbor.
- Fixed points. Without the clamp, a fixed point of line L8 solves . The tests compare the result with Gaussian elimination.
- Exit condition. If the loop stops before the cap, the mean predicted compression is at most .
- Momentum. The pressure acceleration 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 .
The predicted density is a first order model. The measured compression after the step is larger: in the squeezed block above it is 0.57% after the step with .
Proof: The density condition, the diagonal, the fixed points and the momentum laws of IISPHfull
We use the notation of the page. The arithmetic is exact real arithmetic. The pairs are the unordered pairs with , and a sum over is over the neighbors of . The kernel is radial, so for a scalar , and . IISPH has no proof that the clamped loop converges; the claims below hold for every run.
The system is the density condition
Claim 1. Move every particle by , with the neighbors and densities of time . Then the first order change of is .
Proof. , with the term constant. The first order change for the displacements is . With this is .
In the step, lines L10 and L11 give . The same expansion for the displacement gives of line L3. So, to first order, the density after the step is , and is the condition that it equals .
The diagonal
Claim 2. The coefficient of in is of line L4, and when has a neighbor with .
Proof. Set , the unit vector of particle . Then with . For a neighbor , only the term of in the sum of has , so . Particles that are not neighbors of do not enter through , because sums over neighbors only. So
which is line L4. Both terms are at least 0, and the second is positive when some , since .
Fixed points
Claim 3. Without the clamp, if for all , then is a fixed point of line L8 if and only if .
Proof. Line L8 maps to with . This equals for all if and only if for all .
With the clamp, a fixed point has, for each , either and , or and , that is . So at a fixed point no particle is predicted to be compressed, and particles with a predicted low density have zero pressure.
Exit condition
Claim 4. If the loop of line L6 stops after fewer than the maximum number of passes, then the mean over of is at most , where is the pressure at the start of the last pass.
Proof. , and line L9 computes the mean of the positive parts. After at least 2 passes and below the cap, the loop stops only when this mean is at most .
Momentum
Claim 5. With , no walls and any pressures , one step keeps and .
Proof. Write . Each pair adds to and to . So the pair adds to . Its torque is , because is parallel to . So and . With , by line L10, so the linear momentum is kept. With by line L11,
since , and the last sum is 0.
The claim does not use the values of , so it holds for any number of passes, with or without the clamp. The density of time is used in all the sums of a step, so the masses and densities do not change inside the step and the pair terms stay opposite.
Complexity
One pass costs time for pairs: line L7 is two sweeps over the pairs, and line L8 is one sweep over the particles. A step with passes costs , and lines L1 to L4 add once. With a density near , . The memory is ; the matrix is never stored. The number is a measurement, not a bound. The paper reports fewer passes and larger steps than PCISPH on its scenes, at .
Properties
- Matrix free. Line L7 computes from the SPH sums, so the cost per pass is the cost of two SPH sums.
- Per-particle diagonal. Each particle has its own , so a particle with few neighbors gets a smaller step than in PCISPH, where one factor is used for all.
- Not symmetric. With different masses or densities, is not symmetric, so the conjugate gradient method does not apply directly.
- Momentum. Linear and angular momentum are kept by the pressure force (proved).
- Slow smooth errors. Jacobi removes local errors fast and smooth errors over many particles slowly. So deep fluids need more passes (a heuristic). In the tests, the unclamped solve of 16 particles needs about 200 passes for a relative error of (measured).
Variants and improvements
- Displacement form. The paper computes the same system with the terms and , which are the pressure displacements.
- Divergence-free SPH. DFSPH uses a density solver of the same kind and adds a second solver that makes the velocity field divergence free.
- Boundary particles. Fixed particles on the walls take part in and in , and give smoother walls than the clamp of line L11.
- Other solvers. Conjugate gradient or multigrid on a symmetric form of the system, as in projection methods of incompressible SPH in engineering.
When to use it
Use IISPH for SPH liquids with a small density error, such as 0.1%, at large steps. It is a good default when PCISPH needs too many passes, because the per-particle diagonal handles the free surface better. For deep or large scenes, add the divergence solver of DFSPH, or use a grid method such as FLIP.
Pitfalls
- Sign of the diagonal. The diagonal of line L4 is negative. Line L8 divides by , so with a positive diagonal the pressure goes the wrong way.
- Missing self term. Line L4 has the term , the push of on the neighbors. Without it, the diagonal is near 0 inside the fluid, where .
- Error with the clamp. Line L9 counts only compression. If it also counts the low density at the free surface, the loop never reaches .
- Predicted is not measured. The error of line L9 is a first order prediction. Do not report it as the density error of the result.
- No minimum. Without the 2 passes of line L6, a warm start can stop the loop at once with a pressure from the last step.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/implicit-incompressible-sph/. The authors are listed in prov/V1STXV.jsonl.
"""Implicit incompressible SPH (IISPH) in 2D.
The pressure p solves the discrete pressure Poisson equation A p = s with
a^p_i = -sum_j m_j (p_i / rho_i^2 + p_j / rho_j^2) grad W_ij,
(A p)_i = dt^2 sum_j m_j (a^p_i - a^p_j) . grad W_ij,
s_i = rho0 - rho^adv_i,
rho^adv_i = rho_i + dt sum_j m_j (v^adv_i - v^adv_j) . grad W_ij,
so that the predicted density rho^adv_i + (A p)_i equals rho0. The solver is
relaxed Jacobi with omega = 0.5 and the diagonal
a_ii = -(dt^2 / rho_i^2) (|sum_j m_j grad W_ij|^2 + m_i sum_j m_j |grad W_ij|^2),
with each pressure clamped at 0, in the operator form of the tutorial of
Koschier et al. (2019). Ihmsen et al. (2014) write the same system with the
displacement terms d_ii and d_ij. The solve stops when the mean predicted
compression is below eta rho0 and at least min_iter passes have run.
"""
import math
from sph import density, grad_w, neighbor_pairs
GRAVITY = (0.0, -9.81)
class Neighborhood:
"""The pairs, their gradients and the per-particle gradient sums of one step."""
def __init__(self, pos, masses, h):
self.n = len(pos)
self.pairs = neighbor_pairs(pos, 2.0 * h)
self.grads = [grad_w((pos[i][0] - pos[j][0], pos[i][1] - pos[j][1]), h) for i, j in self.pairs]
self.rho = density(pos, masses, h)
self.m = masses
def pressure_acc(nb, p):
"""a^p_i = -sum_j m_j (p_i / rho_i^2 + p_j / rho_j^2) grad W_ij."""
ax = [0.0] * nb.n
ay = [0.0] * nb.n
rho, m = nb.rho, nb.m
for (i, j), (gx, gy) in zip(nb.pairs, nb.grads):
s = p[i] / (rho[i] * rho[i]) + p[j] / (rho[j] * rho[j])
ax[i] -= m[j] * s * gx
ay[i] -= m[j] * s * gy
ax[j] += m[i] * s * gx
ay[j] += m[i] * s * gy
return ax, ay
def apply_a(nb, p, dt):
"""(A p)_i = dt^2 sum_j m_j (a^p_i - a^p_j) . grad W_ij."""
ax, ay = pressure_acc(nb, p)
out = [0.0] * nb.n
m = nb.m
for (i, j), (gx, gy) in zip(nb.pairs, nb.grads):
d = (ax[i] - ax[j]) * gx + (ay[i] - ay[j]) * gy
out[i] += m[j] * d
out[j] += m[i] * d # grad W_ji = -grad W_ij and a_j - a_i = -(a_i - a_j)
return [dt * dt * t for t in out]
def diagonal(nb, dt):
"""a_ii = -(dt^2 / rho_i^2) (|sum_j m_j grad W_ij|^2 + m_i sum_j m_j |grad W_ij|^2)."""
sx = [0.0] * nb.n
sy = [0.0] * nb.n
sq = [0.0] * nb.n
m = nb.m
for (i, j), (gx, gy) in zip(nb.pairs, nb.grads):
sx[i] += m[j] * gx
sy[i] += m[j] * gy
sx[j] -= m[i] * gx
sy[j] -= m[i] * gy
g2 = gx * gx + gy * gy
sq[i] += m[j] * g2
sq[j] += m[i] * g2
return [-(dt * dt) / (nb.rho[i] ** 2) * (sx[i] ** 2 + sy[i] ** 2 + m[i] * sq[i]) for i in range(nb.n)]
def source(nb, vel_adv, dt, rho0):
"""s_i = rho0 - rho^adv_i."""
rho_adv = list(nb.rho)
m = nb.m
for (i, j), (gx, gy) in zip(nb.pairs, nb.grads):
d = (vel_adv[i][0] - vel_adv[j][0]) * gx + (vel_adv[i][1] - vel_adv[j][1]) * gy
rho_adv[i] += dt * m[j] * d
rho_adv[j] += dt * m[i] * d
return [rho0 - r for r in rho_adv]
def relaxed_jacobi(nb, s, diag, dt, rho0, p0, omega=0.5, eta=0.001, min_iter=2,
max_iter=100, clamp=True):
"""Solve A p = s by relaxed Jacobi. Returns (p, iterations, mean error / rho0)."""
p = list(p0)
it = 0
err = float("inf")
while it < min_iter or (err > eta * rho0 and it < max_iter): # @line L6
ap = apply_a(nb, p, dt) # @line L7
err = 0.0
for i in range(nb.n):
if diag[i] != 0.0:
p[i] = p[i] + omega * (s[i] - ap[i]) / diag[i] # @line L8
if clamp and p[i] < 0.0:
p[i] = 0.0
err += max(ap[i] - s[i], 0.0) # @line L9
err /= nb.n
it += 1
return p, it, err / rho0
def step(pos, vel, masses, dt, h, rho0, p_prev=None, gravity=GRAVITY,
eta=0.001, min_iter=2, max_iter=100, box=None):
"""One IISPH step. Returns (pos, vel, p, info) with info = (iterations, error)."""
nb = Neighborhood(pos, masses, h) # @line L1
vel_adv = [(v[0] + dt * gravity[0], v[1] + dt * gravity[1]) for v in vel] # @line L2
s = source(nb, vel_adv, dt, rho0) # @line L3
diag = diagonal(nb, dt) # @line L4
p0 = [0.5 * q for q in p_prev] if p_prev is not None else [0.0] * nb.n # @line L5
p, it, err = relaxed_jacobi(nb, s, diag, dt, rho0, p0, 0.5, eta, min_iter, max_iter)
ax, ay = pressure_acc(nb, p)
vel = [(vel_adv[i][0] + dt * ax[i], vel_adv[i][1] + dt * ay[i]) for i in range(nb.n)] # @line L10
new = [(pos[i][0] + dt * vel[i][0], pos[i][1] + dt * vel[i][1]) for i in range(nb.n)] # @line L11
if box is not None:
x0, y0, x1, y1 = box
for i in range(nb.n):
x, y = new[i]
u, v = vel[i]
if x < x0 or x > x1:
x, u = min(max(x, x0), x1), 0.0
if y < y0 or y > y1:
y, v = min(max(y, y0), y1), 0.0
new[i] = (x, y)
vel[i] = (u, v)
return new, vel, p, (it, err)
def momentum(vel, masses):
return (sum(m * v[0] for m, v in zip(masses, vel)), sum(m * v[1] for m, v in zip(masses, vel)))
def angular_momentum(pos, vel, masses):
return sum(m * (x[0] * v[1] - x[1] * v[0]) for m, x, v in zip(masses, pos, vel))
def mean_compression(pos, masses, h, rho0):
rho = density(pos, masses, h)
return sum(max(r - rho0, 0.0) for r in rho) / (rho0 * len(rho))
def speed(v):
return math.hypot(v[0], v[1])
sph.py 127 lines
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The 2D cubic spline kernel, a uniform grid neighbor search and the SPH density.
This file is copied byte for byte into each impl/python folder that needs it.
It holds no solver step of a page: no equation of state, no pressure force,
no pressure solve and no time integration. The method of each page lives in
its slug file.
Conventions (prompts/graphics-ext.md, "Particles and SPH"):
- Positions are 2D tuples (x, y) in meters. Masses are in kg; in 2D a
density is in kg/m^2.
- h is the smoothing length. The cubic spline of Monaghan has support 2h:
W(r, h) = 0 for r >= 2h.
- grad_w(xij, h) is the gradient of W(|x_i - x_j|, h) with respect to x_i,
where xij = x_i - x_j. It is antisymmetric: grad_w(-xij) = -grad_w(xij).
- The density of particle i is rho_i = sum_j m_j W(|x_i - x_j|, h), with
j = i included.
"""
import math
# The 2D normalization constant of the cubic spline: W(0, h) = SIGMA_2D / h^2.
SIGMA_2D = 10.0 / (7.0 * math.pi)
def w_cubic(r, h):
"""Return the 2D cubic spline kernel W(r, h) for a distance r >= 0.
W = SIGMA_2D / h^2 * (1 - 1.5 q^2 + 0.75 q^3) for 0 <= q < 1,
W = SIGMA_2D / h^2 * 0.25 (2 - q)^3 for 1 <= q < 2, and W = 0 for
q >= 2, with q = r / h. Unit 1/m^2. Cost O(1).
"""
q = r / h
s = SIGMA_2D / (h * h)
if q < 1.0:
return s * (1.0 - 1.5 * q * q + 0.75 * q * q * q)
if q < 2.0:
t = 2.0 - q
return s * 0.25 * t * t * t
return 0.0
def dw_cubic(r, h):
"""Return the radial derivative dW/dr of the 2D cubic spline. Unit 1/m^3."""
q = r / h
s = SIGMA_2D / (h * h * h)
if q < 1.0:
return s * (-3.0 * q + 2.25 * q * q)
if q < 2.0:
t = 2.0 - q
return s * (-0.75 * t * t)
return 0.0
def grad_w(xij, h):
"""Return the gradient of W(|xij|, h) with respect to x_i, for xij = x_i - x_j.
The gradient is dW/dr * xij / |xij|. It is (0, 0) at r = 0, where the
kernel has a smooth maximum. Cost O(1).
"""
r = math.hypot(xij[0], xij[1])
if r == 0.0:
return (0.0, 0.0)
d = dw_cubic(r, h) / r
return (d * xij[0], d * xij[1])
def neighbor_pairs(positions, radius):
"""Return the sorted list of pairs (i, j), i < j, with |x_i - x_j| < radius.
The search puts the particles in a uniform grid of square cells of side
radius, keyed by (floor(x / radius), floor(y / radius)). Two particles at
a distance below radius are in the same cell or in adjacent cells, so
the search looks only at the 3 by 3 block of cells around each particle.
The result is the same as a test of all pairs. For the cubic spline,
pass radius = 2h. Cost O(n + q') for q' candidate pairs in adjacent
cells; this is O(n) when the number of particles per cell is bounded.
"""
cells = {}
keys = []
for i, p in enumerate(positions):
key = (math.floor(p[0] / radius), math.floor(p[1] / radius))
keys.append(key)
cells.setdefault(key, []).append(i)
r2 = radius * radius
pairs = []
for i, p in enumerate(positions):
cx, cy = keys[i]
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
for j in cells.get((cx + dx, cy + dy), ()):
if j <= i:
continue
ex = p[0] - positions[j][0]
ey = p[1] - positions[j][1]
if ex * ex + ey * ey < r2:
pairs.append((i, j))
pairs.sort()
return pairs
def neighbor_lists(positions, radius):
"""Return, for each particle i, the sorted list of j != i with |x_i - x_j| < radius."""
lists = [[] for _ in positions]
for i, j in neighbor_pairs(positions, radius):
lists[i].append(j)
lists[j].append(i)
for nb in lists:
nb.sort()
return lists
def density(positions, masses, h):
"""Return the list of SPH densities rho_i = sum_j m_j W(|x_i - x_j|, h), j = i included.
The sum runs over the neighbor pairs at distances below 2h, found with
the grid search. Cost O(n + q) for q neighbor pairs.
"""
w0 = w_cubic(0.0, h)
rho = [m * w0 for m in masses]
for i, j in neighbor_pairs(positions, 2.0 * h):
r = math.hypot(positions[i][0] - positions[j][0], positions[i][1] - positions[j][1])
w = w_cubic(r, h)
rho[i] += masses[j] * w
rho[j] += masses[i] * w
return rho
test_implicit_incompressible_sph.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/implicit-incompressible-sph/. The authors are listed in prov/V1STXV.jsonl.
import random
import implicit_incompressible_sph as ii
DX = 0.02
H = 1.3 * DX
RHO0 = 1000.0
M = RHO0 * DX * DX
def lattice(n_side, spacing):
return [((i + 0.5) * spacing, (j + 0.5) * spacing) for i in range(n_side) for j in range(n_side)]
def solve_dense(a, b):
n = len(b)
a = [row[:] + [b[k]] for k, row in enumerate(a)]
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(a[r][c]))
a[c], a[piv] = a[piv], a[c]
for r in range(c + 1, n):
f = a[r][c] / a[c][c]
for k in range(c, n + 1):
a[r][k] -= f * a[c][k]
x = [0.0] * n
for r in range(n - 1, -1, -1):
x[r] = (a[r][n] - sum(a[r][k] * x[k] for k in range(r + 1, n))) / a[r][r]
return x
def squeezed_cluster(rng, n_side=5):
pos = [(x + rng.uniform(-0.1, 0.1) * DX, y + rng.uniform(-0.1, 0.1) * DX) for x, y in lattice(n_side, 0.8 * DX)]
ms = [M * rng.uniform(0.9, 1.1) for _ in pos]
return pos, ms
def test_diagonal_equals_the_operator_on_unit_vectors() -> None:
rng = random.Random(1)
pos, ms = squeezed_cluster(rng)
nb = ii.Neighborhood(pos, ms, H)
dt = 0.003
diag = ii.diagonal(nb, dt)
for i in range(nb.n):
e = [0.0] * nb.n
e[i] = 1.0
col = ii.apply_a(nb, e, dt)
assert abs(col[i] - diag[i]) < 1e-10 * abs(diag[i])
assert diag[i] < 0.0
def test_operator_is_the_predicted_density_change() -> None:
# (A p)_i is the first order change of rho_i when the pressure acceleration
# acts for one step dt: x_j moves by dt^2 a^p_j.
rng = random.Random(2)
pos, ms = squeezed_cluster(rng)
nb = ii.Neighborhood(pos, ms, H)
dt = 1e-4
p = [rng.uniform(0.0, 50.0) for _ in pos]
ax, ay = ii.pressure_acc(nb, p)
ap = ii.apply_a(nb, p, dt)
moved = [(x + dt * dt * ax[k], y + dt * dt * ay[k]) for k, (x, y) in enumerate(pos)]
rho_new = ii.density(moved, ms, H)
for i in range(nb.n):
assert abs((rho_new[i] - nb.rho[i]) - ap[i]) < 1e-3 * max(abs(ap[i]), 1e-12) + 1e-12
def test_relaxed_jacobi_equals_gaussian_elimination() -> None:
# Without the clamp, relaxed Jacobi converges to the exact solution of A p = s.
rng = random.Random(3)
pos, ms = squeezed_cluster(rng, 4)
nb = ii.Neighborhood(pos, ms, H)
dt = 0.003
vel_adv = [(0.0, 0.0)] * nb.n
s = ii.source(nb, vel_adv, dt, RHO0)
diag = ii.diagonal(nb, dt)
cols = [ii.apply_a(nb, [1.0 if k == c else 0.0 for k in range(nb.n)], dt) for c in range(nb.n)]
a = [[cols[c][r] for c in range(nb.n)] for r in range(nb.n)]
ref = solve_dense(a, s)
p, it, err = ii.relaxed_jacobi(nb, s, diag, dt, RHO0, [0.0] * nb.n, eta=0.0, min_iter=500,
max_iter=500, clamp=False)
assert it == 500
scale = max(abs(t) for t in ref)
for x, y in zip(p, ref):
assert abs(x - y) < 1e-9 * scale
def test_momentum_is_conserved_without_walls_and_gravity() -> None:
rng = random.Random(4)
pos, ms = squeezed_cluster(rng, 6)
vel = [(rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)) for _ in pos]
p0 = ii.momentum(vel, ms)
l0 = ii.angular_momentum(pos, vel, ms)
p = None
for _ in range(8):
pos, vel, p, _ = ii.step(pos, vel, ms, 0.002, H, RHO0, p, gravity=(0.0, 0.0))
p1 = ii.momentum(vel, ms)
l1 = ii.angular_momentum(pos, vel, ms)
scale = sum(m * ii.speed(v) for m, v in zip(ms, vel))
assert abs(p1[0] - p0[0]) < 1e-10 * scale and abs(p1[1] - p0[1]) < 1e-10 * scale
assert abs(l1 - l0) < 1e-10 * scale
def test_small_dam_break_reaches_its_tolerance() -> None:
n_side = 8
pos = lattice(n_side, DX)
ms = [M] * len(pos)
vel = [(0.0, 0.0)] * len(pos)
box = (0.0, 0.0, 0.4, 0.4)
p = None
worst = 0.0
for _ in range(100):
pos, vel, p, (it, err) = ii.step(pos, vel, ms, 0.002, H, RHO0, p, eta=0.001, box=box)
assert 2 <= it < 100
assert err <= 0.001
worst = max(worst, ii.mean_compression(pos, ms, H, RHO0))
# The solver bounds the predicted error; the measured compression after the
# step is larger (first order prediction, wall clamp) but stays below 1%.
assert worst < 0.01
assert max(x for x, _ in pos) > n_side * DX + 0.1
assert all(q >= 0.0 for q in p)
History
PCISPH (Solenthaler and Pajarola 2009) corrects the pressure with one factor from a prototype particle. Ihmsen, Cornelis, Solenthaler, Horvath and Teschner (2014) wrote the same density condition as a linear system with a per-particle diagonal and solved it with relaxed Jacobi. Bender and Koschier (2015) then added a divergence solver in DFSPH. The tutorial of Koschier, Bender, Solenthaler and Teschner (2019) writes the IISPH system in the operator form used here.
References
- Markus Ihmsen, Jens Cornelis, Barbara Solenthaler, Christopher Horvath and Matthias Teschner, Implicit incompressible SPH, IEEE Transactions on Visualization and Computer Graphics 20(3), 426-435, 2014, the derivation of the pressure system, the relaxed Jacobi solver with omega = 0.5 and the results
- Dan Koschier, Jan Bender, Barbara Solenthaler and Matthias Teschner, Smoothed particle hydrodynamics techniques for the physics based simulation of fluids and solids, Eurographics tutorial, 2019, the section on pressure solvers (the operator form of the IISPH system)
- Barbara Solenthaler and Renato Pajarola, Predictive-corrective incompressible SPH, ACM Transactions on Graphics 28(3), article 40, 2009, the whole paper (the density condition that IISPH writes as a linear system)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 V1STXV Edit this page History Report an error Markdown