Algorithm Search⌘K

Algorithmadvanced

Particle level set method

Also called hybrid particle level set.

Move a liquid surface as a level set and fix its loss of volume with marker particles on both sides. A particle that crosses the surface by more than its radius rebuilds it nearby.

Time
Θ(n + p) advect · correctO(n c) reinitializeO(n c + p) step
Space
Θ(n + p) extra
Where
c = the number of points where the interface crosses a grid edge; n = the number of grid nodes; p = the number of particles
Properties
not conservativerandomizednot exact
Origin
Douglas Enright, Ronald Fedkiw, Joel Ferziger, Ian Mitchell, 2002

The particle level set method of Enright, Fedkiw, Ferziger and Mitchell (2002) tracks a moving interface, such as the surface of water, with two tools at once. A level set φ\varphi on a grid gives the surface as the set φ=0\varphi = 0. It handles changes of topology with no extra work, but each step smooths it a little, so thin parts and sharp corners lose volume and vanish. Marker particles carried by the flow keep their shape well, but they give no surface by themselves. The method puts particles on both sides of the surface, near it. When a particle is found on the wrong side of the level set by more than its radius, it has "escaped": the level set has lost something there. The particle then rebuilds φ\varphi in its grid cell with the help of the small circle around it. The level set stays in charge of the surface, and the particles only repair it.

In plain words

Think of a puddle drawn on graph paper. Each grid point knows how far it is from the edge of the puddle, and on which side. When the water moves, these numbers are moved too, but each move blurs them a little. After many moves, thin parts of the puddle disappear.

So we also drop many small beads near the edge, some in the water and some in the air. The beads move with the water and do not blur. If a water bead ends up in the air side of the drawing, by more than its own size, the drawing is wrong there. The bead then pulls the edge back out around itself. Air beads do the same on the other side.

The problem

Given a velocity field u\mathbf u and an interface as the zero set of φ\varphi, move the interface with the flow: φt+u⋅∇φ=0\varphi_t + \mathbf u \cdot \nabla \varphi = 0. In a fluid solver, u\mathbf u is the fluid velocity, and φ<0\varphi < 0 marks the liquid. Grid methods for this equation are smooth by design. Where the interface is thinner than a few cells, or has corners, they lose part of the shape, and in a liquid this is a loss of volume. The paper calls this the "excessive regularization" of a level set method. We want a level set that keeps the detail that the flow carries, while it keeps the simple grid operations of a level set.

This page uses φ<0\varphi < 0 for the liquid and φ>0\varphi > 0 for the air. The paper uses φ>0\varphi > 0 for one region and φ≤0\varphi \le 0 for the other. Only the signs matter: positive particles live where φ>0\varphi > 0 and negative ones where φ<0\varphi < 0.

The algorithm

Each particle pp has a position xp\mathbf x_p, a sign sp=±1s_p = \pm 1 and a radius rpr_p between rmin=0.1Δxr_{min} = 0.1 \Delta x and rmax=0.5Δxr_{max} = 0.5 \Delta x (the paper's equations 6 and 7). Its own small level set is φp(x)=sp(rp−∣x−xp∣)\varphi_p(\mathbf x) = s_p (r_p - |\mathbf x - \mathbf x_p|) (equation 10). φ(xp)\varphi(\mathbf x_p) is interpolated from the grid.

Seeding. Put particles of both signs at random in the cells near the interface (the paper takes cells with a corner where ∣φ∣<3Δx|\varphi| < 3 \Delta x, and 16 particles of each sign per cell in 2D). Give each particle a goal value φgoal=sp U[bmin,bmax]\varphi_{goal} = s_p\, U[b_{min}, b_{max}], with bmin=rminb_{min} = r_{min} and bmax=3Δxb_{max} = 3 \Delta x. Move it along the normal N=∇φ/∣∇φ∣\mathbf N = \nabla \varphi / |\nabla \varphi| by xp←xp+λ(φgoal−φ(xp))N\mathbf x_p \leftarrow \mathbf x_p + \lambda (\varphi_{goal} - \varphi(\mathbf x_p)) \mathbf N (equation 8), with λ=1\lambda = 1, halved while the point leaves the domain. Accept the point when it is in the band spφ∈[bmin,bmax]s_p \varphi \in [b_{min}, b_{max}]; else move with λ/2\lambda / 2 and try again. Delete the particle after 15 tries. Then set rpr_p as in line L7 (equation 9).

One step.

  1. PLS-STEP(φ, particles, u, Δt)
  2. 1move φ with u over Δt on the grid, and move each particle x_p with u over Δt
  3. 2E <- the particles with s_p φ(x_p) < 0 and |φ(x_p)| > r_p (the escaped particles)
  4. 3φ+ <- max(φ, φ_p) over the positive particles of E, and φ- <- min(φ, φ_p) over the negative ones, at the corners of each particle's cell
  5. 4at each node, φ <- φ+ if |φ+| <= |φ-|, else φ-
  6. 5reinitialize φ to a signed distance
  7. 6repeat lines L2 to L4 with the new φ
  8. 7r_p <- min(max(s_p φ(x_p), r_min), r_max) for each particle

Lines L2 to L4 run once after line L1 and once more after line L5, because reinitialization can also move the interface (the paper's section 2.3.4). During line L5, the particles do not move. Line L7 lets a particle shrink as the interface comes close, so that small and slow drift does not count as an escape. Escaped particles are not deleted: they mark detail that the grid cannot hold now, and they may help again later.

Reseeding. Stretching flows leave parts of the interface with few particles. Every few steps, or when the interface length changes much, the paper adds particles to cells near the interface that have too few, deletes non-escaped particles far from it, and keeps the particles nearest to the interface in cells that have too many. The code of this page seeds once and does not reseed.

The parts of the paper. The paper moves φ\varphi with a fifth order Hamilton-Jacobi WENO scheme and the particles with third order TVD Runge-Kutta, and reinitializes by the PDE φτ+sgn⁡(φ0)(∣∇φ∣−1)=0\varphi_\tau + \operatorname{sgn}(\varphi_0)(|\nabla \varphi| - 1) = 0. The code here uses simpler parts for a small test: it moves φ\varphi by semi-Lagrangian sampling, which is a form of the method of characteristics, as in the 2005 paper of Enright, Losasso and Fedkiw; it moves particles by the exact flow of a rotation; and it reinitializes by a brute force search for the nearest crossing point.

Example

One escaped particle, by hand. Let φ=y−1/2\varphi = y - 1/2 on a 32×3232 \times 32 grid, so the liquid is below y=1/2y = 1/2. A negative particle with rp=0.3Δxr_p = 0.3 \Delta x sits at a height 0.4Δx0.4 \Delta x above the surface. Then φ(xp)=0.4Δx>rp\varphi(\mathbf x_p) = 0.4 \Delta x > r_p, and the particle has escaped. The node of its cell just above it is at distance 0.1Δx0.1 \Delta x, so φp=−(0.3−0.1)Δx=−0.2Δx\varphi_p = -(0.3 - 0.1)\Delta x = -0.2 \Delta x there, and φ=0.5Δx\varphi = 0.5 \Delta x. Line L3 gives φ−=−0.2Δx\varphi^- = -0.2 \Delta x and φ+=0.5Δx\varphi^+ = 0.5 \Delta x. Line L4 takes −0.2Δx-0.2 \Delta x, so this node moves into the liquid. The other three corners keep their values. If the same particle were only 0.2Δx0.2 \Delta x above the surface, it would not count as escaped, and nothing would change.

Zalesak's disk, measured. Zalesak's slotted disk (1979) is the standard test for this kind of loss. The paper uses a disk of radius 15 at (50,75)(50, 75) in a 100×100100 \times 100 domain, with a slot of width 5 and length 25 cut from the bottom, turned once about the center of the domain. On the unit square, this is a disk of radius 0.15 at (0.5,0.75)(0.5, 0.75), with the area 0.0582. The code turns it once on a 32×3232 \times 32 grid, so the slot is 1.6 cells wide, with 400 particles from seed 3. Areas are counted on 200×200200 \times 200 sample points:

Steps per turn Level set only: area (loss) Particle level set: area (loss) Area of wrong sign, level set only Area of wrong sign, particles
32 0.0458 (21.3%) 0.0549 (5.6%) 0.0324 0.0222
64 0.0273 (53.1%) 0.0536 (8.0%) 0.0481 0.0242
128 0 (100%) 0.0529 (9.1%) 0.0582 0.0246

Without particles, each step blurs φ\varphi once more, so more steps lose more, and at 128 steps the disk is gone. With particles, the loss stays near 10 percent, and most of the remaining error is the slot, which the grid cannot hold at this size. For four other seeds at 64 steps, the area with particles was between 0.052 and 0.057.

The paper's table 2 reports, for one turn with the particle level set, a loss of 14.9% on a 50×5050 \times 50 grid, 0.31% on 100×100100 \times 100 and 0.20% on 200×200200 \times 200. Its level set alone (table 1) loses the whole disk on the 50×5050 \times 50 grid. These numbers come from a fifth order scheme and 16 particles per cell, so they are not directly comparable with the small test here.

Correctness

The claims are proved in proofs/correctness.md.

  1. Seeded particles have not escaped. After seeding, every particle has spφ(xp)≥rps_p \varphi(\mathbf x_p) \ge r_p, so the correction changes nothing until the flow moves things.
  2. The escape test. If φ\varphi is a signed distance near xp\mathbf x_p, a particle has escaped exactly when its whole circle is on the wrong side.
  3. Local and one-sided. Lines L3 and L4 change only the corners of the cells of escaped particles. Positive particles can only raise φ\varphi, negative ones can only lower it, and where both meet the value closer to zero wins.
  4. One particle. For a single escaped negative particle, a positive corner at distance dd becomes negative exactly when d<rpd < r_p and rp−d≤φr_p - d \le \varphi.

These are statements about one correction. The method does not conserve volume exactly: the paper's own tables show small losses and gains. Particles also cannot restore detail where no particle is left, which is why reseeding matters.

Proof: Seeded particles do not escape, the escape test, and what the correction changesfull

We use the line numbers of the page. φ\varphi is sampled at the nodes of a square grid of spacing Δx\Delta x, and φ(x)\varphi(\mathbf x) off the nodes is the bilinear interpolation. A particle pp has a position xp\mathbf x_p, a sign sp∈{+1,−1}s_p \in \{+1, -1\} and a radius rp∈[rmin,rmax]r_p \in [r_{min}, r_{max}], with rmin=0.1Δxr_{min} = 0.1 \Delta x and rmax=0.5Δxr_{max} = 0.5 \Delta x. The band is [bmin,bmax][b_{min}, b_{max}] with bmin=rminb_{min} = r_{min} and bmax=3Δxb_{max} = 3 \Delta x. The particle's own level set is φp(x)=sp(rp−∣x−xp∣)\varphi_p(\mathbf x) = s_p (r_p - |\mathbf x - \mathbf x_p|): it has the sign sps_p inside the circle of radius rpr_p about xp\mathbf x_p, and the other sign outside it. A particle has escaped (line L2) when spφ(xp)<0s_p \varphi(\mathbf x_p) < 0 and ∣φ(xp)∣>rp|\varphi(\mathbf x_p)| > r_p, that is, when spφ(xp)<−rps_p \varphi(\mathbf x_p) < -r_p.

Lemma 1 (seeded particles have not escaped). After seeding, no particle has escaped, so lines L2 to L4 change nothing. After line L7, a particle has escaped exactly when spφ(xp)<−rmins_p \varphi(\mathbf x_p) < -r_{min}.

Proof. Seeding keeps a particle only if bmin≤spφ(xp)≤bmaxb_{min} \le s_p \varphi(\mathbf x_p) \le b_{max}, and sets rp=min⁡(max⁡(spφ(xp),rmin),rmax)r_p = \min(\max(s_p \varphi(\mathbf x_p), r_{min}), r_{max}). Line L7 uses the same formula. Let a=spφ(xp)a = s_p \varphi(\mathbf x_p). If a≥0a \ge 0, then a>−rpa > -r_p, so pp has not escaped. If a<0a < 0, which is possible only after line L7, then rp=rminr_p = r_{min}, and the particle has escaped exactly when a<−rmina < -r_{min}. After seeding, a≥bmin>0a \ge b_{min} > 0. With no escaped particle, φ+=φ−=φ\varphi^+ = \varphi^- = \varphi in line L3, and line L4 gives φ\varphi back. □\square

So after line L7, a particle that was out by more than rminr_{min} is still marked as escaped. Line L7 makes it as small as allowed, so that it repairs only a small region the next time. The test file checks that 400 seeded particles around Zalesak's disk are all in the band with rp≤spφ(xp)r_p \le s_p \varphi(\mathbf x_p), and that line L2 finds none of them.

Lemma 2 (what the escape test means). If φ\varphi is the signed distance to the interface near xp\mathbf x_p, then pp has escaped exactly when the whole open disk of radius rpr_p about xp\mathbf x_p is on the side of sign −sp-s_p.

Proof. For a signed distance, ∣φ(xp)∣|\varphi(\mathbf x_p)| is the distance from xp\mathbf x_p to the interface. The disk misses the interface exactly when this distance is at least rpr_p, and then the whole disk has the sign of φ(xp)\varphi(\mathbf x_p). So the disk lies on the side −sp-s_p with no point on the interface exactly when spφ(xp)<0s_p \varphi(\mathbf x_p) < 0 and ∣φ(xp)∣>rp|\varphi(\mathbf x_p)| > r_p, up to the case of equality, which the strict test leaves out. □\square

A particle that only touches the interface, or that is out by less than its radius, has not escaped. The paper chooses this test so that the small errors of a well resolved level set do not trigger a repair (its section 2.3.3). The test file checks a particle out by 0.2Δx0.2 \Delta x with radius 0.3Δx0.3 \Delta x: it has not escaped.

Theorem 1 (the correction is local and one-sided). Lines L3 and L4 change φ\varphi only at the four nodes around each escaped particle, that is, the corners of the grid cell that contains xp\mathbf x_p. At every node, the new value is φ+\varphi^+ or φ−\varphi^-, with φ−≤φ≤φ+\varphi^- \le \varphi \le \varphi^+. If only escaped particles of one sign ss reach a node, the new value there is either the old value or max⁡pφp\max_p \varphi_p (for s=+1s = +1) or min⁡pφp\min_p \varphi_p (for s=−1s = -1) over those particles, and in the second case it is closer to zero than the old value or equal in magnitude.

Proof. Line L3 sets φ+\varphi^+ to the maximum of φ\varphi and the values φp\varphi_p of the positive escaped particles at the corners of their cells, and φ−\varphi^- to the minimum of φ\varphi and the values of the negative ones. At any other node, φ+=φ−=φ\varphi^+ = \varphi^- = \varphi, so line L4 gives φ\varphi. Taking a maximum cannot lower a value, and taking a minimum cannot raise it, so φ−≤φ≤φ+\varphi^- \le \varphi \le \varphi^+. Let only positive particles reach a node. Then φ−=φ\varphi^- = \varphi, and φ+\varphi^+ is either φ\varphi or max⁡pφp>φ\max_p \varphi_p > \varphi. Line L4 takes φ+\varphi^+ if ∣φ+∣≤∣φ∣|\varphi^+| \le |\varphi|, else φ\varphi. The negative case is the mirror image. □\square

So positive particles can only push the interface toward the φ<0\varphi < 0 side, which gives more room to φ>0\varphi > 0, and negative particles do the opposite. A node changes sign only if a particle circle covers it more firmly than the old value says it is on the other side. Where escaped particles of both signs meet, line L4 keeps the value that is closer to the interface. The paper argues that this value is the more reliable one (its section 2.3.3).

Theorem 2 (a single escaped particle). Let pp be the only escaped particle, let it be negative, and let y\mathbf y be a corner of its cell, at the distance d=∣y−xp∣d = |\mathbf y - \mathbf x_p|. Then y\mathbf y changes from positive to negative exactly when φ(y)>0\varphi(\mathbf y) > 0, d<rpd < r_p and rp−d≤φ(y)r_p - d \le \varphi(\mathbf y), and its new value is then φp(y)=−(rp−d)\varphi_p(\mathbf y) = -(r_p - d). A corner with φ(y)≤0\varphi(\mathbf y) \le 0 does not change. A positive corner stays positive in all other cases.

Proof. Only pp reaches y\mathbf y, and it is negative, so φ+=φ\varphi^+ = \varphi and φ−=min⁡(φ,φp)\varphi^- = \min(\varphi, \varphi_p) at y\mathbf y. There are four cases.

  1. φ(y)≤0\varphi(\mathbf y) \le 0. Then φ−=min⁡(φ,φp)≤φ(y)≤0\varphi^- = \min(\varphi, \varphi_p) \le \varphi(\mathbf y) \le 0 and φ+=φ\varphi^+ = \varphi. If φp(y)<φ(y)\varphi_p(\mathbf y) < \varphi(\mathbf y), then ∣φ−∣>∣φ+∣|\varphi^-| > |\varphi^+| and line L4 takes φ+=φ\varphi^+ = \varphi. Otherwise φ−=φ\varphi^- = \varphi. Either way the value does not change.
  2. φ(y)>0\varphi(\mathbf y) > 0 and φp(y)≥φ(y)\varphi_p(\mathbf y) \ge \varphi(\mathbf y). Then φ−=φ\varphi^- = \varphi and nothing changes.
  3. φ(y)>0\varphi(\mathbf y) > 0 and 0≤φp(y)<φ(y)0 \le \varphi_p(\mathbf y) < \varphi(\mathbf y). Then ∣φ−∣<∣φ+∣|\varphi^-| < |\varphi^+|, and the new value is φp(y)≥0\varphi_p(\mathbf y) \ge 0. The node stays on the positive side, closer to zero.
  4. φ(y)>0\varphi(\mathbf y) > 0 and φp(y)<0\varphi_p(\mathbf y) < 0, which means d<rpd < r_p. Then φ−=φp(y)\varphi^- = \varphi_p(\mathbf y), and the new value is φp(y)<0\varphi_p(\mathbf y) < 0 if rp−d≤φ(y)r_p - d \le \varphi(\mathbf y), and φ(y)>0\varphi(\mathbf y) > 0 otherwise.

So y\mathbf y becomes negative exactly in case 4 with rp−d≤φ(y)r_p - d \le \varphi(\mathbf y). □\square

The test file uses φ=y−1/2\varphi = y - 1/2 on a 32×3232 \times 32 grid, a negative particle at (1/2+Δx/2, 1/2+0.4Δx)(1/2 + \Delta x / 2,\ 1/2 + 0.4 \Delta x) with rp=0.3Δxr_p = 0.3 \Delta x. The node (16,16)(16, 16) at height 1/2+0.5Δx1/2 + 0.5 \Delta x is at distance 0.1Δx0.1 \Delta x from the particle, so case 4 applies: φp=−0.2Δx\varphi_p = -0.2 \Delta x and 0.2Δx≤0.5Δx0.2 \Delta x \le 0.5 \Delta x. The node becomes −0.2Δx-0.2 \Delta x, and the liquid gains the region near the particle. The two corners below the surface are in case 1. The corner (17,16)(17, 16) is at distance 1.005Δx1.005 \Delta x, so φp=0.705Δx≥0.5Δx=φ\varphi_p = 0.705 \Delta x \ge 0.5 \Delta x = \varphi, which is case 2. These three do not change, and the test checks that (16,16)(16, 16) is the only node that changes.

Lemma 3 (the motion of the particles). For a rigid rotation, the code moves each particle by the exact rotation, so after one full turn every particle is back at its start up to rounding.

Proof. rotation returns the map x↦c+R(ω Δt)(x−c)\mathbf x \mapsto \mathbf c + R(\omega\, \Delta t)(\mathbf x - \mathbf c), which is the exact flow of the field u=ω(−(y−cy),x−cx)\mathbf u = \omega (-(y - c_y), x - c_x) over the time Δt\Delta t. The composition of these maps over steps that add up to 2π/ω2\pi / \omega is the rotation by 2π2\pi, the identity. □\square

The particles thus carry the shape without error in this test, while the level set is resampled on the grid each step and smooths the corners. Lines L2 to L4 repair φ\varphi where the two disagree by more than a particle radius. This is why, in the test file, a turn of Zalesak's disk in 64 steps on a 32×3232 \times 32 grid keeps 92 percent of the area with particles and 47 percent without them. These are measurements, not consequences of the lemmas: the particles do not conserve area exactly, and they cannot restore detail where no particle remains.

Complexity

Let nn be the number of grid nodes and pp the number of particles. Line L1 costs Θ(n)\Theta(n) for the grid and Θ(p)\Theta(p) for the particles. Lines L2 to L4 cost Θ(p)\Theta(p) for the tests and four nodes per escaped particle. The code copies φ\varphi twice, so it costs Θ(n+p)\Theta(n + p). Line L7 costs Θ(p)\Theta(p). Reinitialization by fast marching costs O(nlog⁡n)O(n \log n), and a PDE solver costs O(n)O(n) per iteration; both can be limited to a band near the interface. The brute force search of the code costs O(nc)O(n c), where cc is the number of crossing points. So one step of the code costs O(nc+p)O(n c + p). Space is Θ(n+p)\Theta(n + p).

The particles live only in a band of about 3 cells on each side, so pp grows with the area of the interface in 3D, not with the volume. The paper notes that only escaped particles in poorly resolved regions need the square roots of line L3.

Properties

  • The level set decides. The surface is always the zero set of φ\varphi. Particles never define it directly; they only correct φ\varphi.
  • Both signs are needed. Positive particles repair the corners that the liquid rounds off from outside, and negative particles repair those it rounds off from inside. In the paper's figure 14, the two kinds of particles repair different corners of the slot.
  • Topology is free. Merging and splitting come from the level set, as in a plain level set method, and particles need no links to each other.
  • Not exactly conservative. It reduces the loss of volume but does not remove it. A volume of fluid method conserves volume to rounding error, but places it less sharply.
  • Random. Seeding is random. The code takes a seeded random generator, so a run can be repeated.

Variants and improvements

  • Semi-Lagrangian particle level set. Enright, Losasso and Fedkiw (2005) move φ\varphi with a semi-Lagrangian step and use the particles to recover the accuracy that the simpler step loses.
  • Water in animation. Enright, Marschner and Fedkiw (2002) used the method for water surfaces, with a "thickened" front tracking technique and a velocity extrapolation that moves the surface smoothly.
  • Other escape thresholds. The paper uses "out by more than the radius", and notes that any nonzero multiple of the radius would do.

When to use it

Use it to track a liquid surface on a grid in a fluid simulation when thin sheets, drops and sharp features must survive many steps. For smooth, well resolved surfaces, a plain level set with a good scheme may be enough. For particle based fluids such as FLIP, the fluid particles themselves can define the surface; see particle fluid surfacing. When exact volume matters more than sharp shape, a volume of fluid method fits better.

Pitfalls

  • Escape threshold too small. If any crossing of the interface counts, rounding and interpolation errors trigger repairs all the time. The paper requires the particle to be out by more than its radius.
  • φ\varphi not a signed distance. The escape test and the formula φp\varphi_p compare distances with values of φ\varphi. If φ\varphi is steep or flat, they disagree. Reinitialize every step.
  • Moving particles in line L5. Reinitialization should not move the interface, so the particles must stay fixed while it runs.
  • Deleting escaped particles. They mark lost detail; delete only non-escaped particles far from the interface.
  • Too much reseeding. New particles are attracted to the current φ\varphi, which may already be wrong. The paper warns that where the geometry is poorly resolved, reseeding may make the interface worse.
  • Inaccurate particle motion. The repair is only as good as the particle paths. The paper uses trilinear interpolation of the velocity and third order TVD Runge-Kutta for them.

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.

macgrid.pyI0RawGitHub
# 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/.
"""A 2D MAC grid with sampling, divergence, pressure projection and advection.

This file is copied byte for byte into each impl/python folder that needs it.
Do not edit a copy. The reference is in
graphics-and-signals/fluid-animation/mac-grid/impl/python/.

Layout (the MAC layout of Harlow and Welch 1965, as in Bridson 2015):
- The grid has nx by ny cells of size dx. i is the x index, j is the y index.
- p[i][j] is at ((i + 1/2) dx, (j + 1/2) dx), for i < nx and j < ny.
- u[i][j] is at (i dx, (j + 1/2) dx), for i = 0..nx and j < ny.
- v[i][j] is at ((i + 1/2) dx, j dx), for i < nx and j = 0..ny.
- label[i][j] is FLUID, SOLID or AIR. A cell outside the grid counts as
  SOLID, so the border of the grid is a fixed wall.

Units are SI. In 2D a density rho is in kg/m^2 if you read the grid as a
sheet, or in kg/m^3 per unit depth; the code does not care.
"""

import math
from collections import deque

FLUID, SOLID, AIR = 0, 1, 2


class Grid:
    """The arrays of a MAC grid. All arrays are lists of lists indexed [i][j]."""

    def __init__(self, nx, ny, dx):
        if nx < 1 or ny < 1 or dx <= 0:
            raise ValueError("need nx >= 1, ny >= 1 and dx > 0")
        self.nx = nx
        self.ny = ny
        self.dx = float(dx)
        self.p = zeros(nx, ny)
        self.u = zeros(nx + 1, ny)
        self.v = zeros(nx, ny + 1)
        self.label = [[FLUID] * ny for _ in range(nx)]


def make_grid(nx, ny, dx):
    """A grid of nx by ny FLUID cells of size dx, with p, u and v set to zero."""
    return Grid(nx, ny, dx)


def zeros(a, b):
    """An a by b list of lists of 0.0."""
    return [[0.0] * b for _ in range(a)]


def copy_field(q):
    """A deep copy of a 2D field."""
    return [list(col) for col in q]


def cell_label(g, i, j):
    """The label of cell (i, j). A cell outside the grid is SOLID."""
    if 0 <= i < g.nx and 0 <= j < g.ny:
        return g.label[i][j]
    return SOLID


def cell_center(g, i, j):
    """The position ((i + 1/2) dx, (j + 1/2) dx) of the center of cell (i, j)."""
    return ((i + 0.5) * g.dx, (j + 0.5) * g.dx)


def sample(q, x, y, dx, ox, oy):
    """Bilinear sample at (x, y) of a field whose value q[a][b] is at ((a + ox) dx, (b + oy) dx).

    A point outside the sample positions is clamped to the nearest one, so the
    result is always a convex combination of at most four values of q.
    """
    na, nb = len(q), len(q[0])
    fx = x / dx - ox
    fy = y / dx - oy
    fx = min(max(fx, 0.0), float(na - 1))
    fy = min(max(fy, 0.0), float(nb - 1))
    a0 = min(int(math.floor(fx)), na - 2) if na > 1 else 0
    b0 = min(int(math.floor(fy)), nb - 2) if nb > 1 else 0
    a1 = a0 + 1 if na > 1 else a0
    b1 = b0 + 1 if nb > 1 else b0
    s = fx - a0
    t = fy - b0
    return ((1.0 - s) * ((1.0 - t) * q[a0][b0] + t * q[a0][b1])
            + s * ((1.0 - t) * q[a1][b0] + t * q[a1][b1]))


def u_at(g, x, y):
    """The x velocity at (x, y), by bilinear sampling of u."""
    return sample(g.u, x, y, g.dx, 0.0, 0.5)


def v_at(g, x, y):
    """The y velocity at (x, y), by bilinear sampling of v."""
    return sample(g.v, x, y, g.dx, 0.5, 0.0)


def vel_at(g, x, y):
    """The velocity (u, v) at (x, y)."""
    return (u_at(g, x, y), v_at(g, x, y))


def center_at(g, q, x, y):
    """Bilinear sample at (x, y) of a cell centered field q (same layout as p)."""
    return sample(q, x, y, g.dx, 0.5, 0.5)


def divergence(g):
    """The discrete divergence (u[i+1][j] - u[i][j] + v[i][j+1] - v[i][j]) / dx of every cell."""
    d = zeros(g.nx, g.ny)
    for i in range(g.nx):
        ui, ui1 = g.u[i], g.u[i + 1]
        vi = g.v[i]
        for j in range(g.ny):
            d[i][j] = (ui1[j] - ui[j] + vi[j + 1] - vi[j]) / g.dx
    return d


def max_fluid_divergence(g):
    """The largest |divergence| over the FLUID cells (0.0 if there is none)."""
    d = divergence(g)
    m = 0.0
    for i in range(g.nx):
        for j in range(g.ny):
            if g.label[i][j] == FLUID:
                m = max(m, abs(d[i][j]))
    return m


def is_solid_u_face(g, i, j):
    """True if the u face (i, j), between cells (i - 1, j) and (i, j), touches a SOLID cell."""
    return cell_label(g, i - 1, j) == SOLID or cell_label(g, i, j) == SOLID


def is_solid_v_face(g, i, j):
    """True if the v face (i, j), between cells (i, j - 1) and (i, j), touches a SOLID cell."""
    return cell_label(g, i, j - 1) == SOLID or cell_label(g, i, j) == SOLID


def set_solid_boundaries(g, solid_velocity=None):
    """Set the normal velocity on every face that touches a SOLID cell.

    A face on the border of the grid is a fixed wall and gets 0. A face inside
    the grid that touches a SOLID cell gets the normal component of
    solid_velocity(x, y) at the face center, or 0 if solid_velocity is None.
    """
    dx = g.dx
    for i in range(g.nx + 1):
        for j in range(g.ny):
            if is_solid_u_face(g, i, j):
                if i == 0 or i == g.nx or solid_velocity is None:
                    g.u[i][j] = 0.0
                else:
                    g.u[i][j] = float(solid_velocity(i * dx, (j + 0.5) * dx)[0])
    for i in range(g.nx):
        for j in range(g.ny + 1):
            if is_solid_v_face(g, i, j):
                if j == 0 or j == g.ny or solid_velocity is None:
                    g.v[i][j] = 0.0
                else:
                    g.v[i][j] = float(solid_velocity((i + 0.5) * dx, j * dx)[1])


def _fluid_system(g, dt, rho):
    """Index the FLUID cells and build the 5-point Laplacian and the right side.

    Returns (cells, diag, nbrs, b, has_air) where cells[k] = (i, j), diag[k] is
    the number of neighbors that are not SOLID, nbrs[k] lists the indices of the
    FLUID neighbors, and b[k] = -(rho dx / dt) (u[i+1][j] - u[i][j] + v[i][j+1] - v[i][j]).
    has_air[k] is True if the cell has an AIR neighbor.
    """
    idx = {}
    cells = []
    for i in range(g.nx):
        for j in range(g.ny):
            if g.label[i][j] == FLUID:
                idx[(i, j)] = len(cells)
                cells.append((i, j))
    diag, nbrs, b, has_air = [], [], [], []
    scale = -rho * g.dx / dt
    for (i, j) in cells:
        dcount = 0
        nb = []
        air = False
        for (a, c) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
            lab = cell_label(g, a, c)
            if lab == SOLID:
                continue
            dcount += 1
            if lab == FLUID:
                nb.append(idx[(a, c)])
            else:
                air = True
        diag.append(dcount)
        nbrs.append(nb)
        has_air.append(air)
        b.append(scale * (g.u[i + 1][j] - g.u[i][j] + g.v[i][j + 1] - g.v[i][j]))
    return cells, diag, nbrs, b, has_air


def _components(nbrs):
    """The connected components of the FLUID cells, as lists of indices."""
    n = len(nbrs)
    comp = [-1] * n
    out = []
    for s in range(n):
        if comp[s] >= 0:
            continue
        comp[s] = len(out)
        members = [s]
        queue = deque([s])
        while queue:
            k = queue.popleft()
            for m in nbrs[k]:
                if comp[m] < 0:
                    comp[m] = comp[s]
                    members.append(m)
                    queue.append(m)
        out.append(members)
    return out


def _apply(diag, nbrs, x):
    return [diag[k] * x[k] - sum(x[m] for m in nbrs[k]) for k in range(len(x))]


def pressure_solve(g, dt, rho, tol=1e-12, max_iter=None):
    """Solve the pressure Poisson equation by conjugate gradients and store p in g.p.

    The system is A p = b on the FLUID cells, with the 5-point Laplacian A
    (Neumann at SOLID faces, p = 0 in AIR cells) and
    b = -(rho dx^2 / dt) times the divergence. A connected group of FLUID cells
    with no AIR neighbor has a singular block: the mean of b is removed on it
    before the solve (the compatibility condition) and the mean of p is removed
    after it. CG stops when max |r| <= tol * max |b|. Returns the number of
    iterations. p is 0 in SOLID and AIR cells.
    """
    cells, diag, nbrs, b, has_air = _fluid_system(g, dt, rho)
    n = len(cells)
    g.p = zeros(g.nx, g.ny)
    if n == 0:
        return 0
    closed = [c for c in _components(nbrs) if not any(has_air[k] for k in c)]
    for c in closed:
        mean = sum(b[k] for k in c) / len(c)
        for k in c:
            b[k] -= mean
    bmax = max(abs(t) for t in b)
    x = [0.0] * n
    it = 0
    if bmax > 0.0:
        if max_iter is None:
            max_iter = max(100, 4 * n)
        r = list(b)
        d = list(r)
        rr = sum(t * t for t in r)
        while it < max_iter and max(abs(t) for t in r) > tol * bmax:
            q = _apply(diag, nbrs, d)
            dq = sum(d[k] * q[k] for k in range(n))
            if dq <= 0.0:
                break
            alpha = rr / dq
            for k in range(n):
                x[k] += alpha * d[k]
                r[k] -= alpha * q[k]
            rr_new = sum(t * t for t in r)
            beta = rr_new / rr
            rr = rr_new
            for k in range(n):
                d[k] = r[k] + beta * d[k]
            it += 1
    for c in closed:
        mean = sum(x[k] for k in c) / len(c)
        for k in c:
            x[k] -= mean
    for k, (i, j) in enumerate(cells):
        g.p[i][j] = x[k]
    return it


def subtract_pressure_gradient(g, dt, rho):
    """u[i][j] -= dt / (rho dx) (p[i][j] - p[i-1][j]), and the same for v.

    Only faces with a FLUID cell on at least one side and no SOLID cell are
    changed. The pressure of an AIR cell is 0.
    """
    s = dt / (rho * g.dx)
    for i in range(1, g.nx):
        for j in range(g.ny):
            a, c = g.label[i - 1][j], g.label[i][j]
            if a == SOLID or c == SOLID or (a != FLUID and c != FLUID):
                continue
            g.u[i][j] -= s * (g.p[i][j] - g.p[i - 1][j])
    for i in range(g.nx):
        for j in range(1, g.ny):
            a, c = g.label[i][j - 1], g.label[i][j]
            if a == SOLID or c == SOLID or (a != FLUID and c != FLUID):
                continue
            g.v[i][j] -= s * (g.p[i][j] - g.p[i][j - 1])


def project(g, dt, rho, tol=1e-12, solid_velocity=None):
    """Make the velocity divergence free in the FLUID cells. Returns the CG iteration count."""
    set_solid_boundaries(g, solid_velocity)
    it = pressure_solve(g, dt, rho, tol)
    subtract_pressure_gradient(g, dt, rho)
    return it


def backtrace(g, x, y, dt):
    """The start point of the path that ends at (x, y) after time dt, by an RK2 (midpoint) step.

    A negative dt traces forward in time.
    """
    u1, v1 = vel_at(g, x, y)
    xm, ym = x - 0.5 * dt * u1, y - 0.5 * dt * v1
    u2, v2 = vel_at(g, xm, ym)
    return (x - dt * u2, y - dt * v2)


def advect(g, q, dt, ox=0.5, oy=0.5):
    """Semi-Lagrangian advection of the field q by the velocity of g, for time dt.

    q[a][b] is at ((a + ox) dx, (b + oy) dx): the default is a cell centered
    field; use (0, 0.5) for u and (0.5, 0) for v. Each new value is the bilinear
    sample of q at the RK2 backtrace of its sample point. Returns a new field.
    """
    dx = g.dx
    out = zeros(len(q), len(q[0]))
    for a in range(len(q)):
        for b in range(len(q[0])):
            xb, yb = backtrace(g, (a + ox) * dx, (b + oy) * dx, dt)
            out[a][b] = sample(q, xb, yb, dx, ox, oy)
    return out


def advect_velocity(g, dt):
    """Advect u and v by the velocity of g. Returns (new_u, new_v); g is not changed."""
    return advect(g, g.u, dt, 0.0, 0.5), advect(g, g.v, dt, 0.5, 0.0)


def kinetic_energy(g, rho):
    """(1/2) rho dx^2 times the sum of u^2 and v^2 over all faces (per unit depth in 2D)."""
    s = sum(t * t for col in g.u for t in col) + sum(t * t for col in g.v for t in col)
    return 0.5 * rho * g.dx * g.dx * s
particle_level_set.py 251 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/particle-level-set/. The authors are listed in prov/S6VHF6.jsonl.

"""The particle level set method of Enright, Fedkiw, Ferziger and Mitchell (2002) in 2D.

phi < 0 inside the liquid and phi > 0 outside, sampled at the cell centers
of a square grid (the p layout of macgrid.py). Marker particles sit on both
sides of the interface, within a band of a few cells. A particle has a sign
s (+1 outside, -1 inside) and a radius r in [r_min, r_max] = [0.1 dx, 0.5 dx].
It has escaped when it is on the wrong side of the interface by more than its
radius: s phi(x_p) < 0 and |phi(x_p)| > r. Each escaped particle defines the
small signed distance function phi_p(x) = s (r - |x - x_p|), and the level
set is rebuilt near it from the union of these circles:

    phi+ = max(phi, phi_p over the positive escaped particles),
    phi- = min(phi, phi_p over the negative escaped particles),
    phi  = phi+ if |phi+| <= |phi-| else phi-.

The level set is moved by semi-Lagrangian advection (bilinear sampling at the
backtraced point), which the 2005 paper of Enright, Losasso and Fedkiw also
uses; the 2002 paper uses fifth order HJ-WENO. The caller gives the flow as
a map trace(x, y, t, dt) from a point at time t to its position at time
t + dt; a negative dt traces backward.
"""

import math
import random

import macgrid


class ParticleLevelSet:
    """A level set on an n by n grid of cells of size dx, with marker particles."""

    def __init__(self, n, dx, phi0, rng=None, per_cell=4, band=3.0, max_particles=400, use_particles=True):
        if n < 2 or dx <= 0.0 or per_cell < 0 or max_particles < 0:
            raise ValueError("need n >= 2, dx > 0, per_cell >= 0 and max_particles >= 0")
        self.n, self.dx = n, float(dx)
        self.phi = [[float(phi0((i + 0.5) * dx, (j + 0.5) * dx)) for j in range(n)] for i in range(n)]
        self.r_min, self.r_max = 0.1 * dx, 0.5 * dx
        self.b_min, self.b_max = 0.1 * dx, band * dx
        self.particles = []  # [x, y, s, r]
        self.use_particles = use_particles
        reinitialize(self)
        if use_particles:
            self.seed(rng if rng is not None else random.Random(0), per_cell, max_particles)

    def value(self, x, y):
        """phi at (x, y), by bilinear interpolation."""
        return macgrid.sample(self.phi, x, y, self.dx, 0.5, 0.5)

    def normal(self, x, y):
        """grad phi / |grad phi| at (x, y), by central differences of the interpolated phi."""
        h = 0.5 * self.dx
        gx = (self.value(x + h, y) - self.value(x - h, y)) / (2.0 * h)
        gy = (self.value(x, y + h) - self.value(x, y - h)) / (2.0 * h)
        m = math.hypot(gx, gy)
        return (gx / m, gy / m) if m > 0.0 else (0.0, 0.0)

    def seed(self, rng, per_cell, max_particles):
        """Put per_cell particles of each sign in every cell near the interface, and attract each to its side.

        A particle of sign s gets a goal phi_goal = s U[b_min, b_max]. As in
        section 2.3.1 of the paper, it tries x + lam (phi_goal - phi(x)) N(x)
        with lam = 1, halves lam while the point is outside the domain, and
        accepts the point if it is in the band. Otherwise it moves with lam / 2
        and tries again. A particle that is not in the band after 15 tries is
        dropped. At most max_particles are kept, chosen at random.
        """
        n, dx = self.n, self.dx
        L = n * dx

        def in_band(s, x, y):
            return self.b_min <= s * self.value(x, y) <= self.b_max

        cells = [(i, j) for i in range(n) for j in range(n) if abs(self.phi[i][j]) < self.b_max]
        out = []
        for (i, j) in cells:
            for k in range(2 * per_cell):
                s = 1.0 if k % 2 == 0 else -1.0
                x, y = (i + rng.random()) * dx, (j + rng.random()) * dx
                goal = s * rng.uniform(self.b_min, self.b_max)
                ok = in_band(s, x, y)
                for _ in range(15):
                    if ok:
                        break
                    ph = self.value(x, y)
                    nx, ny = self.normal(x, y)
                    lam = 1.0
                    while lam > 1e-6 and not (0.0 <= x + lam * (goal - ph) * nx <= L and 0.0 <= y + lam * (goal - ph) * ny <= L):
                        lam *= 0.5
                    xn, yn = x + lam * (goal - ph) * nx, y + lam * (goal - ph) * ny
                    if in_band(s, xn, yn):
                        x, y, ok = xn, yn, True
                    else:
                        x, y = x + 0.5 * lam * (goal - ph) * nx, y + 0.5 * lam * (goal - ph) * ny
                        ok = in_band(s, x, y)
                if ok:
                    out.append([x, y, s, min(max(s * self.value(x, y), self.r_min), self.r_max)])
        rng.shuffle(out)
        self.particles = out[:max_particles]

    def escaped(self):
        """The particles on the wrong side of the interface by more than their radius."""
        out = []
        for p in self.particles:
            ph = self.value(p[0], p[1])
            if p[2] * ph < 0.0 and abs(ph) > p[3]:  # @line L2
                out.append(p)
        return out

    def correct(self):
        """Rebuild phi near the escaped particles. Returns the number of escaped particles."""
        if not self.use_particles:
            return 0
        esc = self.escaped()
        n, dx = self.n, self.dx
        plus = [list(c) for c in self.phi]
        minus = [list(c) for c in self.phi]
        for (x, y, s, r) in esc:
            i0 = min(max(int(math.floor(x / dx - 0.5)), 0), n - 2)
            j0 = min(max(int(math.floor(y / dx - 0.5)), 0), n - 2)
            for i in (i0, i0 + 1):
                for j in (j0, j0 + 1):
                    php = s * (r - math.hypot((i + 0.5) * dx - x, (j + 0.5) * dx - y))
                    if s > 0.0:
                        plus[i][j] = max(plus[i][j], php)  # @line L3
                    else:
                        minus[i][j] = min(minus[i][j], php)
        for i in range(n):
            for j in range(n):
                a, b = plus[i][j], minus[i][j]
                self.phi[i][j] = a if abs(a) <= abs(b) else b  # @line L4
        return len(esc)

    def adjust_radii(self):
        """r = clamp(s phi(x_p), r_min, r_max); an escaped particle gets r_min."""
        for p in self.particles:
            p[3] = min(max(p[2] * self.value(p[0], p[1]), self.r_min), self.r_max)  # @line L7

    def step(self, trace, t, dt):
        """One step of the method from time t to t + dt."""
        n, dx = self.n, self.dx
        old = self.phi
        new = macgrid.zeros(n, n)
        for i in range(n):
            for j in range(n):
                xb, yb = trace((i + 0.5) * dx, (j + 0.5) * dx, t + dt, -dt)
                new[i][j] = macgrid.sample(old, xb, yb, dx, 0.5, 0.5)
        self.phi = new
        for p in self.particles:
            p[0], p[1] = trace(p[0], p[1], t, dt)  # @line L1
        self.correct()
        reinitialize(self)  # @line L5
        self.correct()  # @line L6
        self.adjust_radii()


def crossings(phi, dx):
    """The points where phi changes sign between two neighboring cell centers, by linear interpolation."""
    n = len(phi)
    pts = []
    for i in range(n):
        for j in range(n):
            a = phi[i][j]
            for (k, l) in ((i + 1, j), (i, j + 1)):
                if k < n and l < n:
                    b = phi[k][l]
                    if (a < 0.0) != (b < 0.0):
                        t = a / (a - b)
                        pts.append(((i + 0.5 + t * (k - i)) * dx, (j + 0.5 + t * (l - j)) * dx))
    return pts


def reinitialize(st, width=5.0):
    """Make phi a signed distance near the interface, without moving it much.

    A cell next to a sign change keeps its value. Any other cell with
    |phi| < width dx gets its sign times the distance to the nearest crossing
    point. Cells farther away are left alone. This brute force search stands
    in for the PDE or fast marching reinitialization of the papers.
    """
    phi, dx, n = st.phi, st.dx, st.n
    pts = crossings(phi, dx)
    if not pts:
        return
    lim = width * dx
    near = set()
    for i in range(n):
        for j in range(n):
            for (k, l) in ((i + 1, j), (i, j + 1)):
                if k < n and l < n and (phi[i][j] < 0.0) != (phi[k][l] < 0.0):
                    near.add((i, j))
                    near.add((k, l))
    new = [list(c) for c in phi]
    for i in range(n):
        for j in range(n):
            if (i, j) in near or abs(phi[i][j]) >= lim:
                continue
            x, y = (i + 0.5) * dx, (j + 0.5) * dx
            d = min(math.hypot(x - px, y - py) for (px, py) in pts)
            new[i][j] = math.copysign(d, phi[i][j])
    st.phi = new


def rotation(cx, cy, omega):
    """The exact trace of a rigid rotation about (cx, cy) with angular speed omega."""
    def trace(x, y, t, dt):
        c, s = math.cos(omega * dt), math.sin(omega * dt)
        dx, dy = x - cx, y - cy
        return (cx + c * dx - s * dy, cy + s * dx + c * dy)
    return trace


def inside_area(phi_at, L, m):
    """The area where phi_at < 0 in [0, L]^2, counted on an m by m grid of sample points."""
    h = L / m
    cnt = 0
    for a in range(m):
        for b in range(m):
            if phi_at((a + 0.5) * h, (b + 0.5) * h) < 0.0:
                cnt += 1
    return cnt * h * h


def area_of_difference(phi_at, exact_at, L, m):
    """The area where phi_at and exact_at have different signs, counted on an m by m grid of samples."""
    h = L / m
    cnt = 0
    for a in range(m):
        for b in range(m):
            x, y = (a + 0.5) * h, (b + 0.5) * h
            if (phi_at(x, y) < 0.0) != (exact_at(x, y) < 0.0):
                cnt += 1
    return cnt * h * h


def zalesak(cx, cy, R, w, depth):
    """A disk of radius R about (cx, cy) with a slot of width w cut up from its bottom to the height depth.

    Returns phi(x, y) = max(disk, -slot), negative inside the shape.
    """
    def phi(x, y):
        d_disk = math.hypot(x - cx, y - cy) - R
        qx, qy = abs(x - cx) - 0.5 * w, max((cy - R) - y, y - (cy - R + depth))
        if qx > 0.0 and qy > 0.0:
            d_slot = math.hypot(qx, qy)
        else:
            d_slot = max(qx, qy)
        return max(d_disk, -d_slot)
    return phi
test_particle_level_set.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/particle-level-set/. The authors are listed in prov/S6VHF6.jsonl.

"""Tests of the particle level set: seeding, the correction, and Zalesak's slotted disk."""

import math
import random

import pytest

import particle_level_set as P

N = 32
DX = 1.0 / N
SLOT = P.zalesak(0.5, 0.75, 0.15, 0.05, 0.25)
TURN = P.rotation(0.5, 0.5, 2.0 * math.pi)  # one turn in the time 1
M = 200  # sample points per side for the areas; the slot is then 10 samples wide


def run(use, steps, seed=3):
    st = P.ParticleLevelSet(N, DX, SLOT, random.Random(seed), use_particles=use)
    for k in range(steps):
        st.step(TURN, k / steps, 1.0 / steps)
    return st


def test_rotation_trace_is_exact():
    x, y = 0.3, 0.8
    for _ in range(8):
        x, y = TURN(x, y, 0.0, 0.125)
    assert abs(x - 0.3) < 1e-12 and abs(y - 0.8) < 1e-12
    assert TURN(*TURN(0.3, 0.8, 0.0, 0.1), 0.1, -0.1) == pytest.approx((0.3, 0.8), abs=1e-12)


def test_reinitialize_gives_a_distance_and_keeps_the_sign():
    def d(x, y):
        return math.hypot(x - 0.5, y - 0.5) - 0.3

    st = P.ParticleLevelSet(N, DX, lambda x, y: 1.5 * d(x, y), use_particles=False)
    cells = [(i, j) for i in range(N) for j in range(N) if 1.2 * DX < abs(d((i + 0.5) * DX, (j + 0.5) * DX)) < 3 * DX]
    assert len(cells) > 100
    assert max(abs(st.phi[i][j] - d((i + 0.5) * DX, (j + 0.5) * DX)) for (i, j) in cells) < 0.1 * DX
    assert all((st.phi[i][j] < 0.0) == (d((i + 0.5) * DX, (j + 0.5) * DX) < 0.0) for i in range(N) for j in range(N))


def test_seeded_particles_are_on_their_side_and_none_has_escaped():
    st = P.ParticleLevelSet(N, DX, SLOT, random.Random(3))
    assert len(st.particles) == 400
    pos = sum(1 for p in st.particles if p[2] > 0.0)
    assert 150 < pos < 250
    for (x, y, s, r) in st.particles:
        ph = st.value(x, y)
        assert st.b_min - 1e-12 <= s * ph <= st.b_max + 1e-12
        assert st.r_min <= r <= st.r_max and r <= s * ph + 1e-12
    before = [list(c) for c in st.phi]
    assert st.correct() == 0
    assert st.phi == before


def test_one_escaped_particle_moves_the_interface():
    st = P.ParticleLevelSet(N, DX, lambda x, y: y - 0.5, per_cell=0)
    assert st.particles == []
    x, y, r = 0.5 + 0.5 * DX, 0.5 + 0.4 * DX, 0.3 * DX  # an inside particle above the surface y = 0.5
    st.particles = [[x, y, -1.0, r]]
    old = [list(c) for c in st.phi]
    assert len(st.escaped()) == 1
    assert st.correct() == 1
    assert st.phi[16][16] == pytest.approx(-0.2 * DX, abs=1e-12)  # min(0.5 dx, -(0.3 - 0.1) dx)
    for (i, j) in ((16, 15), (15, 16), (17, 16), (15, 15), (17, 15)):
        assert st.phi[i][j] == old[i][j]
    changed = [(i, j) for i in range(N) for j in range(N) if st.phi[i][j] != old[i][j]]
    assert changed == [(16, 16)]


def test_a_particle_that_is_not_out_by_its_radius_has_not_escaped():
    st = P.ParticleLevelSet(N, DX, lambda x, y: y - 0.5, per_cell=0)
    st.particles = [[0.5, 0.5 + 0.2 * DX, -1.0, 0.3 * DX], [0.5, 0.5 + 0.2 * DX, 1.0, 0.3 * DX]]
    assert st.escaped() == []
    st.adjust_radii()
    assert st.particles[0][3] == st.r_min  # on the wrong side: the smallest radius
    assert st.particles[1][3] == pytest.approx(0.2 * DX)


def test_the_exact_slotted_disk_has_the_area_of_the_paper():
    assert abs(P.inside_area(SLOT, 1.0, M) - 0.05822) < 2e-4  # 582.2 on the 100 by 100 domain of the paper


def test_particles_keep_the_slotted_disk_through_a_turn():
    a0 = P.inside_area(SLOT, 1.0, M)
    plain = run(False, 64)
    pls = run(True, 64)
    a_plain = P.inside_area(plain.value, 1.0, M)
    a_pls = P.inside_area(pls.value, 1.0, M)
    assert a_plain < 0.5 * a0  # the plain level set loses more than half of the area
    assert a_pls > 0.9 * a0
    assert abs(a_plain - 0.02728) < 1e-4 and abs(a_pls - 0.05355) < 1e-4
    e_plain = P.area_of_difference(plain.value, SLOT, 1.0, M)
    e_pls = P.area_of_difference(pls.value, SLOT, 1.0, M)
    assert e_pls < 0.55 * e_plain


def test_more_steps_lose_more_area_without_particles():
    a32 = P.inside_area(run(False, 32).value, 1.0, M)
    a64 = P.inside_area(run(False, 64).value, 1.0, M)
    assert a64 < 0.7 * a32
    b32 = P.inside_area(run(True, 32).value, 1.0, M)
    assert abs(b32 - 0.05493) < 1e-4


def test_bad_input():
    with pytest.raises(ValueError):
        P.ParticleLevelSet(1, DX, SLOT)
    with pytest.raises(ValueError):
        P.ParticleLevelSet(N, 0.0, SLOT)

History

Marker particles go back to the marker-and-cell method of 1965, which filled the liquid with particles. Osher and Sethian (1988) introduced the level set method, and it became the common way to capture interfaces with changes of topology. Its loss of volume in thin and sharp regions was a known weakness. In 2002, Enright, Fedkiw, Ferziger and Mitchell combined the two: particles only near the interface, on both sides, and used only where the level set fails. They showed the gain on Zalesak's disk, on a vortex that stretches a disk into a thin filament, on a deformation field, and on 3D tests. In the same year, Enright, Marschner and Fedkiw brought the method to water in computer graphics. Enright, Losasso and Fedkiw (2005) made a faster semi-Lagrangian version.

References

  1. Douglas Enright, Ronald Fedkiw, Joel Ferziger and Ian Mitchell, A hybrid particle level set method for improved interface capturing, Journal of Computational Physics 183(1), 83-116, 2002, section 2.2 (marker particles, equations 5 to 7), section 2.3 (seeding and attraction, equations 8 and 9; escape and correction, equations 10 to 13; reinitialization and the order of the steps; reseeding), section 3.1 (Zalesak's disk, tables 1 and 2)
  2. Douglas Enright, Stephen Marschner and Ronald Fedkiw, Animation and rendering of complex water surfaces, ACM Transactions on Graphics 21(3), 736-744, 2002 (SIGGRAPH 2002), the use of the particle level set for water in animation
  3. Douglas Enright, Frank Losasso and Ronald Fedkiw, A fast and accurate semi-Lagrangian particle level set method, Computers and Structures 83, 479-490, 2005, the semi-Lagrangian version
  4. Stanley Osher and James A. Sethian, Fronts propagating with curvature-dependent speed: algorithms based on Hamilton-Jacobi formulations, Journal of Computational Physics 79(1), 12-49, 1988, the level set method
  5. Steven T. Zalesak, Fully multidimensional flux-corrected transport algorithms for fluids, Journal of Computational Physics 31, 335-362, 1979, the slotted disk test

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.advect
  • a full proof of time.correct
  • a full proof of time.reinitialize
  • a full proof of time.step
  • 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