Algorithm Search⌘K

Algorithmcore

Fluid-implicit-particle method

Also called FLIP.

Like particle-in-cell, but add only the change of the grid velocity to each particle, which reduces the dissipation of PIC and adds noise.

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
not conserves angular momentumconserves linear momentumdeterministicnot dissipativenot exact
Origin
Jeremiah U. Brackbill, Hans M. Ruppel, Yongning Zhu, Robert Bridson, 1986

The fluid-implicit-particle method (FLIP) is the particle-in-cell method with a different grid to particle transfer. A PIC particle takes the new grid velocity, which is an average and loses energy. A FLIP particle keeps its own velocity and adds only the change of the grid velocity over the step. So small swirls that the grid cannot hold stay on the particles, and the dissipation is much smaller. The cost is noise: the particle velocities drift away from the smooth grid field, because nothing pulls them back. In practice the update is a blend of FLIP and a small part of PIC.

In plain words

The water is a cloud of particles over a grid of boxes, as in PIC. The particles give their speeds to the grid, and the grid adds gravity and makes sure that the water does not squeeze. In PIC, each particle then forgets its speed and takes the average speed of the grid near it. In FLIP, each particle keeps its speed and adds only what the grid changed. So a particle does not lose its small motions in each step, and swirls last much longer. But the particles can now get speeds that differ a little from their neighbors, which shows as noise. A small part of PIC in the mix calms the noise.

The problem

The input and the output are those of PIC: nn particles with masses mpm_p, positions xpx_p and velocities (up,vp)(u_p, v_p), a MAC grid of cells of size Δx\Delta x with fixed walls, the density ρ\rho, gravity g=−9.81g = -9.81 m/s² on the yy axis, the step Δt\Delta t, and the blend weight α∈[0,1]\alpha \in [0, 1]. This is one method for fluid simulation for animation. The weights wfpw_{fp} are the bilinear weights of PIC.

The algorithm

  1. FLIP-STEP(x, u, v, Δt, α)
  2. 1for each cell: FLUID if it holds a particle, else AIR (walls stay SOLID)
  3. 2for 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
  4. 3u_old ← u, v_old ← v (the grid velocity of line L2)
  5. 4for each v face f with m_f > 0: v_f ← v_f + Δt g
  6. 5project the grid velocity (pressure solve on the FLUID cells)
  7. 6for each particle p: uₚ ← α (uₚ + Σ_f w_fp (u_f - u_old,f)) + (1 - α) Σ_f w_fp u_f, the same for v
  8. 7for each particle p: move xₚ through the grid velocity for Δt, keep it Δx/2 from the walls

Lines L1, L2, L4, L5 and L7 are the lines of PIC. Line L3 saves the grid velocity right after the transfer, before the forces and the projection. Line L6 is the only real change. Its first term is the FLIP update: the old particle velocity plus the change of the grid velocity, interpolated to the particle. Its second term is the PIC update. With α=1\alpha = 1 the update is pure FLIP, and with α=0\alpha = 0 it is PIC. The code uses α=0.95\alpha = 0.95; values from 0.95 to 0.99 are common in graphics, and the value is a tuning choice.

Example

Take an 8 by 8 grid of unit size, all filled with liquid (four particles per cell, unit masses), with no gravity. The start velocity is the swirl u=sin⁡(πx)cos⁡(πy)u = \sin(\pi x)\cos(\pi y), v=−cos⁡(πx)sin⁡(πy)v = -\cos(\pi x)\sin(\pi y), which has no divergence and no flow through the walls. In an ideal liquid its kinetic energy would stay constant. Run steps of 0.02 s. The table gives the particle kinetic energy as a fraction of the start value (measured).

steps PIC (α=0\alpha = 0) blend (α=0.95\alpha = 0.95) FLIP (α=1\alpha = 1)
1 0.8916 0.9871 0.9924
5 0.5732 0.9470 0.9781
10 0.3378 0.9029 0.9676
20 0.1203 0.8267 0.9544
40 0.0152 0.7455 0.9521

PIC loses almost all of the swirl in 40 steps on this coarse grid. FLIP keeps 95% of the energy. The noise goes the other way: after 40 steps, the root mean square difference between the particle velocity and the grid velocity at the particle is 0.0005 m/s with PIC, 0.069 m/s with the blend and 0.159 m/s with FLIP, for a start speed of up to 1 m/s.

Correctness

FLIP 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:

  • No change, no update. With α=1\alpha = 1, if the grid velocity does not change between lines L3 and L6, line L6 leaves every particle velocity exactly as it was.
  • The PIC end. With α=0\alpha = 0, line L6 is the PIC transfer.
  • Linear momentum. For every α\alpha, the particle momentum after line L6 equals the grid momentum after line L5, with the face masses of line L2.
  • Energy. FLIP has no energy bound like the one of PIC; with α=1\alpha = 1 a transfer can add energy. The energy table above is a measurement.

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: The end cases, the momentum and the energy of the FLIP transferfull

We use the notation of the page, with exact real arithmetic. We write the claims for the uu faces; the vv faces are the same. The masses are mp>0m_p > 0, mf=∑pwfpmpm_f = \sum_p w_{fp} m_p is the face mass of line L2, ufoldu^{old}_f is the copy of line L3 and ufu_f is the grid velocity after line L5. The particle positions in line L6 are those of line L2. The weights satisfy wfp≥0w_{fp} \ge 0 and ∑fwfp=1\sum_f w_{fp} = 1 for each particle (the proof of the PIC page, Claim 1). Line L6 is

up′=α(up+∑fwfp(uf−ufold))+(1−α)∑fwfpuf.u'_p = \alpha\left(u_p + \sum_f w_{fp}(u_f - u^{old}_f)\right) + (1 - \alpha)\sum_f w_{fp} u_f.

The end cases

Claim 1. If α=1\alpha = 1 and uf=ufoldu_f = u^{old}_f for every face, then up′=upu'_p = u_p for every particle.

Proof. Every term uf−ufoldu_f - u^{old}_f is 0, and the second term has the factor 1−α=01 - \alpha = 0. □\square

Claim 2. If α=0\alpha = 0, then up′=∑fwfpufu'_p = \sum_f w_{fp} u_f, the PIC transfer.

Proof. The first term has the factor 0. □\square

Linear momentum

Claim 3. For every α\alpha, ∑pmpup′=∑fmfuf\sum_p m_p u'_p = \sum_f m_f u_f.

Proof. Line L2 gives mfufold=∑pwfpmpupm_f u^{old}_f = \sum_p w_{fp} m_p u_p for each face with mass, and a face with no mass has wfp=0w_{fp} = 0 for all pp. So ∑fmfufold=∑pmpup\sum_f m_f u^{old}_f = \sum_p m_p u_p. For any face field qfq_f, ∑pmp∑fwfpqf=∑fmfqf\sum_p m_p\sum_f w_{fp} q_f = \sum_f m_f q_f. Then

∑pmp(up+∑fwfp(uf−ufold))=∑fmfufold+∑fmf(uf−ufold)=∑fmfuf,\sum_p m_p\left(u_p + \sum_f w_{fp}(u_f - u^{old}_f)\right) = \sum_f m_f u^{old}_f + \sum_f m_f(u_f - u^{old}_f) = \sum_f m_f u_f,

and the PIC term gives ∑fmfuf\sum_f m_f u_f too. A blend of two quantities that are both equal to ∑fmfuf\sum_f m_f u_f is equal to it. □\square

So the transfers add no momentum; only lines L4 and L5 change it (gravity and the walls).

Energy

Claim 4. With α=1\alpha = 1, line L6 can give a particle kinetic energy larger than the grid kinetic energy 12∑fmfuf2\frac12\sum_f m_f u_f^2 after line L5.

Proof. Take a grid that does not change between lines L3 and L6. By Claim 1, the particle energy after line L6 is the particle energy before line L2. By Claim 4 of the PIC proof (Jensen's inequality), that energy is at least the grid energy after line L2, and it is strictly larger if two particles with different velocities have a weight on the same face. The grid energy after line L5 is the grid energy after line L2, because the grid did not change. □\square

So FLIP has no bound of the kind that PIC has: the particle energy is not limited by the grid energy. The kinetic energy that the grid does not see stays on the particles, which is the reason for the low dissipation and also for the noise.

Angular momentum

Line L6 does not keep the angular momentum in general. With α=0\alpha = 0 it is the PIC transfer, which loses angular momentum (the PIC page). With α=1\alpha = 1 and uf−ufoldu_f - u^{old}_f equal to a constant δ\delta on every face, up′=up+δu'_p = u_p + \delta. The particle angular momentum changes by −δ∑pmpyp-\delta\sum_p m_p y_p and the grid angular momentum by −δ∑fmfyf-\delta\sum_f m_f y_f. Without clamping these are equal (the PIC proof, Claim 2), but for a general change of the grid field the interpolated change ∑fwfp(uf−ufold)\sum_f w_{fp}(u_f - u^{old}_f) has the same defect as the PIC transfer. ■\blacksquare

Complexity

The cost is the cost of PIC, O(n+c)O(n + c) for the transfers and O(kc)O(k c) for the projection, plus one copy of the grid velocity in line L3. The memory is O(n+c)O(n + c).

Properties

  • Low dissipation. FLIP does not average the particle velocities in each step, so it keeps much more energy than PIC (measured in the example).
  • Noise. The particle velocities are not tied to the grid field, so they drift apart and the liquid looks noisy. The noise grows with α\alpha (measured).
  • Linear momentum. The transfers keep it for every α\alpha (proved).
  • Angular momentum. Line L6 does not keep it in general.
  • The null space. The grid has about 2 velocity values per cell and the particles have 8 per cell. Particle velocity fields that give the same grid field are not seen by the grid, and FLIP never damps them. This is one source of the noise.

Variants and improvements

  • PIC and FLIP blend. The weight α\alpha of line L6 trades noise for dissipation.
  • APIC. APIC gives low dissipation with the stability of PIC, by a velocity gradient on each particle in place of the FLIP update.
  • Adaptive blends. Some solvers make α\alpha depend on the position, for example less FLIP near the walls and the free surface.
  • MPM. The material point method often uses a FLIP or APIC transfer for solids and sand.
  • Surfacing. FLIP liquids need a surface for rendering; see surface reconstruction from fluid particles.

When to use it

Use FLIP, with a small part of PIC, for splashing liquids where swirls and thin sheets should last. Use PIC for very viscous liquids and sand, where the dissipation does no harm. If the noise is a problem, use APIC.

Pitfalls

  • The wrong old velocity. Line L3 must save the grid velocity after the transfer of line L2 and before line L4. Saving it after line L4 loses gravity in the FLIP term, and saving it before line L2 adds the whole velocity again.
  • Moved particles in line L6. Line L6 must use the positions of line L2. A particle that moved before line L6 can read a face with no mass, which is 0 in the copy of line L3 and nonzero after line L5, and the FLIP term gets a false jump.
  • Pure FLIP. With α=1\alpha = 1 in line L6 the noise grows and can make the liquid unstable. Keep a small part of PIC.
  • A different velocity in line L7. Line L7 moves the particles in the grid velocity. Moving them with the noisy particle velocity of line L6 puts the noise into the positions too.

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.

fluid_implicit_particle.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fluid-implicit-particle/. The authors are listed in prov/QNPJRR.jsonl.
"""The fluid-implicit-particle method (FLIP) for a liquid on a 2D MAC grid.

The step is the PIC step with one change in the grid to particle transfer:
each particle adds the change of the grid velocity over the step to its own
velocity, in place of taking the new grid velocity. A blend with weight alpha
mixes the two:

    u_p <- alpha (u_p + sum_f w_fp (u_f - u_f_old)) + (1 - alpha) sum_f w_fp u_f.

alpha = 1 is pure FLIP and alpha = 0 is PIC. The default alpha = 0.95 is a
tuning value; values from 0.95 to 0.99 are common.

The weights are bilinear, with the same clamping as macgrid.sample. 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). The weights are at least 0 and add up to 1.
    A point outside the samples is clamped as in macgrid.sample.
    """
    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)), (a0, b0 + 1, (1.0 - s) * t),
            (a0 + 1, b0, s * (1.0 - t)), (a0 + 1, b0 + 1, s * t))


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. 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_flip(g, u_old, v_old, xs, ys, us, vs, alpha):
    """The blend of the FLIP update (old particle velocity plus the grid change) and the PIC update (the new grid velocity)."""
    nus, nvs = [], []
    for x, y, u, v in zip(xs, ys, us, vs):
        uw = u_weights(g, x, y)
        vw = v_weights(g, x, y)
        u_pic = sum(w * g.u[a][b] for a, b, w in uw)
        v_pic = sum(w * g.v[a][b] for a, b, w in vw)
        du = sum(w * (g.u[a][b] - u_old[a][b]) for a, b, w in uw)
        dv = sum(w * (g.v[a][b] - v_old[a][b]) for a, b, w in vw)
        nus.append(alpha * (u + du) + (1.0 - alpha) * u_pic)
        nvs.append(alpha * (v + dv) + (1.0 - alpha) * v_pic)
    return nus, nvs


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, alpha=0.95, rho=1000.0, gravity=-9.81):
    """One FLIP 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
    u_old, v_old = mg.copy_field(g.u), mg.copy_field(g.v)  # @line L3
    add_gravity(g, mv, dt, gravity)  # @line L4
    mg.project(g, dt, rho)  # @line L5
    us, vs = g2p_flip(g, u_old, v_old, xs, ys, us, vs, alpha)  # @line L6
    xs, ys = advect_particles(g, xs, ys, dt)  # @line L7
    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 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)))
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_fluid_implicit_particle.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fluid-implicit-particle/. The authors are listed in prov/QNPJRR.jsonl.

import math
import random

import macgrid as mg
import fluid_implicit_particle as fl

N = 8
DX = 1.0 / N


def random_state(seed, count=200):
    rng = random.Random(seed)
    xs = [rng.uniform(0.0, 1.0) for _ in range(count)]
    ys = [rng.uniform(0.0, 1.0) for _ in range(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 rng, xs, ys, us, vs, ms


def test_no_grid_change_keeps_the_particle_velocities() -> None:
    _, xs, ys, us, vs, ms = random_state(1)
    g = mg.make_grid(N, N, DX)
    fl.p2g(g, xs, ys, us, vs, ms)
    u_old, v_old = mg.copy_field(g.u), mg.copy_field(g.v)
    us2, vs2 = fl.g2p_flip(g, u_old, v_old, xs, ys, us, vs, 1.0)
    assert us2 == us and vs2 == vs


def test_alpha_zero_is_pic() -> None:
    rng, xs, ys, us, vs, ms = random_state(2)
    g = mg.make_grid(N, N, DX)
    fl.p2g(g, xs, ys, us, vs, ms)
    u_old, v_old = mg.copy_field(g.u), mg.copy_field(g.v)
    g.u = [[c + rng.uniform(-0.5, 0.5) for c in col] for col in g.u]
    g.v = [[c + rng.uniform(-0.5, 0.5) for c in col] for col in g.v]
    us2, vs2 = fl.g2p_flip(g, u_old, v_old, xs, ys, us, vs, 0.0)
    for x, y, u, v in zip(xs, ys, us2, vs2):
        assert abs(u - mg.u_at(g, x, y)) < 1e-12
        assert abs(v - mg.v_at(g, x, y)) < 1e-12


def test_transfers_keep_linear_momentum_for_every_alpha() -> None:
    rng, xs, ys, us, vs, ms = random_state(3)
    g = mg.make_grid(N, N, DX)
    p0 = fl.particle_momentum(us, vs, ms)
    mu, mv = fl.p2g(g, xs, ys, us, vs, ms)
    p1 = fl.grid_momentum(g, mu, mv)
    u_old, v_old = mg.copy_field(g.u), mg.copy_field(g.v)
    g.u = [[c + rng.uniform(-0.5, 0.5) for c in col] for col in g.u]
    g.v = [[c + rng.uniform(-0.5, 0.5) for c in col] for col in g.v]
    p2 = fl.grid_momentum(g, mu, mv)
    for alpha in (0.0, 0.95, 1.0):
        us2, vs2 = fl.g2p_flip(g, u_old, v_old, xs, ys, us, vs, alpha)
        p3 = fl.particle_momentum(us2, vs2, ms)
        for a in range(2):
            assert abs(p1[a] - p0[a]) < 1e-12 * len(xs)
            assert abs(p3[a] - p2[a]) < 1e-12 * len(xs)


def swirl_energy(alpha, steps):
    rng = random.Random(4)
    g = mg.make_grid(N, N, DX)
    xs, ys = fl.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)]
    e0 = fl.particle_kinetic_energy(us, vs, ms)
    for _ in range(steps):
        xs, ys, us, vs = fl.step(g, xs, ys, us, vs, ms, 0.02, alpha=alpha, gravity=0.0)
        assert mg.max_fluid_divergence(g) < 1e-9
    return fl.particle_kinetic_energy(us, vs, ms) / e0


def test_flip_keeps_more_energy_than_pic() -> None:
    # A measurement on a closed box full of liquid, without gravity.
    e_pic = swirl_energy(0.0, 10)
    e_flip = swirl_energy(0.95, 10)
    assert e_pic < 0.5
    assert e_flip > 0.8


def test_small_dam_break() -> None:
    rng = random.Random(5)
    n, dx, dt = 12, 0.05, 0.005
    g = mg.make_grid(n, n, dx)
    xs, ys = fl.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 = fl.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

Brackbill and Ruppel (1986) introduced FLIP to remove the large numerical dissipation of the particle-in-cell method of Harlow. Their particles carry all of the state, and the grid is only a work space for the update of each step. Zhu and Bridson (2005) brought PIC and FLIP to computer graphics, with a MAC grid and a pressure projection. Blends of FLIP with a small part of PIC are now widely used for liquids in visual effects. Jiang, Schroeder, Selle, Teran and Stomakhin (2015) proposed APIC as a stable alternative with low dissipation.

References

  1. J. U. Brackbill and H. M. Ruppel, FLIP. A method for adaptively zoned, particle-in-cell calculations of fluid flows in two dimensions, Journal of Computational Physics 65(2), 314-343, 1986, the whole paper (the update of the particle velocity by the change of the grid velocity)
  2. 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
  3. Fluid Simulation for Computer Graphics, the chapter on particle methods

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