Techniquecore
Vorticity confinement
Also called vorticity confinement force.
Add a force at right angles to the gradient of the vorticity magnitude, which spins up the small swirls that numerical dissipation removes from smoke on a coarse grid.
Vorticity confinement is a force that a grid fluid solver adds to its velocity to keep small swirls alive. Stable solvers for animation, such as stable fluids, use semi-Lagrangian advection, which averages the velocity at each step. On a coarse grid this averaging damps the rotation of the flow much faster than the real viscosity of air would. The force finds the places where the vorticity is concentrated and pushes the fluid around them, so the swirls become stronger and stay small. Steinhoff and Underhill (1994) built the method for vortices around helicopter rotors. Fedkiw, Stam and Jensen (2001) brought it to smoke in graphics, with a factor so that the force goes to zero as the grid is refined. The force adds energy. It is a tuning tool, and its strength is chosen by eye.
In plain words
A swirl in smoke is like a small paddle wheel that turns the air around it. The usual stable solver smears the velocity a little at each step, so the paddle wheels slow down and the smoke looks thick and dull.
Vorticity confinement looks at how fast the air turns at each cell. It finds the direction toward the cells that turn faster, which is the direction to the center of a swirl. Then it pushes the air at right angles to that direction, in the sense that the swirl already turns. The push makes the swirl turn faster and keeps it tight. The push is weak where the air turns slowly and zero where every cell turns at the same rate. You set one number for its strength. If it is too large, the smoke gains energy and the flow can become noisy.
When it applies
- The solver dissipates rotation more than the physics would, mostly by the interpolation in semi-Lagrangian advection on a coarse grid.
- The goal is the look of the flow, not a measured flow. The force changes the equations by a term that goes to zero only as .
- The flow is a gas, such as smoke or the hot products of fire, with swirls of a few cells across. Most uses add the force to an incompressible solver before the pressure projection, which then removes any part of the force that is a gradient.
- The velocity is known on a grid, or can be estimated at particles, so that the curl and the gradient of its magnitude can be computed.
The template
Fedkiw, Stam and Jensen give the force by three equations (their equations 9 to 11):
The paper writes for the grid spacing . In 2D, is a scalar, the part of the curl, and . Each step of the solver does the following.
- Compute the vorticity at each cell center. On a MAC grid, average the face velocities to the centers, and take central differences.
- Compute at each cell center by central differences of .
- Normalize: , with a small .
- Compute the force at each cell center.
- Add to the velocity, at each face the mean of the two cells beside it. Then advect and project as usual.
VORTICITY-CONFINEMENT(u, ε, Δx, Δt)- 1
for each cell c: ω_c ← curl of u at c, by central differences - 2
for each cell c: η_c ← gradient of |ω| at c - 3
N_c ← η_c / (|η_c| + δ) - 4
f_c ← ε Δx (N_c × ω_c) - 5
for each face: u ← u + Δt (mean of f over the two cells of the face)
Why the direction is right. Near the center of a swirl, has a peak, so points toward the center. The cross product is at right angles to , and it turns in the sense of . So the force is tangent to circles around the center, in the direction of the flow there. It is not along the gradient of , but at right angles to it.
Why the size is right. Where , and . The force is large where the rotation is large, and it is zero where . The factor makes the force go to zero as the grid is refined, which is the paper's reason to call the method consistent with the Euler equations.
Units. has the units of a velocity. For to be a force per unit mass, must have the units . The paper says only that controls the amount of detail.
Order in the step. The paper multiplies each force by the time step and adds it to the velocity, then advects, then solves for the pressure. The pressure projection removes the part of that is a gradient. Around a swirl, goes along the flow, so it has a positive circulation around the center, and a gradient field has none. That part stays.
Cost. Each of lines L1 to L5 visits every cell or face once with a constant number of neighbors, so the force costs time and extra space on a grid of cells. This is small next to the pressure solve.
Classic examples
A hand computation. Let m, , and at one cell let (counterclockwise) with : the center of the swirl is to the left. Then and . A counterclockwise swirl moves upward on its right side, so the force goes with the flow. With s, the vertical velocity at that cell grows by m/s.
Solid body rotation. For , at every cell, and central differences give it to rounding error. So and the force is zero. A flow that turns as one rigid body has no concentrated swirl, so the method leaves it alone. The tests check and on a grid.
A Gaussian vortex on a coarse grid. The test file puts a vortex with a Gaussian profile, , on a grid of the unit square with walls, and runs 10 steps of with semi-Lagrangian advection and projection. The kinetic energy at the end, as a fraction of the start, was
| () | 0 | 1 | 3 |
|---|---|---|---|
| energy kept | 0.650 | 0.792 | 1.150 |
Without the force, the solver loses a third of the energy in 10 steps. With it loses a fifth. With the flow ends with more energy than it started with. These are measurements of this code, not general bounds.
Smoke. Fedkiw, Stam and Jensen (2001) add the force to a solver in the style of stable fluids on a MAC grid, together with buoyancy, and show the rolling motion that it keeps on grids that are coarse even for graphics.
Fire. The fire method of Nguyen, Fedkiw and Jensen (2002) adds the same force, with separate values of for the fuel and for the hot products.
Variations
- Steinhoff's original form. Steinhoff and Underhill (1994) added a confinement term to the Euler equations for vortices around rotors. The 2001 paper describes it as similar to its equation 11 but without the factor .
- 3D. The equations are the same, with a vector. Then needs all three components of at each cell.
- On particles. Particle methods estimate and from sums over neighbors and apply the force to each particle. Position based fluids (Macklin and Müller 2013) do this to give back energy that the position solver removes.
- Vortex particles. Selle, Rasmussen and Fedkiw (2005) carry vorticity on particles, where advection does not damp it, and give it back to the grid by a force of the same kind. This keeps swirls that the grid alone has already lost. See the vortex particle method.
- Less dissipative advection. BFECC and the unconditionally stable MacCormack method attack the cause by making advection more accurate. They can be used with or without confinement.
Pitfalls
- Dividing by a zero gradient. Where is flat, is rounding noise, and is a unit vector in a random direction. For solid body rotation with , the test file measures a force of exactly at some cell, where the true force is zero. Add a small , here .
- Too large a strength. The force adds energy and nothing in it limits the growth. The paper says that the method is stable as long as the force stays below a certain threshold. The table above shows a run that gains 15% of its energy with . Tune on the grid and time step of the final shot.
- It amplifies every peak. The force spins up any local peak of , of either sign. Around a Gaussian vortex there is a ring of opposite vorticity, and the test file finds that the force there points against the main flow. Noise in the velocity is also a set of small peaks.
- It cannot make new detail. The force strengthens rotation that the grid still holds. A swirl that the advection has already smoothed away does not come back. This is the motivation of the vortex particle variation above.
- No claim of accuracy. The term changes the equations. The result is a flow with more swirls, and the method does not claim that it is closer to the true flow.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A 2D MAC grid with sampling, divergence, pressure projection and advection.
This file is copied byte for byte into each impl/python folder that needs it.
Do not edit a copy. The reference is in
graphics-and-signals/fluid-animation/mac-grid/impl/python/.
Layout (the MAC layout of Harlow and Welch 1965, as in Bridson 2015):
- The grid has nx by ny cells of size dx. i is the x index, j is the y index.
- p[i][j] is at ((i + 1/2) dx, (j + 1/2) dx), for i < nx and j < ny.
- u[i][j] is at (i dx, (j + 1/2) dx), for i = 0..nx and j < ny.
- v[i][j] is at ((i + 1/2) dx, j dx), for i < nx and j = 0..ny.
- label[i][j] is FLUID, SOLID or AIR. A cell outside the grid counts as
SOLID, so the border of the grid is a fixed wall.
Units are SI. In 2D a density rho is in kg/m^2 if you read the grid as a
sheet, or in kg/m^3 per unit depth; the code does not care.
"""
import math
from collections import deque
FLUID, SOLID, AIR = 0, 1, 2
class Grid:
"""The arrays of a MAC grid. All arrays are lists of lists indexed [i][j]."""
def __init__(self, nx, ny, dx):
if nx < 1 or ny < 1 or dx <= 0:
raise ValueError("need nx >= 1, ny >= 1 and dx > 0")
self.nx = nx
self.ny = ny
self.dx = float(dx)
self.p = zeros(nx, ny)
self.u = zeros(nx + 1, ny)
self.v = zeros(nx, ny + 1)
self.label = [[FLUID] * ny for _ in range(nx)]
def make_grid(nx, ny, dx):
"""A grid of nx by ny FLUID cells of size dx, with p, u and v set to zero."""
return Grid(nx, ny, dx)
def zeros(a, b):
"""An a by b list of lists of 0.0."""
return [[0.0] * b for _ in range(a)]
def copy_field(q):
"""A deep copy of a 2D field."""
return [list(col) for col in q]
def cell_label(g, i, j):
"""The label of cell (i, j). A cell outside the grid is SOLID."""
if 0 <= i < g.nx and 0 <= j < g.ny:
return g.label[i][j]
return SOLID
def cell_center(g, i, j):
"""The position ((i + 1/2) dx, (j + 1/2) dx) of the center of cell (i, j)."""
return ((i + 0.5) * g.dx, (j + 0.5) * g.dx)
def sample(q, x, y, dx, ox, oy):
"""Bilinear sample at (x, y) of a field whose value q[a][b] is at ((a + ox) dx, (b + oy) dx).
A point outside the sample positions is clamped to the nearest one, so the
result is always a convex combination of at most four values of q.
"""
na, nb = len(q), len(q[0])
fx = x / dx - ox
fy = y / dx - oy
fx = min(max(fx, 0.0), float(na - 1))
fy = min(max(fy, 0.0), float(nb - 1))
a0 = min(int(math.floor(fx)), na - 2) if na > 1 else 0
b0 = min(int(math.floor(fy)), nb - 2) if nb > 1 else 0
a1 = a0 + 1 if na > 1 else a0
b1 = b0 + 1 if nb > 1 else b0
s = fx - a0
t = fy - b0
return ((1.0 - s) * ((1.0 - t) * q[a0][b0] + t * q[a0][b1])
+ s * ((1.0 - t) * q[a1][b0] + t * q[a1][b1]))
def u_at(g, x, y):
"""The x velocity at (x, y), by bilinear sampling of u."""
return sample(g.u, x, y, g.dx, 0.0, 0.5)
def v_at(g, x, y):
"""The y velocity at (x, y), by bilinear sampling of v."""
return sample(g.v, x, y, g.dx, 0.5, 0.0)
def vel_at(g, x, y):
"""The velocity (u, v) at (x, y)."""
return (u_at(g, x, y), v_at(g, x, y))
def center_at(g, q, x, y):
"""Bilinear sample at (x, y) of a cell centered field q (same layout as p)."""
return sample(q, x, y, g.dx, 0.5, 0.5)
def divergence(g):
"""The discrete divergence (u[i+1][j] - u[i][j] + v[i][j+1] - v[i][j]) / dx of every cell."""
d = zeros(g.nx, g.ny)
for i in range(g.nx):
ui, ui1 = g.u[i], g.u[i + 1]
vi = g.v[i]
for j in range(g.ny):
d[i][j] = (ui1[j] - ui[j] + vi[j + 1] - vi[j]) / g.dx
return d
def max_fluid_divergence(g):
"""The largest |divergence| over the FLUID cells (0.0 if there is none)."""
d = divergence(g)
m = 0.0
for i in range(g.nx):
for j in range(g.ny):
if g.label[i][j] == FLUID:
m = max(m, abs(d[i][j]))
return m
def is_solid_u_face(g, i, j):
"""True if the u face (i, j), between cells (i - 1, j) and (i, j), touches a SOLID cell."""
return cell_label(g, i - 1, j) == SOLID or cell_label(g, i, j) == SOLID
def is_solid_v_face(g, i, j):
"""True if the v face (i, j), between cells (i, j - 1) and (i, j), touches a SOLID cell."""
return cell_label(g, i, j - 1) == SOLID or cell_label(g, i, j) == SOLID
def set_solid_boundaries(g, solid_velocity=None):
"""Set the normal velocity on every face that touches a SOLID cell.
A face on the border of the grid is a fixed wall and gets 0. A face inside
the grid that touches a SOLID cell gets the normal component of
solid_velocity(x, y) at the face center, or 0 if solid_velocity is None.
"""
dx = g.dx
for i in range(g.nx + 1):
for j in range(g.ny):
if is_solid_u_face(g, i, j):
if i == 0 or i == g.nx or solid_velocity is None:
g.u[i][j] = 0.0
else:
g.u[i][j] = float(solid_velocity(i * dx, (j + 0.5) * dx)[0])
for i in range(g.nx):
for j in range(g.ny + 1):
if is_solid_v_face(g, i, j):
if j == 0 or j == g.ny or solid_velocity is None:
g.v[i][j] = 0.0
else:
g.v[i][j] = float(solid_velocity((i + 0.5) * dx, j * dx)[1])
def _fluid_system(g, dt, rho):
"""Index the FLUID cells and build the 5-point Laplacian and the right side.
Returns (cells, diag, nbrs, b, has_air) where cells[k] = (i, j), diag[k] is
the number of neighbors that are not SOLID, nbrs[k] lists the indices of the
FLUID neighbors, and b[k] = -(rho dx / dt) (u[i+1][j] - u[i][j] + v[i][j+1] - v[i][j]).
has_air[k] is True if the cell has an AIR neighbor.
"""
idx = {}
cells = []
for i in range(g.nx):
for j in range(g.ny):
if g.label[i][j] == FLUID:
idx[(i, j)] = len(cells)
cells.append((i, j))
diag, nbrs, b, has_air = [], [], [], []
scale = -rho * g.dx / dt
for (i, j) in cells:
dcount = 0
nb = []
air = False
for (a, c) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
lab = cell_label(g, a, c)
if lab == SOLID:
continue
dcount += 1
if lab == FLUID:
nb.append(idx[(a, c)])
else:
air = True
diag.append(dcount)
nbrs.append(nb)
has_air.append(air)
b.append(scale * (g.u[i + 1][j] - g.u[i][j] + g.v[i][j + 1] - g.v[i][j]))
return cells, diag, nbrs, b, has_air
def _components(nbrs):
"""The connected components of the FLUID cells, as lists of indices."""
n = len(nbrs)
comp = [-1] * n
out = []
for s in range(n):
if comp[s] >= 0:
continue
comp[s] = len(out)
members = [s]
queue = deque([s])
while queue:
k = queue.popleft()
for m in nbrs[k]:
if comp[m] < 0:
comp[m] = comp[s]
members.append(m)
queue.append(m)
out.append(members)
return out
def _apply(diag, nbrs, x):
return [diag[k] * x[k] - sum(x[m] for m in nbrs[k]) for k in range(len(x))]
def pressure_solve(g, dt, rho, tol=1e-12, max_iter=None):
"""Solve the pressure Poisson equation by conjugate gradients and store p in g.p.
The system is A p = b on the FLUID cells, with the 5-point Laplacian A
(Neumann at SOLID faces, p = 0 in AIR cells) and
b = -(rho dx^2 / dt) times the divergence. A connected group of FLUID cells
with no AIR neighbor has a singular block: the mean of b is removed on it
before the solve (the compatibility condition) and the mean of p is removed
after it. CG stops when max |r| <= tol * max |b|. Returns the number of
iterations. p is 0 in SOLID and AIR cells.
"""
cells, diag, nbrs, b, has_air = _fluid_system(g, dt, rho)
n = len(cells)
g.p = zeros(g.nx, g.ny)
if n == 0:
return 0
closed = [c for c in _components(nbrs) if not any(has_air[k] for k in c)]
for c in closed:
mean = sum(b[k] for k in c) / len(c)
for k in c:
b[k] -= mean
bmax = max(abs(t) for t in b)
x = [0.0] * n
it = 0
if bmax > 0.0:
if max_iter is None:
max_iter = max(100, 4 * n)
r = list(b)
d = list(r)
rr = sum(t * t for t in r)
while it < max_iter and max(abs(t) for t in r) > tol * bmax:
q = _apply(diag, nbrs, d)
dq = sum(d[k] * q[k] for k in range(n))
if dq <= 0.0:
break
alpha = rr / dq
for k in range(n):
x[k] += alpha * d[k]
r[k] -= alpha * q[k]
rr_new = sum(t * t for t in r)
beta = rr_new / rr
rr = rr_new
for k in range(n):
d[k] = r[k] + beta * d[k]
it += 1
for c in closed:
mean = sum(x[k] for k in c) / len(c)
for k in c:
x[k] -= mean
for k, (i, j) in enumerate(cells):
g.p[i][j] = x[k]
return it
def subtract_pressure_gradient(g, dt, rho):
"""u[i][j] -= dt / (rho dx) (p[i][j] - p[i-1][j]), and the same for v.
Only faces with a FLUID cell on at least one side and no SOLID cell are
changed. The pressure of an AIR cell is 0.
"""
s = dt / (rho * g.dx)
for i in range(1, g.nx):
for j in range(g.ny):
a, c = g.label[i - 1][j], g.label[i][j]
if a == SOLID or c == SOLID or (a != FLUID and c != FLUID):
continue
g.u[i][j] -= s * (g.p[i][j] - g.p[i - 1][j])
for i in range(g.nx):
for j in range(1, g.ny):
a, c = g.label[i][j - 1], g.label[i][j]
if a == SOLID or c == SOLID or (a != FLUID and c != FLUID):
continue
g.v[i][j] -= s * (g.p[i][j] - g.p[i][j - 1])
def project(g, dt, rho, tol=1e-12, solid_velocity=None):
"""Make the velocity divergence free in the FLUID cells. Returns the CG iteration count."""
set_solid_boundaries(g, solid_velocity)
it = pressure_solve(g, dt, rho, tol)
subtract_pressure_gradient(g, dt, rho)
return it
def backtrace(g, x, y, dt):
"""The start point of the path that ends at (x, y) after time dt, by an RK2 (midpoint) step.
A negative dt traces forward in time.
"""
u1, v1 = vel_at(g, x, y)
xm, ym = x - 0.5 * dt * u1, y - 0.5 * dt * v1
u2, v2 = vel_at(g, xm, ym)
return (x - dt * u2, y - dt * v2)
def advect(g, q, dt, ox=0.5, oy=0.5):
"""Semi-Lagrangian advection of the field q by the velocity of g, for time dt.
q[a][b] is at ((a + ox) dx, (b + oy) dx): the default is a cell centered
field; use (0, 0.5) for u and (0.5, 0) for v. Each new value is the bilinear
sample of q at the RK2 backtrace of its sample point. Returns a new field.
"""
dx = g.dx
out = zeros(len(q), len(q[0]))
for a in range(len(q)):
for b in range(len(q[0])):
xb, yb = backtrace(g, (a + ox) * dx, (b + oy) * dx, dt)
out[a][b] = sample(q, xb, yb, dx, ox, oy)
return out
def advect_velocity(g, dt):
"""Advect u and v by the velocity of g. Returns (new_u, new_v); g is not changed."""
return advect(g, g.u, dt, 0.0, 0.5), advect(g, g.v, dt, 0.5, 0.0)
def kinetic_energy(g, rho):
"""(1/2) rho dx^2 times the sum of u^2 and v^2 over all faces (per unit depth in 2D)."""
s = sum(t * t for col in g.u for t in col) + sum(t * t for col in g.v for t in col)
return 0.5 * rho * g.dx * g.dx * s
vorticity_confinement.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vorticity-confinement/. The authors are listed in prov/8A418J.jsonl.
"""Vorticity confinement on a 2D MAC grid, as in Fedkiw, Stam and Jensen (2001).
The vorticity w = dv/dx - du/dy is a scalar in 2D (the z part of curl u).
It is computed at the cell centers from the velocities averaged to the
centers, with central differences (one-sided at the border of the grid).
Then
eta = grad |w|, N = eta / (|eta| + delta), f = eps dx (N x w),
and in 2D, with w along z, N x w = (N_y w, -N_x w). The force at the faces is
the mean of the two cells on each side, and it is added to the velocity with
the time step dt before the pressure projection. delta keeps N small where
|w| is flat; without it, rounding noise in eta would give N a full unit length.
"""
import math
import macgrid
from macgrid import FLUID
def center_velocity(g):
"""The velocity averaged to the cell centers: uc[i][j] = (u[i][j] + u[i+1][j]) / 2, and the same for v."""
uc = [[0.5 * (g.u[i][j] + g.u[i + 1][j]) for j in range(g.ny)] for i in range(g.nx)]
vc = [[0.5 * (g.v[i][j] + g.v[i][j + 1]) for j in range(g.ny)] for i in range(g.nx)]
return uc, vc
def _ddx(q, i, j, n, dx):
a, b = max(i - 1, 0), min(i + 1, n - 1)
return (q[b][j] - q[a][j]) / ((b - a) * dx) if b > a else 0.0
def _ddy(q, i, j, n, dx):
a, b = max(j - 1, 0), min(j + 1, n - 1)
return (q[i][b] - q[i][a]) / ((b - a) * dx) if b > a else 0.0
def vorticity(g):
"""w = dv/dx - du/dy at every cell center."""
uc, vc = center_velocity(g)
nx, ny, dx = g.nx, g.ny, g.dx
return [[_ddx(vc, i, j, nx, dx) - _ddy(uc, i, j, ny, dx) for j in range(ny)] for i in range(nx)]
def confinement_force(g, eps, delta=None):
"""The force f = eps dx (N x w) at every cell center, as two fields (fx, fy).
delta defaults to 1e-6 max|w| / dx. Cells that are not FLUID get no force.
"""
if eps < 0.0:
raise ValueError("eps must be >= 0")
nx, ny, dx = g.nx, g.ny, g.dx
w = vorticity(g) # @line L1
a = [[abs(t) for t in col] for col in w]
if delta is None:
delta = 1e-6 * max(max(col) for col in a) / dx
fx, fy = macgrid.zeros(nx, ny), macgrid.zeros(nx, ny)
for i in range(nx):
for j in range(ny):
if g.label[i][j] != FLUID:
continue
ex, ey = _ddx(a, i, j, nx, dx), _ddy(a, i, j, ny, dx) # @line L2
m = math.hypot(ex, ey) + delta
if m == 0.0:
continue
Nx, Ny = ex / m, ey / m # @line L3
fx[i][j] = eps * dx * Ny * w[i][j] # @line L4
fy[i][j] = -eps * dx * Nx * w[i][j]
return fx, fy
def add_confinement(g, eps, dt, delta=None):
"""Add dt times the confinement force to the faces that do not touch a SOLID cell. Returns (fx, fy)."""
fx, fy = confinement_force(g, eps, delta)
for i in range(1, g.nx):
for j in range(g.ny):
if not macgrid.is_solid_u_face(g, i, j):
g.u[i][j] += dt * 0.5 * (fx[i - 1][j] + fx[i][j]) # @line L5
for i in range(g.nx):
for j in range(1, g.ny):
if not macgrid.is_solid_v_face(g, i, j):
g.v[i][j] += dt * 0.5 * (fy[i][j - 1] + fy[i][j])
return fx, fy
def set_velocity(g, vel):
"""Set every face to vel(x, y) at its center: u gets vel[0], v gets vel[1]."""
dx = g.dx
for i in range(g.nx + 1):
for j in range(g.ny):
g.u[i][j] = vel(i * dx, (j + 0.5) * dx)[0]
for i in range(g.nx):
for j in range(g.ny + 1):
g.v[i][j] = vel((i + 0.5) * dx, j * dx)[1]
def gaussian_vortex(cx, cy, sigma, strength):
"""The velocity of a Gaussian vortex: speed strength r / sigma^2 exp(-r^2 / (2 sigma^2)) around (cx, cy), counterclockwise."""
def vel(x, y):
rx, ry = x - cx, y - cy
k = strength / (sigma * sigma) * math.exp(-(rx * rx + ry * ry) / (2.0 * sigma * sigma))
return (-k * ry, k * rx)
return vel
def step(g, dt, rho, eps):
"""One smoke step without sources: confinement force, advection, projection."""
if eps > 0.0:
add_confinement(g, eps, dt)
g.u, g.v = macgrid.advect_velocity(g, dt)
macgrid.project(g, dt, rho)
test_vorticity_confinement.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vorticity-confinement/. The authors are listed in prov/8A418J.jsonl.
"""Tests of vorticity confinement on a small MAC grid."""
import math
import pytest
import macgrid
import vorticity_confinement as V
N = 20
DX = 1.0 / N
def grid_with(vel, project=False):
g = macgrid.make_grid(N, N, DX)
V.set_velocity(g, vel)
if project:
macgrid.project(g, 0.01, 1.0)
return g
def rotation(x, y):
return (-(y - 0.5), x - 0.5) # solid body rotation, vorticity 2
VORTEX = V.gaussian_vortex(0.5, 0.5, 0.12, 0.06)
def test_vorticity_of_a_solid_rotation_is_two():
w = V.vorticity(grid_with(rotation))
assert max(abs(t - 2.0) for c in w for t in c) < 1e-12
def test_no_force_for_uniform_flow_or_solid_rotation():
fx, fy = V.confinement_force(grid_with(lambda x, y: (0.3, -0.2)), 0.5)
assert max(abs(t) for c in fx + fy for t in c) == 0.0
fx, fy = V.confinement_force(grid_with(rotation), 0.5)
assert max(abs(t) for c in fx + fy for t in c) < 1e-9
def test_without_delta_rounding_noise_gives_a_full_force():
fx, fy = V.confinement_force(grid_with(rotation), 0.3, delta=0.0)
big = max(math.hypot(fx[i][j], fy[i][j]) for i in range(N) for j in range(N))
assert big == pytest.approx(0.3 * DX * 2.0, rel=1e-9) # eps dx |w| from a direction that is only noise
def test_force_is_perpendicular_to_n_and_has_size_eps_dx_w():
g = grid_with(VORTEX)
w = V.vorticity(g)
fx, fy = V.confinement_force(g, 0.5)
a = [[abs(t) for t in c] for c in w]
checked = 0
for i in range(1, N - 1):
for j in range(1, N - 1):
ex = (a[i + 1][j] - a[i - 1][j]) / (2 * DX)
ey = (a[i][j + 1] - a[i][j - 1]) / (2 * DX)
if math.hypot(ex, ey) < 0.05 * max(map(max, a)) / DX: # far from the peak, where delta does not matter
continue
checked += 1
assert abs(fx[i][j] * ex + fy[i][j] * ey) < 1e-12 * math.hypot(ex, ey)
assert math.hypot(fx[i][j], fy[i][j]) == pytest.approx(0.5 * DX * abs(w[i][j]), rel=1e-4)
assert checked > 50
def test_force_pushes_along_the_flow_of_a_vortex():
g = grid_with(VORTEX, project=True)
fx, fy = V.confinement_force(g, 0.5)
uc, vc = V.center_velocity(g)
for i in (11, 12): # right of the center (0.5, 0.5), inside the core: w > 0 and the flow goes up
j = 10
assert vc[i][j] > 0.0 and fy[i][j] > 0.0 and fx[i][j] * uc[i][j] + fy[i][j] * vc[i][j] > 0.0
w = V.vorticity(g)
assert w[13][10] < 0.0 and fy[13][10] < 0.0 # the ring of opposite vorticity around a Gaussian vortex
assert sum(fx[i][j] * uc[i][j] + fy[i][j] * vc[i][j] for i in range(N) for j in range(N)) > 0.0
e0 = macgrid.kinetic_energy(g, 1.0)
V.add_confinement(g, 0.5, 0.05)
assert macgrid.kinetic_energy(g, 1.0) > e0 # the force adds energy
def test_force_is_linear_in_eps_and_zero_for_eps_zero():
g = grid_with(VORTEX)
f1 = V.confinement_force(g, 0.25)
f2 = V.confinement_force(g, 0.5)
for a, b in zip(f1, f2):
assert max(abs(2.0 * s - t) for c1, c2 in zip(a, b) for s, t in zip(c1, c2)) < 1e-15
u0, v0 = macgrid.copy_field(g.u), macgrid.copy_field(g.v)
V.add_confinement(g, 0.0, 0.05)
assert g.u == u0 and g.v == v0
def test_walls_get_no_force():
g = grid_with(VORTEX)
g.label[10][10] = macgrid.SOLID
V.add_confinement(g, 1.0, 0.05)
assert all(g.u[0][j] == VORTEX(0.0, (j + 0.5) * DX)[0] for j in range(N))
assert g.u[10][10] == VORTEX(10 * DX, 10.5 * DX)[0] and g.v[10][11] == VORTEX(10.5 * DX, 11 * DX)[1]
def decay(eps, steps=10):
g = grid_with(VORTEX, project=True)
e0 = macgrid.kinetic_energy(g, 1.0)
for _ in range(steps):
V.step(g, 0.05, 1.0, eps)
assert macgrid.max_fluid_divergence(g) < 1e-9
return macgrid.kinetic_energy(g, 1.0) / e0
def test_confinement_slows_the_numerical_decay_and_too_much_adds_energy():
r0, r1, r3 = decay(0.0), decay(1.0), decay(3.0)
assert abs(r0 - 0.64968) < 1e-4 # semi-Lagrangian advection loses a third of the energy in 10 steps
assert abs(r1 - 0.79221) < 1e-4
assert r3 > 1.1 # eps = 3 ends with more energy than the start
def test_bad_input():
with pytest.raises(ValueError):
V.confinement_force(grid_with(VORTEX), -1.0)
Exercises
- Show that the force is zero for any flow whose vorticity is the same at every point. Answer: then is constant, , and , so .
- Show that , and that in 2D. Answer: is a multiple of , which is at right angles to and so to , and .
- At a cell with (clockwise), , and m, find . Answer: and . The center is above the cell, and a clockwise swirl moves to the left below its center, so the force goes with the flow.
- Why does the pressure projection not remove the force around a swirl? Answer: the projection removes exactly the gradient part. The force goes along the flow around the center, so its integral around a circle about the center is positive, while the integral of a gradient around a closed curve is zero.
References
- Ronald Fedkiw, Jos Stam and Henrik Wann Jensen, Visual simulation of smoke, Proceedings of SIGGRAPH 2001, 15-22, section 3 (equations 9 to 11: the vorticity, the vectors N and the force), section 4 (forces at the voxel centers, added with the time step before the advection and the pressure solve), section 1.2 (stable while the force stays below a threshold)
- John Steinhoff and David Underhill, Modification of the Euler equations for vorticity confinement: application to the computation of interacting vortex rings, Physics of Fluids 6(8), 2738-2744, 1994, the original confinement term in computational fluid dynamics, without the grid spacing factor
- Andrew Selle, Nick Rasmussen and Ronald Fedkiw, A vortex particle method for smoke, water and explosions, ACM Transactions on Graphics 24(3), 910-914, 2005, vorticity carried on particles and given back to the grid by a confinement-like force
- Miles Macklin and Matthias Müller, Position based fluids, ACM Transactions on Graphics 32(4), 2013, vorticity confinement on particles to give back the energy that the position solver removes
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 8A418J Edit this page History Report an error Markdown