Algorithm Search⌘K

Algorithmadvanced

Variational solid-fluid coupling

Also called variational pressure projection.

Find the pressure that minimizes the kinetic energy of fluid and solids, with face weights for cells that a solid cuts. Walls need not follow the grid, and rigid bodies couple in one solve.

Time
Θ(n + m) matvecO((n + m) k) projectΘ(n) weights
Space
Θ(n) extra
Where
k = the number of conjugate gradient iterations; m = the number of faces that the body covers; n = the number of grid cells
Properties
deterministicnot exact
Origin
Christopher Batty, Florence Bertails, Robert Bridson, 2007

Variational solid-fluid coupling, from Batty, Bertails and Bridson (2007), changes how the pressure step of a grid fluid sees solids. The usual "voxelized" solve marks each cell as solid or fluid, so a slanted or curved wall becomes a staircase. The variational method instead writes the pressure step as a minimization of kinetic energy. Each velocity sample on a MAC grid is weighted by the part of its face that is open to the fluid. The minimum is a sparse, symmetric positive semidefinite linear system that has the same shape as the usual one. So the same solver works, and walls at any angle need no special stencils. A rigid body adds its own kinetic energy to the sum. The fluid and the body then get their new velocities from one solve, with no iteration between two solvers.

In plain words

The pressure step makes the water flow so that no cell gains or loses water. Among all the ways to do that, it picks the one with the least change of motion energy.

The new method counts the energy honestly in cells that a wall cuts. A cell face that is half in the wall counts half. So the water can slide along a sloped wall instead of hitting steps.

A floating box is part of the same count. Its mass and speed go into the energy, so the pressure that moves the water also pushes the box. Heavy boxes sink, light boxes rise, and a box as heavy as water stays still.

The problem

The input is a velocity field u∗\mathbf u^* after advection and forces, the walls, and the rigid bodies with their velocities V∗V^* (here V=(vx,vy,ω)V = (v_x, v_y, \omega) in 2D). Find a pressure pp such that the new fluid velocity u=u∗−(Δt/ρ)∇p\mathbf u = \mathbf u^* - (\Delta t / \rho) \nabla p has zero divergence, the fluid neither enters nor leaves a solid, and each body gets the force and torque of the pressure on its surface. On the boundary this is u⋅n^=vsolid⋅n^\mathbf u \cdot \hat n = \mathbf v_{solid} \cdot \hat n, which is hard to discretize where the wall cuts a cell.

The energy. The paper's equation 3 is the kinetic energy of fluid and solids,

KE=∭fluid12ρ∣u∣2+12VTMSV,\mathrm{KE} = \iiint_{\text{fluid}} \tfrac12 \rho |\mathbf u|^2 + \tfrac12 V^\mathsf{T} M_S V,

and the pressure equation with its boundary condition is the condition for the minimum over pp. So we can discretize the energy, which is easy, and get the boundary condition for free.

The algorithm

On a MAC grid, each face ff has a fluid weight wfw_f: the part of the face outside every solid (the paper's figure 3 uses the part of the control volume of the face; it names the face area as a simpler estimate, which the code uses). Let bfb_f be the part inside the body. (Gp)f(G p)_f is the pressure difference across ff divided by Δx\Delta x, GTG^\mathsf{T} is minus the divergence, and RfVR_f V is the normal component of the rigid velocity at ff. The discrete energy is 12ρΔx2∑fwfuf2+12VTMV\tfrac12 \rho \Delta x^2 \sum_f w_f u_f^2 + \tfrac12 V^\mathsf{T} M V, with M=ρsΔx2RTBRM = \rho_s \Delta x^2 R^\mathsf{T} B R.

  1. VARIATIONAL-PROJECT(u*, V*, walls, body, Δt)
  2. 1for each face f: s_f and b_f <- the parts of f in the walls and in the body; w_f <- 1 - s_f - b_f
  3. 2the unknowns are the cells that are not AIR or SOLID and have a face with w_f > 0
  4. 3r <- Gᵀ (W u* + B R V*)
  5. 4A <- (Δt/ρ) Gᵀ W G + (Δt/ρ_s) Gᵀ B R (Rᵀ B R)⁻¹ Rᵀ B G
  6. 5solve A p = r by conjugate gradients, with p = 0 in AIR cells
  7. 6u_f <- u*_f - (Δt/ρ) (G p)_f on every face with w_f > 0
  8. 7V <- V* - (Δt/ρ_s) (Rᵀ B R)⁻¹ Rᵀ B G p

Weights (L1). With a level set for each solid, the part of a face inside the solid comes from the values at the two ends of the face, by linear interpolation. The paper lists three estimates of the fluid mass of a velocity sample: the exact fluid volume of its control volume, Δx\Delta x times the fluid area of its face (which gives a method related to finite volumes), and Δx2\Delta x^2 times the fluid part of the segment between the two pressure samples. The voxelized solve is the case where every weight is 0 or 1.

Pressure (L3 to L5). Without a body, setting the derivative of the energy to zero gives the paper's equation 6, (Δt/ρ2)GTMFGp=(1/ρ)GTMFu~(\Delta t / \rho^2) G^\mathsf{T} M_F G p = (1 / \rho) G^\mathsf{T} M_F \tilde{\mathbf u}, with the fluid masses MFM_F. In 2D, its equation 7 is a 5-point stencil whose coefficients are the face weights. The right side is minus the divergence of the mixed velocity Wu∗+BRV∗W \mathbf u^* + B R V^*. The body adds Δt JTMS−1J\Delta t\, J^\mathsf{T} M_S^{-1} J to the matrix, where JJ maps the pressure to the net force and torque on the body (its equations 8 to 12, written as volume integrals of ∇p\nabla p). This term has rank 3 in 2D and rank 6 in 3D, and the code applies it without forming it.

Scripted solids. A solid whose motion is given has an infinite mass. Then MS−1=0M_S^{-1} = 0: the term leaves the matrix, and only its velocity stays on the right side.

Cells inside the body. A cell whose four faces are all inside the body has a zero column in JJ, because the contributions of opposite faces cancel. Its pressure does not matter, and the code leaves it out.

Example

A face cut by a wall. Let the wall level set be −1-1 at one end of a face and 33 at the other. The wall crosses the face at a quarter of its length, so sf=0.25s_f = 0.25 and wf=0.75w_f = 0.75. In the energy, the velocity sample counts with three quarters of the mass of a full face; in the 5-point stencil, the coefficient of this neighbor is 0.75 instead of 1.

Still water in a round bowl. On a 24 by 24 grid of the unit square, take water inside a circle of radius 0.46 up to the height 0.75, gravity g=9.81g = 9.81 m/s² and Δt=0.01\Delta t = 0.01 s. After gravity and one projection, every face velocity is below 10−1310^{-13} m/s, and the pressure equals ρg\rho g times the depth to 10−910^{-9} Pa. Conjugate gradients take 94 iterations on 344 unknowns. This holds for any shape of the container (Theorem 3 of the proof).

Flow along a tilted channel. A straight channel of width 0.24 crosses a 24 by 16 grid at 10 or 20 degrees, open at both ends. A uniform flow of speed 1 along the channel is already divergence free and tangent to the walls, so the projection should not change it. The variational solve keeps it to 10−1510^{-15}. The voxelized solve of macgrid changes it:

angle variational flux voxelized flux
10° 0.2400 0.2239
20° 0.2400 0.2186

The paper's figure 2 shows the same effect on a vortex in a rotated box.

A sinking and a rising disk. Put a disk of radius 0.1 at (0.5,0.45)(0.5, 0.45) in the bowl, and take one step from rest. A cylinder in unbounded still fluid starts with the acceleration g(ρs−ρ)/(ρs+ρ)g (\rho_s - \rho) / (\rho_s + \rho): the fluid that must move with it acts as an added mass equal to the fluid it displaces. The coupled solve finds this added mass without a model for it:

ρs/ρ\rho_s / \rho measured a/ga / g unbounded fluid
2 -0.3316 -0.3333
1 0 (to 10−1510^{-15}) 0
0.5 0.3299 0.3333
0.1 0.8066 0.8182

The walls of the bowl add a little to the added mass, so the measured values are slightly smaller. The light disk with ρs=0.1ρ\rho_s = 0.1 \rho is stable; the paper notes that the method of Carlson et al. (2004) cannot handle bodies lighter than about 0.45 times the fluid density.

Correctness

The proofs are in proofs/correctness.md.

  1. Lines L3 to L5 minimize the energy. The gradient of the discrete energy is zero exactly when Ap=rA p = r, and then the mixed velocity of fluid and body has zero divergence in every unknown cell.
  2. The matrix. AA is symmetric positive semidefinite. Constant vectors are in its null space when no AIR cell is present; with an AIR cell next to each group of fluid cells, AA is positive definite. So the system is not positive definite in every case; the paper calls it "symmetric positive semi-definite".
  3. No energy is added. The projection never increases the kinetic energy of fluid and body.
  4. Hydrostatic rest. Still water in a container of any shape stays still, with p=ρgp = \rho g times the depth, and a body with the density of the fluid stays at rest if its mass matrix comes from the same face weights.
  5. Binary weights. With weights 0 and 1 from the cell labels, the method is the usual voxelized solve.
  6. Straight walls. A uniform flow along straight walls is kept exactly.

The method is a discretization. The face area estimate of the mass is exact for the flux through straight walls (item 6) and only approximates a curved wall. The paper calls its results accurate on coarse grids, which means without the stair-step artifacts, not a proved order of convergence.

Proof: The pressure minimizes the kinetic energy, the matrix is semidefinite, and still water stays stillfull

We use the line numbers of the page and the notation of the code. A face ff has the fluid weight wfw_f, the body weight bfb_f and the wall weight sfs_f, with wf+bf+sf=1w_f + b_f + s_f = 1. (Gp)f=(pr−pl)/Δx(G p)_f = (p_r - p_l) / \Delta x for the cells ll and rr on the two sides of ff, with p=0p = 0 in AIR cells. GTqG^\mathsf{T} q is minus the discrete divergence of a face field qq. RfR_f is the row with $R_f V = $ the normal component at ff of the rigid velocity V=(vx,vy,ω)V = (v_x, v_y, \omega): Rf=(1,0,−(yf−cy))R_f = (1, 0, -(y_f - c_y)) on a uu face and (0,1,xf−cx)(0, 1, x_f - c_x) on a vv face. WW and BB are the diagonal matrices of the wfw_f and the bfb_f. Let Mg=RTBRM_g = R^\mathsf{T} B R; the mass matrix of the body is M=ρsΔx2MgM = \rho_s \Delta x^2 M_g per unit depth.

Lemma 1 (the energy). For a pressure vector pp on the unknown cells, let u(p)=u∗−(Δt/ρ)Gpu(p) = u^* - (\Delta t / \rho) G p and V(p)=V∗−(Δt/ρs)Mg−1RTBGpV(p) = V^* - (\Delta t / \rho_s) M_g^{-1} R^\mathsf{T} B G p (lines L6 and L7). Then

E(p)=12ρΔx2 u(p)TWu(p)+12V(p)TMV(p)E(p) = \tfrac12 \rho \Delta x^2\, u(p)^\mathsf{T} W u(p) + \tfrac12 V(p)^\mathsf{T} M V(p)

is a convex quadratic function of pp, and its gradient is zero exactly when Ap=rA p = r, with AA and rr of lines L3 and L4.

Proof. Write K=Mg−1RTBGK = M_g^{-1} R^\mathsf{T} B G. The derivative of the first term is −ΔtΔx2GTWu(p)-\Delta t \Delta x^2 G^\mathsf{T} W u(p). The second term is 12ρsΔx2V(p)TMgV(p)\tfrac12 \rho_s \Delta x^2 V(p)^\mathsf{T} M_g V(p), and its derivative is −ΔtΔx2KTMgV(p)=−ΔtΔx2GTBRV(p)-\Delta t \Delta x^2 K^\mathsf{T} M_g V(p) = -\Delta t \Delta x^2 G^\mathsf{T} B R V(p), because MgM_g is symmetric. So the gradient is −ΔtΔx2GT(Wu(p)+BRV(p))-\Delta t \Delta x^2 G^\mathsf{T} (W u(p) + B R V(p)). Expand u(p)u(p) and V(p)V(p):

GT(Wu(p)+BRV(p))=GT(Wu∗+BRV∗)−(ΔtρGTWG+ΔtρsGTBRMg−1RTBG)p=r−Ap.G^\mathsf{T} (W u(p) + B R V(p)) = G^\mathsf{T} (W u^* + B R V^*) - \left(\frac{\Delta t}{\rho} G^\mathsf{T} W G + \frac{\Delta t}{\rho_s} G^\mathsf{T} B R M_g^{-1} R^\mathsf{T} B G\right) p = r - A p.

EE is a sum of squares of affine functions of pp with weights wf≥0w_f \ge 0 and M⪰0M \succeq 0, so it is convex. □\square

The gradient also shows what a minimum means: GT(Wu+BRV)=0G^\mathsf{T}(W u + B R V) = 0, the mixed velocity of fluid and body has zero divergence in every unknown cell. This is the discrete form of ∇⋅u=0\nabla \cdot \mathbf u = 0 in the fluid and u⋅n^=v⋅n^\mathbf u \cdot \hat n = \mathbf v \cdot \hat n on the body. The paper (section 2) derives the same equations; its equation 6 is the case without a body, and section 3.1 adds the body.

Theorem 1 (the matrix). AA is symmetric positive semidefinite. If every connected group of unknown cells (joined by faces with wf>0w_f > 0) has a face with wf>0w_f > 0 to an AIR cell, AA is positive definite.

Proof. A=(Δt/ρ)GTWG+(Δt/ρs)(RTBG)TMg−1(RTBG)A = (\Delta t / \rho) G^\mathsf{T} W G + (\Delta t / \rho_s) (R^\mathsf{T} B G)^\mathsf{T} M_g^{-1} (R^\mathsf{T} B G), and both terms have the form XTDXX^\mathsf{T} D X with DD symmetric positive semidefinite (Mg−1M_g^{-1} is positive definite when MgM_g is invertible, which the code checks). So AA is symmetric and xTAx≥(Δt/ρ)∑fwf(Gx)f2≥0x^\mathsf{T} A x \ge (\Delta t / \rho) \sum_f w_f (G x)_f^2 \ge 0. If xTAx=0x^\mathsf{T} A x = 0, then (Gx)f=0(G x)_f = 0 on every face with wf>0w_f > 0, so xx is constant on each group, and it is 0 on a group that has a face with wf>0w_f > 0 to an AIR cell, where the other value is 0. □\square

Without AIR, constant vectors are in the null space: GG of a constant is zero on every face between two unknowns. The paper calls the system "symmetric positive semi-definite" for this reason. The right side is then compatible: summed over all cells of the grid, GTqG^\mathsf{T} q telescopes to the flux through the grid border, which is zero, and a cell inside the body has zero divergence of the rigid field (a constant uu along each row and a constant vv along each column). The code removes the mean of rr and of pp in this case. The test file checks on an 8 by 8 grid that AA is symmetric, that A1=0A \mathbf 1 = 0 and xTAx≥0x^\mathsf{T} A x \ge 0 for 20 random xx without AIR, and that Cholesky has positive pivots with a row of AIR.

Theorem 2 (the minimum). Under the condition of Theorem 1 for definiteness, line L5 gives the unique minimizer pp of EE. After lines L6 and L7, the mixed divergence is zero in every unknown cell, and E(p)≤E(0)E(p) \le E(0): the projection does not add kinetic energy.

Proof. By Lemma 1 and Theorem 1, EE is a strictly convex quadratic, its only stationary point solves Ap=rA p = r, and that point is its minimum. E(0)E(0) is the energy of u∗u^* and V∗V^*. □\square

The test file checks E(p)<E(0)E(p) < E(0) and E(p)<E(p+δ)E(p) < E(p + \delta) for 10 random δ\delta, with random u∗u^* and a body that moves and spins.

Lemma 2 (cells inside the body). Let a cell cc have bf=1b_f = 1 on its four faces. Then the column of cc in RTBGR^\mathsf{T} B G is zero, so the pressure in cc does not act on the body or on the fluid.

Proof. The left and right uu faces of cc contribute +Rf/Δx+R_f / \Delta x and −Rf/Δx-R_f / \Delta x to the column. Their rows Rf=(1,0,−(y−cy))R_f = (1, 0, -(y - c_y)) are equal, because both faces are at the height of the center of cc. The same holds for the two vv faces, which have the same xx. wf=0w_f = 0 on all four faces, so cc does not appear in GTWGG^\mathsf{T} W G either. □\square

This is the telescoping that the paper notes after its equation 10. The code does not make such cells unknowns, and uses p=0p = 0 in them.

Theorem 3 (still water stays still). Let the AIR cells be all cells above some row, let the walls be any level set, and let u∗=0u^* = 0 and v∗=−gΔtv^* = -g \Delta t on every face with wf>0w_f > 0 next to a FLUID cell. Then the solution is p=ρg(ya−y)p = \rho g (y_a - y), where yay_a is the height of the centers of the first AIR row, and every fluid face velocity is 0 after line L6. If a body of density ρs=ρ\rho_s = \rho is also present, with V∗=(0,−gΔt,0)V^* = (0, -g \Delta t, 0), and every cell with a face bf>0b_f > 0 either is an unknown or has bf=1b_f = 1 on its four faces, then also V=0V = 0.

Proof. For this pp, (Gp)f=0(G p)_f = 0 on a uu face and −ρg-\rho g on a vv face, also on a face to the first AIR row. So line L6 gives 00 on a uu face and −gΔt+(Δt/ρ)ρg=0-g \Delta t + (\Delta t / \rho) \rho g = 0 on a vv face. By Lemma 2 we may give the cells inside the body the same formula without a change. Then RTBGp=−ρg∑v facesbf(0,1,xf−cx)TR^\mathsf{T} B G p = -\rho g \sum_{v\text{ faces}} b_f (0, 1, x_f - c_x)^\mathsf{T}, which is −ρg-\rho g times the second column of MgM_g, because RfR_f has a zero second entry on uu faces. So Mg−1RTBGp=(0,−ρg,0)M_g^{-1} R^\mathsf{T} B G p = (0, -\rho g, 0), and line L7 gives V=(0,−gΔt+Δtρg/ρs,0)=0V = (0, -g \Delta t + \Delta t \rho g / \rho_s, 0) = 0. The mixed velocity is zero, so its divergence is zero, and by Lemma 1 this pp is the minimizer. □\square

The container may be round or tilted; only the face weights change, and they do not enter the argument. The paper states this result for the hydrostatic case after its equation 7, and says that a neutrally buoyant body needs the mass matrix from the same volumes. In the test file, still water in a round bowl on a 24 by 24 grid stays still to 10−1010^{-10}, and a disk of density ρ\rho stays at rest to 10−1210^{-12}.

Theorem 4 (binary weights). Let there be no body and no wall level set, so that wf=0w_f = 0 on faces that touch a SOLID cell and wf=1w_f = 1 elsewhere. If every group of FLUID cells touches an AIR cell, the result is that of macgrid.project.

Proof. Multiply row ii of Ap=rA p = r by ρΔx2/Δt\rho \Delta x^2 / \Delta t. It becomes ∑j(pi−pj)=−(ρΔx2/Δt)div⁡i\sum_{j} (p_i - p_j) = -(\rho \Delta x^2 / \Delta t) \operatorname{div}_i over the neighbors jj that are not SOLID, with pj=0p_j = 0 for AIR, and the divergence uses 0 on faces that touch a SOLID cell. This is the 5-point system of macgrid.pressure_solve after macgrid.set_solid_boundaries. Both solutions are unique, and both updates subtract (Δt/(ρΔx))(\Delta t / (\rho \Delta x)) times the pressure difference on the same faces. □\square

The test file checks this on a 12 by 12 grid with random SOLID cells to 10−1010^{-10}. (Without AIR, the helper removes the mean on each closed group and this code on all unknowns at once, so the two can differ by a constant in pp when there are several groups.)

Lemma 3 (flow along a straight wall). Let u∗u^* be a constant field U\mathbf U, let the wall level set be linear in each cell that a wall crosses, and let U\mathbf U be parallel to each wall. Then r=0r = 0 in every unknown cell, so p=0p = 0 and the flow does not change.

Proof. The fluid part PP of a cell is a polygon. Its border is the fluid part of each face, of length wfΔxw_f \Delta x (exact, because the level set is linear along the face), and the pieces of wall. The flux of a constant field out of a closed polygon is zero, and U⋅n^=0\mathbf U \cdot \hat n = 0 on a wall piece. So ∑f±wfΔx Uf=0\sum_f \pm w_f \Delta x\, U_f = 0, which is Δx2\Delta x^2 times the weighted divergence. □\square

In the test file, a channel of width 0.24 at 10 and 20 degrees across a 24 by 16 grid keeps a uniform flow of speed 1 to 10−1210^{-12}, with the flux 0.24. The voxelized solve of the same channel gives the fluxes 0.2239 and 0.2186: the stair steps block part of the flow.

Complexity

Let nn be the number of cells and mm the number of faces that the body covers. The weights cost Θ(n)\Theta(n) level set evaluations. One product with AA costs Θ(n)\Theta(n) for the fluid part and Θ(m)\Theta(m) for the body part, since JJ is a sum over the covered faces followed by a 3 by 3 solve. With kk iterations of conjugate gradients, the projection costs O((n+m)k)O((n + m) k); the paper uses a modified incomplete Cholesky preconditioner, which applies because the fluid part is still a symmetric M-matrix. The paper notes that its general sparse storage of the body term is wasteful and that its low rank could be used. The space is Θ(n)\Theta(n).

Properties

  • Same stencil. The fluid part is the 5-point (7-point in 3D) stencil with face weights, so existing solvers and preconditioners work.
  • Sub-grid detail. A gap narrower than a cell still has weights above zero, so fluid can flow through it; the paper shows a box that nearly blocks a channel, with gaps of half a cell.
  • One solve for two-way coupling. Fluid and body velocities come out of one linear system. There is no iteration between a fluid solver and a body solver.
  • Not conservative of energy. The projection removes the part of the energy that violates the constraint; it never adds energy.

Variants and improvements

  • Wall separation. The paper's section 4 replaces u⋅n^=vsolid⋅n^\mathbf u \cdot \hat n = \mathbf v_{solid} \cdot \hat n with u⋅n^≥vsolid⋅n^\mathbf u \cdot \hat n \ge \mathbf v_{solid} \cdot \hat n and p≥0p \ge 0 on the walls (its equation 15). The minimization becomes a quadratic program, and fluid can leave a ceiling or a wall instead of sticking. The paper solves the equivalent linear complementarity problem with the PATH solver, on small problems.
  • Free surface. The paper uses the ghost fluid boundary condition of Gibou et al. (2002) for p=0p = 0 at a free surface. The code here sets p=0p = 0 at the centers of AIR cells.
  • Deformable solids. Any solid whose kinetic energy is a quadratic form in its velocities fits the framework; the paper does rigid bodies and expects deformable ones to follow.
  • Thin solids. A shell has no interior that the grid samples, so the method as written does not apply to it. The paper suggests ghost pressures on the two sides as future work.

When to use it

Use it when solids do not follow the grid: curved containers, rotated boxes, moving paddles and floating bodies on a coarse grid. Use it for two-way rigid body coupling where the bodies can be much lighter or heavier than the fluid. If every wall follows the grid, the voxelized solve gives the same result (Theorem 4 of the proof).

Pitfalls

  • A closed container. Without AIR, the matrix is singular. The right side is compatible only if the solids do not change the volume of the fluid; a scripted piston that pushes into a closed box makes the system inconsistent, and the paper then removes the null space part of the right side.
  • Inconsistent masses. The body's mass matrix must come from the same volumes as JJ. Otherwise a body with the density of the fluid drifts; the paper notes that this matters most for hydrostatic rest.
  • Faces with zero weight. A face with wf=0w_f = 0 has no fluid velocity. For advection, extrapolate the tangential velocity into the solid, as the paper does.
  • Tiny weights. A cell whose faces all have weights near zero has a small diagonal entry, which makes the matrix worse conditioned and slows the solver.
  • Thin bodies. A body thinner than a cell has no interior cells, and pressure leaks across it.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

macgrid.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A 2D MAC grid with sampling, divergence, pressure projection and advection.

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

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

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

import math
from collections import deque

FLUID, SOLID, AIR = 0, 1, 2


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

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


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


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


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


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


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


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

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


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


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


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


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


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


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


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


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


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

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


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

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


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


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


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

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


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

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


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


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

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


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

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


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


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

"""Variational pressure projection with face weights, and two-way coupling with a rigid body.

This is the method of Batty, Bertails and Bridson (2007) on the 2D MAC grid of
macgrid.py. The pressure p minimizes the kinetic energy

    KE(p) = 1/2 rho dx^2 sum_f w_f u_f^2 + 1/2 V^T M V,
    u = u* - (dt / rho) G p,   V = V* + dt M^-1 J p,

where w_f in [0, 1] is the part of face f that is open to the fluid, G p is
the pressure difference across a face divided by dx, and V = (vx, vy, omega)
is the velocity of one rigid body. The body covers the part b_f of face f. Its
mass matrix M = rho_s dx^2 R^T B R comes from the same face weights, where R
maps V to the normal rigid velocity at each face. The minimum solves

    A p = G^T (W u* + B R V*),
    A = (dt / rho) G^T W G + (dt / rho_s) G^T B R (R^T B R)^-1 R^T B G.

G^T q is minus the divergence of the face field q, so the right side is minus
the divergence of the mixed velocity W u* + B R V*. A is symmetric positive
semidefinite; it is definite when every group of unknown cells touches an AIR
cell. With w_f in {0, 1} and no body, A and the right side are those of
macgrid.pressure_solve.

Walls are the grid border, the SOLID cells of the grid, and an optional
static level set wall_phi(x, y) < 0. A body is given by its own level set.
Only the weights on faces enter: the method uses the face area fractions,
which the paper names as one of its approximations of the mass in the
control volume of a face.
"""

import math

import macgrid
from macgrid import AIR, FLUID


def inside_fraction(a, b):
    """The part of a segment where a linear function with end values a and b is negative."""
    if a < 0.0 and b < 0.0:
        return 1.0
    if a >= 0.0 and b >= 0.0:
        return 0.0
    neg, pos = (a, b) if a < 0.0 else (b, a)
    return -neg / (pos - neg)


def node_values(g, phi):
    """phi(x, y) at the (nx + 1) by (ny + 1) grid nodes (i dx, j dx)."""
    return [[phi(i * g.dx, j * g.dx) for j in range(g.ny + 1)] for i in range(g.nx + 1)]


def face_fractions(g, phi):
    """The part of each u face and each v face where phi < 0, from phi at the two ends of the face."""
    nd = node_values(g, phi)
    fu = [[inside_fraction(nd[i][j], nd[i][j + 1]) for j in range(g.ny)] for i in range(g.nx + 1)]
    fv = [[inside_fraction(nd[i][j], nd[i + 1][j]) for j in range(g.ny + 1)] for i in range(g.nx)]
    return fu, fv


class Body:
    """A rigid body: a level set shape(x, y) < 0 in its own frame, its center, angle, velocity and density.

    V = [vx, vy, omega]. A scripted body has an infinite mass: the fluid does
    not change its velocity.
    """

    def __init__(self, shape, center, rho_s, V=(0.0, 0.0, 0.0), angle=0.0, scripted=False):
        if not scripted and rho_s <= 0.0:
            raise ValueError("need rho_s > 0")
        self.shape = shape
        self.center = [float(center[0]), float(center[1])]
        self.angle = float(angle)
        self.V = [float(t) for t in V]
        self.rho_s = float(rho_s)
        self.scripted = scripted

    def phi(self, x, y):
        """The level set of the body in world coordinates."""
        dx, dy = x - self.center[0], y - self.center[1]
        c, s = math.cos(self.angle), math.sin(self.angle)
        return self.shape(c * dx + s * dy, -s * dx + c * dy)

    def move(self, dt):
        """Move the body with its velocity for time dt (forward Euler)."""
        self.center[0] += dt * self.V[0]
        self.center[1] += dt * self.V[1]
        self.angle += dt * self.V[2]


class Weights:
    """The face weights: s (static wall), b (body) and w = 1 - s - b (fluid) for every u and v face."""

    def __init__(self, g, wall_phi=None, body=None):
        nx, ny = g.nx, g.ny
        su = macgrid.zeros(nx + 1, ny)
        sv = macgrid.zeros(nx, ny + 1)
        if wall_phi is not None:
            su, sv = face_fractions(g, wall_phi)
        if body is not None:
            bu, bv = face_fractions(g, body.phi)
        else:
            bu, bv = macgrid.zeros(nx + 1, ny), macgrid.zeros(nx, ny + 1)
        for i in range(nx + 1):
            for j in range(ny):
                if macgrid.is_solid_u_face(g, i, j):
                    su[i][j], bu[i][j] = 1.0, 0.0
        for i in range(nx):
            for j in range(ny + 1):
                if macgrid.is_solid_v_face(g, i, j):
                    sv[i][j], bv[i][j] = 1.0, 0.0
        self.su, self.sv, self.bu, self.bv = su, sv, bu, bv
        self.wu = [[max(0.0, 1.0 - su[i][j] - bu[i][j]) for j in range(ny)] for i in range(nx + 1)]  # @line L1
        self.wv = [[max(0.0, 1.0 - sv[i][j] - bv[i][j]) for j in range(ny + 1)] for i in range(nx)]


def binary_weights(g):
    """Weights from the cell labels only: w = 0 on a face that touches a SOLID cell, else 1."""
    return Weights(g)


def _unknowns(g, W):
    """The cells that are not SOLID or AIR and have a face with w > 0, and their index map."""
    cells, idx = [], {}
    for i in range(g.nx):
        for j in range(g.ny):
            if g.label[i][j] != FLUID:
                continue
            if W.wu[i][j] > 0.0 or W.wu[i + 1][j] > 0.0 or W.wv[i][j] > 0.0 or W.wv[i][j + 1] > 0.0:  # @line L2
                idx[(i, j)] = len(cells)
                cells.append((i, j))
    return cells, idx


def _faces(g):
    """Every face as (axis, i, j, left cell, right cell, x, y)."""
    dx = g.dx
    out = []
    for i in range(g.nx + 1):
        for j in range(g.ny):
            out.append((0, i, j, (i - 1, j), (i, j), i * dx, (j + 0.5) * dx))
    for i in range(g.nx):
        for j in range(g.ny + 1):
            out.append((1, i, j, (i, j - 1), (i, j), (i + 0.5) * dx, j * dx))
    return out


def _rigid_row(body, axis, x, y):
    """R_f: the normal rigid velocity at a face is R_f . V."""
    if axis == 0:
        return (1.0, 0.0, -(y - body.center[1]))
    return (0.0, 1.0, x - body.center[0])


def _solve3(M, r):
    """Solve the 3 by 3 system M z = r by Gaussian elimination with partial pivoting."""
    a = [list(M[k]) + [r[k]] for k in range(3)]
    for c in range(3):
        piv = max(range(c, 3), key=lambda k: abs(a[k][c]))
        a[c], a[piv] = a[piv], a[c]
        if a[c][c] == 0.0:
            raise ValueError("the body covers too few faces")
        for k in range(c + 1, 3):
            f = a[k][c] / a[c][c]
            for m in range(c, 4):
                a[k][m] -= f * a[c][m]
    z = [0.0, 0.0, 0.0]
    for c in (2, 1, 0):
        z[c] = (a[c][3] - sum(a[c][m] * z[m] for m in range(c + 1, 3))) / a[c][c]
    return z


class System:
    """The pressure system of one projection: unknown cells, faces with weights, and the body terms."""

    def __init__(self, g, W, dt, rho, body=None):
        if dt <= 0.0 or rho <= 0.0:
            raise ValueError("need dt > 0 and rho > 0")
        self.g, self.W, self.dt, self.rho, self.body = g, W, dt, rho, body
        self.cells, self.idx = _unknowns(g, W)
        self.faces = []
        for (axis, i, j, L, Rc, x, y) in _faces(g):
            w = (W.wu if axis == 0 else W.wv)[i][j]
            bb = (W.bu if axis == 0 else W.bv)[i][j] if body is not None else 0.0
            if w == 0.0 and bb == 0.0:
                continue
            kl, kr = self.idx.get(L, -1), self.idx.get(Rc, -1)
            if kl < 0 and kr < 0 and bb == 0.0:
                continue
            rrow = _rigid_row(body, axis, x, y) if bb > 0.0 else None
            self.faces.append((axis, i, j, kl, kr, w, bb, rrow))
        self.coupled = body is not None and not body.scripted
        if body is not None:
            M = [[0.0] * 3 for _ in range(3)]
            for f in self.faces:
                bb, rrow = f[6], f[7]
                if bb > 0.0:
                    for a in range(3):
                        for c in range(3):
                            M[a][c] += bb * rrow[a] * rrow[c]
            self.Mgeo = M  # the mass matrix is rho_s dx^2 Mgeo (per unit depth)

    def grad(self, p, f):
        """(G p)_f: the pressure difference across face f over dx; p is 0 outside the unknowns."""
        kl, kr = f[3], f[4]
        return ((p[kr] if kr >= 0 else 0.0) - (p[kl] if kl >= 0 else 0.0)) / self.g.dx

    def _gt(self, out, f, q):
        """out += G^T q_f for one face."""
        kl, kr = f[3], f[4]
        if kr >= 0:
            out[kr] += q / self.g.dx
        if kl >= 0:
            out[kl] -= q / self.g.dx

    def body_force(self, p):
        """R^T B G p: the pressure force and torque on the body, divided by -dx^2."""
        y = [0.0, 0.0, 0.0]
        for f in self.faces:
            if f[6] > 0.0:
                gp = self.grad(p, f)
                for a in range(3):
                    y[a] += f[6] * gp * f[7][a]
        return y

    def apply(self, p):
        """A p."""
        out = [0.0] * len(self.cells)
        c = self.dt / self.rho
        for f in self.faces:
            if f[5] > 0.0:
                self._gt(out, f, c * f[5] * self.grad(p, f))
        if self.coupled:
            z = _solve3(self.Mgeo, self.body_force(p))
            cs = self.dt / self.body.rho_s
            for f in self.faces:
                if f[6] > 0.0:
                    self._gt(out, f, cs * f[6] * sum(f[7][a] * z[a] for a in range(3)))  # @line L4
        return out

    def rhs(self, u, v):
        """G^T (W u* + B R V*): minus the divergence of the mixed velocity of fluid and body."""
        out = [0.0] * len(self.cells)
        for f in self.faces:
            axis, i, j = f[0], f[1], f[2]
            q = f[5] * (u if axis == 0 else v)[i][j]
            if f[6] > 0.0:
                q += f[6] * sum(f[7][a] * self.body.V[a] for a in range(3))  # @line L3
            self._gt(out, f, q)
        return out

    def has_air(self):
        """True if some face with w > 0 joins an unknown cell to an AIR cell."""
        g = self.g
        for (axis, i, j, kl, kr, w, bb, rrow) in self.faces:
            if w > 0.0 and (kl < 0) != (kr < 0):
                a, c = ((i - 1, j), (i, j)) if axis == 0 else ((i, j - 1), (i, j))
                other = a if kl < 0 else c
                if macgrid.cell_label(g, other[0], other[1]) == AIR:
                    return True
        return False


def conjugate_gradients(apply, b, tol=1e-12, max_iter=None):
    """Solve A x = b for a symmetric positive (semi)definite A given by apply(x). Returns (x, iterations)."""
    n = len(b)
    x = [0.0] * n
    bmax = max((abs(t) for t in b), default=0.0)
    if bmax == 0.0:
        return x, 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)
    it = 0
    while it < max_iter and max(abs(t) for t in r) > tol * bmax:
        q = apply(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
    return x, it


def project(g, dt, rho, W, body=None, tol=1e-12):
    """Minimize the kinetic energy of fluid and body over the pressure, and update u, v, p and body.V.

    g.u and g.v hold u* (after advection and forces); body.V holds V*. On a face
    with w = 0, the velocity is set to the normal velocity of the solid there
    (0 for a wall). Returns the System and the number of CG iterations.
    """
    S = System(g, W, dt, rho, body)
    b = S.rhs(g.u, g.v)
    closed = not S.has_air()
    if closed and b:
        mean = sum(b) / len(b)
        b = [t - mean for t in b]
    p, it = conjugate_gradients(S.apply, b, tol)  # @line L5
    if closed and p:
        mean = sum(p) / len(p)
        p = [t - mean for t in p]
    if S.coupled:
        z = _solve3(S.Mgeo, S.body_force(p))
        cs = dt / body.rho_s
        body.V = [body.V[a] - cs * z[a] for a in range(3)]  # @line L7
    s = dt / rho
    for f in S.faces:
        axis, i, j, w, bb = f[0], f[1], f[2], f[5], f[6]
        arr = g.u if axis == 0 else g.v
        if w > 0.0:
            arr[i][j] -= s * S.grad(p, f)  # @line L6
        elif bb > 0.0:
            arr[i][j] = sum(f[7][a] * body.V[a] for a in range(3))
    for i in range(g.nx + 1):
        for j in range(g.ny):
            if W.wu[i][j] == 0.0 and W.bu[i][j] == 0.0:
                g.u[i][j] = 0.0
    for i in range(g.nx):
        for j in range(g.ny + 1):
            if W.wv[i][j] == 0.0 and W.bv[i][j] == 0.0:
                g.v[i][j] = 0.0
    g.p = macgrid.zeros(g.nx, g.ny)
    for k, (i, j) in enumerate(S.cells):
        g.p[i][j] = p[k]
    S.p = p
    return S, it


def kinetic_energy(S, u, v, V=None):
    """(1/2) rho dx^2 sum w u^2 over the faces of S, plus (1/2) V^T M V for a coupled body."""
    dx2 = S.g.dx * S.g.dx
    ke = 0.0
    for f in S.faces:
        q = (u if f[0] == 0 else v)[f[1]][f[2]]
        ke += f[5] * q * q
    ke *= 0.5 * S.rho * dx2
    if S.coupled and V is not None:
        M = S.Mgeo
        ke += 0.5 * S.body.rho_s * dx2 * sum(V[a] * M[a][c] * V[c] for a in range(3) for c in range(3))
    return ke


def energy_of_pressure(S, u0, v0, V0, p):
    """KE(p): the kinetic energy after the pressure update with p, from u*, v* and V*."""
    u = macgrid.copy_field(u0)
    v = macgrid.copy_field(v0)
    s = S.dt / S.rho
    for f in S.faces:
        if f[5] > 0.0:
            (u if f[0] == 0 else v)[f[1]][f[2]] -= s * S.grad(p, f)
    V = None
    if S.coupled:
        z = _solve3(S.Mgeo, S.body_force(p))
        V = [V0[a] - S.dt / S.body.rho_s * z[a] for a in range(3)]
    return kinetic_energy(S, u, v, V)


def mixed_divergence(S, u, v):
    """The largest |div(W u + B R V)| over the unknown cells, with the current body velocity."""
    r = S.rhs(u, v)
    return max((abs(t) for t in r), default=0.0)


def matrix(S):
    """The dense matrix A, column by column (for tests on small grids)."""
    n = len(S.cells)
    cols = []
    for k in range(n):
        e = [0.0] * n
        e[k] = 1.0
        cols.append(S.apply(e))
    return [[cols[c][r] for c in range(n)] for r in range(n)]


def gravity(g, W, dt, grav, body=None):
    """Add -grav dt to v on faces with w > 0 next to a FLUID cell, and to the body if it is not scripted."""
    for i in range(g.nx):
        for j in range(g.ny + 1):
            if W.wv[i][j] > 0.0 and FLUID in (macgrid.cell_label(g, i, j - 1), macgrid.cell_label(g, i, j)):
                g.v[i][j] -= dt * grav
    if body is not None and not body.scripted:
        body.V[1] -= dt * grav
test_variational_solid_fluid_coupling.py 221 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variational-solid-fluid-coupling/. The authors are listed in prov/T5ZPKE.jsonl.

"""Tests of the variational pressure projection and the rigid body coupling."""

import math
import random

import pytest

import macgrid
from macgrid import AIR, SOLID
import variational_solid_fluid_coupling as VC

RHO, G, DT = 1000.0, 9.81, 0.01


def bowl_grid(n, level=0.75):
    """An n by n grid of the unit square; cells above the level are AIR."""
    g = macgrid.make_grid(n, n, 1.0 / n)
    for i in range(n):
        for j in range(n):
            if (j + 0.5) / n > level:
                g.label[i][j] = AIR
    return g


def bowl(x, y):
    """A round container: fluid inside the circle of radius 0.46 about (0.5, 0.5)."""
    return 0.46 - math.hypot(x - 0.5, y - 0.5)


def disk(r):
    return lambda x, y: math.hypot(x, y) - r


def test_inside_fraction():
    assert VC.inside_fraction(-1.0, -2.0) == 1.0
    assert VC.inside_fraction(1.0, 0.0) == 0.0
    assert VC.inside_fraction(-1.0, 3.0) == 0.25
    assert VC.inside_fraction(3.0, -1.0) == 0.25


def test_binary_weights_match_the_voxelized_solve():
    rng = random.Random(1)
    n = 12
    g = macgrid.make_grid(n, n, 1.0 / n)
    for i in range(n):
        for j in range(n):
            if j >= 9:
                g.label[i][j] = AIR
            elif rng.random() < 0.15:
                g.label[i][j] = SOLID
    g.u = [[rng.uniform(-1, 1) for j in range(n)] for i in range(n + 1)]
    g.v = [[rng.uniform(-1, 1) for j in range(n + 1)] for i in range(n)]
    h = macgrid.make_grid(n, n, 1.0 / n)
    h.label = [list(c) for c in g.label]
    h.u, h.v = macgrid.copy_field(g.u), macgrid.copy_field(g.v)
    macgrid.project(h, DT, RHO)
    VC.project(g, DT, RHO, VC.binary_weights(g))
    for a, b in ((g.u, h.u), (g.v, h.v)):
        assert max(abs(x - y) for c1, c2 in zip(a, b) for x, y in zip(c1, c2)) < 1e-10
    assert max(abs(x - y) for c1, c2 in zip(g.p, h.p) for x, y in zip(c1, c2)) < 1e-7


def channel(deg):
    """A straight channel of width 0.24 at deg degrees across a 24 by 16 grid, open at both ends."""
    nx, ny = 24, 16
    dx = 1.0 / nx
    th = math.radians(deg)
    t = (math.cos(th), math.sin(th))
    c = (0.5, 0.5 * ny * dx)

    def wall(x, y):
        return 0.12 - abs(-t[1] * (x - c[0]) + t[0] * (y - c[1]))

    def grid():
        g = macgrid.make_grid(nx, ny, dx)
        for j in range(ny):
            g.label[0][j] = AIR
            g.label[nx - 1][j] = AIR
        g.u = [[t[0]] * ny for _ in range(nx + 1)]
        g.v = [[t[1]] * (ny + 1) for _ in range(nx)]
        return g

    return wall, grid


@pytest.mark.parametrize("deg, vox_flux", [(10, 0.22388), (20, 0.21864)])
def test_uniform_flow_along_a_tilted_channel_is_kept(deg, vox_flux):
    wall, grid = channel(deg)
    g = grid()
    W = VC.Weights(g, wall)
    u0, v0 = macgrid.copy_field(g.u), macgrid.copy_field(g.v)
    VC.project(g, DT, RHO, W)
    assert max(abs(g.u[i][j] - u0[i][j]) for i in range(25) for j in range(16) if W.wu[i][j] > 0) < 1e-12
    assert max(abs(g.v[i][j] - v0[i][j]) for i in range(24) for j in range(17) if W.wv[i][j] > 0) < 1e-12
    flux = sum(W.wu[12][j] * g.u[12][j] for j in range(16)) / 24
    assert abs(flux - 0.24) < 1e-12  # speed 1 times the width 0.24
    h = grid()  # the voxelized solve: a cell is SOLID if its center is in the wall
    for i in range(1, 23):
        for j in range(16):
            if wall((i + 0.5) / 24, (j + 0.5) / 24) < 0.0:
                h.label[i][j] = SOLID
    macgrid.project(h, DT, RHO)
    vflux = sum(h.u[12][j] for j in range(16) if not macgrid.is_solid_u_face(h, 12, j)) / 24
    assert abs(vflux - vox_flux) < 1e-4


def test_hydrostatic_rest_in_a_round_bowl():
    n = 24
    g = bowl_grid(n)
    W = VC.Weights(g, bowl)
    VC.gravity(g, W, DT, G)
    S, _ = VC.project(g, DT, RHO, W)
    assert max(abs(t) for c in g.u + g.v for t in c) < 1e-10
    top = max(j for j in range(n) if g.label[0][j] != AIR)
    assert max(abs(g.p[i][j] - RHO * G * (top + 1 - j) / n) for (i, j) in S.cells) < 1e-8


def test_neutrally_buoyant_body_stays_at_rest():
    g = bowl_grid(24)
    body = VC.Body(disk(0.1), (0.5, 0.45), RHO, angle=0.3)
    W = VC.Weights(g, bowl, body)
    VC.gravity(g, W, DT, G, body)
    VC.project(g, DT, RHO, W, body)
    assert max(abs(t) for t in body.V) < 1e-12
    assert max(abs(t) for c in g.u + g.v for t in c) < 1e-10


@pytest.mark.parametrize("ratio, a_over_g", [(2.0, -0.33159), (0.5, 0.32986), (0.1, 0.80659)])
def test_heavy_and_light_bodies_feel_the_added_mass(ratio, a_over_g):
    g = bowl_grid(24)
    body = VC.Body(disk(0.1), (0.5, 0.45), ratio * RHO)
    W = VC.Weights(g, bowl, body)
    VC.gravity(g, W, DT, G, body)
    S, _ = VC.project(g, DT, RHO, W, body)
    a = body.V[1] / DT / G
    assert abs(a - a_over_g) < 1e-4
    # a cylinder in unbounded still fluid: a = g (rho_s - rho) / (rho_s + rho)
    assert abs(a + (ratio - 1.0) / (ratio + 1.0)) < 0.02
    assert abs(body.V[0]) < 1e-12 and abs(body.V[2]) < 1e-12
    assert VC.mixed_divergence(S, g.u, g.v) < 1e-9


def small_system(with_air):
    n = 8
    g = macgrid.make_grid(n, n, 1.0 / n)
    if with_air:
        for i in range(n):
            g.label[i][n - 1] = AIR
    body = VC.Body(disk(0.2), (0.45, 0.5), 700.0, angle=0.0)
    W = VC.Weights(g, bowl, body)
    return VC.System(g, W, DT, RHO, body)


def cholesky_pivots(A):
    n = len(A)
    L = [[0.0] * n for _ in range(n)]
    piv = []
    for k in range(n):
        d = A[k][k] - sum(L[k][m] ** 2 for m in range(k))
        piv.append(d)
        if d <= 0.0:
            return piv
        L[k][k] = math.sqrt(d)
        for r in range(k + 1, n):
            L[r][k] = (A[r][k] - sum(L[r][m] * L[k][m] for m in range(k))) / L[k][k]
    return piv


def test_matrix_is_semidefinite_and_definite_with_air():
    S = small_system(False)
    A = VC.matrix(S)
    n = len(A)
    scale = max(abs(A[r][c]) for r in range(n) for c in range(n))
    assert max(abs(A[r][c] - A[c][r]) for r in range(n) for c in range(n)) < 1e-12 * scale
    assert max(abs(sum(row)) for row in A) < 1e-12 * scale  # constants are in the null space
    rng = random.Random(5)
    for _ in range(20):
        x = [rng.uniform(-1, 1) for _ in range(n)]
        assert sum(x[r] * A[r][c] * x[c] for r in range(n) for c in range(n)) >= -1e-12 * scale
    S = small_system(True)
    assert min(cholesky_pivots(VC.matrix(S))) > 0.0


def test_pressure_minimizes_the_kinetic_energy():
    rng = random.Random(7)
    n = 12
    g = bowl_grid(n)
    body = VC.Body(disk(0.15), (0.45, 0.4), 500.0, V=(0.3, -0.2, 1.0))
    W = VC.Weights(g, bowl, body)
    g.u = [[rng.uniform(-1, 1) for j in range(n)] for i in range(n + 1)]
    g.v = [[rng.uniform(-1, 1) for j in range(n + 1)] for i in range(n)]
    u0, v0, V0 = macgrid.copy_field(g.u), macgrid.copy_field(g.v), list(body.V)
    S, _ = VC.project(g, DT, RHO, W, body)
    best = VC.energy_of_pressure(S, u0, v0, V0, S.p)
    assert abs(best - VC.kinetic_energy(S, g.u, g.v, body.V)) < 1e-9 * best
    assert best < VC.energy_of_pressure(S, u0, v0, V0, [0.0] * len(S.p))  # the projection never adds energy
    for _ in range(10):
        q = [p + rng.uniform(-50, 50) for p in S.p]
        assert VC.energy_of_pressure(S, u0, v0, V0, q) > best
    assert VC.mixed_divergence(S, g.u, g.v) < 1e-9


def test_scripted_body_pushes_the_fluid():
    g = bowl_grid(16)
    body = VC.Body(disk(0.12), (0.45, 0.4), 0.0, V=(0.5, 0.2, 2.0), scripted=True)
    W = VC.Weights(g, bowl, body)
    S, _ = VC.project(g, DT, RHO, W, body)
    assert body.V == [0.5, 0.2, 2.0]
    assert VC.mixed_divergence(S, g.u, g.v) < 1e-9
    assert max(abs(t) for c in g.u for t in c) > 0.1  # the fluid moves out of the way


def test_bad_input():
    with pytest.raises(ValueError):
        VC.Body(disk(0.1), (0.5, 0.5), 0.0)
    g = macgrid.make_grid(2, 2, 0.5)
    with pytest.raises(ValueError):
        VC.System(g, VC.binary_weights(g), 0.0, RHO)

History

Foster and Metaxas (1996) brought the MAC grid to graphics with voxelized solids. Foster and Fedkiw (2001) let the fluid slip along walls by setting the velocity after the solve, and Houston et al. (2003) and Rasmussen et al. (2004) extended this. These methods still used the voxelized solve with its stair-step artifacts, and the paper notes that they fail for still water in a container with oblique walls. For coupling, Takahashi et al. (2002) and Guendelman et al. (2005) alternated between fluid and body solves; Carlson et al. (2004) treated bodies as fluid and then made them rigid; Klingner et al. (2006) and Chentanez et al. (2006) coupled fluids with solids on tetrahedral meshes. In 2007, Batty, Bertails and Bridson wrote the pressure solve as a kinetic energy minimization on a regular grid. They reported a paddle in smoke on an 80×40×6080 \times 40 \times 60 grid at 3 seconds per frame, about 20 times faster than the tetrahedral mesh method of Klingner et al. on a comparable example.

References

  1. Christopher Batty, Florence Bertails and Robert Bridson, A fast variational framework for accurate solid-fluid coupling, ACM Transactions on Graphics 26(3), article 100, 2007 (SIGGRAPH 2007), section 2 (equations 1 to 3, the energy), section 2.1 (equations 4 to 7, the weights and the pressure system), section 3 (equations 8 to 13, rigid bodies; time integration and results), section 4 (equations 14 and 15, wall separation)
  2. Carlson, Mucha and Turk, Rigid fluid, the earlier coupling that treats the body as fluid and then makes it rigid

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.matvec
  • a full proof of time.project
  • a full proof of time.weights
  • 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
  • at least three sources
  • a scene preset for the example