Algorithmadvanced
Incompressible smoothed particle hydrodynamics
Also called ISPH.
Enforces incompressibility in SPH by a projection step that solves a pressure Poisson equation on the particles, instead of a stiff equation of state.
- Solves
- Navier-Stokes equations
- Time
- Θ(K N I) worst
- Space
- Θ(N) extra
- Where
- I = the conjugate gradient iterations per step; K = the number of time steps; N = the number of particles
- Model
- Real RAM
- Properties
- conserves momentum exactlydeterministiclagrangianlinear solve per stepmeshless
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Sharen J. Cummins, Murray Rudman, Songdong Shao, Edmond Y. M. Lo, 1999
Incompressible SPH (ISPH) is smoothed particle hydrodynamics in which the pressure comes from a linear system instead of an equation of state. Each step moves the particles with a provisional velocity, then solves a pressure Poisson equation on the particles and subtracts the pressure gradient, as in the projection method on a grid. The graphics solvers IISPH, DFSPH and PCISPH also find pressures that keep the density or the divergence in check, with a few Jacobi-like sweeps per frame, and weakly compressible SPH avoids the solve with a stiff equation of state and small steps. What the accurate method adds is a symmetric pressure system solved to a set tolerance by a Krylov solver, measured convergence on test flows, and an explicit account of the errors that remain because the discrete Laplacian is not the product of the discrete divergence and gradient.
In plain words
Water hardly compresses, so a particle simulation of water must keep the particles from bunching up or spreading out. One way is to treat water as slightly compressible and let any bunching make a large pressure, but then the time step must be tiny. ISPH does it the other way. It first moves the particles as if there were no pressure, then asks: what pressure field would push the velocities back to a flow with no compression? That question is a Poisson equation, one unknown pressure per particle, linked to its neighbors. Solving it is the expensive part of each step. The pressure gradient is then taken off the velocities, and the particles move on. The result is a flow that is nearly incompressible at time steps set by the flow speed, not by the speed of sound.
The problem
Solve the incompressible Navier-Stokes equations , , in Lagrangian form: particles at positions with velocities follow . The density is the constant (here ), so each of the particles carries the same volume in a periodic box of area . The output is the particle positions and velocities at time . Here is the kinematic viscosity; the Courant number is written .
The algorithm
ISPH(x, v, Δt, K; ν, g)- 1
repeat K times - 2
find the pairs (i, j) with |x_i - x_j| < 2h ▷ cell list - 3
v* ← v + Δt (ν ∇²_h v + g) ▷ viscous predictor - 4
x* ← x + Δt v - 5
at x*: solve -L φ = mean(D v*) - D v* by conjugate gradients ▷ pressure Poisson equation - 6
v' ← v* - G φ ▷ projection, p = φ / Δt - 7
x ← x + Δt (v + v') / 2; v ← v' - 8
return x, v
The kernel is the cubic SPH smoothing kernel in 2D with support and , where is the initial particle spacing. For a pair, (with the minimum image in a periodic box), , and . The discrete operators are
is the standard SPH divergence; is the symmetric SPH gradient, whose pair terms are equal and opposite. is the compact SPH Laplacian, which uses only the first derivative of the kernel and so links only neighbors within ; the same form gives the viscous term of Morris, Fox and Zhu (1997). This is a first-order projection in the form of Cummins and Rudman (1999).
Line L3 adds viscosity and body forces at the old positions. Line L4 moves the particles to provisional positions, and line L5 finds the neighbor pairs again there and solves the pressure equation. The matrix is symmetric and positive semidefinite, with the constants as its null space, so the right-hand side has its mean removed; the solution is taken with zero mean. Line L6 is the projection. Line L7 moves the particles with the mean of the old and new velocities.
Example
Uniform flow, by hand. If every particle has the same velocity , every is zero. Then the viscous term is zero, , the solver returns in zero iterations, and the flow stays uniform; all particles move by . With gravity in a periodic box, every velocity becomes in the same way. The tests check both cases on a randomly perturbed lattice to .
One matrix entry, by hand. On a lattice in the unit box, , and . Take two nearest neighbors, and . The 2D cubic spline has . The off-diagonal entry of for this pair is
the value the implementation produces. The diagonal entry is the sum over all 20 neighbors, 404.26.
The operators on a lattice. Applied to and on an lattice, the operators give the right shape, with an amplitude below the exact one:
| 12 | 24 | 48 | |
|---|---|---|---|
| , amplitude / | 0.919 | 0.965 | 0.977 |
| and , amplitude / | 0.900 | 0.967 | 0.985 |
The error falls as the particles are refined, but more slowly than , because the lattice sums of the kernel do not match the integrals exactly at a fixed ratio (see the lattice table on the kernel page).
Projecting out a gradient. Take the Taylor-Green field , which has zero divergence, and add the gradient of . One projection (lines L5 and L6) should give back . The table gives the root mean square distance to after the projection; before it, the distance is 0.707. The jitter is a random shift of each particle of up to the given fraction of in each direction.
| 12 | 16 | 24 | |
|---|---|---|---|
| lattice | 0.118 | 0.068 | 0.031 |
| jitter 0.1 | 0.128 | 0.117 | 0.135 |
| jitter 0.3 | 0.231 | 0.298 | 0.403 |
On a lattice the projection converges at about second order. On disordered particles it does not converge: the error of the SPH operators on a disordered set grows like the disorder divided by . This is the main accuracy problem of ISPH, and the reason for particle shifting (see below).
Taylor-Green decay. In the unit periodic box with , the Taylor-Green vortex keeps its shape and its kinetic energy decays like . Runs from a lattice with ( to ) for 20 steps gave:
| 12 | 16 | 24 | 32 | |
|---|---|---|---|---|
| decay rate / exact | 0.936 | 0.959 | 0.976 | 0.983 |
| max velocity error | 0.0090 | 0.0061 | 0.0030 | 0.0025 |
| max before, after | 0.17, 0.087 | 0.18, 0.059 | 0.18, 0.043 | 0.18, 0.039 |
| CG iterations, last step | 8 | 15 | 24 | 31 |
The particle density stayed within 0.3% of its lattice value. The total momentum stayed at zero to . The divergence is reduced by a factor of 2 to 5 by each projection, not removed.
Correctness
The proof file shows four exact properties of the update. The matrix is symmetric and positive semidefinite, with the constants as its null space when the neighbor graph is connected, so the pressure system with the mean removed has a solution, and conjugate gradients from zero finds the zero-mean one. The pair terms of and of the viscous term are equal and opposite, so total momentum changes by exactly per step. The viscous term only removes kinetic energy. A uniform flow stays uniform. The proof does not claim , which is false for this approximate projection.
Proof: The ISPH pressure system is solvable, and the step conserves momentumfull
We use the notation of the page and of the implementation. There are particles in a periodic square box, each with volume and density . A pair is a pair of particles with , where is taken with the minimum image and . For a pair, , so and . The operators are
with , , and the viscous acceleration with . We claim, in exact arithmetic:
- The matrix is symmetric and positive semidefinite. If the graph of pairs is connected, its null space is the constant vectors, and the system with (where the bar is the mean over particles) has a solution. Conjugate gradients started from stays in the space of vectors with zero mean and reaches the unique zero-mean solution in at most iterations.
- Each step changes the total momentum by exactly . With the total momentum is constant.
- The viscous term never adds kinetic energy: .
- A uniform flow for all stays uniform: after one step every particle has velocity and has moved by .
The sign of the weights. For the cubic spline, for , which is negative for , and for . So on and for every pair. The weight depends only on , so .
Claim 1. The matrix has and for a pair, and 0 otherwise. It is symmetric because . For any vector , grouping the terms by pairs gives
So is positive semidefinite. If , then for every pair, because each ; if the graph of pairs is connected, is constant. So the null space is spanned by . Because is symmetric, its range is the orthogonal complement of its null space, which is the set of vectors with zero sum. The vector has zero sum by construction, so has a solution.
Let be the space of vectors with zero sum. Every row of sums to zero, and is symmetric, so every column sums to zero too, and for every . So maps every vector into , and in particular maps to itself. On the form is zero only for , so restricted to is symmetric positive definite. Conjugate gradients from builds its iterates in the Krylov space spanned by , which lies in . So it is ordinary conjugate gradients for a symmetric positive definite operator on the space of dimension , and it reaches the unique solution in in at most iterations. (In floating point the iteration stops at the residual tolerance instead.)
Claim 2. The velocity after a step is . Sum over . For the viscous term, each pair adds to and to , so . For the gradient, each pair adds to and to , so for every , whatever the solver returns. So , and multiplying by gives the claim. This also holds for the inexact of a stopped solver, and it does not need the positions of the predictor and the projection to be the same.
Claim 3. Group the sum by pairs:
because and . So for the viscous part of the motion.
Claim 4. If for all , every is zero, so and . Again every is zero, so and . Conjugate gradients returns at once (the initial residual is zero), so and . The position update gives . All particles move by the same vector, so their relative positions, and with them all pairs and weights, do not change, and the argument repeats at the next step.
These are exact statements about the update. They do not say that : the projection uses the compact , which is not the product , so the divergence measured by is reduced but not removed, and the page reports how large it stays. That the scheme approximates the incompressible Navier-Stokes equations is a consistency property of the SPH operators on regular particle arrangements, and it is checked by measurement on the page, not proved here.
Complexity
With a cell list, finding the pairs costs for a bounded number of neighbors per particle (about 20 in 2D at ). Building the matrix and each conjugate gradient iteration also cost . So a step costs and a run , with memory. Without a preconditioner, grows like the square root of the condition number of the Laplacian, so like in 2D (the table above: 8 to 31 iterations for to 32). Production codes use preconditioned CG, BiCGSTAB, or algebraic multigrid, which keep almost constant.
Properties
- Momentum is conserved exactly, for any solver tolerance, because the pressure and viscous forces act in equal and opposite pairs.
- Approximately incompressible. The density stays within a fraction of a percent of its rest value in smooth flows, much less than the 1% of weakly compressible SPH, but the discrete divergence is not zero.
- Time step set by the flow, through a limit on , and by viscosity, not by a sound speed.
- Smooth pressure. The pressure comes from an elliptic solve, so it has much less noise than an equation of state applied to density errors.
- Galilean invariant: only velocity differences enter , and the viscous term.
Variants and improvements
- Source term. Cummins and Rudman (1999) use the divergence of , as here. Shao and Lo (2003) use a source proportional to the density error, , which keeps the density on target but gives noisy pressures. Xu, Stansby and Laurence (2009) compare the two on Taylor-Green and spin-down tests.
- Particle shifting. Xu, Stansby and Laurence (2009) move each particle slightly away from crowded neighbors after each step and correct its velocity by a Taylor expansion. This keeps the particles regular, so the disorder error of the table above does not grow. Lind and co-authors later based the shift on Fick's law of diffusion.
- Free surfaces. Particles whose density or neighbor count is below a threshold are marked as surface particles and get as a Dirichlet condition, which also removes the null space.
- Exact projection. Using itself as the Laplacian makes exact, with a stencil that reaches . In a test run with the operators above, one such step on the moved particles of the Taylor-Green case cut the kinetic energy from 0.25 to , so the exact discrete projection is not a cure. Practical codes use the compact Laplacian.
- Graphics solvers. IISPH solves a pressure equation with the density error as source by relaxed Jacobi; DFSPH runs a divergence solve and a density solve each step; PCISPH corrects pressures by a fixed factor in a predict-correct loop. They stop after a few iterations or a density error of 0.1% to 1%, which is what animation needs.
- Semi-implicit particle methods of the same family solve a similar Poisson equation with a different weight function.
When to use it
Use ISPH for liquids where the pressure matters: wave loads on structures, sloshing tanks, dam breaks, flows at low Reynolds number. There the noise of a weakly compressible pressure is a problem and the time step of a stiff equation of state is too small. Use weakly compressible SPH when the code must be explicit and simple to run in parallel, or when the flow has violent splashing and fragmentation where the pressure solve is hard to set up. For graphics, the faster IISPH and DFSPH are the usual choice. For flows in a fixed domain without free surfaces, a grid projection method is usually more accurate for the same work.
Pitfalls
- Particle disorder. The table shows that on disordered particles the projection error does not go down with refinement. Without shifting or another regularization, a long run becomes noisy and the particles form clumps and voids.
- An inconsistent right-hand side. In a periodic box, or with only Neumann conditions, , which is zero on a lattice but not on disordered particles. Without removing the mean, the pressure system has no solution and the solver stalls.
- Expecting zero divergence. The compact Laplacian is not , so is reduced but not zero. Test with the density error and with flows that have exact solutions, not with alone.
- The sign of . is negative semidefinite. Conjugate gradients needs the positive matrix , so the right-hand side changes sign too, as on line L5.
- Solving at the wrong positions. The pressure equation of line L5 must use the neighbor pairs at , not at , or the correction is applied to a different particle arrangement than the one it was computed for.
- Mixing the time scale into the pressure. With , a change of changes ; plot .
- Kernel truncation at free surfaces. Near a free surface the kernel support is only partly filled, so and are wrong there. Surface detection and the Dirichlet condition must be done with care.
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/incompressible-sph/. The authors are listed in prov/H0ZQP6.jsonl.
"""Incompressible SPH (ISPH) by a projection step, in a periodic 2D box.
The fluid has the constant density rho0 = 1, so every particle has the volume
V = m / rho0 = L^2 / N. The kernel is the 2D cubic spline with support 2h.
One step of the scheme (a first-order projection, as in Cummins and Rudman 1999):
v* = v + dt (nu lap v + g) viscous predictor at the old positions
x* = x + dt v provisional positions
solve L phi = D v* pressure Poisson equation at x*
v' = v* - G phi projection, the pressure is p = phi / dt
x' = x + dt (v + v') / 2
The discrete operators, for particles i and their neighbours j within 2h:
(G phi)_i = sum_j V (phi_i + phi_j) grad_i W_ij symmetric gradient, conserves momentum
(D v)_i = -sum_j V (v_i - v_j) . grad_i W_ij SPH divergence
(L phi)_i = sum_j 2 V (phi_i - phi_j) x_ij . grad_i W_ij / (r_ij^2 + eta^2) compact Laplacian
with eta^2 = 0.01 h^2. L is not D G, so the projection is approximate: D v' is
reduced but not zero. The matrix -L is symmetric positive semidefinite with
constant null vectors, so the right-hand side is made consistent by removing its mean.
The viscous term is the one of Morris, Fox and Zhu (1997) with constant density:
(nu lap v)_i = sum_j 2 nu V (x_ij . grad_i W_ij) / (r_ij^2 + eta^2) (v_i - v_j)
"""
from __future__ import annotations
import math
import random
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Sequence, Tuple
from scisparse import cg
Vec = Tuple[float, float]
Pair = Tuple[int, int, float, float, float, float, float]
@dataclass
class ISPHState:
x: List[float]
y: List[float]
u: List[float]
v: List[float]
box: float
h: float
@dataclass
class StepInfo:
div_before: float # max |D v*| at x*
div_after: float # max |D v'| at x*
cg_iterations: int
def kernel_2d(r: float, h: float) -> float:
"""Cubic spline W(r, h) in 2D, normalization 10 / (7 pi h^2), support 2h."""
q = r / h
s = 10.0 / (7.0 * math.pi * h * h)
if q < 1.0:
return s * (1.0 - 1.5 * q * q + 0.75 * q ** 3)
if q < 2.0:
return s * 0.25 * (2.0 - q) ** 3
return 0.0
def kernel_derivative_2d(r: float, h: float) -> float:
"""dW/dr of the 2D cubic spline."""
q = r / h
s = 10.0 / (7.0 * math.pi * h ** 3)
if q < 1.0:
return s * (-3.0 * q + 2.25 * q * q)
if q < 2.0:
return -s * 0.75 * (2.0 - q) ** 2
return 0.0
def neighbour_pairs(x: Sequence[float], y: Sequence[float], box: float, h: float) -> List[Pair]:
"""All pairs (i, j, dx, dy, dW/dx_i, dW/dy_i, r) with i < j and 0 < r < 2h, minimum image.
A cell list with cells of side at least 2h; cost O(N k) for k neighbours per
particle. Requires box >= 6h so that each pair is found once.
"""
n = len(x)
nc = int(box // (2.0 * h))
if nc < 3:
raise ValueError("the box must be at least 6h wide")
cell = box / nc
cells: Dict[Tuple[int, int], List[int]] = {}
for i in range(n):
key = (int(x[i] // cell) % nc, int(y[i] // cell) % nc)
cells.setdefault(key, []).append(i)
pairs: List[Pair] = []
cut = 4.0 * h * h
half = 0.5 * box
for (cx, cy), members in cells.items():
near: List[int] = []
for ox in (-1, 0, 1):
for oy in (-1, 0, 1):
near.extend(cells.get(((cx + ox) % nc, (cy + oy) % nc), ()))
for i in members:
for j in near:
if j <= i:
continue
dx = x[i] - x[j]
dy = y[i] - y[j]
if dx > half:
dx -= box
elif dx < -half:
dx += box
if dy > half:
dy -= box
elif dy < -half:
dy += box
r2 = dx * dx + dy * dy
if 0.0 < r2 < cut:
r = math.sqrt(r2)
d = kernel_derivative_2d(r, h) / r
pairs.append((i, j, dx, dy, d * dx, d * dy, r))
pairs.sort()
return pairs
def density(pairs: Sequence[Pair], n: int, vol: float, h: float) -> List[float]:
"""Summation density rho_i = sum_j V W_ij with rho0 = 1 (self term included)."""
rho = [vol * kernel_2d(0.0, h)] * n
for i, j, _, _, _, _, r in pairs:
w = vol * kernel_2d(r, h)
rho[i] += w
rho[j] += w
return rho
def divergence(pairs: Sequence[Pair], u: Sequence[float], v: Sequence[float], vol: float) -> List[float]:
"""(D v)_i = -sum_j V (v_i - v_j) . grad_i W_ij."""
out = [0.0] * len(u)
for i, j, _, _, gx, gy, _ in pairs:
w = -vol * ((u[i] - u[j]) * gx + (v[i] - v[j]) * gy)
out[i] += w
out[j] += w # (v_j - v_i) . grad_j W_ji is the same number
return out
def gradient(pairs: Sequence[Pair], phi: Sequence[float], vol: float) -> Tuple[List[float], List[float]]:
"""(G phi)_i = sum_j V (phi_i + phi_j) grad_i W_ij, antisymmetric in each pair."""
gxo = [0.0] * len(phi)
gyo = [0.0] * len(phi)
for i, j, _, _, gx, gy, _ in pairs:
s = vol * (phi[i] + phi[j])
gxo[i] += s * gx
gyo[i] += s * gy
gxo[j] -= s * gx
gyo[j] -= s * gy
return gxo, gyo
def viscous_term(pairs: Sequence[Pair], u: Sequence[float], v: Sequence[float], vol: float,
nu: float, h: float) -> Tuple[List[float], List[float]]:
"""Morris, Fox and Zhu viscous acceleration, pairwise antisymmetric."""
n = len(u)
au = [0.0] * n
av = [0.0] * n
eta2 = 0.01 * h * h
for i, j, dx, dy, gx, gy, r in pairs:
c = 2.0 * nu * vol * (dx * gx + dy * gy) / (r * r + eta2) # c <= 0
du = c * (u[i] - u[j])
dv = c * (v[i] - v[j])
au[i] += du
av[i] += dv
au[j] -= du
av[j] -= dv
return au, av
def laplacian_matrix(pairs: Sequence[Pair], n: int, vol: float, h: float) -> List[Dict[int, float]]:
"""A = -L for the compact Laplacian; symmetric, diagonally dominant, rows sum to zero."""
A: List[Dict[int, float]] = [dict() for _ in range(n)]
eta2 = 0.01 * h * h
for i, j, dx, dy, gx, gy, r in pairs:
c = -2.0 * vol * (dx * gx + dy * gy) / (r * r + eta2) # c >= 0
A[i][i] = A[i].get(i, 0.0) + c
A[j][j] = A[j].get(j, 0.0) + c
A[i][j] = A[i].get(j, 0.0) - c
A[j][i] = A[j].get(i, 0.0) - c
return A
def pressure_solve(pairs: Sequence[Pair], u: Sequence[float], v: Sequence[float], vol: float,
h: float, tol: float = 1e-12) -> Tuple[List[float], int]:
"""Solve L phi = D v - mean(D v) by CG on -L; returns (phi with mean 0, iterations)."""
n = len(u)
div = divergence(pairs, u, v, vol)
A = laplacian_matrix(pairs, n, vol, h)
mean = sum(div) / n
b = [mean - d for d in div] # -L phi = -(D v - mean), a consistent system
return cg(A, b, tol=tol)
def project(pairs: Sequence[Pair], u: Sequence[float], v: Sequence[float], vol: float, h: float,
tol: float = 1e-12) -> Tuple[List[float], List[float], List[float], int]:
"""Return (u', v', phi, CG iterations) with (u', v') = (u, v) - G phi."""
n = len(u)
phi, its = pressure_solve(pairs, u, v, vol, h, tol)
gx, gy = gradient(pairs, phi, vol)
return [u[i] - gx[i] for i in range(n)], [v[i] - gy[i] for i in range(n)], phi, its
def isph_step(s: ISPHState, dt: float, nu: float = 0.0, g: Vec = (0.0, 0.0),
tol: float = 1e-12) -> Tuple[ISPHState, StepInfo]:
"""One projection step. Cost O(N k) to build plus O(N k) per CG iteration."""
n = len(s.x)
vol = s.box * s.box / n
pairs = neighbour_pairs(s.x, s.y, s.box, s.h) # @line L2
if nu:
au, av = viscous_term(pairs, s.u, s.v, vol, nu, s.h)
else:
au, av = [0.0] * n, [0.0] * n
us = [s.u[i] + dt * (au[i] + g[0]) for i in range(n)] # @line L3
vs = [s.v[i] + dt * (av[i] + g[1]) for i in range(n)]
xs = [(s.x[i] + dt * s.u[i]) % s.box for i in range(n)] # @line L4
ys = [(s.y[i] + dt * s.v[i]) % s.box for i in range(n)]
pairs = neighbour_pairs(xs, ys, s.box, s.h)
d0 = divergence(pairs, us, vs, vol)
phi, its = pressure_solve(pairs, us, vs, vol, s.h, tol) # @line L5
gx, gy = gradient(pairs, phi, vol)
un = [us[i] - gx[i] for i in range(n)] # @line L6
vn = [vs[i] - gy[i] for i in range(n)]
d1 = divergence(pairs, un, vn, vol)
xn = [(s.x[i] + 0.5 * dt * (s.u[i] + un[i])) % s.box for i in range(n)] # @line L7
yn = [(s.y[i] + 0.5 * dt * (s.v[i] + vn[i])) % s.box for i in range(n)]
info = StepInfo(max(abs(d) for d in d0), max(abs(d) for d in d1), its)
return ISPHState(xn, yn, un, vn, s.box, s.h), info
def isph(s0: ISPHState, dt: float, steps: int, nu: float = 0.0, g: Vec = (0.0, 0.0),
tol: float = 1e-12) -> Tuple[ISPHState, List[StepInfo]]:
"""Run `steps` ISPH steps from s0, which is not changed.
Precondition: dt > 0, steps >= 0, box >= 6h. Cost: steps times one pressure
solve on N particles with about 20 neighbours each.
"""
if dt <= 0 or steps < 0:
raise ValueError("need dt > 0 and steps >= 0")
s = ISPHState(list(s0.x), list(s0.y), list(s0.u), list(s0.v), s0.box, s0.h)
infos: List[StepInfo] = []
for _ in range(steps): # @line L1
s, info = isph_step(s, dt, nu, g, tol)
infos.append(info)
return s, infos # @line L8
def lattice(n: int, box: float = 1.0, eta: float = 1.2,
velocity: Optional[Callable[[float, float], Vec]] = None,
jitter: float = 0.0, seed: int = 0) -> ISPHState:
"""n x n particles on a square lattice, h = eta * spacing, optional random jitter."""
rng = random.Random(seed)
dx = box / n
x: List[float] = []
y: List[float] = []
u: List[float] = []
v: List[float] = []
for a in range(n):
for b in range(n):
px = ((a + 0.5) * dx + jitter * dx * (rng.random() - 0.5)) % box
py = ((b + 0.5) * dx + jitter * dx * (rng.random() - 0.5)) % box
x.append(px)
y.append(py)
vx, vy = velocity(px, py) if velocity else (0.0, 0.0)
u.append(vx)
v.append(vy)
return ISPHState(x, y, u, v, box, eta * dx)
def kinetic_energy(s: ISPHState) -> float:
"""(1/2) sum V |v|^2 with V = box^2 / N and rho0 = 1."""
vol = s.box * s.box / len(s.x)
return 0.5 * vol * sum(a * a + b * b for a, b in zip(s.u, s.v))
def momentum(s: ISPHState) -> Vec:
"""Total momentum sum V v with rho0 = 1."""
vol = s.box * s.box / len(s.x)
return (vol * sum(s.u), vol * sum(s.v))
def taylor_green(x: float, y: float) -> Vec:
"""A divergence-free periodic field on the unit box; KE decays like exp(-16 pi^2 nu t)."""
k = 2.0 * math.pi
return (-math.cos(k * x) * math.sin(k * y), math.sin(k * x) * math.cos(k * y))
scisparse.py 189 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Tridiagonal solvers, sparse matrices and simple iterative solvers.
A vector is a list. A sparse matrix is a list of rows, and each row is a
dict that maps a column index to a value. Entries may be int, float or
fractions.Fraction. thomas, thomas_periodic, spmatvec, from_dense and
to_dense keep Fraction entries exact. cg takes square roots and works in
float.
API (fixed; other pages copy this file byte for byte):
thomas(a, b, c, d) solve a tridiagonal system. Row i reads
a[i] x[i-1] + b[i] x[i] + c[i] x[i+1] = d[i];
a[0] and c[n-1] are not used.
thomas_periodic(a, b, c, d) solve a cyclic tridiagonal system: as
thomas, but a[0] multiplies x[n-1] and
c[n-1] multiplies x[0]. Uses the
Sherman-Morrison formula. n >= 3.
from_dense(A) sparse copy of a dense matrix (drops zeros)
to_dense(A, ncols=None) dense copy of a sparse matrix
spmatvec(A, x) A times x
poisson2d(nx, ny, dx, dy, bc="dirichlet")
the matrix of MINUS the 5-point Laplacian
on nx by ny unknowns, numbered
k = i + nx * j (i along x, j along y).
bc = "dirichlet": unknowns at the interior
nodes ((i + 1) dx, (j + 1) dy) with zero
values outside; the matrix is symmetric
positive definite.
bc = "periodic": the grid wraps around in
both directions; the matrix is symmetric
positive semidefinite, and its null space
is the constant vectors.
bc = "neumann": unknowns at cell centers,
zero normal derivative at the walls (a
missing neighbor drops out of the
stencil); null space as for "periodic".
cg(A, b, tol=1e-10, maxit=None, x0=None)
conjugate gradient for a symmetric
positive (semi)definite A. Stops when
||b - A x||_2 <= tol * ||b||_2. Returns
(x, iterations). For a singular A, b must
be in the range of A (for the Poisson
matrices above: sum(b) = 0).
gauss_seidel(A, b, iters, x0=None)
iters forward Gauss-Seidel sweeps; every
row needs a nonzero diagonal entry.
"""
import math
def thomas(a, b, c, d):
n = len(d)
if n == 0:
return []
cp = [0] * n
dp = [0] * n
cp[0] = c[0] / b[0] if n > 1 else 0
dp[0] = d[0] / b[0]
for i in range(1, n):
m = b[i] - a[i] * cp[i - 1]
if i < n - 1:
cp[i] = c[i] / m
dp[i] = (d[i] - a[i] * dp[i - 1]) / m
x = [0] * n
x[n - 1] = dp[n - 1]
for i in range(n - 2, -1, -1):
x[i] = dp[i] - cp[i] * x[i + 1]
return x
def thomas_periodic(a, b, c, d):
"""Cyclic tridiagonal solve. A = T + u v^T with u = (gamma, 0, .., 0, c[n-1])
and v = (1, 0, .., 0, a[0] / gamma), so T is tridiagonal."""
n = len(d)
if n < 3:
raise ValueError("thomas_periodic needs n >= 3")
gamma = -b[0]
bb = list(b)
bb[0] = b[0] - gamma
bb[n - 1] = b[n - 1] - c[n - 1] * a[0] / gamma
y = thomas(a, bb, c, d)
u = [0] * n
u[0] = gamma
u[n - 1] = c[n - 1]
z = thomas(a, bb, c, u)
vy = y[0] + a[0] * y[n - 1] / gamma
vz = z[0] + a[0] * z[n - 1] / gamma
f = vy / (1 + vz)
return [y[i] - f * z[i] for i in range(n)]
def from_dense(A):
return [{j: v for j, v in enumerate(row) if v != 0} for row in A]
def to_dense(A, ncols=None):
if ncols is None:
ncols = len(A)
out = []
for row in A:
r = [0] * ncols
for j, v in row.items():
r[j] = v
out.append(r)
return out
def spmatvec(A, x):
return [sum(v * x[j] for j, v in row.items()) for row in A]
def poisson2d(nx, ny, dx, dy, bc="dirichlet"):
if bc not in ("dirichlet", "periodic", "neumann"):
raise ValueError("bc must be dirichlet, periodic or neumann")
cx = 1 / (dx * dx)
cy = 1 / (dy * dy)
A = []
for j in range(ny):
for i in range(nx):
row = {}
k = i + nx * j
for (ii, jj, w) in ((i - 1, j, cx), (i + 1, j, cx), (i, j - 1, cy), (i, j + 1, cy)):
inside = 0 <= ii < nx and 0 <= jj < ny
if bc == "periodic":
ii %= nx
jj %= ny
inside = True
if bc == "neumann" and not inside:
continue
row[k] = row.get(k, 0) + w
if inside:
m = ii + nx * jj
row[m] = row.get(m, 0) - w
A.append({m: v for m, v in row.items() if v != 0})
return A
def cg(A, b, tol=1e-10, maxit=None, x0=None):
n = len(b)
if maxit is None:
maxit = 10 * n
x = [0.0] * n if x0 is None else [float(v) for v in x0]
if x0 is None:
r = [float(v) for v in b]
else:
ax = spmatvec(A, x)
r = [b[i] - ax[i] for i in range(n)]
bnorm = math.sqrt(sum(float(v) * float(v) for v in b))
stop = tol * bnorm
rr = sum(v * v for v in r)
if math.sqrt(rr) <= stop:
return x, 0
p = list(r)
for it in range(1, maxit + 1):
ap = spmatvec(A, p)
pap = sum(p[i] * ap[i] for i in range(n))
if pap <= 0:
return x, it
alpha = rr / pap
for i in range(n):
x[i] += alpha * p[i]
r[i] -= alpha * ap[i]
rr_new = sum(v * v for v in r)
if math.sqrt(rr_new) <= stop:
return x, it
beta = rr_new / rr
rr = rr_new
p = [r[i] + beta * p[i] for i in range(n)]
return x, maxit
def gauss_seidel(A, b, iters, x0=None):
n = len(b)
x = [0] * n if x0 is None else list(x0)
for _ in range(iters):
for i in range(n):
row = A[i]
s = b[i]
diag = 0
for j, v in row.items():
if j == i:
diag = v
else:
s -= v * x[j]
x[i] = s / diag
return x
test_incompressible_sph.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/incompressible-sph/. The authors are listed in prov/H0ZQP6.jsonl.
import math
import random
from incompressible_sph import (
density,
divergence,
gradient,
isph,
kernel_2d,
kernel_derivative_2d,
kinetic_energy,
laplacian_matrix,
lattice,
momentum,
neighbour_pairs,
pressure_solve,
project,
taylor_green,
viscous_term,
)
from scisparse import spmatvec
def setup(n=12, jitter=0.3, seed=1, velocity=taylor_green):
s = lattice(n, velocity=velocity, jitter=jitter, seed=seed)
vol = 1.0 / (n * n)
return s, vol, neighbour_pairs(s.x, s.y, s.box, s.h)
def test_kernel_normalization_and_lattice_density():
h = 0.3
steps = 4000
total = 0.0
for k in range(steps): # integral of W over the disc of radius 2h
r = (k + 0.5) * 2 * h / steps
total += kernel_2d(r, h) * 2 * math.pi * r * 2 * h / steps
assert abs(total - 1) < 1e-6
eps = 1e-6
for r in (0.1, 0.35, 0.5):
num = (kernel_2d(r + eps, h) - kernel_2d(r - eps, h)) / (2 * eps)
assert abs(num - kernel_derivative_2d(r, h)) < 1e-5
s, vol, pairs = setup(jitter=0.0)
rho = density(pairs, len(s.x), vol, s.h)
assert max(abs(r - 0.9997573067) for r in rho) < 1e-9 # lattice sum, h = 1.2 dx
def test_neighbour_pairs_match_brute_force():
s, vol, pairs = setup(n=10, jitter=0.8, seed=3)
found = {(i, j) for i, j, *_ in pairs}
brute = set()
n = len(s.x)
for i in range(n):
for j in range(i + 1, n):
dx = (s.x[i] - s.x[j] + 0.5) % 1.0 - 0.5
dy = (s.y[i] - s.y[j] + 0.5) % 1.0 - 0.5
if dx * dx + dy * dy < 4 * s.h * s.h:
brute.add((i, j))
assert found == brute
def test_laplacian_matrix_is_symmetric_with_zero_row_sums():
s, vol, pairs = setup()
A = laplacian_matrix(pairs, len(s.x), vol, s.h)
for i, row in enumerate(A):
assert abs(sum(row.values())) < 1e-9 * row[i]
for j, a in row.items():
assert abs(a - A[j][i]) < 1e-12 * row[i]
assert (a > 0) if j == i else (a <= 0)
rng = random.Random(7)
x = [rng.uniform(-1, 1) for _ in A]
ax = spmatvec(A, x)
assert sum(a * b for a, b in zip(x, ax)) > 0 # positive on a nonconstant vector
def test_pressure_solve_is_consistent():
s, vol, pairs = setup()
phi, its = pressure_solve(pairs, s.u, s.v, vol, s.h)
assert its < len(s.x)
div = divergence(pairs, s.u, s.v, vol)
mean = sum(div) / len(div)
A = laplacian_matrix(pairs, len(s.x), vol, s.h)
res = [a + d - mean for a, d in zip(spmatvec(A, phi), div)] # -L phi + (D v - mean)
assert max(abs(r) for r in res) < 1e-9 * max(abs(d) for d in div)
assert abs(sum(phi)) < 1e-9 * max(abs(p) for p in phi)
def test_pair_terms_conserve_momentum_and_viscosity_dissipates():
s, vol, pairs = setup()
rng = random.Random(11)
phi = [rng.uniform(-1, 1) for _ in s.x]
gx, gy = gradient(pairs, phi, vol)
assert abs(sum(gx)) < 1e-10 and abs(sum(gy)) < 1e-10
u = [rng.uniform(-1, 1) for _ in s.x]
v = [rng.uniform(-1, 1) for _ in s.x]
au, av = viscous_term(pairs, u, v, vol, 0.1, s.h)
assert abs(sum(au)) < 1e-10 and abs(sum(av)) < 1e-10
assert sum(a * b for a, b in zip(u, au)) + sum(a * b for a, b in zip(v, av)) < 0
def test_uniform_flow_and_gravity_are_kept_exactly():
s = lattice(12, velocity=lambda x, y: (0.3, -0.2), jitter=0.3, seed=5)
s1, infos = isph(s, 0.01, 5, nu=0.05)
assert max(abs(a - 0.3) for a in s1.u) < 1e-14 and max(abs(b + 0.2) for b in s1.v) < 1e-14
assert all(info.cg_iterations == 0 for info in infos)
for i in range(len(s.x)):
assert abs((s1.x[i] - s.x[i] - 0.015 + 0.5) % 1.0 - 0.5) < 1e-12
assert abs((s1.y[i] - s.y[i] + 0.010 + 0.5) % 1.0 - 0.5) < 1e-12
s2, _ = isph(lattice(12), 0.01, 4, g=(0.0, -1.0))
assert max(abs(b + 0.04) for b in s2.v) < 1e-14
def tg_plus_gradient(x, y):
a, b = taylor_green(x, y)
k = 2 * math.pi # add the gradient of sin(kx) sin(ky) / k
return a + math.cos(k * x) * math.sin(k * y), b + math.sin(k * x) * math.cos(k * y)
def rms_distance_to_tg(s, u, v):
tot = 0.0
for i in range(len(s.x)):
a, b = taylor_green(s.x[i], s.y[i])
tot += (u[i] - a) ** 2 + (v[i] - b) ** 2
return math.sqrt(tot / len(s.x))
def test_projection_removes_a_gradient_field():
errs = []
for n in (12, 16):
s, vol, pairs = setup(n=n, jitter=0.0, velocity=tg_plus_gradient)
u, v, phi, its = project(pairs, s.u, s.v, vol, s.h)
assert abs(rms_distance_to_tg(s, s.u, s.v) - math.sqrt(0.5)) < 1e-12
errs.append(rms_distance_to_tg(s, u, v))
assert abs(errs[0] - 0.1177) < 2e-4 and abs(errs[1] - 0.0683) < 2e-4
s, vol, pairs = setup(jitter=0.3, velocity=tg_plus_gradient)
u, v, phi, its = project(pairs, s.u, s.v, vol, s.h)
assert 0.2 < rms_distance_to_tg(s, u, v) < 0.26 # disorder error, does not shrink with n
assert abs(sum(u) - sum(s.u)) < 1e-12 and abs(sum(v) - sum(s.v)) < 1e-12
def test_taylor_green_decay_rate():
ratios = []
for n in (12, 16):
s = lattice(n, velocity=taylor_green)
s1, infos = isph(s, 0.002, 20, nu=0.05)
rate = -math.log(kinetic_energy(s1) / kinetic_energy(s)) / 0.04
ratios.append(rate / (16 * math.pi ** 2 * 0.05))
assert max(i.div_after for i in infos) < 0.6 * max(i.div_before for i in infos)
mx, my = momentum(s1)
assert abs(mx) < 1e-14 and abs(my) < 1e-14
rho = density(neighbour_pairs(s1.x, s1.y, 1.0, s1.h), n * n, 1.0 / (n * n), s1.h)
assert max(abs(r / 0.9997573067 - 1) for r in rho) < 0.004
assert abs(ratios[0] - 0.93606) < 2e-4 and abs(ratios[1] - 0.95917) < 2e-4
assert abs(1 - ratios[1]) < abs(1 - ratios[0])
def test_rejects_bad_input():
s = lattice(12)
for dt, steps in ((0.0, 1), (0.01, -1)):
try:
isph(s, dt, steps)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
try:
neighbour_pairs([0.1], [0.1], 1.0, 0.2)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
History
Cummins and Rudman (1999) wrote SPH as a projection method: integrate the velocity without the pressure, then project it onto a divergence-free field by a pressure Poisson equation, in the spirit of the Helmholtz-Hodge decomposition. Shao and Lo (2003) applied the idea to dam breaks and mudflows with free surfaces, using a source term from the density error. Xu, Stansby and Laurence (2009) analyzed the accuracy of the variants and introduced particle shifting, which made long ISPH runs stable and accurate. In computer graphics, PCISPH (2009), IISPH (2014) and DFSPH (2015) brought pressure solves on particles to animation, with simpler solvers and looser tolerances.
References
- Sharen J. Cummins and Murray Rudman, An SPH projection method, Journal of Computational Physics 152 (1999) 584-607, the fractional step, the approximate projection and the pressure Poisson equation on particles
- Songdong Shao and Edmond Y. M. Lo, Incompressible SPH method for simulating Newtonian and non-Newtonian flows with a free surface, Advances in Water Resources 26 (2003) 787-800, the prediction-correction steps, the density-invariance source term and the free-surface condition
- Joseph P. Morris, Patrick J. Fox and Yi Zhu, Modeling low Reynolds number incompressible flows using SPH, Journal of Computational Physics 136 (1997) 214-226, the SPH viscous term with the first derivative of the kernel
- Rui Xu, Peter Stansby and Dominique Laurence, Accuracy and stability in incompressible SPH (ISPH) based on the projection method and a new approach, Journal of Computational Physics 228 (2009) 6703-6725, divergence-free and density-invariant source terms, Taylor-Green tests and particle shifting
- Joseph J. Monaghan, Smoothed particle hydrodynamics, Reports on Progress in Physics 68 (2005) 1703-1759
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 H0ZQP6 Edit this page History Report an error Markdown