Algorithm Search⌘K

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.

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
Properties
conserves momentum exactlydeterministiclagrangianlinear solve per stepmeshless
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 ∂tv+v⋅∇v=−∇p/ρ0+ν∇2v+g\partial_tv + v \cdot \nabla v = -\nabla p/\rho_0 + \nu\nabla^2v + g, ∇⋅v=0\nabla \cdot v = 0, in Lagrangian form: particles at positions xix_i with velocities viv_i follow x˙i=vi\dot x_i = v_i. The density is the constant ρ0\rho_0 (here ρ0=1\rho_0 = 1), so each of the NN particles carries the same volume VV in a periodic box of area NVNV. The output is the particle positions and velocities at time KΔtK\Delta t. Here ν\nu is the kinematic viscosity; the Courant number is written Co=∣v∣max⁡Δt/h\mathrm{Co} = |v|_{\max}\Delta t/h.

The algorithm

  1. ISPH(x, v, Δt, K; ν, g)
  2. 1repeat K times
  3. 2find the pairs (i, j) with |x_i - x_j| < 2h ▷ cell list
  4. 3v* ← v + Δt (ν ∇²_h v + g) ▷ viscous predictor
  5. 4x* ← x + Δt v
  6. 5at x*: solve -L φ = mean(D v*) - D v* by conjugate gradients ▷ pressure Poisson equation
  7. 6v' ← v* - G φ ▷ projection, p = φ / Δt
  8. 7x ← x + Δt (v + v') / 2; v ← v'
  9. 8return x, v

The kernel is the cubic SPH smoothing kernel W(r,h)W(r, h) in 2D with support 2h2h and h=1.2Δxh = 1.2\Delta x, where Δx\Delta x is the initial particle spacing. For a pair, xij=xi−xjx_{ij} = x_i - x_j (with the minimum image in a periodic box), vij=vi−vjv_{ij} = v_i - v_j, and η2=0.01h2\eta^2 = 0.01h^2. The discrete operators are

(Dv)i=−∑jV vij⋅∇iWij,(Gϕ)i=∑jV(ϕi+ϕj)∇iWij,(D v)_i = -\sum_j V\,v_{ij} \cdot \nabla_iW_{ij}, \qquad (G\phi)_i = \sum_j V(\phi_i + \phi_j)\nabla_iW_{ij},
(Lϕ)i=∑j2V xij⋅∇iWijrij2+η2(ϕi−ϕj),(ν∇h2v)i=∑j2νV xij⋅∇iWijrij2+η2 vij.(L\phi)_i = \sum_j \frac{2V\,x_{ij} \cdot \nabla_iW_{ij}}{r_{ij}^2 + \eta^2}(\phi_i - \phi_j), \qquad (\nu\nabla_h^2v)_i = \sum_j \frac{2\nu V\,x_{ij} \cdot \nabla_iW_{ij}}{r_{ij}^2 + \eta^2}\,v_{ij}.

DD is the standard SPH divergence; GG is the symmetric SPH gradient, whose pair terms are equal and opposite. LL is the compact SPH Laplacian, which uses only the first derivative of the kernel and so links only neighbors within 2h2h; 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 −L-L is symmetric and positive semidefinite, with the constants as its null space, so the right-hand side has its mean removed; the solution ϕ\phi 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 UU, every vijv_{ij} is zero. Then the viscous term is zero, Dv∗=0Dv^* = 0, the solver returns ϕ=0\phi = 0 in zero iterations, and the flow stays uniform; all particles move by Δt U\Delta t\,U. With gravity in a periodic box, every velocity becomes U+Δt gU + \Delta t\,g in the same way. The tests check both cases on a randomly perturbed lattice to 10−1410^{-14}.

One matrix entry, by hand. On a 12×1212 \times 12 lattice in the unit box, Δx=112\Delta x = \frac1{12}, h=0.1h = 0.1 and V=1144V = \frac1{144}. Take two nearest neighbors, r=Δxr = \Delta x and q=r/h=56q = r/h = \frac56. The 2D cubic spline has W′(r)=107πh3(−3q+94q2)=454.728⋅(−0.9375)=−426.307W'(r) = \frac{10}{7\pi h^3}(-3q + \frac94q^2) = 454.728 \cdot (-0.9375) = -426.307. The off-diagonal entry of −L-L for this pair is

−cij=2V rW′(r)r2+η2=2⋅1144⋅112⋅(−426.307)1144+0.0001=−70.04,-c_{ij} = \frac{2V\,rW'(r)}{r^2 + \eta^2} = \frac{2 \cdot \frac1{144} \cdot \frac1{12} \cdot (-426.307)}{\frac1{144} + 0.0001} = -70.04,

the value the implementation produces. The diagonal entry is the sum over all 20 neighbors, 404.26.

The operators on a lattice. Applied to cos⁡2πx\cos 2\pi x and sin⁡2πx\sin 2\pi x on an n×nn \times n lattice, the operators give the right shape, with an amplitude below the exact one:

nn 12 24 48
LL, amplitude / 4π24\pi^2 0.919 0.965 0.977
GG and DD, amplitude / 2π2\pi 0.900 0.967 0.985

The error falls as the particles are refined, but more slowly than h2h^2, because the lattice sums of the kernel do not match the integrals exactly at a fixed ratio h/Δxh/\Delta x (see the lattice table on the kernel page).

Projecting out a gradient. Take the Taylor-Green field vTG=(−cos⁡2πxsin⁡2πy, sin⁡2πxcos⁡2πy)v_{TG} = (-\cos 2\pi x\sin 2\pi y,\ \sin 2\pi x\cos 2\pi y), which has zero divergence, and add the gradient of sin⁡(2πx)sin⁡(2πy)/(2π)\sin(2\pi x)\sin(2\pi y)/(2\pi). One projection (lines L5 and L6) should give back vTGv_{TG}. The table gives the root mean square distance to vTGv_{TG} 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 Δx\Delta x in each direction.

nn 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 hh. 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 ν=0.05\nu = 0.05, the Taylor-Green vortex keeps its shape and its kinetic energy decays like e−16π2νte^{-16\pi^2\nu t}. Runs from a lattice with Δt=0.002\Delta t = 0.002 (Co≈0.02\mathrm{Co} \approx 0.02 to 0.060.06) for 20 steps gave:

nn 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 ∣Dv∗∣\lvert Dv^*\rvert 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 ∑jVWij\sum_jVW_{ij} stayed within 0.3% of its lattice value. The total momentum stayed at zero to 10−1710^{-17}. 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 −L-L 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 GG and of the viscous term are equal and opposite, so total momentum changes by exactly NVΔt gNV\Delta t\,g per step. The viscous term only removes kinetic energy. A uniform flow stays uniform. The proof does not claim Dv′=0Dv' = 0, 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 NN particles in a periodic square box, each with volume VV and density ρ0=1\rho_0 = 1. A pair (i,j)(i, j) is a pair of particles with 0<rij<2h0 < r_{ij} < 2h, where xij=xi−xjx_{ij} = x_i - x_j is taken with the minimum image and rij=∣xij∣r_{ij} = |x_{ij}|. For a pair, ∇iWij=W′(rij) xij/rij\nabla_iW_{ij} = W'(r_{ij})\,x_{ij}/r_{ij}, so xij⋅∇iWij=rijW′(rij)x_{ij} \cdot \nabla_iW_{ij} = r_{ij}W'(r_{ij}) and ∇jWji=−∇iWij\nabla_jW_{ji} = -\nabla_iW_{ij}. The operators are

(Gϕ)i=∑jV(ϕi+ϕj)∇iWij,(Dv)i=−∑jV vij⋅∇iWij,(Lϕ)i=−∑jcij(ϕi−ϕj),(G\phi)_i = \sum_j V(\phi_i + \phi_j)\nabla_iW_{ij}, \qquad (Dv)_i = -\sum_j V\,v_{ij} \cdot \nabla_iW_{ij}, \qquad (L\phi)_i = -\sum_j c_{ij}(\phi_i - \phi_j),

with cij=−2VrijW′(rij)/(rij2+η2)c_{ij} = -2Vr_{ij}W'(r_{ij})/(r_{ij}^2 + \eta^2), η2=0.01h2\eta^2 = 0.01h^2, and the viscous acceleration ai=∑jν bij vija_i = \sum_j \nu\,b_{ij}\,v_{ij} with bij=−cijb_{ij} = -c_{ij}. We claim, in exact arithmetic:

  1. The matrix A=−LA = -L is symmetric and positive semidefinite. If the graph of pairs is connected, its null space is the constant vectors, and the system Aϕ=bA\phi = b with b=Dv∗‾−Dv∗b = \overline{Dv^*} - Dv^* (where the bar is the mean over particles) has a solution. Conjugate gradients started from ϕ=0\phi = 0 stays in the space of vectors with zero mean and reaches the unique zero-mean solution in at most N−1N - 1 iterations.
  2. Each step changes the total momentum P=V∑iviP = V\sum_i v_i by exactly NVΔt gNV\Delta t\,g. With g=0g = 0 the total momentum is constant.
  3. The viscous term never adds kinetic energy: ∑ivi⋅ai≤0\sum_i v_i \cdot a_i \le 0.
  4. A uniform flow vi=Uv_i = U for all ii stays uniform: after one step every particle has velocity U+Δt gU + \Delta t\,g and has moved by Δt U+12Δt2g\Delta t\,U + \frac12\Delta t^2g.

The sign of the weights. For the cubic spline, W′(r)=σh−3q(−3+94q)W'(r) = \sigma h^{-3}q(-3 + \frac94q) for q=r/h<1q = r/h < 1, which is negative for 0<q<430 < q < \frac43, and W′(r)=−34σh−3(2−q)2<0W'(r) = -\frac34\sigma h^{-3}(2 - q)^2 < 0 for 1≤q<21 \le q < 2. So W′<0W' < 0 on (0,2h)(0, 2h) and cij>0c_{ij} > 0 for every pair. The weight cijc_{ij} depends only on rijr_{ij}, so cij=cjic_{ij} = c_{ji}.

Claim 1. The matrix has Aii=∑jcijA_{ii} = \sum_j c_{ij} and Aij=−cijA_{ij} = -c_{ij} for a pair, and 0 otherwise. It is symmetric because cij=cjic_{ij} = c_{ji}. For any vector ϕ\phi, grouping the terms by pairs gives

ϕTAϕ=∑pairs i<jcij(ϕi−ϕj)2≥0.\phi^TA\phi = \sum_{\text{pairs } i < j} c_{ij}(\phi_i - \phi_j)^2 \ge 0.

So AA is positive semidefinite. If ϕTAϕ=0\phi^TA\phi = 0, then ϕi=ϕj\phi_i = \phi_j for every pair, because each cij>0c_{ij} > 0; if the graph of pairs is connected, ϕ\phi is constant. So the null space is spanned by 1=(1,…,1)\mathbf 1 = (1, \dots, 1). Because AA is symmetric, its range is the orthogonal complement of its null space, which is the set of vectors with zero sum. The vector bb has zero sum by construction, so Aϕ=bA\phi = b has a solution.

Let ZZ be the space of vectors with zero sum. Every row of AA sums to zero, and AA is symmetric, so every column sums to zero too, and 1TAψ=0\mathbf 1^TA\psi = 0 for every ψ\psi. So AA maps every vector into ZZ, and in particular maps ZZ to itself. On ZZ the form ψTAψ\psi^TA\psi is zero only for ψ=0\psi = 0, so AA restricted to ZZ is symmetric positive definite. Conjugate gradients from ϕ0=0\phi_0 = 0 builds its iterates in the Krylov space spanned by b,Ab,A2b,…b, Ab, A^2b, \dots, which lies in ZZ. So it is ordinary conjugate gradients for a symmetric positive definite operator on the space ZZ of dimension N−1N - 1, and it reaches the unique solution in ZZ in at most N−1N - 1 iterations. (In floating point the iteration stops at the residual tolerance instead.)

Claim 2. The velocity after a step is vi′=vi+Δt(ai+g)−(Gϕ)iv'_i = v_i + \Delta t(a_i + g) - (G\phi)_i. Sum over ii. For the viscous term, each pair adds νbijvij\nu b_{ij}v_{ij} to aia_i and νbjivji=−νbijvij\nu b_{ji}v_{ji} = -\nu b_{ij}v_{ij} to aja_j, so ∑iai=0\sum_i a_i = 0. For the gradient, each pair adds V(ϕi+ϕj)∇iWijV(\phi_i + \phi_j)\nabla_iW_{ij} to (Gϕ)i(G\phi)_i and V(ϕj+ϕi)∇jWji=−V(ϕi+ϕj)∇iWijV(\phi_j + \phi_i)\nabla_jW_{ji} = -V(\phi_i + \phi_j)\nabla_iW_{ij} to (Gϕ)j(G\phi)_j, so ∑i(Gϕ)i=0\sum_i(G\phi)_i = 0 for every ϕ\phi, whatever the solver returns. So ∑ivi′=∑ivi+NΔt g\sum_i v'_i = \sum_i v_i + N\Delta t\,g, and multiplying by VV gives the claim. This also holds for the inexact ϕ\phi 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:

∑ivi⋅ai=∑pairsνbij(vi⋅vij−vj⋅vij)=∑pairsνbij∣vij∣2≤0,\sum_i v_i \cdot a_i = \sum_{\text{pairs}} \nu b_{ij}(v_i \cdot v_{ij} - v_j \cdot v_{ij}) = \sum_{\text{pairs}} \nu b_{ij}|v_{ij}|^2 \le 0,

because bij=−cij<0b_{ij} = -c_{ij} < 0 and ν≥0\nu \ge 0. So ddt12V∑i∣vi∣2=V∑ivi⋅ai≤0\frac{d}{dt}\frac12V\sum_i|v_i|^2 = V\sum_iv_i \cdot a_i \le 0 for the viscous part of the motion.

Claim 4. If vi=Uv_i = U for all ii, every vijv_{ij} is zero, so ai=0a_i = 0 and vi∗=U+Δt gv^*_i = U + \Delta t\,g. Again every vij∗v^*_{ij} is zero, so Dv∗=0Dv^* = 0 and b=0b = 0. Conjugate gradients returns ϕ=0\phi = 0 at once (the initial residual is zero), so Gϕ=0G\phi = 0 and vi′=U+Δt gv'_i = U + \Delta t\,g. The position update gives xi′=xi+12Δt(U+U+Δt g)x'_i = x_i + \frac12\Delta t(U + U + \Delta t\,g). 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 Dv′=0Dv' = 0: the projection uses the compact LL, which is not the product DGDG, so the divergence measured by DD 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. ■\blacksquare

Complexity

With a cell list, finding the pairs costs Θ(N)\Theta(N) for a bounded number of neighbors per particle (about 20 in 2D at h=1.2Δxh = 1.2\Delta x). Building the matrix and each conjugate gradient iteration also cost Θ(N)\Theta(N). So a step costs Θ(NI)\Theta(NI) and a run Θ(KNI)\Theta(KNI), with Θ(N)\Theta(N) memory. Without a preconditioner, II grows like the square root of the condition number of the Laplacian, so like n=Nn = \sqrt N in 2D (the table above: 8 to 31 iterations for n=12n = 12 to 32). Production codes use preconditioned CG, BiCGSTAB, or algebraic multigrid, which keep II 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 Co=∣v∣Δt/h\mathrm{Co} = |v|\Delta t/h, 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 DD, LL and the viscous term.

Variants and improvements

  • Source term. Cummins and Rudman (1999) use the divergence of v∗v^*, as here. Shao and Lo (2003) use a source proportional to the density error, (ρ0−ρ∗)/(ρ0Δt2)(\rho_0 - \rho^*)/(\rho_0\Delta t^2), 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 p=0p = 0 as a Dirichlet condition, which also removes the null space.
  • Exact projection. Using DGDG itself as the Laplacian makes Dv′=0Dv' = 0 exact, with a stencil that reaches 4h4h. In a test run with the operators above, one such step on the moved particles of the 12×1212 \times 12 Taylor-Green case cut the kinetic energy from 0.25 to 5⋅10−65 \cdot 10^{-6}, 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, ∑i(Dv∗)i=−2V∑ivi∗⋅∑j∇iWij\sum_i(Dv^*)_i = -2V\sum_iv^*_i \cdot \sum_j\nabla_iW_{ij}, 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 DGDG, so Dv′Dv' is reduced but not zero. Test with the density error and with flows that have exact solutions, not with Dv′Dv' alone.
  • The sign of LL. LL is negative semidefinite. Conjugate gradients needs the positive matrix −L-L, 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 x∗x^*, not at xx, 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 ϕ=p Δt/ρ0\phi = p\,\Delta t/\rho_0, a change of Δt\Delta t changes ϕ\phi; plot p=ϕ/Δtp = \phi/\Delta t.
  • Kernel truncation at free surfaces. Near a free surface the kernel support is only partly filled, so DD and LL 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.

incompressible_sph.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example