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
- Model
- Real RAM
- Properties
- conserves angular momentumconserves linear momentumdeterministicnot exactkeeps affine fields
- Evidence
- Proof sketchCode in 1 languages
- 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: , the gradient of the velocity, and , the gradient of the velocity. Together they are the rows of the affine matrix of the paper. The grid is a MAC grid of cells of size with fixed walls, is the density, gravity is m/s² on the axis and is the step. This is one method for fluid simulation for animation. The weight is the bilinear weight of face at particle , is its gradient with respect to the particle position, and is the center of face .
The algorithm
APIC-STEP(x, u, v, cᵘ, cᵛ, Δt)- 1
for each cell: FLUID if it holds a particle, else AIR (walls stay SOLID) - 2
for 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ᵛ - 3
for each v face f with m_f > 0: v_f ← v_f + Δt g - 4
project the grid velocity (pressure solve on the FLUID cells) - 5
for each particle p: uₚ ← Σ_f w_fp u_f, cᵘₚ ← Σ_f u_f ∇w_fp, the same for v - 6
for 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 it is the PIC transfer. Line L5 is the APIC G2P. The paper writes the gradient as , with and . For bilinear weights, is diagonal with the entries and , where is the position of the particle inside the stencil of the component, and . The gradient form has no division and works also when or is 0. Each component of the MAC grid has its own stencil, so differs for and . 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 m, 256 particles at random positions at least half a cell from the walls, unit masses, and the rigid rotation , with and . 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 and to within , and the angular momentum changes by less than of its value.
Now take the closed swirl of the FLIP page: the same box full of liquid with , , 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 () | FLIP () | 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 from the walls. The angular momentum of the particles is : the angular momentum of the centers plus the one of the affine fields. The angular momentum of the grid is , 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 and .
- 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 , with 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 faces, with the center of face ; the faces are the same with the roles of and exchanged. The masses are and .
The bilinear stencil
Fix a particle whose weights are not clamped. Its four faces are with , at and , and , with . The weights are with , , , . The gradient of the code is with , , and the same for .
Lemma 1. For the stencil of :
- , and .
- , and .
- , and .
- For each face, , and . The same holds with in place of .
Proof. Each sum factors into a sum over and a sum over . In one dimension, and , which gives part 1. For part 2, is the product of the two sums of part 1, so it is 0, and . For part 3, and , while the factor or gives the other parts. For part 4, take : . For : . Multiply by . The second identity of part 4 is the first one minus .
For the faces, no clamping means ; for the faces, . Line L6 keeps every particle in this range. We write for of the stencil of and for of its stencil.
Angular momentum
The particle angular momentum is , and the grid angular momentum is .
Claim 1. If no weight is clamped, line L2 gives .
Proof. A face with no mass has for every and adds nothing. For the others, , so
Write . By Lemma 1, , and . So . In the same way, . The difference is .
Claim 2. If no weight is clamped, line L5 gives , with the face masses of line L2.
Proof. After line L5, and . So by Lemma 1, part 4,
The part is the same with , and the difference gives .
Linear momentum
Claim 3. Line L2 gives , and line L5 gives .
Proof. by Lemma 1, part 1. Line L5 is the PIC transfer for , and .
Affine fields
Claim 4. Let , and let every particle carry and . If no weight is clamped, then after lines L2 and L5, and for every particle.
Proof. For every particle, , so each face with mass gets the weighted mean of equal values, . A face in the stencil of a particle has and so has mass, or it has and adds nothing to line L5. Then by Lemma 1, part 1. And by Lemma 1, part 3.
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 . Then and , so when is invertible.
Proof. By Lemma 1, part 4, for each face, and the same with . Multiply by and sum over the faces. is diagonal by Lemma 1, part 2.
Complexity
The transfers cost time, with four faces per component and particle, and a few more operations per face than PIC. Line L4 costs for conjugate gradient iterations. The memory is , 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, is a constant times the identity, and , and is cheap.
- Collocated grids. On a grid with all velocity components at the nodes, as in the material point method, one matrix 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, and have different stencils. Line L5 must compute from the faces and from the faces, each with its own weights.
- Dividing by . For bilinear weights, is singular when a particle is on a grid line of a stencil. Use the gradient form of line L5, not .
- A missing term in line L2. Line L2 must add 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 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 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.
# 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
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag AJQ8H2 Edit this page History Report an error Markdown