Algorithmadvanced
Weakly compressible SPH
Also called WCSPH.
An SPH fluid solver that computes pressure from density with a stiff Tait equation of state, so the fluid compresses by about 1% and needs no pressure solve, at the cost of small time steps.
- Time
- O(n + q) stepΘ(c / h) steps_per_unit_time
- Space
- O(n + q) extra
- Where
- c = the numerical speed of sound; h = the smoothing length; n = the number of particles; q = the number of neighbor pairs
- Model
- Real RAM
- Properties
- conserves angular momentumconserves linear momentumdeterministicnot exactnot implicit
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Joe J. Monaghan, Markus Becker, Matthias Teschner, 1994
Weakly compressible SPH (WCSPH) moves a fluid as a set of particles and computes the pressure of each particle directly from its density. It uses the stiff Tait equation of state , so a small compression gives a large pressure that pushes the particles apart. With a numerical speed of sound about ten times the largest flow speed, the density stays within about 1% of the rest density . There is no linear system to solve, but the time step must shrink as grows, and this is the main cost of the method.
In plain words
Think of the water as many small balls. Each ball looks at the balls near it and counts how crowded its place is. That count is its density. If the place is more crowded than water at rest, the ball gets a high pressure. High pressure pushes the neighbors away, and the push between two balls is equal and opposite. Gravity pulls all balls down. Then each ball changes its speed and moves a short distance, and the loop starts again. The pressure rule is very stiff, so water is squeezed only a little. A stiff rule needs very short steps, or the balls fly apart. So the method is simple to write, but it takes many steps for each second of motion.
The problem
The input is a set of particles with positions , velocities and masses , a rest density , the smoothing length , gravity m/s², and a time step . The output is the state after one step. The particles carry the smoothed particle hydrodynamics approximation of the Euler equations of a fluid with a free surface, as one method for fluid simulation for animation. The page works in 2D, where a density is in kg/m².
The kernel is the cubic spline of Monaghan with support and the 2D constant , so (see SPH smoothing kernel). We write and for its gradient with respect to . This gradient is antisymmetric: , and it points along .
The algorithm
WCSPH-STEP(x, v, m, Δt) ▷ one step, 2D- 1
P ← all pairs (i, j), i < j, with |xᵢ - xⱼ| < 2h ▷ uniform grid search - 2
for each i: ρᵢ ← Σⱼ mⱼ Wᵢⱼ ▷ j = i included - 3
for each i: pᵢ ← B ((ρᵢ / ρ₀)^γ - 1), B = ρ₀ c² / γ ▷ γ = 7 - 4
for each i: aᵢ ← g - 5
for each pair (i, j) in P do - 6
s ← pᵢ / ρᵢ² + pⱼ / ρⱼ² - 7
if (vᵢ - vⱼ)·(xᵢ - xⱼ) < 0 then s ← s + Πᵢⱼ ▷ artificial viscosity - 8
aᵢ ← aᵢ - mⱼ s ∇Wᵢⱼ; aⱼ ← aⱼ + mᵢ s ∇Wᵢⱼ - 9
for each i: vᵢ ← vᵢ + Δt aᵢ ▷ symplectic Euler - 10
for each i: xᵢ ← xᵢ + Δt vᵢ ▷ uses the new velocity - 11
apply the walls
Line L1 puts the particles in a uniform grid with cells of side and tests only the 3 by 3 block of cells around each particle. Line L2 is the SPH density sum, and line L3 is the Tait equation of state with . Lines L5 to L8 add the pressure force of each pair once, with opposite signs on the two particles. The term in line L6 is the symmetric form of the pressure gradient . Line L7 adds the artificial viscosity of Monaghan, with and . It acts only on pairs that approach each other, and is a tuning constant (the tests use 0.1). Lines L9 and L10 are symplectic Euler: the position update uses the velocity of the new step. Line L11 is a simple wall model, outside the method: it clamps each particle into the box and removes the velocity into the wall. Better wall models use fixed boundary particles that add to the density.
The constants come from two rules. The speed of sound is , where is the largest expected speed, for example for a column of height . The step obeys with . Both are heuristics.
Example
Take two particles of mass 1 at and , at rest, with , , , no gravity and . Then and , so line L2 gives . This is above , so line L3 gives a positive pressure. At the kernel slope is , and . Line L8 pushes particle 1 to the left and particle 2 to the right with equal and opposite accelerations.
| step | |||||
|---|---|---|---|---|---|
| 0 | 0.568411 | 0.103845 | |||
| 1 | 0.566922 | 0.100657 | |||
| 2 | 0.564033 | 0.094611 |
Particle 2 is the mirror image: and in each row. The particles move apart, the density drops toward , and the pressure falls. The sum stays 0.
Correctness
WCSPH does not solve the incompressible equations exactly. It solves a slightly compressible fluid, and the stiff equation of state keeps the compression small. Three things are exact for the discrete method.
- Linear momentum. Without walls and gravity, each pair in line L8 adds to the momentum of and to that of . The sum is 0, so does not change in line L9. This is a proved property.
- Angular momentum. The pair force is parallel to , because is. So the internal torques cancel, and under symplectic Euler is the same after the step. This is a proved property.
- Rest state. A particle with a density of exactly has .
The size of the compression is an estimate, not a theorem. For a small relative compression , . The pressure needed to turn a flow of speed is of order , so is of order , and gives about 1% (Monaghan 1994). The proof gives the momentum arguments in full.
Proof: The WCSPH step conserves linear and angular momentumfull
We use the notation of the page. The step has no walls (line L11 is skipped) and no gravity (). The arithmetic is exact real arithmetic; in floating point the same identities hold up to rounding. The masses are positive and constant.
The pair term
Lemma 1. For , , and for a scalar with .
Proof. depends on only through . The chain rule gives for , so . Swapping and changes the sign of and leaves fixed. At the gradient is 0, since the cubic spline has a smooth maximum there.
Lemma 2. The scalar of lines L6 and L7 is symmetric in and .
Proof. is symmetric. In , the product does not change when and swap, because both factors change sign. The same holds for and .
So the code may compute once per pair, as lines L5 to L8 do.
Linear momentum
Claim 1. Let . After lines L4 to L9, has the same value as before.
Proof. With , line L4 sets every to 0. Each pair in line L8 adds to and to . Its contribution to is . So after line L8. Line L9 changes by .
Angular momentum
In 2D the cross product of and is the scalar . It is bilinear and .
Claim 2. The total torque of the forces of line L8 is 0.
Proof. The pair adds times
By Lemma 1, , so this is .
Claim 3. Let . After lines L9 and L10, has the same value as before.
Proof. Write for the old state and for the new state, with and . Then
since . Next,
by Claim 2.
Claim 3 uses the order of lines L9 and L10. The position update must use the new velocity; with the explicit Euler order (, then ) the term is left over, and drifts.
Consistency of the state equation
Claim 4. For , the Tait pressure is 0 if and only if , it is increasing in , and its derivative at is .
Proof. with and is 0 exactly at . Its derivative is . At it is , since .
So is the speed of sound of the discrete fluid near rest, and a compression gives .
Claims 1 and 3 hold for any positions, velocities, masses and step size, and for any . They are the momentum laws of a closed system, kept exactly by the discrete step.
Complexity
One step costs time for neighbor pairs: the grid search in line L1 visits each particle and its candidate pairs, and lines L2 to L10 do constant work per particle and per pair. If the density stays near , each particle has a bounded number of neighbors in its disk of radius , so and the step costs . A test of all pairs would cost . The memory is for the grid and the pair list.
The time step is the real cost. The step limit is proportional to , so a simulated time needs steps. Halving the density error needs about times larger , so about times more steps.
Properties
- Explicit. No linear system and no iteration. Each step is one pass over the pairs.
- Momentum. Linear and angular momentum are conserved by the internal forces (proved above). The walls of line L11 do not conserve them.
- Compressible. The density error is of order and is not bounded by a user tolerance. The incompressible solvers PCISPH, IISPH and DFSPH iterate to a stated tolerance instead.
- Stiff. The step limit falls as . In a measured comparison, PCISPH took steps 35 times larger at the same 1% density error (Solenthaler and Pajarola 2009).
- Tensile instability. Negative pressures at the free surface pull particles into clumps. Clamping at 0 removes the pull but makes the surface less smooth.
Variants and improvements
- Clamped pressure. Set in line L3. The tests use this for the dam break, so the free surface does not clump.
- Other equations of state. The linear law is less stiff and allows larger steps for the same , but compresses more under the same load.
- Physical viscosity. Replace by a Laplacian form for a given kinematic viscosity, as in smoothed particle hydrodynamics.
- Incompressible solvers. PCISPH predicts and corrects the pressure, and IISPH and DFSPH solve a pressure equation. Incompressible SPH in engineering uses a projection.
- Position based fluids. PBF enforces the density as a constraint on positions and takes large steps.
When to use it
Use WCSPH for small scenes, for teaching, and as a reference to test other SPH solvers. It is short to write, it runs on GPUs with one pass per step, and its forces conserve momentum. For large scenes with deep water, the stiff step limit makes it slow; use an incompressible solver. For a surface to render, add a surfacing step.
Pitfalls
- Too small c. If is close to the flow speed, line L3 gives too little pressure and the fluid compresses by much more than 1%.
- Too large step. A step above makes lines L9 and L10 unstable, and the particles explode.
- Missing neighbors at walls. With the clamp walls of line L11, particles near a wall have fewer neighbors, so line L2 gives a low density there. Boundary particles fix this.
- One-sided pair update. Line L8 must change both particles by the same pair term. A loop over each particle with its own form of the term loses momentum conservation.
- Wrong cell size. The grid of line L1 needs a cell side at least , the kernel support. A smaller cell misses neighbors.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The 2D cubic spline kernel, a uniform grid neighbor search and the SPH density.
This file is copied byte for byte into each impl/python folder that needs it.
It holds no solver step of a page: no equation of state, no pressure force,
no pressure solve and no time integration. The method of each page lives in
its slug file.
Conventions (prompts/graphics-ext.md, "Particles and SPH"):
- Positions are 2D tuples (x, y) in meters. Masses are in kg; in 2D a
density is in kg/m^2.
- h is the smoothing length. The cubic spline of Monaghan has support 2h:
W(r, h) = 0 for r >= 2h.
- grad_w(xij, h) is the gradient of W(|x_i - x_j|, h) with respect to x_i,
where xij = x_i - x_j. It is antisymmetric: grad_w(-xij) = -grad_w(xij).
- The density of particle i is rho_i = sum_j m_j W(|x_i - x_j|, h), with
j = i included.
"""
import math
# The 2D normalization constant of the cubic spline: W(0, h) = SIGMA_2D / h^2.
SIGMA_2D = 10.0 / (7.0 * math.pi)
def w_cubic(r, h):
"""Return the 2D cubic spline kernel W(r, h) for a distance r >= 0.
W = SIGMA_2D / h^2 * (1 - 1.5 q^2 + 0.75 q^3) for 0 <= q < 1,
W = SIGMA_2D / h^2 * 0.25 (2 - q)^3 for 1 <= q < 2, and W = 0 for
q >= 2, with q = r / h. Unit 1/m^2. Cost O(1).
"""
q = r / h
s = SIGMA_2D / (h * h)
if q < 1.0:
return s * (1.0 - 1.5 * q * q + 0.75 * q * q * q)
if q < 2.0:
t = 2.0 - q
return s * 0.25 * t * t * t
return 0.0
def dw_cubic(r, h):
"""Return the radial derivative dW/dr of the 2D cubic spline. Unit 1/m^3."""
q = r / h
s = SIGMA_2D / (h * h * h)
if q < 1.0:
return s * (-3.0 * q + 2.25 * q * q)
if q < 2.0:
t = 2.0 - q
return s * (-0.75 * t * t)
return 0.0
def grad_w(xij, h):
"""Return the gradient of W(|xij|, h) with respect to x_i, for xij = x_i - x_j.
The gradient is dW/dr * xij / |xij|. It is (0, 0) at r = 0, where the
kernel has a smooth maximum. Cost O(1).
"""
r = math.hypot(xij[0], xij[1])
if r == 0.0:
return (0.0, 0.0)
d = dw_cubic(r, h) / r
return (d * xij[0], d * xij[1])
def neighbor_pairs(positions, radius):
"""Return the sorted list of pairs (i, j), i < j, with |x_i - x_j| < radius.
The search puts the particles in a uniform grid of square cells of side
radius, keyed by (floor(x / radius), floor(y / radius)). Two particles at
a distance below radius are in the same cell or in adjacent cells, so
the search looks only at the 3 by 3 block of cells around each particle.
The result is the same as a test of all pairs. For the cubic spline,
pass radius = 2h. Cost O(n + q') for q' candidate pairs in adjacent
cells; this is O(n) when the number of particles per cell is bounded.
"""
cells = {}
keys = []
for i, p in enumerate(positions):
key = (math.floor(p[0] / radius), math.floor(p[1] / radius))
keys.append(key)
cells.setdefault(key, []).append(i)
r2 = radius * radius
pairs = []
for i, p in enumerate(positions):
cx, cy = keys[i]
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
for j in cells.get((cx + dx, cy + dy), ()):
if j <= i:
continue
ex = p[0] - positions[j][0]
ey = p[1] - positions[j][1]
if ex * ex + ey * ey < r2:
pairs.append((i, j))
pairs.sort()
return pairs
def neighbor_lists(positions, radius):
"""Return, for each particle i, the sorted list of j != i with |x_i - x_j| < radius."""
lists = [[] for _ in positions]
for i, j in neighbor_pairs(positions, radius):
lists[i].append(j)
lists[j].append(i)
for nb in lists:
nb.sort()
return lists
def density(positions, masses, h):
"""Return the list of SPH densities rho_i = sum_j m_j W(|x_i - x_j|, h), j = i included.
The sum runs over the neighbor pairs at distances below 2h, found with
the grid search. Cost O(n + q) for q neighbor pairs.
"""
w0 = w_cubic(0.0, h)
rho = [m * w0 for m in masses]
for i, j in neighbor_pairs(positions, 2.0 * h):
r = math.hypot(positions[i][0] - positions[j][0], positions[i][1] - positions[j][1])
w = w_cubic(r, h)
rho[i] += masses[j] * w
rho[j] += masses[i] * w
return rho
weakly_compressible_sph.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weakly-compressible-sph/. The authors are listed in prov/XB7CYE.jsonl.
"""Weakly compressible SPH (WCSPH) in 2D with the Tait equation of state.
One step (Monaghan 1994; Becker and Teschner 2007):
1. find the neighbor pairs at a distance below 2h,
2. rho_i = sum_j m_j W_ij (j = i included),
3. p_i = B ((rho_i / rho0)^gamma - 1) with B = rho0 c^2 / gamma,
4. a_i = g - sum_j m_j (p_i / rho_i^2 + p_j / rho_j^2 + Pi_ij) grad W_ij,
with the artificial viscosity Pi_ij of Monaghan,
5. symplectic Euler: v += dt a, then x += dt v.
The kernel, the neighbor search and the density come from the shared helper
sph.py. Each pair force is applied with opposite signs to i and j, so the
internal forces conserve linear and angular momentum.
"""
import math
from sph import density, grad_w, neighbor_pairs
GRAVITY = (0.0, -9.81)
def tait_b(rho0, c, gamma=7.0):
"""The stiffness B = rho0 c^2 / gamma of the Tait equation (Pa)."""
return rho0 * c * c / gamma
def tait_pressure(rho, rho0, c, gamma=7.0, clamp=False):
"""p = B ((rho / rho0)^gamma - 1). With clamp, a negative p is set to 0."""
p = tait_b(rho0, c, gamma) * ((rho / rho0) ** gamma - 1.0)
if clamp and p < 0.0:
return 0.0
return p
def time_step_limit(h, c, v_max, lam=0.4):
"""The CFL type limit dt <= lam h / (c + v_max) (a heuristic, lam about 0.4)."""
return lam * h / (c + v_max)
def accelerations(pos, vel, masses, h, rho0, c, gravity=GRAVITY, alpha=0.0,
gamma=7.0, clamp=False):
"""Return (acc, rho, p) for the particles. Cost O(n + q) for q pairs."""
n = len(pos)
pairs = neighbor_pairs(pos, 2.0 * h) # @line L1
rho = density(pos, masses, h) # @line L2
p = [tait_pressure(r, rho0, c, gamma, clamp) for r in rho] # @line L3
ax = [gravity[0]] * n # @line L4
ay = [gravity[1]] * n
eps = 0.01 * h * h
for i, j in pairs: # @line L5
dx = pos[i][0] - pos[j][0]
dy = pos[i][1] - pos[j][1]
gx, gy = grad_w((dx, dy), h)
s = p[i] / (rho[i] * rho[i]) + p[j] / (rho[j] * rho[j]) # @line L6
if alpha > 0.0:
vx = vel[i][0] - vel[j][0]
vy = vel[i][1] - vel[j][1]
vr = vx * dx + vy * dy
if vr < 0.0: # @line L7
mu = h * vr / (dx * dx + dy * dy + eps)
s += -alpha * c * mu / (0.5 * (rho[i] + rho[j]))
ax[i] -= masses[j] * s * gx # @line L8
ay[i] -= masses[j] * s * gy
ax[j] += masses[i] * s * gx
ay[j] += masses[i] * s * gy
return list(zip(ax, ay)), rho, p
def apply_box(pos, vel, box, restitution=0.0):
"""Clamp the particles into box = (x0, y0, x1, y1) and reflect the normal velocity.
This is a simple wall model (a heuristic), not part of WCSPH itself.
"""
x0, y0, x1, y1 = box
out_p, out_v = [], []
for (x, y), (u, v) in zip(pos, vel):
if x < x0:
x, u = x0, -restitution * u if u < 0.0 else u
elif x > x1:
x, u = x1, -restitution * u if u > 0.0 else u
if y < y0:
y, v = y0, -restitution * v if v < 0.0 else v
elif y > y1:
y, v = y1, -restitution * v if v > 0.0 else v
out_p.append((x, y))
out_v.append((u, v))
return out_p, out_v
def step(pos, vel, masses, dt, h, rho0, c, gravity=GRAVITY, alpha=0.0,
gamma=7.0, clamp=False, box=None):
"""Advance one step of WCSPH. Returns (pos, vel, rho) with rho at the start."""
acc, rho, _ = accelerations(pos, vel, masses, h, rho0, c, gravity, alpha,
gamma, clamp)
vel = [(v[0] + dt * a[0], v[1] + dt * a[1]) for v, a in zip(vel, acc)] # @line L9
pos = [(x[0] + dt * v[0], x[1] + dt * v[1]) for x, v in zip(pos, vel)] # @line L10
if box is not None: # @line L11
pos, vel = apply_box(pos, vel, box)
return pos, vel, rho
def momentum(vel, masses):
"""The total linear momentum sum_i m_i v_i."""
return (sum(m * v[0] for m, v in zip(masses, vel)),
sum(m * v[1] for m, v in zip(masses, vel)))
def angular_momentum(pos, vel, masses):
"""The total angular momentum sum_i m_i (x_i v_i,y - y_i v_i,x) about the origin."""
return sum(m * (x[0] * v[1] - x[1] * v[0]) for m, x, v in zip(masses, pos, vel))
def max_speed(vel):
"""The largest particle speed."""
return max((math.hypot(v[0], v[1]) for v in vel), default=0.0)
test_weakly_compressible_sph.py 234 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weakly-compressible-sph/. The authors are listed in prov/XB7CYE.jsonl.
import math
import random
import sph
import weakly_compressible_sph as wc
# ---------------------------------------------------------------- the shared helper sph.py
def brute_pairs(pos, radius):
out = []
for i in range(len(pos)):
for j in range(i + 1, len(pos)):
if (pos[i][0] - pos[j][0]) ** 2 + (pos[i][1] - pos[j][1]) ** 2 < radius * radius:
out.append((i, j))
return out
def test_kernel_check_value() -> None:
assert abs(sph.SIGMA_2D - 0.454728) < 1e-6
assert abs(sph.w_cubic(0.0, 1.0) - 0.454728) < 1e-6
assert abs(sph.w_cubic(0.0, 0.5) - 0.454728 / 0.25) < 1e-5
assert sph.w_cubic(2.0, 1.0) == 0.0
assert sph.w_cubic(3.0, 1.0) == 0.0
def test_kernel_integrates_to_one() -> None:
for h in (1.0, 0.05, 0.3):
# Simpson's rule on [0, h] and [h, 2h] of W(r) 2 pi r dr.
total = 0.0
n = 200
for a in (0.0, h):
step = h / n
s = 0.0
for k in range(n + 1):
r = a + k * step
f = sph.w_cubic(r, h) * 2.0 * math.pi * r
wgt = 1 if k in (0, n) else (4 if k % 2 else 2)
s += wgt * f
total += s * step / 3.0
assert abs(total - 1.0) < 1e-3
def test_kernel_is_continuous_and_derivative_matches() -> None:
h = 0.7
for q in (1.0, 2.0):
r = q * h
assert abs(sph.w_cubic(r - 1e-9, h) - sph.w_cubic(r + 1e-9, h)) < 1e-7
for q in (0.1, 0.5, 0.9, 1.1, 1.5, 1.9):
r = q * h
e = 1e-6
num = (sph.w_cubic(r + e, h) - sph.w_cubic(r - e, h)) / (2 * e)
assert abs(num - sph.dw_cubic(r, h)) < 1e-6 * max(1.0, abs(num))
def test_gradient_is_antisymmetric_and_numeric() -> None:
rng = random.Random(7)
h = 0.2
assert sph.grad_w((0.0, 0.0), h) == (0.0, 0.0)
for _ in range(200):
d = (rng.uniform(-0.45, 0.45), rng.uniform(-0.45, 0.45))
g = sph.grad_w(d, h)
gm = sph.grad_w((-d[0], -d[1]), h)
assert abs(g[0] + gm[0]) < 1e-12 and abs(g[1] + gm[1]) < 1e-12
e = 1e-7
for c in range(2):
dp = list(d)
dm = list(d)
dp[c] += e
dm[c] -= e
num = (sph.w_cubic(math.hypot(*dp), h) - sph.w_cubic(math.hypot(*dm), h)) / (2 * e)
assert abs(num - g[c]) < 1e-5 * max(1.0, abs(num))
def test_neighbor_pairs_equal_brute_force() -> None:
rng = random.Random(2024)
for radius in (0.05, 0.1, 0.25):
pos = [(rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)) for _ in range(200)]
assert sph.neighbor_pairs(pos, radius) == brute_pairs(pos, radius)
# Points on cell borders and at exactly the radius.
pos = [(0.0, 0.0), (0.1, 0.0), (0.2, 0.0), (0.1, 0.1), (-0.1, -0.1), (0.05, 0.05)]
assert sph.neighbor_pairs(pos, 0.1) == brute_pairs(pos, 0.1)
assert sph.neighbor_pairs([], 0.1) == []
assert sph.neighbor_pairs([(0.3, 0.3)], 0.1) == []
lists = sph.neighbor_lists(pos, 0.1)
for i, nb in enumerate(lists):
assert nb == [j for j in range(len(pos)) if j != i and ((pos[i][0] - pos[j][0]) ** 2 + (pos[i][1] - pos[j][1]) ** 2) < 0.01]
def test_density_equals_brute_force_sum() -> None:
rng = random.Random(11)
h = 0.06
pos = [(rng.uniform(0, 0.6), rng.uniform(0, 0.6)) for _ in range(200)]
ms = [rng.uniform(0.5, 1.5) for _ in pos]
rho = sph.density(pos, ms, h)
for i in range(len(pos)):
ref = sum(ms[j] * sph.w_cubic(math.hypot(pos[i][0] - pos[j][0], pos[i][1] - pos[j][1]), h) for j in range(len(pos)))
assert abs(rho[i] - ref) < 1e-9 * ref
def test_density_on_a_lattice_is_near_rest_density() -> None:
dx = 0.02
rho0 = 1000.0
h = 1.3 * dx
n = 15
pos = [(i * dx, j * dx) for i in range(n) for j in range(n)]
ms = [rho0 * dx * dx] * len(pos)
rho = sph.density(pos, ms, h)
for k, p in enumerate(pos):
i, j = round(p[0] / dx), round(p[1] / dx)
if 3 <= i < n - 3 and 3 <= j < n - 3:
assert abs(rho[k] - rho0) < 0.01 * rho0
# ---------------------------------------------------------------- WCSPH
def random_blob(rng, n, dx, rho0):
side = int(math.ceil(math.sqrt(n)))
pos = []
for k in range(n):
i, j = k % side, k // side
pos.append((i * dx + rng.uniform(-0.2, 0.2) * dx, j * dx + rng.uniform(-0.2, 0.2) * dx))
vel = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
ms = [rho0 * dx * dx * rng.uniform(0.8, 1.2) for _ in range(n)]
return pos, vel, ms
def brute_accelerations(pos, vel, ms, h, rho0, c, gravity, alpha):
n = len(pos)
rho = [sum(ms[j] * sph.w_cubic(math.hypot(pos[i][0] - pos[j][0], pos[i][1] - pos[j][1]), h) for j in range(n)) for i in range(n)]
b = rho0 * c * c / 7.0
p = [b * ((r / rho0) ** 7 - 1.0) for r in rho]
acc = []
for i in range(n):
ax, ay = gravity
for j in range(n):
if j == i:
continue
d = (pos[i][0] - pos[j][0], pos[i][1] - pos[j][1])
g = sph.grad_w(d, h)
s = p[i] / rho[i] ** 2 + p[j] / rho[j] ** 2
vr = (vel[i][0] - vel[j][0]) * d[0] + (vel[i][1] - vel[j][1]) * d[1]
if alpha > 0 and vr < 0:
mu = h * vr / (d[0] ** 2 + d[1] ** 2 + 0.01 * h * h)
s += -alpha * c * mu / (0.5 * (rho[i] + rho[j]))
ax -= ms[j] * s * g[0]
ay -= ms[j] * s * g[1]
acc.append((ax, ay))
return acc
def test_tait_check_values() -> None:
assert abs(wc.tait_b(1000.0, 10.0) - 14285.714285714286) < 1e-9
assert wc.tait_pressure(1000.0, 1000.0, 10.0) == 0.0
p = wc.tait_pressure(1010.0, 1000.0, 10.0)
assert abs(p - 14285.714285714286 * (1.01 ** 7 - 1.0)) < 1e-9
assert abs(p - 1030.505030) < 1e-5
# For a small compression e, p is close to c^2 rho0 e.
assert abs(wc.tait_pressure(1000.1, 1000.0, 10.0) - 100.0 * 0.1) < 0.01
assert wc.tait_pressure(990.0, 1000.0, 10.0) < 0.0
assert wc.tait_pressure(990.0, 1000.0, 10.0, clamp=True) == 0.0
assert abs(wc.time_step_limit(0.026, 18.0, 2.0) - 0.4 * 0.026 / 20.0) < 1e-15
def test_accelerations_equal_brute_force() -> None:
rng = random.Random(5)
dx = 0.02
pos, vel, ms = random_blob(rng, 49, dx, 1000.0)
h = 1.3 * dx
for alpha in (0.0, 0.2):
acc, _, _ = wc.accelerations(pos, vel, ms, h, 1000.0, 15.0, (0.0, -9.81), alpha)
ref = brute_accelerations(pos, vel, ms, h, 1000.0, 15.0, (0.0, -9.81), alpha)
for a, r in zip(acc, ref):
scale = max(1.0, abs(r[0]), abs(r[1]))
assert abs(a[0] - r[0]) < 1e-9 * scale and abs(a[1] - r[1]) < 1e-9 * scale
def test_momentum_is_conserved_without_walls_and_gravity() -> None:
rng = random.Random(9)
dx = 0.02
pos, vel, ms = random_blob(rng, 64, dx, 1000.0)
h = 1.3 * dx
c = 15.0
dt = wc.time_step_limit(h, c, 2.0)
p0 = wc.momentum(vel, ms)
l0 = wc.angular_momentum(pos, vel, ms)
scale = sum(m * math.hypot(*v) for m, v in zip(ms, vel))
lscale = sum(m * math.hypot(*x) * math.hypot(*v) for m, x, v in zip(ms, pos, vel))
for _ in range(60):
pos, vel, _ = wc.step(pos, vel, ms, dt, h, 1000.0, c, (0.0, 0.0), alpha=0.1)
p1 = wc.momentum(vel, ms)
l1 = wc.angular_momentum(pos, vel, ms)
assert abs(p1[0] - p0[0]) < 1e-10 * scale and abs(p1[1] - p0[1]) < 1e-10 * scale
assert abs(l1 - l0) < 1e-10 * lscale
def test_gravity_alone_gives_free_fall() -> None:
pos = [(0.0, 0.0), (1.0, 0.0)]
vel = [(0.0, 0.0), (0.0, 0.0)]
ms = [1.0, 1.0]
dt = 0.01
for _ in range(10):
pos, vel, _ = wc.step(pos, vel, ms, dt, 0.1, 1000.0, 10.0)
# Symplectic Euler: v_n = n g dt and y_n = g dt^2 n (n + 1) / 2.
assert abs(vel[0][1] + 9.81 * 0.1) < 1e-12
assert abs(pos[1][1] + 9.81 * dt * dt * 55) < 1e-12
def test_small_dam_break_keeps_the_density_error_near_one_percent() -> None:
dx = 0.02
rho0 = 1000.0
h = 1.3 * dx
n_side = 8
v_max = math.sqrt(2 * 9.81 * n_side * dx)
c = 10.0 * v_max
pos = [((i + 0.5) * dx, (j + 0.5) * dx) for i in range(n_side) for j in range(n_side)]
vel = [(0.0, 0.0)] * len(pos)
ms = [rho0 * dx * dx] * len(pos)
dt = wc.time_step_limit(h, c, v_max)
box = (0.0, 0.0, 0.4, 0.4)
worst_mean = 0.0
for _ in range(280):
pos, vel, rho = wc.step(pos, vel, ms, dt, h, rho0, c, alpha=0.1, clamp=True, box=box)
worst_mean = max(worst_mean, sum(max(r - rho0, 0.0) for r in rho) / (rho0 * len(rho)))
assert worst_mean < 0.01
assert wc.max_speed(vel) < 1.2 * v_max
# The column has collapsed: the front moved to the right.
assert max(x for x, _ in pos) > n_side * dx + 0.05
for x, y in pos:
assert 0.0 <= x <= 0.4 and 0.0 <= y <= 0.4
History
Lucy (1977) and Gingold and Monaghan (1977) introduced SPH for astrophysics. Monaghan (1992) reviewed the method, with the cubic spline kernel and the artificial viscosity. Monaghan (1994) used the Tait equation of state to simulate free surface flows with a small compression. Becker and Teschner (2007) used the weakly compressible form with for fluids in computer graphics. Later solvers in graphics, such as PCISPH (2009), IISPH (2014) and DFSPH (2015), keep the SPH sums but replace the equation of state by a pressure iteration.
References
- Joe J. Monaghan, Simulating free surface flows with SPH, Journal of Computational Physics 110(2), 399-406, 1994, the whole paper (the Tait equation of state and the choice of the speed of sound)
- Markus Becker and Matthias Teschner, Weakly compressible SPH for free surface flows, Symposium on Computer Animation 2007, 209-217, the whole paper (the Tait equation with gamma = 7 for graphics fluids)
- Joe J. Monaghan, Smoothed particle hydrodynamics, Annual Review of Astronomy and Astrophysics 30, 543-574, 1992, the whole paper (the cubic spline kernel, the symmetric pressure term and the artificial viscosity)
- Dan Koschier, Jan Bender, Barbara Solenthaler and Matthias Teschner, Smoothed particle hydrodynamics techniques for the physics based simulation of fluids and solids, Eurographics tutorial, 2019, the sections on the state equation and on time stepping
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 XB7CYE Edit this page History Report an error Markdown