Algorithm Search⌘K

Algorithmresearch

Affine particle-in-cell

Also called APIC.

Store an affine velocity matrix on each particle; under the hypotheses of the paper, the particle to grid and grid to particle transfers then conserve angular momentum.

Time
O(n + k c) stepO(n + c) transfers
Space
O(n + c) extra
Where
c = the number of grid cells; k = the number of conjugate gradient iterations of the projection; n = the number of particles
Properties
conserves angular momentumconserves linear momentumdeterministicnot exactkeeps affine fields
Origin
Chenfanfu Jiang, Craig Schroeder, Andrew Selle, Joseph Teran, Alexey Stomakhin, 2015

The affine particle-in-cell method (APIC) is the particle-in-cell method with a richer particle. Each particle carries its velocity and also the gradient of the velocity near it, so it carries a small affine velocity field. The particle to grid transfer (P2G) spreads this affine field to the grid, and the grid to particle transfer (G2P) reads back both the velocity and the gradient. So a linear flow, such as a rigid rotation, goes through both transfers with no loss, and the angular momentum is kept exactly. APIC loses much less energy than PIC, and it has much less noise than FLIP.

In plain words

The water is a cloud of particles over a grid of boxes, as in PIC. In PIC, each particle only knows its own speed, so when the grid averages the speeds, a turning motion is smoothed away. In APIC, each particle also knows how the speed changes around it: faster to the left, slower above, and so on. When it gives its speed to the grid, each grid edge gets the speed that the particle expects at that edge, not only the speed at the particle. When it reads back, the particle learns both the speed and how the speed changes. So a turning motion goes to the grid and back with no loss.

The problem

The input and the output are those of PIC, with two more vectors on each particle: cpuc^u_p, the gradient of the xx velocity, and cpvc^v_p, the gradient of the yy velocity. Together they are the rows of the affine matrix CpC_p of the paper. The grid is a MAC grid of cells of size Δx\Delta x with fixed walls, ρ\rho is the density, gravity is g=−9.81g = -9.81 m/s² on the yy axis and Δt\Delta t is the step. This is one method for fluid simulation for animation. The weight wfpw_{fp} is the bilinear weight of face ff at particle pp, ∇wfp\nabla w_{fp} is its gradient with respect to the particle position, and xfx_f is the center of face ff.

The algorithm

  1. APIC-STEP(x, u, v, cᵘ, cᵛ, Δt)
  2. 1for each cell: FLUID if it holds a particle, else AIR (walls stay SOLID)
  3. 2for each u face f: m_f ← Σₚ w_fp mₚ; u_f ← Σₚ w_fp mₚ (uₚ + cᵘₚ·(x_f - xₚ)) / m_f, the same for v with cᵛ
  4. 3for each v face f with m_f > 0: v_f ← v_f + Δt g
  5. 4project the grid velocity (pressure solve on the FLUID cells)
  6. 5for each particle p: uₚ ← Σ_f w_fp u_f, cᵘₚ ← Σ_f u_f ∇w_fp, the same for v
  7. 6for each particle p: move xₚ through the grid velocity for Δt, keep it Δx/2 from the walls

Line L2 is the APIC P2G: each particle gives each face the value of its affine field at the face center. With c=0c = 0 it is the PIC transfer. Line L5 is the APIC G2P. The paper writes the gradient as BpDp−1B_p D_p^{-1}, with Bp=∑fwfpuf(xf−xp)TB_p = \sum_f w_{fp} u_f (x_f - x_p)^T and Dp=∑fwfp(xf−xp)(xf−xp)TD_p = \sum_f w_{fp}(x_f - x_p)(x_f - x_p)^T. For bilinear weights, DpD_p is diagonal with the entries s(1−s)Δx2s(1-s)\Delta x^2 and t(1−t)Δx2t(1-t)\Delta x^2, where (s,t)(s, t) is the position of the particle inside the stencil of the component, and BpDp−1=∑fuf∇wfpB_p D_p^{-1} = \sum_f u_f\nabla w_{fp}. The gradient form has no division and works also when ss or tt is 0. Each component of the MAC grid has its own stencil, so DpD_p differs for uu and vv. Lines L1, L3, L4 and L6 are the lines of PIC; line L6 keeps the particles in the range where no weight is clamped.

Example

Take an 8 by 8 grid with Δx=1/8\Delta x = 1/8 m, 256 particles at random positions at least half a cell from the walls, unit masses, and the rigid rotation u=−(y−1/2)u = -(y - 1/2), v=x−1/2v = x - 1/2 with cu=(0,−1)c^u = (0, -1) and cv=(1,0)c^v = (1, 0). Do lines L2 and L5 only, again and again at the same positions. With PIC, the kinetic energy after 1, 2, 5 and 10 round trips is 0.9340, 0.8758, 0.7279 and 0.5397 of the start value (the example of the PIC page). With APIC it is 1 to within rounding after every round trip, the gradients stay (0,−1)(0, -1) and (1,0)(1, 0) to within 4⋅10−154\cdot 10^{-15}, and the angular momentum changes by less than 10−1510^{-15} of its value.

Now take the closed swirl of the FLIP page: the same box full of liquid with u=sin⁡(πx)cos⁡(πy)u = \sin(\pi x)\cos(\pi y), v=−cos⁡(πx)sin⁡(πy)v = -\cos(\pi x)\sin(\pi y), no gravity and steps of 0.02 s. APIC starts with the exact gradients of this field. The table gives the measured particle energy as a fraction of the start value, and the root mean square difference between the particle velocity and the grid velocity at the particle after 40 steps, as a measure of noise.

steps PIC FLIP (α=0.95\alpha = 0.95) FLIP (α=1\alpha = 1) APIC
1 0.8916 0.9871 0.9924 0.9927
10 0.3378 0.9029 0.9676 0.9655
40 0.0152 0.7455 0.9521 0.9765
noise after 40 steps (m/s) 0.0005 0.069 0.159 0.028

APIC keeps about as much energy as pure FLIP on this flow, with less noise than the blend. The energy of APIC is not monotone in the steps; it is not bounded by a proof here.

Correctness

APIC is an approximation of the Euler equations of a liquid, and its error is not bounded here. The claims below hold for bilinear weights, at the same particle positions in lines L2 and L5, and with no weight clamped, which holds if every particle is at least Δx/2\Delta x/2 from the walls. The angular momentum of the particles is ∑pmp(xpvp−ypup+cp,xvDp,xxv−cp,yuDp,yyu)\sum_p m_p(x_p v_p - y_p u_p + c^v_{p,x} D^v_{p,xx} - c^u_{p,y} D^u_{p,yy}): the angular momentum of the centers plus the one of the affine fields. The angular momentum of the grid is ∑v facesmfxfvf−∑u facesmfyfuf\sum_{v\text{ faces}} m_f x_f v_f - \sum_{u\text{ faces}} m_f y_f u_f, with the face masses of line L2. The tests check these facts, and the proof gives the arguments:

  • Angular momentum. Line L2 keeps the angular momentum exactly, and line L5 keeps it exactly too.
  • Linear momentum. Lines L2 and L5 keep ∑mu\sum m u and ∑mv\sum m v.
  • Affine fields. If every particle carries the same affine field, lines L2 and L5 give it back exactly, both the velocity and the gradient.
  • The gradient. Line L5 gives BpDp−1B_p D_p^{-1}, with DpD_p diagonal.

Gravity and the projection of line L4, through the walls, change the angular momentum; the claims are about the transfers only. The tests also run a small dam break and check that the divergence stays near 0 and that the particles stay in the box.

Proof: Angular momentum, linear momentum and affine fields in the APIC transfersfull

We use the notation of the page, with exact real arithmetic. Lines L2 and L5 use the same particle positions. We write the claims for the uu faces, with the center xf=(xf,yf)x_f = (x_f, y_f) of face ff; the vv faces are the same with the roles of xx and yy exchanged. The masses are mp>0m_p > 0 and mf=∑pwfpmpm_f = \sum_p w_{fp} m_p.

The bilinear stencil

Fix a particle pp whose uu weights are not clamped. Its four faces are (a0+α,b0+β)(a_0 + \alpha, b_0 + \beta) with α,β∈{0,1}\alpha, \beta \in \{0, 1\}, at xf=x0+αΔxx_f = x_0 + \alpha\Delta x and yf=y0+βΔxy_f = y_0 + \beta\Delta x, and xp=x0+sΔxx_p = x_0 + s\Delta x, yp=y0+tΔxy_p = y_0 + t\Delta x with s,t∈[0,1]s, t \in [0, 1]. The weights are wfp=XαYβw_{fp} = X_\alpha Y_\beta with X0=1−sX_0 = 1 - s, X1=sX_1 = s, Y0=1−tY_0 = 1 - t, Y1=tY_1 = t. The gradient of the code is ∇wfp=(Xα′Yβ,XαYβ′)\nabla w_{fp} = (X'_\alpha Y_\beta, X_\alpha Y'_\beta) with X0′=−1/ΔxX'_0 = -1/\Delta x, X1′=1/ΔxX'_1 = 1/\Delta x, and the same for Y′Y'.

Lemma 1. For the stencil of pp:

  1. ∑fwfp=1\sum_f w_{fp} = 1, ∑fwfp(xf−xp)=0\sum_f w_{fp}(x_f - x_p) = 0 and ∑fwfp(yf−yp)=0\sum_f w_{fp}(y_f - y_p) = 0.
  2. Dxy=∑fwfp(xf−xp)(yf−yp)=0D_{xy} = \sum_f w_{fp}(x_f - x_p)(y_f - y_p) = 0, Dxx=∑fwfp(xf−xp)2=s(1−s)Δx2D_{xx} = \sum_f w_{fp}(x_f - x_p)^2 = s(1-s)\Delta x^2 and Dyy=t(1−t)Δx2D_{yy} = t(1-t)\Delta x^2.
  3. ∑f∇wfp=0\sum_f\nabla w_{fp} = 0, ∑fxf∇wfp=(1,0)\sum_f x_f\nabla w_{fp} = (1, 0) and ∑fyf∇wfp=(0,1)\sum_f y_f\nabla w_{fp} = (0, 1).
  4. For each face, wfp yp+∂ywfp Dyy=wfp yfw_{fp}\,y_p + \partial_y w_{fp}\,D_{yy} = w_{fp}\,y_f, and wfp(yf−yp)=Dyy ∂ywfpw_{fp}(y_f - y_p) = D_{yy}\,\partial_y w_{fp}. The same holds with xx in place of yy.

Proof. Each sum factors into a sum over α\alpha and a sum over β\beta. In one dimension, X0+X1=1X_0 + X_1 = 1 and X0(−sΔx)+X1(1−s)Δx=0X_0(-s\Delta x) + X_1(1 - s)\Delta x = 0, which gives part 1. For part 2, DxyD_{xy} is the product of the two sums of part 1, so it is 0, and X0s2Δx2+X1(1−s)2Δx2=s(1−s)Δx2X_0 s^2\Delta x^2 + X_1(1-s)^2\Delta x^2 = s(1-s)\Delta x^2. For part 3, X0′+X1′=0X'_0 + X'_1 = 0 and X0′x0+X1′(x0+Δx)=1X'_0 x_0 + X'_1(x_0 + \Delta x) = 1, while the factor ∑βYβ=1\sum_\beta Y_\beta = 1 or ∑βYβ′=0\sum_\beta Y'_\beta = 0 gives the other parts. For part 4, take β=0\beta = 0: Y0yp+Y0′t(1−t)Δx2=(1−t)(yp−tΔx)=(1−t)y0=Y0yfY_0 y_p + Y'_0 t(1-t)\Delta x^2 = (1-t)(y_p - t\Delta x) = (1-t)y_0 = Y_0 y_f. For β=1\beta = 1: Y1yp+Y1′t(1−t)Δx2=t(yp+(1−t)Δx)=t yfY_1 y_p + Y'_1 t(1-t)\Delta x^2 = t(y_p + (1-t)\Delta x) = t\,y_f. Multiply by XαX_\alpha. The second identity of part 4 is the first one minus wfpypw_{fp} y_p. □\square

For the uu faces, no clamping means yp∈[Δx/2,(ny−1/2)Δx]y_p \in [\Delta x/2, (n_y - 1/2)\Delta x]; for the vv faces, xp∈[Δx/2,(nx−1/2)Δx]x_p \in [\Delta x/2, (n_x - 1/2)\Delta x]. Line L6 keeps every particle in this range. We write Dp,yyuD^u_{p,yy} for DyyD_{yy} of the uu stencil of pp and Dp,xxvD^v_{p,xx} for DxxD_{xx} of its vv stencil.

Angular momentum

The particle angular momentum is LP=∑pmp(xpvp−ypup+cp,xvDp,xxv−cp,yuDp,yyu)L_P = \sum_p m_p(x_p v_p - y_p u_p + c^v_{p,x}D^v_{p,xx} - c^u_{p,y}D^u_{p,yy}), and the grid angular momentum is LG=∑vmfxfvf−∑umfyfufL_G = \sum_{v} m_f x_f v_f - \sum_{u} m_f y_f u_f.

Claim 1. If no weight is clamped, line L2 gives LG=LPL_G = L_P.

Proof. A face with no mass has wfp=0w_{fp} = 0 for every pp and adds nothing. For the others, mfuf=∑pwfpmp(up+cpu⋅(xf−xp))m_f u_f = \sum_p w_{fp} m_p (u_p + c^u_p\cdot(x_f - x_p)), so

∑umfyfuf=∑pmp∑fwfp yf(up+cp,xu(xf−xp)+cp,yu(yf−yp)).\sum_u m_f y_f u_f = \sum_p m_p\sum_f w_{fp}\,y_f\left(u_p + c^u_{p,x}(x_f - x_p) + c^u_{p,y}(y_f - y_p)\right).

Write yf=yp+(yf−yp)y_f = y_p + (y_f - y_p). By Lemma 1, ∑fwfpyf=yp\sum_f w_{fp} y_f = y_p, ∑fwfpyf(xf−xp)=Dxy+yp⋅0=0\sum_f w_{fp} y_f(x_f - x_p) = D_{xy} + y_p\cdot 0 = 0 and ∑fwfpyf(yf−yp)=Dyy\sum_f w_{fp} y_f(y_f - y_p) = D_{yy}. So ∑umfyfuf=∑pmp(ypup+cp,yuDp,yyu)\sum_u m_f y_f u_f = \sum_p m_p(y_p u_p + c^u_{p,y}D^u_{p,yy}). In the same way, ∑vmfxfvf=∑pmp(xpvp+cp,xvDp,xxv)\sum_v m_f x_f v_f = \sum_p m_p(x_p v_p + c^v_{p,x}D^v_{p,xx}). The difference is LPL_P. □\square

Claim 2. If no weight is clamped, line L5 gives LP=LGL_P = L_G, with the face masses of line L2.

Proof. After line L5, up=∑fwfpufu_p = \sum_f w_{fp}u_f and cp,yu=∑f∂ywfp ufc^u_{p,y} = \sum_f\partial_y w_{fp}\,u_f. So by Lemma 1, part 4,

∑pmp(ypup+cp,yuDp,yyu)=∑pmp∑fuf(wfpyp+∂ywfpDp,yyu)=∑pmp∑fwfp yfuf=∑umfyfuf.\sum_p m_p(y_p u_p + c^u_{p,y}D^u_{p,yy}) = \sum_p m_p\sum_f u_f(w_{fp}y_p + \partial_y w_{fp}D^u_{p,yy}) = \sum_p m_p\sum_f w_{fp}\,y_f u_f = \sum_u m_f y_f u_f.

The vv part is the same with xx, and the difference gives LP=LGL_P = L_G. □\square

Linear momentum

Claim 3. Line L2 gives ∑fmfuf=∑pmpup\sum_f m_f u_f = \sum_p m_p u_p, and line L5 gives ∑pmpup=∑fmfuf\sum_p m_p u_p = \sum_f m_f u_f.

Proof. ∑fmfuf=∑pmp(up+cpu⋅∑fwfp(xf−xp))=∑pmpup\sum_f m_f u_f = \sum_p m_p(u_p + c^u_p\cdot\sum_f w_{fp}(x_f - x_p)) = \sum_p m_p u_p by Lemma 1, part 1. Line L5 is the PIC transfer for upu_p, and ∑pmp∑fwfpuf=∑fmfuf\sum_p m_p\sum_f w_{fp}u_f = \sum_f m_f u_f. □\square

Affine fields

Claim 4. Let u(x)=a+b x+c yu(x) = a + b\,x + c\,y, and let every particle carry up=u(xp)u_p = u(x_p) and cpu=(b,c)c^u_p = (b, c). If no weight is clamped, then after lines L2 and L5, up=u(xp)u_p = u(x_p) and cpu=(b,c)c^u_p = (b, c) for every particle.

Proof. For every particle, up+cpu⋅(xf−xp)=u(xf)u_p + c^u_p\cdot(x_f - x_p) = u(x_f), so each face with mass gets the weighted mean of equal values, uf=u(xf)u_f = u(x_f). A face in the stencil of a particle has wfp>0w_{fp} > 0 and so has mass, or it has wfp=0w_{fp} = 0 and adds nothing to line L5. Then ∑fwfpu(xf)=a+bxp+cyp\sum_f w_{fp}u(x_f) = a + b x_p + c y_p by Lemma 1, part 1. And ∑f∇wfp u(xf)=a⋅0+b(1,0)+c(0,1)=(b,c)\sum_f\nabla w_{fp}\,u(x_f) = a\cdot 0 + b(1, 0) + c(0, 1) = (b, c) by Lemma 1, part 3. □\square

With the gradients set to 0, the same field is the PIC case, and the energy loss of the PIC proof applies.

The gradient as B D^-1

Claim 5. Let B=∑fwfpuf(xf−xp)B = \sum_f w_{fp}u_f(x_f - x_p). Then Bx=Dxx cp,xuB_x = D_{xx}\,c^u_{p,x} and By=Dyy cp,yuB_y = D_{yy}\,c^u_{p,y}, so cpu=BD−1c^u_p = B D^{-1} when DD is invertible.

Proof. By Lemma 1, part 4, wfp(yf−yp)=Dyy ∂ywfpw_{fp}(y_f - y_p) = D_{yy}\,\partial_y w_{fp} for each face, and the same with xx. Multiply by ufu_f and sum over the faces. DD is diagonal by Lemma 1, part 2. ■\blacksquare

Complexity

The transfers cost O(n+c)O(n + c) time, with four faces per component and particle, and a few more operations per face than PIC. Line L4 costs O(kc)O(k c) for kk conjugate gradient iterations. The memory is O(n+c)O(n + c), with four more numbers per particle in 2D than PIC.

Properties

  • Angular momentum. Kept exactly by the transfers, under the hypotheses above (proved).
  • Linear fields. Kept exactly by a round trip (proved), so rigid rotations and shears are not damped by the transfers.
  • Stability. The particle state is read back from the grid in line L5, as in PIC, so APIC does not build up the free particle noise of FLIP.
  • Dissipation. Lower than PIC, because only the part of the flow that is not affine near a particle is averaged away (measured in the example).
  • Energy. This page gives no energy bound for APIC; the swirl table is a measurement.

Variants and improvements

  • Other kernels. With quadratic or cubic B-spline weights, DpD_p is a constant times the identity, 14Δx2\frac14\Delta x^2 and 13Δx2\frac13\Delta x^2, and Cp=BpDp−1C_p = B_p D_p^{-1} is cheap.
  • Collocated grids. On a grid with all velocity components at the nodes, as in the material point method, one matrix DpD_p serves both components, and the transfers are the same in form.
  • Polynomial PIC. Later work stores more polynomial terms on each particle, which keeps more of the flow at a higher cost.
  • FLIP blends. Some solvers mix APIC with a small part of the FLIP update for more detail.

When to use it

Use APIC for liquids where swirls should last and the noise of FLIP is not acceptable, and in the material point method for solids, sand and snow. Use PIC if the dissipation does no harm and the code must be as simple as possible.

Pitfalls

  • One matrix for both components. On a MAC grid, uu and vv have different stencils. Line L5 must compute cuc^u from the uu faces and cvc^v from the vv faces, each with its own weights.
  • Dividing by DpD_p. For bilinear weights, DpD_p is singular when a particle is on a grid line of a stencil. Use the gradient form of line L5, not BpDp−1B_p D_p^{-1}.
  • A missing term in line L2. Line L2 must add cp⋅(xf−xp)c_p\cdot(x_f - x_p) before the division by the face mass. Without it APIC is PIC, and the gradients of line L5 are lost in the next step.
  • Clamped weights. If a particle is closer than Δx/2\Delta x/2 to a wall, the weights clamp, the gradient of line L5 is wrong and the angular momentum is not kept. Line L6 keeps the particles away from this zone.
  • Angular momentum of the centers only. The particle angular momentum includes the affine term. Measuring only ∑m(xv−yu)\sum m(x v - y u) gives a false loss.

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.

affine_particle_in_cell.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/affine-particle-in-cell/. The authors are listed in prov/AJQ8H2.jsonl.
"""The affine particle-in-cell method (APIC) for a liquid on a 2D MAC grid.

Each particle carries its velocity (u_p, v_p) and the gradients c^u_p and c^v_p
of the two velocity components, so it carries an affine velocity field. The
transfers are

    P2G: u_f = sum_p w_fp m_p (u_p + c^u_p . (x_f - x_p)) / sum_p w_fp m_p,
    G2P: u_p = sum_f w_fp u_f,  c^u_p = sum_f grad w_fp u_f,

and the same for v. For bilinear weights, the gradient form of G2P equals
B_p D_p^-1 of Jiang et al. (2015), with D_p diagonal and the entries
s (1 - s) dx^2 and t (1 - t) dx^2, where (s, t) are the fractional positions of
the particle in the stencil of the component.

The weights are bilinear, with the same clamping as macgrid.sample; the
gradients and the angular momentum claim need a particle that is not clamped,
which advect_particles ensures. The grid must have nx >= 2 and ny >= 2.
Gravity is (0, -9.81) m/s^2 by default.
"""

import math

import macgrid as mg

U_OFFSET = (0.0, 0.5)
V_OFFSET = (0.5, 0.0)


def weights(x, y, dx, ox, oy, na, nb):
    """The bilinear weights of the point (x, y) on a field of na by nb samples at ((a + ox) dx, (b + oy) dx).

    Returns four tuples (a, b, w, dw/dx, dw/dy). The weights are at least 0 and
    add up to 1. A point outside the samples is clamped as in macgrid.sample;
    the gradients are correct only for a point that is not clamped.
    """
    fx = min(max(x / dx - ox, 0.0), float(na - 1))
    fy = min(max(y / dx - oy, 0.0), float(nb - 1))
    a0 = min(int(math.floor(fx)), na - 2)
    b0 = min(int(math.floor(fy)), nb - 2)
    s = fx - a0
    t = fy - b0
    return ((a0, b0, (1.0 - s) * (1.0 - t), -(1.0 - t) / dx, -(1.0 - s) / dx),
            (a0, b0 + 1, (1.0 - s) * t, -t / dx, (1.0 - s) / dx),
            (a0 + 1, b0, s * (1.0 - t), (1.0 - t) / dx, -s / dx),
            (a0 + 1, b0 + 1, s * t, t / dx, s / dx))


def u_weights(g, x, y):
    return weights(x, y, g.dx, U_OFFSET[0], U_OFFSET[1], g.nx + 1, g.ny)


def v_weights(g, x, y):
    return weights(x, y, g.dx, V_OFFSET[0], V_OFFSET[1], g.nx, g.ny + 1)


def u_face(g, a, b):
    """The position of the u face (a, b)."""
    return (a * g.dx, (b + 0.5) * g.dx)


def v_face(g, a, b):
    """The position of the v face (a, b)."""
    return ((a + 0.5) * g.dx, b * g.dx)


def label_cells(g, xs, ys):
    """Mark each cell that holds a particle FLUID and each other cell that is not SOLID AIR."""
    for i in range(g.nx):
        for j in range(g.ny):
            if g.label[i][j] != mg.SOLID:
                g.label[i][j] = mg.AIR
    for x, y in zip(xs, ys):
        i = min(max(int(x / g.dx), 0), g.nx - 1)
        j = min(max(int(y / g.dx), 0), g.ny - 1)
        if g.label[i][j] != mg.SOLID:
            g.label[i][j] = mg.FLUID


def p2g(g, xs, ys, us, vs, cus, cvs, ms):
    """The APIC particle to grid transfer. Returns the face masses (mu, mv).

    cus[p] and cvs[p] are the gradients (d/dx, d/dy) of u and v on particle p.
    With all gradients 0 this is the PIC transfer.
    """
    mu = mg.zeros(g.nx + 1, g.ny)
    mv = mg.zeros(g.nx, g.ny + 1)
    pu = mg.zeros(g.nx + 1, g.ny)
    pv = mg.zeros(g.nx, g.ny + 1)
    for x, y, u, v, cu, cv, m in zip(xs, ys, us, vs, cus, cvs, ms):
        for a, b, w, _, _ in u_weights(g, x, y):
            fx, fy = u_face(g, a, b)
            mu[a][b] += w * m
            pu[a][b] += w * m * (u + cu[0] * (fx - x) + cu[1] * (fy - y))
        for a, b, w, _, _ in v_weights(g, x, y):
            fx, fy = v_face(g, a, b)
            mv[a][b] += w * m
            pv[a][b] += w * m * (v + cv[0] * (fx - x) + cv[1] * (fy - y))
    g.u = [[pu[a][b] / mu[a][b] if mu[a][b] > 0.0 else 0.0 for b in range(g.ny)] for a in range(g.nx + 1)]
    g.v = [[pv[a][b] / mv[a][b] if mv[a][b] > 0.0 else 0.0 for b in range(g.ny + 1)] for a in range(g.nx)]
    return mu, mv


def add_gravity(g, mv, dt, gravity):
    """Add dt * gravity to each v face that has mass."""
    for a in range(g.nx):
        for b in range(g.ny + 1):
            if mv[a][b] > 0.0:
                g.v[a][b] += dt * gravity


def g2p(g, xs, ys):
    """The APIC grid to particle transfer. Returns (us, vs, cus, cvs)."""
    us, vs, cus, cvs = [], [], [], []
    for x, y in zip(xs, ys):
        u = cux = cuy = 0.0
        for a, b, w, wx, wy in u_weights(g, x, y):
            q = g.u[a][b]
            u += w * q
            cux += wx * q
            cuy += wy * q
        v = cvx = cvy = 0.0
        for a, b, w, wx, wy in v_weights(g, x, y):
            q = g.v[a][b]
            v += w * q
            cvx += wx * q
            cvy += wy * q
        us.append(u)
        vs.append(v)
        cus.append((cux, cuy))
        cvs.append((cvx, cvy))
    return us, vs, cus, cvs


def inertia_diagonals(g, x, y):
    """(D^u_yy, D^v_xx) of particle (x, y): sum_f w_fp (y_f - y)^2 on the u faces and sum_f w_fp (x_f - x)^2 on the v faces."""
    duy = sum(w * (u_face(g, a, b)[1] - y) ** 2 for a, b, w, _, _ in u_weights(g, x, y))
    dvx = sum(w * (v_face(g, a, b)[0] - x) ** 2 for a, b, w, _, _ in v_weights(g, x, y))
    return duy, dvx


def advect_particles(g, xs, ys, dt):
    """Move each particle for time dt through the grid velocity (RK2), and keep it half a cell from the walls."""
    lo = 0.5 * g.dx
    hx = g.nx * g.dx - lo
    hy = g.ny * g.dx - lo
    nxs, nys = [], []
    for x, y in zip(xs, ys):
        x1, y1 = mg.backtrace(g, x, y, -dt)
        nxs.append(min(max(x1, lo), hx))
        nys.append(min(max(y1, lo), hy))
    return nxs, nys


def step(g, xs, ys, us, vs, cus, cvs, ms, dt, rho=1000.0, gravity=-9.81):
    """One APIC step. Changes the grid g and returns the new (xs, ys, us, vs, cus, cvs)."""
    label_cells(g, xs, ys)  # @line L1
    mu, mv = p2g(g, xs, ys, us, vs, cus, cvs, ms)  # @line L2
    add_gravity(g, mv, dt, gravity)  # @line L3
    mg.project(g, dt, rho)  # @line L4
    us, vs, cus, cvs = g2p(g, xs, ys)  # @line L5
    xs, ys = advect_particles(g, xs, ys, dt)  # @line L6
    return xs, ys, us, vs, cus, cvs


def seed_block(rng, i_cells, j_cells, dx, jitter=0.2):
    """Four particles per cell in the cells [0, i_cells) x [0, j_cells), each moved at random by up to jitter * dx / 2."""
    xs, ys = [], []
    for i in range(i_cells):
        for j in range(j_cells):
            for a in (0.25, 0.75):
                for b in (0.25, 0.75):
                    xs.append((i + a + rng.uniform(-0.5, 0.5) * jitter) * dx)
                    ys.append((j + b + rng.uniform(-0.5, 0.5) * jitter) * dx)
    return xs, ys


def particle_kinetic_energy(us, vs, ms):
    return 0.5 * sum(m * (u * u + v * v) for u, v, m in zip(us, vs, ms))


def particle_momentum(us, vs, ms):
    return (sum(m * u for u, m in zip(us, ms)), sum(m * v for v, m in zip(vs, ms)))


def grid_momentum(g, mu, mv):
    return (sum(mu[a][b] * g.u[a][b] for a in range(g.nx + 1) for b in range(g.ny)),
            sum(mv[a][b] * g.v[a][b] for a in range(g.nx) for b in range(g.ny + 1)))


def particle_angular_momentum(g, xs, ys, us, vs, cus, cvs, ms):
    """sum_p m_p (x_p v_p - y_p u_p + c^v_x D^v_xx - c^u_y D^u_yy), about the origin."""
    total = 0.0
    for x, y, u, v, cu, cv, m in zip(xs, ys, us, vs, cus, cvs, ms):
        duy, dvx = inertia_diagonals(g, x, y)
        total += m * (x * v - y * u + cv[0] * dvx - cu[1] * duy)
    return total


def grid_angular_momentum(g, mu, mv):
    """sum over the v faces of m_f x_f v_f minus the sum over the u faces of m_f y_f u_f."""
    total = 0.0
    for a in range(g.nx):
        for b in range(g.ny + 1):
            total += mv[a][b] * v_face(g, a, b)[0] * g.v[a][b]
    for a in range(g.nx + 1):
        for b in range(g.ny):
            total -= mu[a][b] * u_face(g, a, b)[1] * g.u[a][b]
    return total
macgrid.py 347 lines
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""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
test_affine_particle_in_cell.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/affine-particle-in-cell/. The authors are listed in prov/AJQ8H2.jsonl.

import math
import random

import macgrid as mg
import affine_particle_in_cell as ap

N = 8
DX = 1.0 / N


def random_state(seed, count=200):
    """Random particles at least half a cell from the walls, so no weight is clamped."""
    rng = random.Random(seed)
    xs = [rng.uniform(0.5 * DX, 1.0 - 0.5 * DX) for _ in range(count)]
    ys = [rng.uniform(0.5 * DX, 1.0 - 0.5 * DX) for _ in range(count)]
    us = [rng.uniform(-1.0, 1.0) for _ in xs]
    vs = [rng.uniform(-1.0, 1.0) for _ in xs]
    cus = [(rng.uniform(-3.0, 3.0), rng.uniform(-3.0, 3.0)) for _ in xs]
    cvs = [(rng.uniform(-3.0, 3.0), rng.uniform(-3.0, 3.0)) for _ in xs]
    ms = [rng.uniform(0.5, 1.5) for _ in xs]
    return rng, xs, ys, us, vs, cus, cvs, ms


def test_transfers_keep_angular_momentum() -> None:
    for seed in (1, 2):
        _, xs, ys, us, vs, cus, cvs, ms = random_state(seed)
        g = mg.make_grid(N, N, DX)
        l0 = ap.particle_angular_momentum(g, xs, ys, us, vs, cus, cvs, ms)
        mu, mv = ap.p2g(g, xs, ys, us, vs, cus, cvs, ms)
        l1 = ap.grid_angular_momentum(g, mu, mv)
        us2, vs2, cus2, cvs2 = ap.g2p(g, xs, ys)
        l2 = ap.particle_angular_momentum(g, xs, ys, us2, vs2, cus2, cvs2, ms)
        scale = sum(m * (abs(u) + abs(v)) for u, v, m in zip(us, vs, ms))
        assert abs(l1 - l0) < 1e-12 * scale
        assert abs(l2 - l1) < 1e-12 * scale


def test_transfers_keep_linear_momentum() -> None:
    _, xs, ys, us, vs, cus, cvs, ms = random_state(3)
    g = mg.make_grid(N, N, DX)
    p0 = ap.particle_momentum(us, vs, ms)
    mu, mv = ap.p2g(g, xs, ys, us, vs, cus, cvs, ms)
    p1 = ap.grid_momentum(g, mu, mv)
    us2, vs2, _, _ = ap.g2p(g, xs, ys)
    p2 = ap.particle_momentum(us2, vs2, ms)
    for a in range(2):
        assert abs(p1[a] - p0[a]) < 1e-12 * len(xs)
        assert abs(p2[a] - p1[a]) < 1e-12 * len(xs)


def test_affine_field_survives_a_round_trip() -> None:
    rng, xs, ys, _, _, _, _, ms = random_state(4)
    a, b, c, d, e, f = (rng.uniform(-1.0, 1.0) for _ in range(6))
    us = [a + b * x + c * y for x, y in zip(xs, ys)]
    vs = [d + e * x + f * y for x, y in zip(xs, ys)]
    g = mg.make_grid(N, N, DX)
    ap.p2g(g, xs, ys, us, vs, [(b, c)] * len(xs), [(e, f)] * len(xs), ms)
    us2, vs2, cus2, cvs2 = ap.g2p(g, xs, ys)
    for i in range(len(xs)):
        assert abs(us2[i] - us[i]) < 1e-12 and abs(vs2[i] - vs[i]) < 1e-12
        assert abs(cus2[i][0] - b) < 1e-11 and abs(cus2[i][1] - c) < 1e-11
        assert abs(cvs2[i][0] - e) < 1e-11 and abs(cvs2[i][1] - f) < 1e-11
    # Without the gradients (the PIC transfer), the same field loses energy.
    zero = [(0.0, 0.0)] * len(xs)
    ap.p2g(g, xs, ys, us, vs, zero, zero, ms)
    us3, vs3, _, _ = ap.g2p(g, xs, ys)
    assert ap.particle_kinetic_energy(us3, vs3, ms) < ap.particle_kinetic_energy(us, vs, ms)


def test_gradient_equals_b_times_d_inverse() -> None:
    rng, xs, ys, _, _, _, _, _ = random_state(5)
    g = mg.make_grid(N, N, DX)
    g.u = [[rng.uniform(-1.0, 1.0) for _ in range(N)] for _ in range(N + 1)]
    g.v = [[rng.uniform(-1.0, 1.0) for _ in range(N + 1)] for _ in range(N)]
    _, _, cus, cvs = ap.g2p(g, xs, ys)
    for p, (x, y) in enumerate(zip(xs, ys)):
        for wts, face, field, grad in ((ap.u_weights(g, x, y), ap.u_face, g.u, cus[p]),
                                       (ap.v_weights(g, x, y), ap.v_face, g.v, cvs[p])):
            bx = by = dxx = dyy = dxy = 0.0
            for a, b, w, _, _ in wts:
                fx, fy = face(g, a, b)
                bx += w * field[a][b] * (fx - x)
                by += w * field[a][b] * (fy - y)
                dxx += w * (fx - x) ** 2
                dyy += w * (fy - y) ** 2
                dxy += w * (fx - x) * (fy - y)
            assert abs(dxy) < 1e-15
            if dxx > 1e-6 * DX * DX and dyy > 1e-6 * DX * DX:
                assert abs(grad[0] - bx / dxx) < 1e-8
                assert abs(grad[1] - by / dyy) < 1e-8


def test_swirl_keeps_most_energy() -> None:
    # A measurement on a closed box full of liquid, without gravity.
    rng = random.Random(4)
    g = mg.make_grid(N, N, DX)
    xs, ys = ap.seed_block(rng, N, N, DX)
    ms = [1.0] * len(xs)
    us = [math.sin(math.pi * x) * math.cos(math.pi * y) for x, y in zip(xs, ys)]
    vs = [-math.cos(math.pi * x) * math.sin(math.pi * y) for x, y in zip(xs, ys)]
    cus = [(0.0, 0.0)] * len(xs)
    cvs = [(0.0, 0.0)] * len(xs)
    e0 = ap.particle_kinetic_energy(us, vs, ms)
    for _ in range(10):
        xs, ys, us, vs, cus, cvs = ap.step(g, xs, ys, us, vs, cus, cvs, ms, 0.02, gravity=0.0)
        assert mg.max_fluid_divergence(g) < 1e-9
    assert ap.particle_kinetic_energy(us, vs, ms) > 0.8 * e0


def test_small_dam_break() -> None:
    rng = random.Random(6)
    n, dx, dt = 12, 0.05, 0.005
    g = mg.make_grid(n, n, dx)
    xs, ys = ap.seed_block(rng, 4, 6, dx)
    ms = [1000.0 * dx * dx / 4] * len(xs)
    us = [0.0] * len(xs)
    vs = [0.0] * len(xs)
    cus = [(0.0, 0.0)] * len(xs)
    cvs = [(0.0, 0.0)] * len(xs)
    for _ in range(60):
        xs, ys, us, vs, cus, cvs = ap.step(g, xs, ys, us, vs, cus, cvs, ms, dt)
        assert mg.max_fluid_divergence(g) < 1e-9
        assert min(xs) >= 0.5 * dx and max(xs) <= n * dx - 0.5 * dx
        assert min(ys) >= 0.5 * dx and max(ys) <= n * dx - 0.5 * dx
    assert max(xs) > 8 * dx

History

PIC (Harlow, from the 1950s) averages away the rotation of the flow near each particle, and FLIP (Brackbill and Ruppel 1986) keeps it but becomes noisy. Jiang, Schroeder, Selle, Teran and Stomakhin (2015) gave each particle an affine velocity field, with transfers that keep linear and angular momentum. Jiang, Schroeder and Teran (2017) gave the analysis in more detail, including a MAC grid version. APIC and its extensions are now common in material point method solvers for graphics.

References

  1. Chenfanfu Jiang, Craig Schroeder, Andrew Selle, Joseph Teran and Alexey Stomakhin, The affine particle-in-cell method, ACM Transactions on Graphics 34(4), 2015, the transfers, the matrix D_p for the interpolation kernels and the conservation of angular momentum
  2. Chenfanfu Jiang, Craig Schroeder and Joseph Teran, An angular momentum conserving affine-particle-in-cell method, Journal of Computational Physics 338, 137-164, 2017, the whole paper (the analysis and the MAC grid transfers)
  3. Yongning Zhu and Robert Bridson, Animating sand as a fluid, ACM Transactions on Graphics 24(3), 965-972, 2005, the section on PIC and FLIP (the base method)

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