Algorithm Search⌘K

Algorithmadvanced

Nguyen-Fedkiw-Jensen fire

Also called physically based fire animation.

Animate fire with a level set for the thin blue core that moves with the fuel plus a flame speed, and two incompressible flows, fuel and hot products, joined by jump conditions at the core.

Time
Θ(s n) level_setO(n k) pressureO(n log n) redistanceO(s n + n log n + n k) step
Space
Θ(n) extra
Where
k = the number of conjugate gradient iterations of the pressure solve; n = the number of grid cells; s = the number of level set substeps per step
Properties
not conservativedeterministicnot exactnot unconditionally stable
Origin
Duc Quang Nguyen, Ronald Fedkiw, Henrik Wann Jensen, 2002

The fire method of Nguyen, Fedkiw and Jensen (2002) animates flames from gas or solid fuel on a grid. It uses the thin flame model from combustion science: the reaction happens on a surface, the blue core, that separates the gaseous fuel from the hot products. A level set tracks this surface, and the surface moves with the fuel plus a flame speed SS into the fuel. The fuel and the products are two incompressible flows with different densities. Where they meet, conservation of mass and momentum gives a jump in the normal velocity and in the pressure. The ghost fluid method carries these jumps through the advection and the pressure solve. The jump in velocity is the expansion of the gas as it burns, and the paper shows that it makes the flames look fuller. Buoyancy, vorticity confinement and a temperature model for the color complete the method. The name "physically based" means that the method uses physical quantities and states its approximations, not that the result is accurate.

In plain words

A gas flame has a thin blue sheet where the fuel burns. Inside it is fuel, outside are hot gases.

The method keeps a number in every grid cell that says how far the cell is from the sheet, and on which side. Each step, the sheet moves with the fuel flow and also eats into the fuel at a fixed speed.

Hot gas is lighter than fuel, so the same mass takes more room. The gas must leave the sheet faster than the fuel arrives, and the pressure drops across the sheet. The method keeps two flows, one for the fuel and one for the hot gas, and links them at the sheet with these two rules. Then the hot gas rises, cools and changes color from white to yellow to red.

The problem

Given a domain with walls, fuel injectors and open boundaries, animate the fuel, the blue core and the hot products. The input is the fuel density ρf\rho_f, the product density ρh<ρf\rho_h < \rho_f, the flame speed SS of the fuel, and the temperatures TairT_{air}, TignT_{ign} and TmaxT_{max}. Speeds are low compared with sound, so both gases are treated as incompressible, which avoids the small time steps of a compressible solver. The output each frame is the velocity, the level set φ\varphi and the temperature TT, which a renderer turns into the color of a blackbody.

The jump conditions. Let φ>0\varphi > 0 in the fuel, and let VV be the normal velocity along the normal that points from the fuel to the products. The front moves at D=Vf−SD = V_f - S: the fuel crosses it at the speed SS. Conservation of mass and momentum across the front (the paper's equations 2 and 3) are

ρh(Vh−D)=ρf(Vf−D),ρh(Vh−D)2+ph=ρf(Vf−D)2+pf,\rho_h (V_h - D) = \rho_f (V_f - D), \qquad \rho_h (V_h - D)^2 + p_h = \rho_f (V_f - D)^2 + p_f,

and they give

Vh=Vf+(ρfρh−1)S,ph=pf−(ρfρh−1)ρfS2.V_h = V_f + \left(\frac{\rho_f}{\rho_h} - 1\right) S, \qquad p_h = p_f - \left(\frac{\rho_f}{\rho_h} - 1\right) \rho_f S^2.

The tangential velocity is the same on both sides. The paper writes n=∇φ/∣∇φ∣\mathbf n = \nabla \varphi / |\nabla \varphi|, which points into the fuel, for the motion of the level set, and the jump formulas hold with VV measured along −n-\mathbf n.

The algorithm

Let J=(ρf/ρh−1)SJ = (\rho_f / \rho_h - 1) S and P=(ρf/ρh−1)ρfS2P = (\rho_f / \rho_h - 1) \rho_f S^2. Velocities live on the faces of a MAC grid, and φ\varphi, pp and TT in the cells.

  1. FIRE-STEP(φ, u, T, Δt)
  2. 1w <- u_f + S n at each cell, with n = ∇φ / |∇φ| by central differences and u_f the fuel velocity
  3. 2φ <- φ - Δt (w · ∇φ) by upwind differences, in substeps that keep |w| Δt / Δx at most 1/2; then redistance φ
  4. 3form the fuel and the product velocity on every face: on the other side, add or subtract J m (ghost values)
  5. 4advect each velocity field by itself; each face keeps the field of the material that is at the face now
  6. 5advect T by the product velocity with the ghost value T_max in the fuel; set T_ign in the fuel; apply the cooling
  7. 6v <- v + Δt α (T - T_air) on the vertical faces
  8. 7solve ∇·(∇p / ρ) = ∇·u* / Δt with the pressure jump P across the front, by the ghost fluid method
  9. 8u <- u* - Δt ∇p / ρ, with the same jump

The level set (L1, L2). The front moves with w=uf+Sn\mathbf w = \mathbf u_f + S \mathbf n, so φt=−w⋅∇φ\varphi_t = -\mathbf w \cdot \nabla \varphi (the paper's equation 6). The paper solves it with first order upwind differences (its equation 7). In the products, uf\mathbf u_f is the ghost fuel velocity of line L3. The paper takes the incompressible step about five times larger than the CFL limit of the level set, and moves φ\varphi in substeps, which cuts the number of pressure solves by about five. It keeps φ\varphi close to a signed distance with the fast marching method. Without this, φ\varphi gets steep in the products, the upwind gradient grows, and the front eats the fuel too fast. In a test of the code here without redistancing, the core of a nozzle flame grew and then burned away.

Ghost velocities (L3, L4). The paper's equations 12 and 13 give the product velocity in the fuel region: take the fuel velocity, keep its tangential part, and add JJ to its normal part. The reverse gives the fuel velocity in the products. A semi-Lagrangian backtrace that crosses the front then reads the velocity of its own material, so the jump is not smeared. The code stores one value per face, the velocity of the material at the face, and makes the other one when it needs it.

Temperature (L5). The paper follows a reaction coordinate YY with Yt=−(u⋅∇)Y−kY_t = -(\mathbf u \cdot \nabla) Y - k, so 1−Y1 - Y is the time since a gas element crossed the core, and maps it to a temperature curve that an animator can shape. For large flames it uses a ghost value instead: a backtrace that looks into the fuel reads TmaxT_{max}. Past the peak, TT cools by −cT((T−Tair)/(Tmax−Tair))4-c_T ((T - T_{air}) / (T_{max} - T_{air}))^4 (the paper's equation 17), which the code integrates exactly. A density for the smoke follows the same pattern.

Forces (L6). Buoyancy is α(T−Tair)\alpha (T - T_{air}) upward (equation 14), the temperature term of Boussinesq buoyancy. Vorticity confinement εh(N×ω)\varepsilon h (\mathbf N \times \boldsymbol\omega) (equation 15) adds back small swirls; the paper uses a different ε\varepsilon for the fuel and the products. The code here leaves it out.

Pressure (L7, L8). Each gas has its own density, and the pressure jumps by PP at the front. In the equation of a cell, the pressure of a neighbor on the other side is replaced by its ghost value, the pressure plus or minus PP. The known jump goes to the right side, and the matrix stays symmetric. The code gives a face that crosses the front the density ρ^=θρa+(1−θ)ρb\hat\rho = \theta \rho_a + (1 - \theta) \rho_b, where θ\theta is the part of the face segment on the side of cell aa, from the values of φ\varphi. The paper refers to Nguyen, Fedkiw and Kang (2001) for the details of its solver.

Solid fuel. A solid that burns is a fuel source. Mass conservation at its surface gives the gas speed Vs+(ρs/ρf−1)SV_s + (\rho_s / \rho_f - 1) S (equation 5). The paper injects gas at this speed from the voxels on the surface of a burning object.

Example

The jumps by hand. With ρf=1\rho_f = 1 kg/m³, ρh=0.2\rho_h = 0.2 kg/m³ and S=0.5S = 0.5 m/s, ρf/ρh−1=4\rho_f / \rho_h - 1 = 4. The products leave the core J=2J = 2 m/s faster than the fuel arrives, and the pressure drops by P=4⋅1⋅0.25=1P = 4 \cdot 1 \cdot 0.25 = 1 Pa. The paper uses S=0.5S = 0.5 m/s for most of its examples and compares ρh=0.2\rho_h = 0.2, 0.10.1 and 0.050.05 with ρf=1\rho_f = 1 in its figure 7:

ρh\rho_h (kg/m³) JJ (m/s) PP (Pa)
0.2 2.0 1.0
0.1 4.5 2.25
0.05 9.5 4.75

For the flamethrower of the paper's section 6, S=0.1S = 0.1 m/s, ρf=1\rho_f = 1 and ρh=0.01\rho_h = 0.01, so J=9.9J = 9.9 m/s while the fuel enters at 30 m/s.

A planar flame, measured. A channel of 16 by 3 cells of 5 cm has an injector at one end that pushes fuel at 0.5 m/s, and an open end. The front is 6.75 cells from the injector side. With the velocities of the table's first row, three steps of 0.02 s keep the front, the fuel speed 0.5 m/s and the product speed 2.5 m/s to 10−1010^{-10}, and the pressure is 1 Pa in the fuel and 0 in the products. This holds for fronts that face +x+x, −x-x and +y+y. If the whole channel starts at 0.5 m/s, one step brings the products to 2.5 m/s. The pressure of that step also holds the impulse that accelerates them: 1 Pa per cell over the 8 product cells.

A nozzle flame, measured. A grid of 12 by 16 cells of 5 cm has a wall at the bottom with a nozzle 0.2 m wide that injects fuel at 1.5 m/s, and an open top. With S=0.5S = 0.5 m/s, ρh=0.2\rho_h = 0.2 and no buoyancy, after 25 steps of 0.02 s the core reaches 0.176 m above the nozzle. With S=0.75S = 0.75 m/s it reaches only 0.023 m. The paper's equation 1, vfAf=SASv_f A_f = S A_S, says the same: the core area that burns the injected fuel shrinks as SS grows. For a triangle in 2D, it gives the heights 0.283 m and 0.173 m. The simulated cores are shorter: the fuel does not move at one speed, and the grid has only 4 cells across the nozzle.

Correctness

The claims are proved in proofs/correctness.md.

  1. Jump conditions. The formulas for VhV_h and php_h satisfy the conservation of mass and momentum exactly, and the tangential velocity does not jump.
  2. The front. For a planar front in fuel at rest, the scheme moves the front at exactly SS.
  3. The projection. If each fluid region touches an open cell, the pressure system is symmetric positive definite, and after line L8 every cell has zero divergence when the faces are read in its own material.
  4. The planar flame. The steady planar flame is an exact fixed point of the step, with the pressure jump PP.
  5. The expansion. In a channel, one step gives the fuel speed SS and the product speed S+JS + J from any start that is uniform across the channel.
  6. Temperature. The cooling is integrated exactly, and TT stays in [Tair,Tmax][T_{air}, T_{max}].

These are statements about the discrete scheme. The model itself is an approximation: a real reaction zone has a thickness, SS depends on the mixture, and in a diffusion flame the burning rate depends on how the fuel mixes with air. The paper says that the thin flame model works well for visual work, not that it is exact.

Proof: The jump conditions of the thin flame, the exactness of the planar flame, and the bounds of the stepfull

We use the line numbers of the page. φ>0\varphi > 0 in the fuel, n=∇φ/∣∇φ∣\mathbf n = \nabla \varphi / |\nabla \varphi| points into the fuel, and m=−n\mathbf m = -\mathbf n points from the fuel to the products. For the jumps, a normal velocity VV is the component along m\mathbf m. Let J=(ρf/ρh−1)SJ = (\rho_f / \rho_h - 1) S and P=(ρf/ρh−1)ρfS2P = (\rho_f / \rho_h - 1) \rho_f S^2.

Lemma 1 (the jump conditions). Let the front move with the normal speed D=Vf−SD = V_f - S (the fuel crosses it at the speed SS). Then conservation of mass, ρh(Vh−D)=ρf(Vf−D)\rho_h (V_h - D) = \rho_f (V_f - D), and of normal momentum, ρh(Vh−D)2+ph=ρf(Vf−D)2+pf\rho_h (V_h - D)^2 + p_h = \rho_f (V_f - D)^2 + p_f, hold exactly when

Vh=Vf+J,ph=pf−P.V_h = V_f + J, \qquad p_h = p_f - P.

The tangential velocity is the same on both sides.

Proof. Vf−D=SV_f - D = S, so mass gives Vh−D=ρfS/ρhV_h - D = \rho_f S / \rho_h and Vh=Vf−S+ρfS/ρh=Vf+JV_h = V_f - S + \rho_f S / \rho_h = V_f + J. Momentum gives ph=pf+ρfS2−ρh(ρfS/ρh)2=pf−(ρf/ρh−1)ρfS2p_h = p_f + \rho_f S^2 - \rho_h (\rho_f S / \rho_h)^2 = p_f - (\rho_f / \rho_h - 1) \rho_f S^2. The tangential momentum flux is the mass flux times the tangential velocity on each side, and the mass flux is the same, so the tangential velocities are equal. □\square

Since ρf>ρh\rho_f > \rho_h, J>0J > 0 and P>0P > 0: the products leave the front faster than the fuel arrives, and the pressure drops across the front. The test file checks both equations exactly with Fraction for ρf=1\rho_f = 1, ρh=1/5\rho_h = 1/5, S=1/2S = 1/2, Vf=3/2V_f = 3/2 and pf=7p_f = 7, which give D=1D = 1, Vh=7/2V_h = 7/2 and ph=6p_h = 6. In the same way, mass alone at the surface of a solid fuel with D=Vs−SD = V_s - S gives the gas speed Vs+(ρs/ρf−1)SV_s + (\rho_s / \rho_f - 1) S, the paper's equation 5.

The paper writes n=∇φ/∣∇φ∣\mathbf n = \nabla \varphi / |\nabla \varphi| in its section 4.1 and D=Vf−SD = V_f - S in section 3.2. These two agree only if VV is measured along −n-\mathbf n, as here. With VV along n\mathbf n, the signs of SS and JJ in the jump formulas change.

Lemma 2 (ghost velocities, line L3). The map from a fuel velocity u\mathbf u to its ghost product velocity is u↦u+Jm\mathbf u \mapsto \mathbf u + J \mathbf m, and its inverse is u↦u−Jm\mathbf u \mapsto \mathbf u - J \mathbf m. It keeps the tangential part and adds JJ to the normal part, as Lemma 1 requires. On a face, the code applies the same map to the face component, with the face component mnm_n of m\mathbf m. A constant field of one material maps to a constant field of the other if m\mathbf m is constant.

Proof. Direct. □\square

Lemma 3 (the front in still fuel, lines L1 and L2). Let ρf=ρh\rho_f = \rho_h, so J=0J = 0, let the fuel be at rest, and let φ(x,y)=x0−x\varphi(x, y) = x_0 - x. Then one substep of length hh gives φ−Sh\varphi - S h at every cell, so the front moves into the fuel at the speed SS exactly.

Proof. The central differences of a linear function are exact, so n=(−1,0)\mathbf n = (-1, 0) and w=(−S,0)\mathbf w = (-S, 0) at every cell. The upwind difference for w1<0w_1 < 0 is the forward difference, which is −1-1 for this φ\varphi, also at the last cell, where the code uses the other one-sided difference. So φ←φ−h(−S)(−1)\varphi \leftarrow \varphi - h (-S)(-1). The redistancing keeps a linear function of xx on each row, because the distance to the nearest crossing point on the row is ∣x−xc∣|x - x_c|. □\square

For a curved front the upwind scheme is first order. The test file burns a disk of fuel at rest with radius 0.35 m for 0.3 s at S=0.5S = 0.5 m/s. The front on the middle row ends at a radius of 0.2−0.003460.2 - 0.00346 m on a 16 by 16 grid and 0.2−0.000800.2 - 0.00080 m on a 32 by 32 grid.

Theorem 1 (the projection, lines L7 and L8). Let each connected group of FLUID cells touch an AIR cell. Then the linear system of line L7 is symmetric positive definite, so it has one solution. After line L8, every FLUID cell has zero divergence, where each face velocity is taken as the velocity of the cell's own material (Lemma 2).

Proof. For cell aa and each neighbor bb that is not SOLID, the code uses the face coefficient cab=1/ρ^abc_{ab} = 1 / \hat\rho_{ab}, where ρ^ab\hat\rho_{ab} depends only on the two cells, so cab=cba>0c_{ab} = c_{ba} > 0. The pressure of bb as seen from the material of aa is pb+πbap_b + \pi_{ba}, with πba=P\pi_{ba} = P if bb is products and aa fuel, −P-P in the other mixed case, and 0 otherwise. The equation of aa is

∑bcab(pa−pb−πba)=−Δx2Δtdiv⁡a∗,\sum_b c_{ab} \left(p_a - p_b - \pi_{ba}\right) = -\frac{\Delta x^2}{\Delta t} \operatorname{div}^*_a,

with pb=0p_b = 0 for an AIR cell. The known terms πba\pi_{ba} go to the right side, so the matrix is ∑bcab\sum_b c_{ab} on the diagonal and −cab-c_{ab} for each FLUID neighbor. This is a weighted graph Laplacian plus a positive diagonal term for each AIR neighbor. Then xTAx=∑FLUID pairscab(xa−xb)2+∑AIR facescabxa2x^\mathsf{T} A x = \sum_{\text{FLUID pairs}} c_{ab} (x_a - x_b)^2 + \sum_{\text{AIR faces}} c_{ab} x_a^2, which is zero only if xx is constant on each group and zero next to an AIR cell, so x=0x = 0. Line L8 subtracts Δt cab(pb+πba−pa)/Δx\Delta t\, c_{ab} (p_b + \pi_{ba} - p_a) / \Delta x from the face velocity. The conversion of Lemma 2 adds a constant, so the face value in the material of aa changes by the same amount. Summed over the faces of aa, the change of div⁡a\operatorname{div}_a is (Δt/Δx2)∑bcab(pa−pb−πba)(\Delta t / \Delta x^2) \sum_b c_{ab} (p_a - p_b - \pi_{ba}), which is −div⁡a∗-\operatorname{div}^*_a by the equation. □\square

The test file checks the divergence with ghost values after every step of a nozzle flame: it stays below 10−810^{-8}.

Theorem 2 (the planar flame is kept exactly). Take a channel with walls on its long sides, an injector that moves at SS into the fuel at one end, and AIR cells at the other end. Let φ\varphi be linear across the channel with its zero between two face rows, let the fuel velocity be SS along the channel and the product velocity S+JS + J, and let α=0\alpha = 0. Then one step leaves φ\varphi and the velocity unchanged, and the pressure is PP in the fuel cells and 0 in the product cells.

Proof. Lemma 3's argument gives n=−m\mathbf n = -\mathbf m constant. The fuel field of line L3 is SS on every face along the channel and the product field is S+JS + J on every face (Lemma 2), and both are 0 across the channel. (L1) In every cell, w=Sm−Sm=0\mathbf w = S \mathbf m - S \mathbf m = 0, so line L2 does not change φ\varphi, and the redistancing keeps it. (L4) Semi-Lagrangian advection keeps a constant field exactly, so each face gets back the value of its material. (L5, L6) The temperature does not act on the velocity when α=0\alpha = 0. (L7) With ghost values, every cell has zero divergence: inside one material the face values are equal, and at the front face the conversion gives the cell's own constant. So the right side is only the jump terms. Set p=Pp = P in the fuel and p=0p = 0 in the products. For a fuel cell next to a product cell, c(pa−pb−πba)=c(P−0−P)=0c (p_a - p_b - \pi_{ba}) = c (P - 0 - P) = 0, and for a product cell next to a fuel cell, c(0−P+P)=0c (0 - P + P) = 0. Inside one material the differences are zero. So this pp solves the system, and by Theorem 1 it is the only solution. (L8) Every face has pb+πba−pa=0p_b + \pi_{ba} - p_a = 0, so no velocity changes. □\square

The test file checks this for a front that faces +x+x, −x-x and +y+y, with ρf=1\rho_f = 1, ρh=0.2\rho_h = 0.2 and S=0.5S = 0.5 m/s. The products move at 2.5 m/s, the fuel pressure is P=1P = 1 Pa, and the errors are below 10−910^{-9}.

Theorem 3 (the expansion in a channel). In the channel of Theorem 2, start from any velocity along the channel that is the same across it. After one step, the fuel moves at SS and the products at S+JS + J, wherever line L2 puts the front.

Proof. Line L7 gives zero divergence with ghost values in each cell (Theorem 1). With no flow across the channel, the divergence of a cell is the difference of its two face values in its material divided by Δx\Delta x. So the face values are equal along each material, and the first one is the injector speed SS. At the front face, the product cell sees the fuel value plus JJ. So the products move at S+JS + J. □\square

In the test, a uniform start of 0.5 m/s gives 0.5 m/s in the fuel and 2.5 m/s in the products after one step. The pressure then also holds the impulse that accelerates the products: it falls by 1 Pa per cell over the 8 product cells.

Lemma 4 (the temperature, line L5). The code replaces TT by the exact solution of T′=−cT((T−Tair)/(Tmax−Tair))4T' = -c_T ((T - T_{air}) / (T_{max} - T_{air}))^4 over Δt\Delta t:

θ(Δt)=θ0(1+3cTΔt θ03/(Tmax−Tair))−1/3,θ=T−TairTmax−Tair.\theta(\Delta t) = \theta_0 \left(1 + 3 c_T \Delta t\, \theta_0^3 / (T_{max} - T_{air})\right)^{-1/3}, \qquad \theta = \frac{T - T_{air}}{T_{max} - T_{air}}.

If every TT starts in [Tair,Tmax][T_{air}, T_{max}], it stays there.

Proof. With θ′=−kθ4\theta' = -k \theta^4 and k=cT/(Tmax−Tair)k = c_T / (T_{max} - T_{air}), (θ−3)′=3k(\theta^{-3})' = 3k, which integrates to the formula. The advection takes convex combinations of values in [Tair,Tmax][T_{air}, T_{max}], because the ghost value in the fuel is TmaxT_{max}. The fuel gets Tign≤TmaxT_{ign} \le T_{max}. The cooling map is increasing in θ0\theta_0, sends 0 to 0, and is at most θ0\theta_0. □\square

The test file checks two half steps against one full step and against 20000 Euler steps, and the range after a nozzle flame.

Complexity

Let nn be the number of cells. Lines L3 to L6 and L8 cost Θ(n)\Theta(n). Line L2 costs Θ(n)\Theta(n) per substep, and the number of substeps ss is about Δtmax⁡∣w∣/(Δx/2)\Delta t \max |\mathbf w| / (\Delta x / 2). Fast marching redistancing costs O(nlog⁡n)O(n \log n); the brute force search in the code costs Θ(nc)\Theta(n c) for cc crossing points, which is good enough for the small test grids. The pressure solve of line L7 costs O(n)O(n) per conjugate gradient iteration, and it is the most expensive part. Without a preconditioner, the number kk of iterations is O(κ)O(\sqrt{\kappa}), and the density ratio raises the condition number κ\kappa. So one step costs O(sn+nlog⁡n+nk)O(s n + n \log n + n k). The space is Θ(n)\Theta(n).

Properties

  • Two flows, one grid. The fuel and the products each satisfy their own incompressible equations, and only the jump conditions couple them.
  • Sharp jumps. Ghost values keep the velocity and pressure jumps at the front, without a smeared transition zone.
  • Volume is not conserved. The front is a source of volume: the products need ρf/ρh\rho_f / \rho_h times the volume of the fuel they replace.
  • Not stable for every step. The upwind level set step has a CFL limit, so it needs substeps. The flow part uses the semi-Lagrangian step of stable fluids.
  • Controllable. SS sets the size of the core, ρf/ρh\rho_f / \rho_h sets the expansion, and the temperature curve and ε\varepsilon are free for the artist.

Variants and improvements

  • Solid fuels. Inject gas from the surface of a burning object at the speed of equation 5, and turn this on or off per voxel to light or put out parts of the object.
  • Temperature curves. Use the reaction coordinate YY and a curve shaped by hand, or the TmaxT_{max} ghost value for large flames.
  • Smoke. Carry a soot density with the products; rendered by its absorption, it shows the smoke above the flame.
  • Rendering. The paper ray marches the products as a participating medium, uses Planck's formula for the emitted spectrum, and maps it to RGB with a von Kries adaptation to the brightest color, so that the flame does not look too red.
  • Explosions and detonations. These are fast and compressible, so a different solver is needed.

When to use it

Use it for flames whose blue core and expansion matter: torches, burners, flamethrowers and burning objects at a scale where the grid resolves the core. For small flames in games, a texture or a particle system costs much less. For smoke without a reaction, use stable fluids with buoyancy and leave out the level set.

Pitfalls

  • The sign of the normal. The jump formulas need the normal from the fuel to the products. With the normal ∇φ/∣∇φ∣\nabla \varphi / |\nabla \varphi| of the level set, the signs flip. A wrong sign makes the products slower than the fuel.
  • No redistancing. The upwind step then moves the front too fast where φ\varphi is steep, and the core burns away.
  • A closed domain. The front adds volume, so the pressure system of a closed box has no solution. Give the products an outlet.
  • Mixing the two velocities. A backtrace from the products that lands in the fuel must read the ghost product velocity, not the fuel velocity. Otherwise the jump smears over a few cells.
  • Too large a level set step. The level set has a CFL limit even though the flow step does not. Use substeps.
  • Buoyancy that is too strong. With α=0.15\alpha = 0.15 m/(K s²) as in the paper's section 6 and T−TairT - T_{air} near 1700 K, the acceleration is over 250 m/s². On a coarse grid this can pull the core apart; in the nozzle test of this page, it shrinks the core to a few cells.

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.

fire_simulation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fire-simulation/. The authors are listed in prov/QHWFYD.jsonl.

"""The thin flame model of Nguyen, Fedkiw and Jensen (2002) on a 2D MAC grid.

A level set phi tracks the blue core: phi > 0 in the gaseous fuel, phi < 0
in the hot products, and the front phi = 0 moves with w = u_f + S n, where
n = grad phi / |grad phi| points into the fuel. The fuel and the products are
two incompressible fluids with densities rho_f > rho_h. Across the front the
normal velocity and the pressure jump by the amounts that conservation of
mass and momentum give (the paper's equations 2 and 3).

Sign convention for the jumps. V is the velocity component along
m = -n, the normal that points from the fuel to the products. Then the front
speed is D = V_f - S, V_h = V_f + (rho_f / rho_h - 1) S and
p_h = p_f - (rho_f / rho_h - 1) rho_f S^2.

Storage. g.u and g.v hold one velocity per face: the velocity of the
material at the face (the sign of phi averaged from the two cells). The
other material's velocity at a face is its ghost value (the paper's
equations 12 and 13): add or subtract J m with J = (rho_f / rho_h - 1) S.

Cells: FLUID cells hold fuel or products, AIR cells are an open outlet with
p = 0 (each group of FLUID cells needs one), SOLID cells are walls or
fuel injectors. phi and T are not changed in SOLID cells.
"""

import math

import macgrid
from macgrid import AIR, FLUID, SOLID


class Fire:
    """The state of the fire: a MAC grid g (velocity and labels), phi and T in the cells, and the constants."""

    def __init__(self, g, phi, rho_f=1.0, rho_h=0.2, S=0.5, T_air=300.0, T_ign=1500.0,
                 T_max=2000.0, c_T=3000.0, alpha=0.15):
        if not rho_f >= rho_h > 0.0 or S < 0.0 or not T_air < T_ign <= T_max:
            raise ValueError("need rho_f >= rho_h > 0, S >= 0 and T_air < T_ign <= T_max")
        self.g = g
        self.phi = phi
        self.rho_f, self.rho_h, self.S = rho_f, rho_h, S
        self.T_air, self.T_ign, self.T_max = T_air, T_ign, T_max
        self.c_T, self.alpha = c_T, alpha
        self.T = [[T_ign if phi[i][j] > 0.0 else T_air for j in range(g.ny)] for i in range(g.nx)]

    def J(self):
        """The jump of the normal velocity, V_h - V_f = (rho_f / rho_h - 1) S."""
        return (self.rho_f / self.rho_h - 1.0) * self.S

    def P(self):
        """The jump of the pressure, p_f - p_h = (rho_f / rho_h - 1) rho_f S^2."""
        return (self.rho_f / self.rho_h - 1.0) * self.rho_f * self.S * self.S


def jump_conditions(rho_f, rho_h, S, V_f, p_f):
    """Solve the paper's equations 2 and 3 for the products. Returns (D, V_h, p_h).

    V is along the normal from the fuel to the products. Exact with Fraction input.
    """
    D = V_f - S
    V_h = V_f + (rho_f / rho_h - 1) * S
    p_h = p_f - (rho_f / rho_h - 1) * rho_f * S * S
    return D, V_h, p_h


def solid_fuel_velocity(V_s, rho_s, rho_f, S):
    """The paper's equation 5: the velocity of the gas that leaves a burning solid, V_f = V_s + (rho_s / rho_f - 1) S."""
    return V_s + (rho_s / rho_f - 1) * S


def ghost_velocity(u, m, J, to_hot):
    """Equation 13 for a vector u of one material: the other material's velocity at the same point.

    m is the unit normal from the fuel to the products. The tangential part is
    kept and the normal part changes by +J (fuel to hot) or -J (hot to fuel).
    """
    s = J if to_hot else -J
    return tuple(a + s * b for a, b in zip(u, m))


def _phi_or(phi, i, j, default):
    if 0 <= i < len(phi) and 0 <= j < len(phi[0]):
        return phi[i][j]
    return default


def normals(phi, dx):
    """n = grad phi / |grad phi| at the cell centers by central differences (one sided at the border)."""
    na, nb = len(phi), len(phi[0])
    nx_, ny_ = macgrid.zeros(na, nb), macgrid.zeros(na, nb)
    for i in range(na):
        for j in range(nb):
            a0, a1 = max(i - 1, 0), min(i + 1, na - 1)
            b0, b1 = max(j - 1, 0), min(j + 1, nb - 1)
            gx = (phi[a1][j] - phi[a0][j]) / ((a1 - a0) * dx) if a1 > a0 else 0.0
            gy = (phi[i][b1] - phi[i][b0]) / ((b1 - b0) * dx) if b1 > b0 else 0.0
            r = math.hypot(gx, gy)
            if r > 0.0:
                nx_[i][j], ny_[i][j] = gx / r, gy / r
    return nx_, ny_


def _face_side(st, i0, j0, i1, j1):
    """For the face between cells (i0, j0) and (i1, j1): (phi at the face, m component along the face normal)."""
    phi = st.phi
    g = st.g
    inside = [(a, b) for (a, b) in ((i0, j0), (i1, j1)) if 0 <= a < g.nx and 0 <= b < g.ny]
    pf = sum(phi[a][b] for a, b in inside) / len(inside)
    return pf, inside


def face_data(st):
    """Per face: True if the face holds fuel, and m_n, the component of m = -n along the face normal.

    Returns (fuel_u, mu, fuel_v, mv) indexed like g.u and g.v.
    """
    g = st.g
    nxs, nys = normals(st.phi, g.dx)
    fuel_u = [[False] * g.ny for _ in range(g.nx + 1)]
    fuel_v = [[False] * (g.ny + 1) for _ in range(g.nx)]
    mu = macgrid.zeros(g.nx + 1, g.ny)
    mv = macgrid.zeros(g.nx, g.ny + 1)
    for i in range(g.nx + 1):
        for j in range(g.ny):
            pf, inside = _face_side(st, i - 1, j, i, j)
            fuel_u[i][j] = pf > 0.0
            mu[i][j] = -sum(nxs[a][b] for a, b in inside) / len(inside)
    for i in range(g.nx):
        for j in range(g.ny + 1):
            pf, inside = _face_side(st, i, j - 1, i, j)
            fuel_v[i][j] = pf > 0.0
            mv[i][j] = -sum(nys[a][b] for a, b in inside) / len(inside)
    return fuel_u, mu, fuel_v, mv


def material_fields(st, fd=None):
    """The fuel and the hot velocity fields on all faces, with ghost values on the other side. Returns (uf, vf, uh, vh)."""
    g = st.g
    J = st.J()
    fuel_u, mu, fuel_v, mv = fd if fd is not None else face_data(st)
    uf, uh = macgrid.copy_field(g.u), macgrid.copy_field(g.u)
    vf, vh = macgrid.copy_field(g.v), macgrid.copy_field(g.v)
    for i in range(g.nx + 1):
        for j in range(g.ny):
            if fuel_u[i][j]:
                uh[i][j] = g.u[i][j] + J * mu[i][j]  # @line L3
            else:
                uf[i][j] = g.u[i][j] - J * mu[i][j]
    for i in range(g.nx):
        for j in range(g.ny + 1):
            if fuel_v[i][j]:
                vh[i][j] = g.v[i][j] + J * mv[i][j]
            else:
                vf[i][j] = g.v[i][j] - J * mv[i][j]
    return uf, vf, uh, vh


def level_set_step(st, dt, cfl=0.5):
    """Move phi by the paper's equation 7 with w = u_f + S n and upwind differences, in substeps. Returns the substep count."""
    g = st.g
    dx = g.dx
    uf, vf, _, _ = material_fields(st)
    nxs, nys = normals(st.phi, dx)
    w1 = [[0.5 * (uf[i][j] + uf[i + 1][j]) + st.S * nxs[i][j] for j in range(g.ny)] for i in range(g.nx)]  # @line L1
    w2 = [[0.5 * (vf[i][j] + vf[i][j + 1]) + st.S * nys[i][j] for j in range(g.ny)] for i in range(g.nx)]
    wmax = max(max(abs(a) for col in w1 for a in col), max(abs(a) for col in w2 for a in col))
    steps = max(1, int(math.ceil(dt * wmax / (cfl * dx) - 1e-12)))
    h = dt / steps
    for _ in range(steps):
        phi = st.phi
        new = macgrid.copy_field(phi)
        for i in range(g.nx):
            for j in range(g.ny):
                if g.label[i][j] == SOLID:
                    continue
                a, b = w1[i][j], w2[i][j]
                back_x = (phi[i][j] - phi[i - 1][j]) / dx if i > 0 else None
                fwd_x = (phi[i + 1][j] - phi[i][j]) / dx if i < g.nx - 1 else None
                back_y = (phi[i][j] - phi[i][j - 1]) / dx if j > 0 else None
                fwd_y = (phi[i][j + 1] - phi[i][j]) / dx if j < g.ny - 1 else None
                px = back_x if (a > 0.0 and back_x is not None) or fwd_x is None else fwd_x
                py = back_y if (b > 0.0 and back_y is not None) or fwd_y is None else fwd_y
                new[i][j] = phi[i][j] - h * (a * (px or 0.0) + b * (py or 0.0))  # @line L2
        st.phi = new
    st.phi = redistance(st.phi, dx, g.label)
    return steps


def redistance(phi, dx, label=None):
    """Make phi a signed distance again away from the front, keeping the front.

    Cells next to the front (a neighbor of the other sign) keep their values.
    Every other cell gets its sign times the distance to the nearest crossing
    point of phi = 0 on a grid edge (linear interpolation). This brute force
    search stands in for the fast marching method of the paper; it is Θ(cells
    times crossings). SOLID cells keep their values.
    """
    na, nb = len(phi), len(phi[0])
    pts = []
    near = [[False] * nb for _ in range(na)]
    for i in range(na):
        for j in range(nb):
            for a, b in ((i + 1, j), (i, j + 1)):
                if a < na and b < nb and (phi[i][j] > 0.0) != (phi[a][b] > 0.0):
                    t = phi[i][j] / (phi[i][j] - phi[a][b])
                    pts.append(((i + 0.5 + t * (a - i)) * dx, (j + 0.5 + t * (b - j)) * dx))
                    near[i][j] = near[a][b] = True
    if not pts:
        return macgrid.copy_field(phi)
    out = macgrid.copy_field(phi)
    for i in range(na):
        for j in range(nb):
            if near[i][j] or (label is not None and label[i][j] == SOLID):
                continue
            x, y = (i + 0.5) * dx, (j + 0.5) * dx
            d = math.sqrt(min((x - px) ** 2 + (y - py) ** 2 for px, py in pts))
            out[i][j] = d if phi[i][j] > 0.0 else -d
    return out


def _grid_with(g, u, v):
    t = macgrid.make_grid(g.nx, g.ny, g.dx)
    t.u, t.v, t.label = u, v, g.label
    return t


def advect_velocity(st, dt, phi_old):
    """Advect the fuel field by itself and the hot field by itself; each face keeps the field of its new material."""
    g = st.g
    phi_new = st.phi
    st.phi = phi_old
    uf, vf, uh, vh = material_fields(st)
    st.phi = phi_new
    gf, gh = _grid_with(g, uf, vf), _grid_with(g, uh, vh)
    auf, avf = macgrid.advect_velocity(gf, dt)
    auh, avh = macgrid.advect_velocity(gh, dt)
    fuel_u, _, fuel_v, _ = face_data(st)
    g.u = [[auf[i][j] if fuel_u[i][j] else auh[i][j] for j in range(g.ny)] for i in range(g.nx + 1)]  # @line L4
    g.v = [[avf[i][j] if fuel_v[i][j] else avh[i][j] for j in range(g.ny + 1)] for i in range(g.nx)]
    return gh


def cool(st, T, dt):
    """Integrate T' = -c_T ((T - T_air) / (T_max - T_air))^4 exactly over dt (the source term of equation 17)."""
    if T <= st.T_air:
        return T
    span = st.T_max - st.T_air
    th = (T - st.T_air) / span
    th = th / (1.0 + 3.0 * st.c_T * dt * th ** 3 / span) ** (1.0 / 3.0)
    return st.T_air + span * th


def update_temperature(st, dt, phi_old, gh):
    """Advect T by the hot velocity with the ghost value T_max in the old fuel, set T_ign in the fuel, then cool."""
    g = st.g
    Tg = [[st.T_max if phi_old[i][j] > 0.0 else st.T[i][j] for j in range(g.ny)] for i in range(g.nx)]
    adv = macgrid.advect(gh, Tg, dt)
    for i in range(g.nx):
        for j in range(g.ny):
            if g.label[i][j] == SOLID:
                continue
            if st.phi[i][j] > 0.0:
                st.T[i][j] = st.T_ign
            else:
                st.T[i][j] = cool(st, adv[i][j], dt)  # @line L5


def add_buoyancy(st, dt):
    """The paper's equation 14: v += dt alpha (T - T_air) on faces that do not touch a SOLID cell."""
    g = st.g
    for i in range(g.nx):
        for j in range(1, g.ny):
            if macgrid.is_solid_v_face(g, i, j):
                continue
            Tf = 0.5 * (st.T[i][j - 1] + st.T[i][j])
            g.v[i][j] += dt * st.alpha * (Tf - st.T_air)  # @line L6


def _jump_from(st, fuel_from, fuel_to):
    """The pressure jump p_to - p_from at the front between two materials."""
    if fuel_from == fuel_to:
        return 0.0
    return -st.P() if fuel_from else st.P()


def _rho_hat(st, phi_a, phi_b):
    """The density of a face between two cells (Liu, Fedkiw and Kang 2000): the mix by the length on each side."""
    fa, fb = phi_a > 0.0, phi_b > 0.0
    ra = st.rho_f if fa else st.rho_h
    rb = st.rho_f if fb else st.rho_h
    if fa == fb:
        return ra
    th = abs(phi_a) / (abs(phi_a) + abs(phi_b))
    return th * ra + (1.0 - th) * rb


def _faces_of(g, i, j):
    """The four faces of cell (i, j): (neighbor, 'u' or 'v', face index, sign of the outward normal)."""
    return (((i - 1, j), "u", (i, j), -1.0), ((i + 1, j), "u", (i + 1, j), 1.0),
            ((i, j - 1), "v", (i, j), -1.0), ((i, j + 1), "v", (i, j + 1), 1.0))


def jump_divergence(st, fd=None):
    """The divergence of every FLUID cell, with each face velocity taken as the cell's own material (ghost values)."""
    g = st.g
    J = st.J()
    fuel_u, mu, fuel_v, mv = fd if fd is not None else face_data(st)
    d = macgrid.zeros(g.nx, g.ny)
    for i in range(g.nx):
        for j in range(g.ny):
            if g.label[i][j] != FLUID:
                continue
            fuel = st.phi[i][j] > 0.0
            s = 0.0
            for _, kind, (a, b), sgn in _faces_of(g, i, j):
                if kind == "u":
                    val, ff, m = g.u[a][b], fuel_u[a][b], mu[a][b]
                else:
                    val, ff, m = g.v[a][b], fuel_v[a][b], mv[a][b]
                if ff and not fuel:
                    val += J * m
                elif fuel and not ff:
                    val -= J * m
                s += sgn * val
            d[i][j] = s / g.dx
    return d


def _cg(diag, off, b, tol, max_iter):
    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
    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 = [diag[k] * d[k] - sum(c * d[m] for m, c in off[k]) for k in range(n)]
        dq = sum(d[k] * q[k] for k in range(n))
        if dq <= 0.0:
            break
        a = rr / dq
        for k in range(n):
            x[k] += a * d[k]
            r[k] -= a * 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(st, dt, solid_velocity=None, tol=1e-12):
    """Solve div(grad p / rho) = div u* / dt with the jumps by the ghost fluid method, and subtract the gradient.

    The pressure of a neighbor of the other material is converted to the cell's
    material with the jump P, and each face uses 1 / rho_hat. The matrix is
    symmetric and positive definite when each group of FLUID cells touches an
    AIR cell. Stores p in g.p and returns the CG iteration count.
    """
    g = st.g
    dx = g.dx
    macgrid.set_solid_boundaries(g, solid_velocity)
    fd = face_data(st)
    div = jump_divergence(st, fd)
    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, off, b = [], [], []
    for (i, j) in cells:
        fa = st.phi[i][j] > 0.0
        dg, of = 0.0, []
        rhs = -dx * dx / dt * div[i][j]
        for (a, c), _, _, _ in _faces_of(g, i, j):
            lab = macgrid.cell_label(g, a, c)
            if lab == SOLID:
                continue
            coef = 1.0 / _rho_hat(st, st.phi[i][j], st.phi[a][c])
            dg += coef
            rhs += coef * _jump_from(st, st.phi[a][c] > 0.0, fa)  # @line L7
            if lab == FLUID:
                of.append((idx[(a, c)], coef))
        diag.append(dg)
        off.append(of)
        b.append(rhs)
    x, it = _cg(diag, off, b, tol, max(100, 4 * len(cells)))
    g.p = macgrid.zeros(g.nx, g.ny)
    for k, (i, j) in enumerate(cells):
        g.p[i][j] = x[k]
    for i in range(1, g.nx):
        for j in range(g.ny):
            _correct(st, dt, "u", i, j, (i - 1, j), (i, j))
    for i in range(g.nx):
        for j in range(1, g.ny):
            _correct(st, dt, "v", i, j, (i, j - 1), (i, j))
    return it


def _correct(st, dt, kind, i, j, ca, cb):
    g = st.g
    la, lb = g.label[ca[0]][ca[1]], g.label[cb[0]][cb[1]]
    if la == SOLID or lb == SOLID or (la != FLUID and lb != FLUID):
        return
    pa, pb = st.phi[ca[0]][ca[1]], st.phi[cb[0]][cb[1]]
    jump = _jump_from(st, pb > 0.0, pa > 0.0)  # p_b seen in the material of a
    grad = (g.p[cb[0]][cb[1]] + jump - g.p[ca[0]][ca[1]]) / g.dx
    s = dt / _rho_hat(st, pa, pb) * grad
    if kind == "u":
        g.u[i][j] -= s  # @line L8
    else:
        g.v[i][j] -= s


def step(st, dt, solid_velocity=None):
    """One step of the fire: level set, velocity advection with ghost values, temperature, buoyancy and the projection."""
    phi_old = macgrid.copy_field(st.phi)
    level_set_step(st, dt)
    gh = advect_velocity(st, dt, phi_old)
    update_temperature(st, dt, phi_old, gh)
    add_buoyancy(st, dt)
    return project(st, dt, solid_velocity)


def max_jump_divergence(st):
    """The largest |divergence| over FLUID cells, with ghost values."""
    d = jump_divergence(st)
    return max((abs(d[i][j]) for i in range(st.g.nx) for j in range(st.g.ny) if st.g.label[i][j] == FLUID), default=0.0)


def fuel_cells(st):
    """The number of FLUID cells with phi > 0."""
    g = st.g
    return sum(1 for i in range(g.nx) for j in range(g.ny) if g.label[i][j] == FLUID and st.phi[i][j] > 0.0)
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_fire_simulation.py 213 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fire-simulation/. The authors are listed in prov/QHWFYD.jsonl.

"""Tests of the thin flame fire model on the MAC grid of macgrid.py."""

import math
import random
from fractions import Fraction as Fr

import pytest

import macgrid
from macgrid import AIR, SOLID
import fire_simulation as F

DX = 0.05


def planar(orientation, init="steady"):
    """A planar flame in a channel: fuel enters at 0.5 m/s through an injector and the products leave through AIR cells.

    orientation is "right" (fuel moves in +x), "left" (in -x) or "up" (in +y).
    The front is at 6.75 cells from the injector side. With init "steady" the
    velocity is the steady solution; with "uniform" it is 0.5 m/s everywhere.
    """
    long_, short = 16, 3
    up = orientation == "up"
    nx, ny = (short, long_) if up else (long_, short)
    g = macgrid.make_grid(nx, ny, DX)
    sgn = -1.0 if orientation == "left" else 1.0
    pos = (lambda i, j: (j + 0.5) * DX) if up else (
        (lambda i, j: (i + 0.5) * DX) if sgn > 0 else (lambda i, j: (nx - i - 0.5) * DX))
    for i in range(nx):
        for j in range(ny):
            k = j if up else (i if sgn > 0 else nx - 1 - i)
            if k == 0:
                g.label[i][j] = SOLID
            elif k == long_ - 1:
                g.label[i][j] = AIR
    x0 = 6.75 * DX
    phi = [[x0 - pos(i, j) for j in range(ny)] for i in range(nx)]
    st = F.Fire(g, phi, alpha=0.0)
    S, J = st.S, st.J()
    if up:
        for i in range(nx):
            for j in range(ny + 1):
                g.v[i][j] = S if init == "uniform" or j * DX < x0 else S + J
        inj = (lambda x, y: (0.0, S))
    else:
        for i in range(nx + 1):
            for j in range(ny):
                d = i * DX if sgn > 0 else (nx - i) * DX
                g.u[i][j] = sgn * (S if init == "uniform" or d < x0 else S + J)
        inj = (lambda x, y: (sgn * S, 0.0))
    return st, inj


def line(st, orientation, field):
    """The values of a face field (u, v) or a cell field along the channel, from the injector side."""
    g = st.g
    if field == "p":
        q = g.p
        if orientation == "up":
            return [q[1][j] for j in range(g.ny)]
        r = [q[i][1] for i in range(g.nx)]
        return r if orientation == "right" else r[::-1]
    if orientation == "up":
        return [g.v[1][j] for j in range(g.ny + 1)]
    r = [g.u[i][1] for i in range(g.nx + 1)]
    return r if orientation == "right" else [-t for t in r[::-1]]


def test_jump_conditions_are_exact():
    rho_f, rho_h, S, V_f, p_f = Fr(1), Fr(1, 5), Fr(1, 2), Fr(3, 2), Fr(7)
    D, V_h, p_h = F.jump_conditions(rho_f, rho_h, S, V_f, p_f)
    assert rho_h * (V_h - D) == rho_f * (V_f - D)  # mass, equation 2
    assert rho_h * (V_h - D) ** 2 + p_h == rho_f * (V_f - D) ** 2 + p_f  # momentum, equation 3
    assert (D, V_h, p_h) == (Fr(1), Fr(7, 2), Fr(6))
    assert F.jump_conditions(rho_f, rho_f, S, V_f, p_f) == (Fr(1), V_f, p_f)
    rho_s, V_s = Fr(500), Fr(0)
    V_g = F.solid_fuel_velocity(V_s, rho_s, rho_f, S)
    D_s = V_s - S
    assert rho_f * (V_g - D_s) == rho_s * (V_s - D_s)  # equation 4
    assert V_g == Fr(499, 2)


def test_ghost_velocity_round_trip():
    rng = random.Random(3)
    for _ in range(20):
        a = rng.uniform(0.0, 2.0 * math.pi)
        m = (math.cos(a), math.sin(a))
        u = (rng.uniform(-2, 2), rng.uniform(-2, 2))
        h = F.ghost_velocity(u, m, 2.0, True)
        back = F.ghost_velocity(h, m, 2.0, False)
        assert max(abs(x - y) for x, y in zip(back, u)) < 1e-14
        dn = (h[0] - u[0]) * m[0] + (h[1] - u[1]) * m[1]
        dt_ = (h[0] - u[0]) * -m[1] + (h[1] - u[1]) * m[0]
        assert abs(dn - 2.0) < 1e-14 and abs(dt_) < 1e-14


def test_planar_front_in_still_fuel_moves_at_flame_speed():
    g = macgrid.make_grid(12, 3, DX)
    phi = [[0.4 - (i + 0.5) * DX for j in range(3)] for i in range(12)]
    st = F.Fire(g, phi, rho_h=1.0, S=0.5)
    for _ in range(10):
        F.level_set_step(st, 0.01)
    assert max(abs(st.phi[i][j] - (0.35 - (i + 0.5) * DX)) for i in range(12) for j in range(3)) < 1e-12


def disk_error(n):
    dx = 1.0 / n
    g = macgrid.make_grid(n, n, dx)
    phi = [[0.35 - math.hypot((i + 0.5) * dx - 0.5, (j + 0.5) * dx - 0.5) for j in range(n)] for i in range(n)]
    st = F.Fire(g, phi, rho_h=1.0, S=0.5)
    for _ in range(6):
        F.level_set_step(st, 0.05)
    j = n // 2
    row = [st.phi[i][j] for i in range(n)]
    i = max(k for k in range(n - 1) if row[k] > 0.0 >= row[k + 1])
    xc = (i + 0.5 + row[i] / (row[i] - row[i + 1])) * dx
    return math.hypot(xc - 0.5, (j + 0.5) * dx - 0.5) - 0.2


def test_burning_disk_shrinks_at_flame_speed():
    e16, e32 = disk_error(16), disk_error(32)
    assert abs(e16 + 0.00346) < 1e-4 and abs(e32 + 0.00080) < 1e-4
    assert abs(e32) < abs(e16) / 2.0


@pytest.mark.parametrize("orientation", ["right", "left", "up"])
def test_steady_planar_flame_is_kept_exactly(orientation):
    st, inj = planar(orientation)
    phi0 = macgrid.copy_field(st.phi)
    for _ in range(3):
        F.step(st, 0.02, inj)
    vel = line(st, orientation, "u")
    assert all(abs(t - 0.5) < 1e-10 for t in vel[1:7])  # fuel
    assert all(abs(t - 2.5) < 1e-10 for t in vel[7:-1])  # products, 0.5 + (1 / 0.2 - 1) 0.5
    p = line(st, orientation, "p")
    assert all(abs(t - 1.0) < 1e-9 for t in p[1:7])  # p_f - p_h = (1 / 0.2 - 1) 1 0.5^2
    assert all(abs(t) < 1e-9 for t in p[7:])
    assert max(abs(a - b) for c1, c2 in zip(st.phi, phi0) for a, b in zip(c1, c2)) < 1e-12
    assert F.max_jump_divergence(st) < 1e-10


def test_expansion_accelerates_the_products():
    st, inj = planar("right", "uniform")
    F.step(st, 0.02, inj)
    vel = line(st, "right", "u")
    assert all(abs(t - 0.5) < 1e-10 for t in vel[1:7])
    assert all(abs(t - 2.5) < 1e-10 for t in vel[7:-1])
    assert abs(line(st, "right", "p")[1] - 9.72) < 1e-9  # includes the impulse that accelerates the products


def test_cooling_is_integrated_exactly():
    g = macgrid.make_grid(2, 2, DX)
    st = F.Fire(g, [[-1.0, -1.0], [-1.0, -1.0]])
    T = 1900.0
    one = F.cool(st, T, 0.02)
    two = F.cool(st, F.cool(st, T, 0.01), 0.01)
    assert abs(one - two) < 1e-9
    th0 = (T - 300.0) / 1700.0
    th = (th0 ** -3 + 3.0 * 3000.0 * 0.02 / 1700.0) ** (-1.0 / 3.0)
    assert abs(one - (300.0 + 1700.0 * th)) < 1e-9
    y, n = T, 20000
    for _ in range(n):
        y -= 0.02 / n * 3000.0 * ((y - 300.0) / 1700.0) ** 4
    assert abs(one - y) < 1e-3
    assert F.cool(st, 300.0, 1.0) == 300.0 and F.cool(st, 250.0, 1.0) == 250.0


def test_buoyancy_force():
    g = macgrid.make_grid(3, 4, DX)
    st = F.Fire(g, [[-1.0] * 4 for _ in range(3)], alpha=0.15)
    st.T = [[300.0 + 100.0 * (i + j) for j in range(4)] for i in range(3)]
    F.add_buoyancy(st, 0.1)
    for i in range(3):
        assert g.v[i][0] == 0.0 and g.v[i][4] == 0.0
        for j in range(1, 4):
            assert abs(g.v[i][j] - 0.1 * 0.15 * 100.0 * (i + j - 0.5)) < 1e-12


def plume(S, steps=25):
    nx, ny = 12, 16
    c = nx * DX / 2.0
    g = macgrid.make_grid(nx, ny, DX)
    for i in range(nx):
        g.label[i][0] = SOLID
        g.label[i][ny - 1] = AIR
    phi = [[min(0.1 - abs((i + 0.5) * DX - c), 0.1 - (j + 0.5) * DX) for j in range(ny)] for i in range(nx)]
    st = F.Fire(g, phi, S=S, alpha=0.0)
    inj = (lambda x, y: (0.0, 1.5 if abs(x - c) < 0.1 else 0.0))
    for _ in range(steps):
        F.step(st, 0.02, inj)
    col = [st.phi[nx // 2][j] for j in range(ny)]
    top = max(j for j in range(ny) if col[j] > 0.0)
    return st, (top + 0.5 + col[top] / (col[top] - col[top + 1])) * DX - DX


def test_nozzle_flame():
    st, h = plume(0.5)
    assert abs(h - 0.1761) < 1e-3  # height of the blue core above the nozzle, in m
    assert F.max_jump_divergence(st) < 1e-8
    Ts = [st.T[i][j] for i in range(st.g.nx) for j in range(1, st.g.ny)]
    assert st.T_air <= min(Ts) and max(Ts) <= st.T_max
    _, h_fast = plume(0.75)
    assert h_fast < h / 4.0  # a faster flame speed gives a smaller core


def test_bad_constants():
    g = macgrid.make_grid(2, 2, DX)
    with pytest.raises(ValueError):
        F.Fire(g, [[1.0, 1.0], [1.0, 1.0]], rho_f=0.1, rho_h=0.2)

History

Markstein (1964) first proposed the thin flame model in combustion science. Before 2002, fire in graphics used textured shapes, flame spread models, or a given velocity field that carried temperature and density with an advection-diffusion equation (Stam and Fiume 1995). Fedkiw, Aslam, Merriman and Osher (1999) introduced the ghost fluid method for jumps at interfaces in compressible flow, and Nguyen, Fedkiw and Kang (2001) used it for incompressible flames with the jump conditions. In 2002, Nguyen, Fedkiw and Jensen brought this solver to animation, together with the blue core, solid fuels, objects that catch fire, and blackbody rendering with chromatic adaptation.

References

  1. 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), sections 3.1 to 3.3 (blue core, equation 1; jump conditions, equations 2 and 3; solid fuels, equations 4 and 5), section 4 (level set, equations 6 and 7; ghost velocities, equations 12 and 13; buoyancy and vorticity confinement, equations 14 and 15; temperature, equations 16 and 17), section 6 (the constants)
  2. Duc Q. Nguyen, Ronald P. Fedkiw and Myungjoo Kang, A boundary condition capturing method for incompressible flame discontinuities, Journal of Computational Physics 172, 71-98, 2001, the pressure solve with the jump conditions, which the fire paper refers to
  3. Ronald P. Fedkiw, Tariq Aslam, Barry Merriman and Stanley Osher, A non-oscillatory Eulerian approach to interfaces in multimaterial flows (the ghost fluid method), Journal of Computational Physics 152, 457-492, 1999, the ghost fluid method
  4. Stanley Osher and James A. Sethian, Fronts propagating with curvature-dependent speed: algorithms based on Hamilton-Jacobi formulations, Journal of Computational Physics 79(1), 12-49, 1988, the level set method

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.level_set
  • a full proof of time.pressure
  • a full proof of time.redistance
  • a full proof of time.step
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example