Algorithmcore
Particle-in-cell method
Also called PIC method.
Carry velocity on particles, transfer it to a grid for forces and pressure projection, and interpolate the grid velocity back to the particles.
- 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
- not conserves angular momentumconserves linear momentumdeterministicdissipativenot exact
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Francis H. Harlow, Yongning Zhu, Robert Bridson, 1964
The particle-in-cell method (PIC) simulates a liquid with particles and a grid together. The particles carry the positions and the velocities, so the liquid moves without the smoothing of a grid advection. The grid is a MAC grid, where gravity and the pressure projection are simple. In each step the particle velocities go to the grid, the grid velocity is made divergence free, and the new grid velocity comes back to the particles. Each transfer is an average, so PIC loses kinetic energy in each step, and fast swirls slow down. FLIP and APIC change the transfers to lose less.
In plain words
The water is a cloud of small particles, and each particle knows its speed. A grid of boxes covers the water. In each step, each edge of the grid takes an average of the speeds of the near particles. On the grid it is easy to add gravity and to make sure that no box takes in more water than it lets out. Then each particle gets a new speed, which is an average of the near grid edges. At last the particles move with the grid flow. The two averages smooth the speeds, so a swirl in the water slowly stops, even when nothing in the water should stop it.
The problem
The input is a set of particles with masses , positions and velocities , a MAC grid of by cells of size with fixed walls, the density , gravity m/s² on the axis and the step . The output is the state after one step. This is one method for fluid simulation for animation. On the MAC grid, is stored at the centers of the vertical faces and at the centers of the horizontal faces. The weight of face at particle is the bilinear weight of the four nearest samples of the same component, so and .
The algorithm
PIC-STEP(x, u, v, Δt)- 1
for each cell: FLUID if it holds a particle, else AIR (walls stay SOLID) - 2
for each face f: m_f ← Σₚ w_fp mₚ; u_f ← Σₚ w_fp mₚ uₚ / m_f (0 if m_f = 0), the same for v - 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, vₚ ← Σ_f w_fp v_f - 6
for each particle p: move xₚ through the grid velocity for Δt, keep it Δx/2 from the walls
Line L1 marks the liquid: a cell with at least one particle is FLUID, and the pressure is 0 in the AIR cells. Line L2 is the particle to grid transfer (P2G), a mass-weighted average of the particle velocities near each face. Line L3 adds gravity on the faces that carry liquid. Line L4 is the projection of the MAC grid page: a conjugate gradient solve for the pressure, then the pressure gradient is subtracted, so the discrete divergence of every FLUID cell is 0. Line L5 is the grid to particle transfer (G2P), with the same weights as line L2. Line L6 moves each particle with a midpoint (RK2) step in the projected grid velocity. The clamp to half a cell from the walls keeps the bilinear weights unclamped, which matters for the angular momentum claim below. The code puts four particles in each cell at the start, with a small random shift.
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 , in 1/s. Do lines L2 and L5 only, with no gravity and no projection, again and again at the same positions. The rigid rotation is a linear field, so an exact method would keep it. The table gives the kinetic energy and the angular momentum as fractions of their start values.
| round trips | grid energy after L2 | particle energy after L5 | particle angular momentum after L5 |
|---|---|---|---|
| 1 | 0.9657 | 0.9340 | 0.9647 |
| 2 | 0.9042 | 0.8758 | 0.9321 |
| 5 | 0.7503 | 0.7279 | 0.8444 |
| 10 | 0.5560 | 0.5397 | 0.7201 |
Each transfer is an average, so each one loses energy, and after 10 round trips almost half of the energy is gone. Line L2 keeps the angular momentum exactly (the grid value after line L2 equals the particle value before it), and line L5 loses it. A uniform flow, in contrast, goes through both transfers with no change.
Correctness
PIC is an approximation of the Euler equations of a liquid, and its error is not bounded here. The tests check these facts, and the proof gives the arguments:
- The weights. Each weight is at least 0 and the four weights of a particle add up to 1, so line L5 is the bilinear sample of the MAC grid page.
- Linear momentum. Lines L2 and L5 keep and , also near the walls.
- Energy. Line L2 does not increase the kinetic energy, and line L5 does not increase it either. The loss is strict unless the velocities near each face are equal.
- Angular momentum. If no particle is closer than to a wall, line L2 keeps the angular momentum exactly. Line L5 does not keep it in general.
- Constant flows. A uniform velocity goes through lines L2 and L5 unchanged.
- Projection. After line L4, the discrete divergence of the FLUID cells is 0, to the tolerance of the solver.
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: Momentum and energy of the PIC transfersfull
We use the notation of the page, with exact real arithmetic. The claims are about lines L2 and L5 at the same particle positions. We prove them for the faces; the faces are the same with the roles of and exchanged. The masses are , and is the mass of face from line L2.
The weights
Claim 1. For each particle, and .
Proof. The code clamps the fractional sample coordinates into the sample range and picks the lower sample so that and are in . The four weights are , , and , which are at least 0, and their sum is . These are the weights of the bilinear sample of the MAC grid page, so line L5 equals that sample.
Claim 2. If the weights of particle are not clamped, then and , where is the center of face .
Proof. The faces are at and with . The weights give when is not clamped, and the same holds for .
For the faces, no clamping means ; for the faces, . Line L6 keeps every particle in this range.
Linear momentum
Claim 3. Line L2 gives , and line L5 gives .
Proof. A face with has for every , so it adds 0 to both sides. For the others, , and the sum over is by Claim 1. For line L5, .
Claim 3 needs no hypothesis on clamping.
Energy
Claim 4. after line L2, and after line L5.
Proof. For a face with , is the mean of the with the weights , which are at least 0 and add up to 1. By Jensen's inequality for the convex function , . The sum over and Claim 1 give the first inequality. For line L5, is a mean with the weights , so . Multiply by and sum over : .
Equality in the first inequality needs all with to be equal for each face. So a velocity field that varies inside the support of a face loses energy in each round trip, as the example of the page shows.
Angular momentum
On the MAC grid, the angular momentum about the origin is .
Claim 5. If no particle is clamped, line L2 gives the grid equal to .
Proof. by Claim 2. In the same way, .
Line L5 does not keep in general. The particle value after line L5 is , while the grid value is . The difference (and the term in ) is not 0 when varies over the stencil of a particle, and the example of the page shows a loss.
Constant flows
Claim 6. If for every particle, then after lines L2 and L5, for every particle.
Proof. Each face with mass gets the mean . Each face in the stencil of a particle has and so has mass, or it has and adds nothing. So by Claim 1.
Complexity
Lines L1, L2, L3, L5 and L6 cost time for particles and cells, because each particle touches four faces of each component. Line L4 costs for conjugate gradient iterations, and grows with the size of the grid. The memory is . In the dam break of the tests, a 12 by 12 grid with 96 particles takes 60 steps of 5 ms in about 0.1 s of Python time (a measurement).
Properties
- Dissipation. Each transfer is an average and loses energy (proved for the transfers). The loss acts like a viscosity that depends on the grid size, and it damps small swirls.
- Linear momentum. The transfers keep it (proved).
- Angular momentum. P2G keeps it under the hypothesis above, and G2P loses it (proved for P2G, shown by the example for G2P).
- Stability. The new particle velocities are averages of the grid values, so PIC is stable for steps where FLIP is noisy.
- No mass loss in advection. The particles carry the liquid, so the volume does not leak away as in a level set advected on a grid. The particle density can still drift.
Variants and improvements
- FLIP. FLIP adds the change of the grid velocity to the particle velocity, which removes most of the dissipation and adds noise. A blend of PIC and FLIP is common.
- APIC. APIC stores a velocity gradient on each particle and makes line L5 keep the angular momentum and linear fields.
- Wider kernels. Quadratic or cubic B-spline weights in place of bilinear ones give smoother transfers at a higher cost.
- Velocity extrapolation. Copying the velocity of the liquid faces into the near AIR faces after line L4 gives better values to line L6 at the free surface.
- MPM. The material point method uses the same transfers for solids and also carries a deformation on each particle.
- Plasma PIC. In plasma physics, particle-in-cell moves charged particles in electric and magnetic fields that are solved on a grid. The transfers are of the same kind, but the forces are different.
When to use it
Use PIC as the base of a particle and grid liquid, or when stability matters more than detail, for example for sand, mud or very viscous liquids. For splashing water, blend it with FLIP or use APIC. For smoke on a fixed grid, stable fluids is simpler.
Pitfalls
- Holes in the liquid. Line L1 makes each empty cell AIR. With too few particles per cell, cells inside the liquid become AIR and get the pressure 0. Use about four particles per cell in 2D.
- Division by the face mass. Line L2 must divide by the sum of the mass weights, not by the number of particles. A face with no mass gets no velocity and must not be used as liquid.
- Gravity on empty faces. Line L3 changes only the faces with mass. Gravity on all faces gives a falling velocity in the air, which line L6 then reads at the surface.
- Different weights. Line L5 must use the same weights as line L2. With different weights the momentum and energy claims fail.
- The free surface in line L6. The midpoint of line L6 can read a face with no mass, which has the velocity 0 and slows the surface. Extrapolate the velocity, or use the velocity of line L5 for the move.
- Particles at the walls. Without the clamp of line L6, particles leave the box or sit on the wall, where the weights clamp and the angular momentum claim fails.
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
# 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_in_cell.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/particle-in-cell/. The authors are listed in prov/N6Z3N3.jsonl.
"""The particle-in-cell method (PIC) for a liquid on a 2D MAC grid.
The particles carry the positions and the velocities. One step labels the
cells, transfers the particle velocities to the faces of the MAC grid (P2G),
adds gravity, makes the grid velocity divergence free with macgrid.project,
interpolates the grid velocity back to the particles (G2P) and moves the
particles through the grid velocity.
The weights are bilinear, with the same clamping as macgrid.sample, so G2P
gives the same values as macgrid.u_at and macgrid.v_at. 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 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, ms):
"""Set each face velocity to the mass-weighted mean of the particle velocities.
u_f = sum_p w_fp m_p u_p / sum_p w_fp m_p, and the same for v. A face with no
mass gets 0. Returns the face masses (mu, mv).
"""
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, m in zip(xs, ys, us, vs, ms):
for a, b, w, _, _ in u_weights(g, x, y):
mu[a][b] += w * m
pu[a][b] += w * m * u
for a, b, w, _, _ in v_weights(g, x, y):
mv[a][b] += w * m
pv[a][b] += w * m * v
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 grid velocity at each particle, with the weights of p2g."""
us, vs = [], []
for x, y in zip(xs, ys):
us.append(sum(w * g.u[a][b] for a, b, w, _, _ in u_weights(g, x, y)))
vs.append(sum(w * g.v[a][b] for a, b, w, _, _ in v_weights(g, x, y)))
return us, vs
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, ms, dt, rho=1000.0, gravity=-9.81):
"""One PIC step. Changes the grid g and returns the new (xs, ys, us, vs)."""
label_cells(g, xs, ys) # @line L1
mu, mv = p2g(g, xs, ys, us, vs, ms) # @line L2
add_gravity(g, mv, dt, gravity) # @line L3
mg.project(g, dt, rho) # @line L4
us, vs = g2p(g, xs, ys) # @line L5
xs, ys = advect_particles(g, xs, ys, dt) # @line L6
return xs, ys, us, vs
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 grid_kinetic_energy(g, mu, mv):
"""(1/2) sum of m_f u_f^2 over the faces, with the face masses of p2g."""
s = sum(mu[a][b] * g.u[a][b] ** 2 for a in range(g.nx + 1) for b in range(g.ny))
s += sum(mv[a][b] * g.v[a][b] ** 2 for a in range(g.nx) for b in range(g.ny + 1))
return 0.5 * s
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)))
test_particle_in_cell.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/particle-in-cell/. The authors are listed in prov/N6Z3N3.jsonl.
import random
import macgrid as mg
import particle_in_cell as pic
N = 8
DX = 1.0 / N
def inner_particles(rng, count):
"""Random particles at least half a cell from the walls, so no weight is clamped."""
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)]
return xs, ys
def random_state(seed, count=200):
rng = random.Random(seed)
xs, ys = inner_particles(rng, count)
us = [rng.uniform(-1.0, 1.0) for _ in xs]
vs = [rng.uniform(-1.0, 1.0) for _ in xs]
ms = [rng.uniform(0.5, 1.5) for _ in xs]
return xs, ys, us, vs, ms
def test_weights_match_macgrid_sample() -> None:
rng = random.Random(1)
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)]
xs = [rng.uniform(-0.2, 1.2) for _ in range(100)]
ys = [rng.uniform(-0.2, 1.2) for _ in range(100)]
us, vs = pic.g2p(g, xs, ys)
for x, y, u, v in zip(xs, ys, us, vs):
assert abs(u - mg.u_at(g, x, y)) < 1e-12
assert abs(v - mg.v_at(g, x, y)) < 1e-12
for wts in (pic.u_weights(g, x, y), pic.v_weights(g, x, y)):
assert min(w for _, _, w, _, _ in wts) >= 0.0
assert abs(sum(w for _, _, w, _, _ in wts) - 1.0) < 1e-12
def test_transfers_do_not_add_kinetic_energy() -> None:
for seed in (2, 3, 4):
xs, ys, us, vs, ms = random_state(seed)
g = mg.make_grid(N, N, DX)
e_particles = pic.particle_kinetic_energy(us, vs, ms)
mu, mv = pic.p2g(g, xs, ys, us, vs, ms)
e_grid = pic.grid_kinetic_energy(g, mu, mv)
us2, vs2 = pic.g2p(g, xs, ys)
e_back = pic.particle_kinetic_energy(us2, vs2, ms)
assert e_grid <= e_particles * (1.0 + 1e-12)
assert e_back <= e_grid * (1.0 + 1e-12)
assert e_back < 0.9 * e_particles
def test_transfers_keep_linear_momentum() -> None:
xs, ys, us, vs, ms = random_state(5)
# Particles near the walls too: the weights are clamped, and the momentum is still kept.
rng = random.Random(6)
xs[:20] = [rng.uniform(0.0, 1.0) for _ in range(20)]
ys[:20] = [rng.uniform(0.0, 1.0) for _ in range(20)]
g = mg.make_grid(N, N, DX)
p0 = pic.particle_momentum(us, vs, ms)
mu, mv = pic.p2g(g, xs, ys, us, vs, ms)
p1 = pic.grid_momentum(g, mu, mv)
us2, vs2 = pic.g2p(g, xs, ys)
p2 = pic.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_p2g_keeps_angular_momentum_and_g2p_loses_it() -> None:
xs, ys, _, _, ms = random_state(7)
us = [-(y - 0.5) for y in ys]
vs = [x - 0.5 for x in xs]
g = mg.make_grid(N, N, DX)
l0 = sum(m * (x * v - y * u) for x, y, u, v, m in zip(xs, ys, us, vs, ms))
mu, mv = pic.p2g(g, xs, ys, us, vs, ms)
l1 = sum(mu[a][b] * -((b + 0.5) * DX) * g.u[a][b] for a in range(N + 1) for b in range(N))
l1 += sum(mv[a][b] * (a + 0.5) * DX * g.v[a][b] for a in range(N) for b in range(N + 1))
assert abs(l1 - l0) < 1e-12 * abs(l0) * len(xs)
us2, vs2 = pic.g2p(g, xs, ys)
l2 = sum(m * (x * v - y * u) for x, y, u, v, m in zip(xs, ys, us2, vs2, ms))
assert l2 < 0.99 * l0
def test_constant_velocity_survives_a_round_trip() -> None:
xs, ys, _, _, ms = random_state(8)
us = [0.3] * len(xs)
vs = [-0.7] * len(xs)
g = mg.make_grid(N, N, DX)
pic.p2g(g, xs, ys, us, vs, ms)
us2, vs2 = pic.g2p(g, xs, ys)
assert max(abs(u - 0.3) for u in us2) < 1e-12
assert max(abs(v + 0.7) for v in vs2) < 1e-12
def test_small_dam_break() -> None:
rng = random.Random(9)
n, dx, dt = 12, 0.05, 0.005
g = mg.make_grid(n, n, dx)
xs, ys = pic.seed_block(rng, 4, 6, dx)
ms = [1000.0 * dx * dx / 4] * len(xs)
us = [0.0] * len(xs)
vs = [0.0] * len(xs)
for _ in range(60):
xs, ys, us, vs = pic.step(g, xs, ys, us, vs, 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
Harlow and his group at Los Alamos developed the particle-in-cell method in the 1950s and early 1960s, for compressible flows with large deformations, and described it in papers of 1963 and 1964. Brackbill and Ruppel (1986) made FLIP, which keeps the full velocity on the particles. Zhu and Bridson (2005) brought PIC and FLIP to computer graphics, with a MAC grid and a pressure projection, for liquids and sand. Jiang, Schroeder, Selle, Teran and Stomakhin (2015) added APIC.
References
- Francis H. Harlow, The particle-in-cell method for numerical solution of problems in fluid dynamics, Proceedings of Symposia in Applied Mathematics 15, 269-288, 1963, the whole paper
- The particle-in-cell computing method for fluid dynamics, the whole chapter
- 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 for liquids (the transfers and the particle labels of the cells)
- Fluid Simulation for Computer Graphics, the chapter on particle methods
Where this leads
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 N6Z3N3 Edit this page History Report an error Markdown