Algorithm Search⌘K

Modelcore

Boussinesq buoyancy

Also called Boussinesq approximation.

Model the lift of hot gas and the weight of smoke by an upward force linear in temperature and smoke density, in a flow that keeps one constant density.

Boussinesq buoyancy is the force that makes hot smoke rise in most smoke solvers for animation. Fedkiw, Stam and Jensen (2001) write it as

fbuoy=(−α s+β (T−Tamb)) y^,\mathbf f_{buoy} = \big(-\alpha\, s + \beta\, (T - T_{amb})\big)\, \hat{\mathbf y},

where ss is the smoke density, TT the temperature, TambT_{amb} the temperature of the surrounding air, y^\hat{\mathbf y} the unit vector up, and α,β≥0\alpha, \beta \ge 0 two constants. The paper writes ρ\rho for the smoke density and z\mathbf z for the up vector; this page uses ss so that ρ\rho can stay the density of the air. The flow itself keeps one constant density and stays incompressible. The change of density that heat and smoke cause enters only through this force, which is the idea of Boussinesq: keep the density difference where gravity acts on it, and nowhere else. The model is an empirical approximation. It is close to the physics only for small differences of temperature and density, and graphics uses it with α\alpha and β\beta tuned by eye, often far outside that range.

The machine

The quantities. On a domain with walls, the state is the velocity u\mathbf u (m/s), the pressure pp (Pa), the temperature TT (K) and the smoke density ss. The air has the constant density ρ0\rho_0 (kg/m³). The smoke density is in kg/m³ of soot, or a concentration without units, as the user chooses; α\alpha takes the matching units.

The equations. With the force above,

∇⋅u=0,∂u∂t+(u⋅∇) u=−1ρ0∇p+fbuoy+fother,\nabla \cdot \mathbf u = 0, \qquad \frac{\partial \mathbf u}{\partial t} + (\mathbf u \cdot \nabla)\, \mathbf u = -\frac{1}{\rho_0} \nabla p + \mathbf f_{buoy} + \mathbf f_{other},
∂T∂t+(u⋅∇) T=0,∂s∂t+(u⋅∇) s=0.\frac{\partial T}{\partial t} + (\mathbf u \cdot \nabla)\, T = 0, \qquad \frac{\partial s}{\partial t} + (\mathbf u \cdot \nabla)\, s = 0.

The last two are the paper's equations 6 and 7: TT and ss are carried by the flow and do not act on it except through fbuoy\mathbf f_{buoy}. Here pp is the pressure minus the hydrostatic pressure of the ambient air. The paper uses the inviscid form of the Navier-Stokes equations; fother\mathbf f_{other} holds, for example, vorticity confinement.

The parameters.

symbol meaning units range
β\beta lift per kelvin above ambient m/(s² K) β≥0\beta \ge 0; g/Tamb≈0.033g / T_{amb} \approx 0.033 for an ideal gas at 300 K
α\alpha weight per unit of smoke m/s² per unit of ss α≥0\alpha \ge 0; g/ρ0≈8.2g / \rho_0 \approx 8.2 m⁴/(kg s²) for soot in kg/m³ in air
TambT_{amb} ambient temperature K Tamb>0T_{amb} > 0
ss, TT smoke density, temperature as above s≥0s \ge 0; the force is zero at s=0s = 0, T=TambT = T_{amb}

The paper calls α\alpha and β\beta two positive constants with units that make the equation meaningful. Nguyen, Fedkiw and Jensen (2002) keep only the temperature term for fire. They write α\alpha for its coefficient and use 0.150.15 m/(K s²), about five times the ideal gas value.

Where the linear law comes from. Start from ρ Du/Dt=−∇pfull−ρgy^\rho\, D\mathbf u / Dt = -\nabla p_{full} - \rho g \hat{\mathbf y}, and write ρ=ρ0+ρ′\rho = \rho_0 + \rho' and pfull=p0+pp_{full} = p_0 + p with ∇p0=−ρ0gy^\nabla p_0 = -\rho_0 g \hat{\mathbf y}, the hydrostatic pressure of the air at rest. Keep ρ′\rho' only in the gravity term and divide by ρ0\rho_0:

DuDt=−1ρ0∇p−g ρ′ρ0 y^.\frac{D\mathbf u}{Dt} = -\frac{1}{\rho_0} \nabla p - g\, \frac{\rho'}{\rho_0}\, \hat{\mathbf y}.

A density that falls linearly with temperature, ρ′=−ρ0βT(T−Tamb)\rho' = -\rho_0 \beta_T (T - T_{amb}), gives the term gβT(T−Tamb)g \beta_T (T - T_{amb}), so β=gβT\beta = g \beta_T. For an ideal gas at fixed pressure, ρ∝1/T\rho \propto 1/T, and the slope at TambT_{amb} is βT=1/Tamb\beta_T = 1/T_{amb}. Soot of mass ss per unit volume adds about ρ′=s\rho' = s, if the volume of the soot itself is neglected, which gives α=g/ρ0\alpha = g / \rho_0.

The standing assumptions.

  1. The density differences are small, ∣ρ′∣≪ρ0|\rho'| \ll \rho_0, so the inertia on the left uses ρ0\rho_0.
  2. The density depends linearly on TT and ss.
  3. The flow is slow compared with sound, so it is incompressible and the gas does not expand as it heats.
  4. The air far away is at rest, at the uniform temperature TambT_{amb}, in hydrostatic balance.
  5. Heat and smoke do not diffuse, cool or decay. Solvers for animation often add such terms by hand; they are not part of the force.

On a MAC grid. TT and ss live at the cell centers of a MAC grid and the force is vertical, so it is added to the vv faces, each with the mean of the two cells below and above it. Then the solver advects and projects, as in stable fluids.

  1. SMOKE-STEP(u, s, T, Δt)
  2. 1f(s, T) = -α s + β (T - T_amb) ▷ upward acceleration
  3. 2for each v face: s_f, T_f ← means of the two cells below and above
  4. 3v ← v + Δt f(s_f, T_f)
  5. 4advect u, s and T by u
  6. 5project u ▷ removes the part of f that is a gradient

Lines L2 and L3 cost Θ(n)\Theta(n) on a grid of nn cells, small next to the pressure solve of line L5.

What it counts

The model predicts the acceleration that differences of temperature and smoke from the ambient air give to the flow: hot gas rises, smoke sinks, and the pressure pushes the rest of the fluid out of the way. Not all of the force makes motion. The projection removes the part that is a gradient, and a force that depends only on the height is a gradient. What drives the flow is the change of the force along the horizontal. Take the curl of the momentum equation in 2D, with ω=∂v/∂x−∂u/∂y\omega = \partial v / \partial x - \partial u / \partial y:

DωDt=∂fy∂x=β ∂T∂x−α ∂s∂x.\frac{D\omega}{Dt} = \frac{\partial f_y}{\partial x} = \beta\, \frac{\partial T}{\partial x} - \alpha\, \frac{\partial s}{\partial x}.

So the model makes rotation where hot and cold gas sit side by side. A hot blob gets a pair of opposite swirls, one on each side, that carry it up through its center and bring cooler gas down at its sides. This is the rolling rise of smoke.

The model does not predict the expansion of gas as it heats, because the flow keeps one density. It does not predict pressure waves or sound, the real rise speed of very hot gas, the cooling of the gas, or the detail below the grid scale. It also says nothing on how the solver keeps the swirls; numerical dissipation removes them, and vorticity confinement is the usual remedy.

Relation to other models

  • The full Navier-Stokes equations. The Navier-Stokes equations for a gas let the density vary everywhere. The buoyancy model keeps it constant except in gravity. A variable density solve keeps ρ\rho in the pressure equation as well, at a higher cost.
  • The ideal gas. The exact density difference of an ideal gas at fixed pressure, as a fraction of ρamb\rho_{amb}, is (T−Tamb)/T(T - T_{amb}) / T. The model replaces it by its tangent (T−Tamb)/Tamb(T - T_{amb}) / T_{amb} at TambT_{amb}. The error is computed below.
  • Fire. The fire method of Nguyen, Fedkiw and Jensen (2002) uses the temperature term alone. It models the expansion that this model leaves out by a jump of the velocity at the burning surface, not by buoyancy.
  • Convection with diffusion. With viscosity and the diffusion of the heat equation added to the equation of TT, the same model gives the classic equations of Rayleigh-Bénard convection in fluid dynamics.
  • Pure advection. Without the force, TT and ss follow the advection equation and do not change the flow at all. They are then only dye.

Known results in the model

A layered fluid stays at rest (proved). If TT and ss depend only on the height yy, then fbuoy=f(y)y^=∇F\mathbf f_{buoy} = f(y) \hat{\mathbf y} = \nabla F with F(y)=∫f dyF(y) = \int f\, dy. The pressure p=ρ0Fp = \rho_0 F balances it, and u=0\mathbf u = 0 stays a solution. This holds for hot gas above and for hot gas below. On a MAC grid it holds exactly: the force on each row of vv faces is the difference of a potential between the rows of cells, so the Chorin projection removes it. The tests check ∣u∣<10−12|\mathbf u| < 10^{-12} after one force step and one projection, for a uniform TT of 400 K and for both linear layerings. The layering with hot gas below is a state of rest, but the vorticity equation above shows that any horizontal difference of TT in it starts a rotation; in physics this is the onset of convection.

The linear law against the ideal gas (proved by algebra). The ratio of the model force β(T−Tamb)\beta (T - T_{amb}), with β=g/Tamb\beta = g / T_{amb}, to g(ρamb−ρ)/ρamb=g(T−Tamb)/Tg (\rho_{amb} - \rho) / \rho_{amb} = g (T - T_{amb}) / T is T/TambT / T_{amb}. For Tamb=300T_{amb} = 300 K:

TT (K) 303 330 600 2000
model force (m/s²) 0.098 0.981 9.81 55.6
ideal gas, g(T−Tamb)/Tg (T - T_{amb}) / T (m/s²) 0.097 0.892 4.91 8.34
ratio 1.01 1.1 2.0 6.67

So the linear law is within 1% for a difference of 3 K and off by a factor of 2 at 600 K. Hot smoke and fire are far outside the range of the derivation, and in that range β\beta is a tuning value, not a property of the gas.

No net flow through a horizontal line (proved). In a closed box the projected velocity has zero divergence and zero normal velocity at the walls. By the divergence theorem on the part of the box below any height, the net flow up through that height is zero. So the rise of hot gas is always paid for by a sinking of other gas. The tests check that the sum of vv over each row of faces is below 10−1010^{-10} after a hot blob gets one kick.

A hot blob, one step (measured). On a 16×2416 \times 24 grid with Δx=1/16\Delta x = 1/16 m and walls, a Gaussian blob with σ=0.1\sigma = 0.1 m and a peak 300 K above ambient, centered at (0.5,0.4)(0.5, 0.4) m, with β=0.0327\beta = 0.0327 m/(s² K) and Δt=0.05\Delta t = 0.05 s, the face at the center of the blob gets the kick Δt β (Tf−Tamb)=0.418\Delta t\, \beta\, (T_f - T_{amb}) = 0.418 m/s. After the projection it moves at 0.1980.198 m/s up. The projection removes more than half of the kick, which is the pressure pushing back. The velocity next to the side walls points down. The field is the mirror image of itself about the vertical line through the blob.

A hot blob, several steps (measured). With the same setup and only the force, semi-Lagrangian advection and projection, the height of the center of the excess temperature was

step 0 4 8 12
height (m) 0.400 0.449 0.549 0.666
peak TT (K) 600 539 486 441

The blob speeds up as it rises. The model has no diffusion of heat, so the fall of the peak comes from the interpolation in the advection, not from the model.

Heavy smoke sinks (measured). A blob of smoke at ambient temperature with α=0.5\alpha = 0.5 gets a downward velocity at its center and an upward one at the side walls, the mirror of the hot blob.

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.

boussinesq_buoyancy.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boussinesq-buoyancy/. The authors are listed in prov/QV9FZM.jsonl.

"""The buoyancy force of smoke in the form of Fedkiw, Stam and Jensen (2001), on a 2D MAC grid.

    f = (-alpha s + beta (T - T_amb)) y_hat

s is the smoke density and T the temperature, both at the cell centers.
alpha >= 0 (m/s^2 per unit of s) and beta >= 0 (m/(s^2 K)) are constants.
The force is a vertical acceleration, so it lives on the v faces: each v face
gets the mean of s and T over the two cells below and above it. Faces that
touch a SOLID cell, which include the top and the bottom of the grid, get no
force; the pressure projection sets them.

The flow stays incompressible with one constant density rho. The density
difference of the hot or smoky gas appears only through this force.
"""

import macgrid


def buoyancy(s, T, alpha, beta, T_amb):
    """The upward acceleration -alpha s + beta (T - T_amb)."""
    return -alpha * s + beta * (T - T_amb)  # @line L1


def add_buoyancy(g, s, T, dt, alpha, beta, T_amb):
    """v += dt f on every v face that does not touch a SOLID cell."""
    if alpha < 0.0 or beta < 0.0 or dt <= 0.0:
        raise ValueError("need alpha >= 0, beta >= 0 and dt > 0")
    for i in range(g.nx):
        for j in range(1, g.ny):
            if macgrid.is_solid_v_face(g, i, j):
                continue
            sf = 0.5 * (s[i][j - 1] + s[i][j])  # @line L2
            Tf = 0.5 * (T[i][j - 1] + T[i][j])
            g.v[i][j] += dt * buoyancy(sf, Tf, alpha, beta, T_amb)  # @line L3


def step(g, s, T, dt, rho, alpha, beta, T_amb):
    """One smoke step: buoyancy, advection of the velocity, s and T, projection. Returns the new (s, T)."""
    add_buoyancy(g, s, T, dt, alpha, beta, T_amb)
    nu, nv = macgrid.advect_velocity(g, dt)  # @line L4
    s2 = macgrid.advect(g, s, dt)
    T2 = macgrid.advect(g, T, dt)
    g.u, g.v = nu, nv
    macgrid.project(g, dt, rho)  # @line L5
    return s2, T2


def ideal_gas_beta(gravity, T_amb):
    """beta = g / T_amb: the slope of g (rho_amb - rho) / rho_amb in T at T = T_amb for an ideal gas at fixed pressure."""
    if T_amb <= 0.0:
        raise ValueError("T_amb must be > 0 (kelvin)")
    return gravity / T_amb


def ideal_gas_force(gravity, T, T_amb):
    """g (rho_amb - rho) / rho_amb = g (T - T_amb) / T for an ideal gas at fixed pressure, without linearization."""
    return gravity * (T - T_amb) / T


def centroid_height(field, base, dx):
    """The height of the center of (field - base) over the cells, weighted by the excess."""
    num = den = 0.0
    for col in field:
        for j, t in enumerate(col):
            w = t - base
            num += w * (j + 0.5) * dx
            den += w
    return num / den
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_boussinesq_buoyancy.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boussinesq-buoyancy/. The authors are listed in prov/QV9FZM.jsonl.

"""Tests of the buoyancy force on a small MAC grid."""

import math

import pytest

import macgrid
import boussinesq_buoyancy as B

NX, NY = 16, 24
DX = 1.0 / 16
TA = 300.0
BETA = B.ideal_gas_beta(9.81, TA)
DT = 0.05


def fields(Tf, sf=lambda x, y: 0.0):
    T = [[Tf((i + 0.5) * DX, (j + 0.5) * DX) for j in range(NY)] for i in range(NX)]
    s = [[sf((i + 0.5) * DX, (j + 0.5) * DX) for j in range(NY)] for i in range(NX)]
    return s, T


def blob(amp, cy=0.4):
    return lambda x, y: amp * math.exp(-((x - 0.5) ** 2 + (y - cy) ** 2) / (2 * 0.1 ** 2))


def kick(Tf, sf=lambda x, y: 0.0, alpha=0.0):
    """One buoyancy kick and one projection from rest."""
    g = macgrid.make_grid(NX, NY, DX)
    s, T = fields(Tf, sf)
    B.add_buoyancy(g, s, T, DT, alpha, BETA, TA)
    macgrid.project(g, DT, 1.0)
    return g


def test_force_is_zero_at_ambient_and_linear():
    assert B.buoyancy(0.0, TA, 0.7, BETA, TA) == 0.0
    assert B.buoyancy(0.0, 400.0, 0.7, BETA, TA) == pytest.approx(100.0 * BETA)
    assert B.buoyancy(2.0, TA, 0.7, BETA, TA) == pytest.approx(-1.4)
    a, b = (0.3, 350.0), (1.1, 420.0)
    f = lambda s, T: B.buoyancy(s, T, 0.7, BETA, TA)
    assert f(a[0] + b[0], a[1] + b[1] - TA) == pytest.approx(f(*a) + f(*b))


def test_ideal_gas_slope():
    assert BETA == pytest.approx(0.0327)
    # the linear force against g (rho_amb - rho) / rho_amb = g (T - T_amb) / T
    for T, ratio in ((303.0, 1.01), (330.0, 1.1), (600.0, 2.0), (2000.0, 20.0 / 3.0)):
        assert BETA * (T - TA) / B.ideal_gas_force(9.81, T, TA) == pytest.approx(ratio)


def test_uniform_heat_in_a_closed_box_does_not_move():
    g = kick(lambda x, y: 400.0)
    assert max(abs(t) for c in g.u + g.v for t in c) < 1e-12


def test_layers_in_a_closed_box_do_not_move():
    g = kick(lambda x, y: 300.0 + 100.0 * y)  # the force depends on the height only: a gradient
    assert max(abs(t) for c in g.u + g.v for t in c) < 1e-12
    g = kick(lambda x, y: 400.0 - 100.0 * y)  # hot below: unstable, but still at rest
    assert max(abs(t) for c in g.u + g.v for t in c) < 1e-12


def test_a_hot_blob_rises_and_the_rest_comes_down():
    g = kick(lambda x, y: TA + blob(300.0)(x, y))
    assert g.v[8][7] == pytest.approx(0.19822, abs=1e-5) and g.v[7][7] == g.v[8][7]
    assert g.v[0][7] < 0.0  # the return flow at the side walls
    assert max(abs(g.u[i][j] + g.u[NX - i][j]) for i in range(NX + 1) for j in range(NY)) < 1e-12  # mirror image
    for j in range(NY + 1):  # a closed box: no net flow through any horizontal line
        assert abs(sum(g.v[i][j] for i in range(NX))) < 1e-10
    assert macgrid.max_fluid_divergence(g) < 1e-10


def test_dense_smoke_sinks():
    g = kick(lambda x, y: TA, blob(1.0, 0.6), alpha=0.5)
    assert g.v[8][10] < 0.0 and g.v[0][10] > 0.0


def test_the_blob_rises_over_time():
    g = macgrid.make_grid(NX, NY, DX)
    s, T = fields(lambda x, y: TA + blob(300.0)(x, y))
    h0 = B.centroid_height(T, TA, DX)
    for _ in range(12):
        s, T = B.step(g, s, T, DT, 1.0, 0.0, BETA, TA)
    assert abs(h0 - 0.40001) < 1e-4
    assert abs(B.centroid_height(T, TA, DX) - 0.66560) < 1e-4
    assert abs(max(max(c) for c in T) - 440.712) < 1e-2  # the peak falls by numerical diffusion, not by the model
    assert macgrid.max_fluid_divergence(g) < 1e-9


def test_bad_input():
    g = macgrid.make_grid(2, 2, 0.5)
    z = macgrid.zeros(2, 2)
    with pytest.raises(ValueError):
        B.add_buoyancy(g, z, z, DT, -1.0, BETA, TA)
    with pytest.raises(ValueError):
        B.ideal_gas_beta(9.81, 0.0)

References

  1. Ronald Fedkiw, Jos Stam and Henrik Wann Jensen, Visual simulation of smoke, Proceedings of SIGGRAPH 2001, 15-22, section 2 (the incompressible Euler equations 1 and 2, the advection of T and of the smoke density, equations 6 and 7, and the buoyancy force, equation 8), section 4 (forces at the voxel centers, added before the advection)
  2. Edward A. Spiegel and George Veronis, On the Boussinesq approximation for a compressible fluid, The Astrophysical Journal 131, 442, 1960, the conditions under which the density can be kept constant except in the gravity term
  3. Duc Quang Nguyen, Ronald Fedkiw and Henrik Wann Jensen, Physically based modeling and animation of fire, ACM Transactions on Graphics 21(3), 721-728, 2002 (SIGGRAPH 2002), section 4, equation 14 (the temperature term alone), and section 6 (the constant 0.15 m/(K s^2))
  4. Robert Bridson, Fluid Simulation for Computer Graphics, second edition, CRC Press, 2015, the chapter Smoke (temperature and smoke concentration, buoyancy)

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW4 complete
  • a review of the text: no review record reviews/QV9FZM/text.yaml