Algorithm Search⌘K

Algorithmadvanced

Ghost fluid method

Treats a material interface given by a level set by filling ghost cells with values that carry the interface jump conditions, so it is not smeared.

Time
Θ(N M) worst
Space
Θ(M) extra
Where
M = the number of grid cells; N = the number of time steps
Properties
not conservativedeterministicexplicitsharp interface
Origin
R. P. Fedkiw, T. Aslam, B. Merriman, S. Osher, X. D. Liu, M. Kang, 1999

The ghost fluid method (GFM) computes two fluids that meet at a sharp interface on one fixed grid, without smearing the interface over several cells. A level set function ϕ\phi marks the interface: ϕ<0\phi < 0 in one fluid and ϕ>0\phi > 0 in the other. Near the interface, each fluid gets ghost cells on the other side. Their values are chosen so that the jump conditions of the interface hold, and then each fluid is computed with an ordinary single-fluid scheme. In compressible flow (Fedkiw, Aslam, Merriman and Osher, 1999), a ghost cell takes the pressure and the velocity of the real fluid in that cell and the entropy of its own fluid. In an incompressible pressure solve (Liu, Fedkiw and Kang, 2000), the known jumps of the pressure and of its normal derivative go into the right-hand side of the Poisson equation, and the matrix stays symmetric. Water, smoke and fire solvers in graphics usually use the simplest case, a free surface where the pressure is zero at the level set, with the fractional distance θ\theta to the interface in the stencil. The full method adds jumps in density, viscosity and equation of state, surface tension as a pressure jump, and moving material interfaces in gas dynamics. Its price is that it is not exactly conservative, and its error at the interface is of first order.

In plain words

When water meets air, or one gas meets another, the two materials follow different rules, and a numerical method that mixes them in the cells near the interface gives wrong values there, such as false pressure jumps. The ghost fluid method does not mix. For each material it imagines that the material continues a little beyond the interface, into "ghost" cells. It fills those cells with values that agree with the other material on what must be equal at the interface, the pressure and the speed, and it keeps the material's own character there. Then each material is computed alone with a standard method, and each cell keeps the result of the material that is really in it.

The problem

Two ideal gases with ratios of specific heats γ0\gamma_0 and γ1\gamma_1 fill a tube. Each follows the Euler equations Ut+F(U)x=0U_t + F(U)_x = 0 with U=(ρ,ρu,E)U = (\rho, \rho u, E) and p=(γk−1)(E−12ρu2)p = (\gamma_k - 1)(E - \tfrac12\rho u^2). They meet at a contact discontinuity, where pressure and velocity are continuous and density, entropy and γ\gamma jump. The interface moves with the fluid. Compute the flow on a fixed grid of MM cells, so that the interface stays sharp and the pressure has no spurious oscillations there.

The algorithm

Each cell holds UiU_i and ϕi\phi_i. The fluid of cell ii is k(i)=0k(i) = 0 if ϕi≤0\phi_i \le 0, else 11. One time step:

  1. GHOST-FLUID-STEP(U, φ, γ_0, γ_1, Δx, Δt)
  2. 1for k ∈ {0, 1}: in each cell of the other fluid put the ghost state (ρ_g, u, p), with u and p of the real state and ρ_g = (p/s)^(1/γ_k), where s = p/ρ^γ_k at the nearest cell of fluid k
  3. 2U^(k) ← one step of a single-fluid scheme with γ_k on all cells, real and ghost
  4. 3φ ← one upwind step of φ_t + u φ_x = 0 with the cell velocities
  5. 4for each cell i: U_i ← U^(k)_i, where k is the fluid given by the sign of the new φ_i

L1 extrapolates the entropy s=p/ργks = p/\rho^{\gamma_k} of fluid kk across the interface as a constant, and copies pp and uu, the quantities that are continuous at a contact. The reference code uses the Rusanov flux in L2 and the nearest real cell in L1. In two and three dimensions the constant extrapolation is done by solving qτ±n⋅∇q=0q_\tau \pm n\cdot\nabla q = 0 for a few pseudo-time steps, with n=∇ϕ/∣∇ϕ∣n = \nabla\phi/|\nabla\phi|.

The pressure solve. For (βux)x=f(\beta u_x)_x = f with β=β−\beta = \beta^- on the left of an interface at α\alpha and β+\beta^+ on the right, and jumps [u]=a[u] = a, [βux]=b[\beta u_x] = b, let xk≤α<xk+1x_k \le \alpha < x_{k+1} and θ=(α−xk)/Δx\theta = (\alpha - x_k)/\Delta x. Liu, Fedkiw and Kang replace β\beta at the face k+12k + \tfrac12 by

β^=β+β−β+θ+β−(1−θ),\hat\beta = \frac{\beta^+\beta^-}{\beta^+\theta + \beta^-(1 - \theta)},

add β^a/Δx2+β^b(1−θ)/(β+Δx)\hat\beta a/\Delta x^2 + \hat\beta b(1 - \theta)/(\beta^+\Delta x) to the right-hand side at node kk, and add −β^a/Δx2+β^bθ/(β−Δx)-\hat\beta a/\Delta x^2 + \hat\beta b\theta/(\beta^-\Delta x) at node k+1k + 1. All other rows are the standard three-point stencil. The matrix is symmetric and negative definite. In the pressure equation of a projection method, β=1/ρ\beta = 1/\rho. For water under air with a=b=0a = b = 0, the limit β+→∞\beta^+ \to \infty gives β^=β−/θ\hat\beta = \beta^-/\theta, which is the free-surface condition p=0p = 0 at the interface used in graphics.

Example

Ghost values by hand. Air (γ0=1.4\gamma_0 = 1.4) with ρ=1\rho = 1, p=1p = 1 on the left, and helium (γ1=53\gamma_1 = \tfrac53) with ρ=0.125\rho = 0.125, p=0.1p = 0.1 on the right, both at rest. For air, the ghost cell on the helium side gets u=0u = 0, p=0.1p = 0.1 and the air entropy s=1s = 1, so ρg=0.11/1.4=0.1931\rho_g = 0.1^{1/1.4} = 0.1931. For helium, the ghost cell on the air side gets p=1p = 1 and the helium entropy s=0.1/0.1255/3=3.200s = 0.1/0.125^{5/3} = 3.200, so ρg=(1/3.200)3/5=0.4976\rho_g = (1/3.200)^{3/5} = 0.4976. Each gas now sees a single-gas shock tube with its own γ\gamma on the whole grid.

Moving contact. p=1p = 1 and u=0.5u = 0.5 everywhere, ρ=1\rho = 1 (air) for x<0.3x < 0.3 and ρ=0.1\rho = 0.1 (helium) to the right, 100 cells, T=0.2T = 0.2. GFM keeps pp and uu to 10−1210^{-12}, the density stays a perfect step, and the interface is at x=0.4x = 0.4, within one cell. The conservative one-fluid Rusanov scheme with the γ\gamma of each cell taken from ϕ\phi makes pressure errors larger than 5% at the interface, the oscillations first explained by Abgrall (1996).

Two-gas shock tube (measurement). The data of the example by hand, T=0.15T = 0.15, Courant number 0.5. The exact solution, from a two-γ\gamma exact Riemann solver, has p∗=0.3144p^* = 0.3144 and u∗=0.9014u^* = 0.9014, so the contact is at x=0.6352x = 0.6352.

cells L1L^1 error of ρ\rho, GFM L1L^1 error of ρ\rho, one-fluid pp within 0.03 of the contact, GFM same, one-fluid mass error, GFM
100 2.17e-2 2.31e-2 0.3143 to 0.3145 0.320 to 0.353 -4.6e-3
200 1.37e-2 1.58e-2 0.3143 to 0.3143 0.256 to 0.365 -2.8e-3
400 8.84e-3 1.06e-2 0.3143 to 0.3143 0.278 to 0.387 -1.9e-3

GFM has no pressure oscillation at the contact, and the one-fluid scheme has oscillations of about 20% that do not shrink with the grid. The price is a small loss of mass, because each fluid is computed on its own grid and the flux at the interface face is not shared. The interface is at 0.615, 0.6225 and 0.626 for 100, 200 and 400 cells: it lags because the first-order scheme smears the velocity near the interface at early times.

Pressure solve with jumps. With β−=1\beta^- = 1, β+=10\beta^+ = 10 and a solution that is linear on each side, the discrete solution is exact to rounding. With u=exu = e^x on the left of α=0.4321\alpha = 0.4321, u=cos⁡xu = \cos x on the right, and the matching ff, aa and bb, the largest error is 3.8e-3, 3.0e-3, 4.6e-4, 1.2e-3 and 3.8e-4 for 20 to 320 cells. It is below 0.25Δx0.25\Delta x on every grid. It is first order but not monotone in Δx\Delta x, because it depends on θ\theta.

Correctness

The proof is in proofs/correctness.md. It shows that one GFM step keeps a contact with uniform pressure and velocity exactly in exact arithmetic, for any densities and any two values of γ\gamma: each fluid sees a single-gas contact, which the Rusanov scheme keeps, and the upwind level set step moves a linear ϕ\phi exactly with the flow. It also shows that the pressure-solve discretization is exact for solutions that are linear on each side and that its matrix is symmetric and negative definite, so the solve has a unique solution.

Proof: The ghost fluid step keeps contacts exactly, and the pressure discretization with jumps is exact for piecewise linear solutions and uniquely solvablefull

Setting. The grid has MM cells of width Δx\Delta x, with transmissive ends (the end cells are copied into one ghost cell on each side). The single-fluid scheme in L2 is the conservative Rusanov scheme Ui←Ui−λ(Fi+1/2−Fi−1/2)U_i \leftarrow U_i - \lambda(F_{i+1/2} - F_{i-1/2}), λ=Δt/Δx\lambda = \Delta t/\Delta x, with

Fi+1/2=12(F(Ui)+F(Ui+1))−12si+1/2(Ui+1−Ui),F_{i+1/2} = \tfrac12\big(F(U_i) + F(U_{i+1})\big) - \tfrac12 s_{i+1/2}(U_{i+1} - U_i),

where si+1/2≥0s_{i+1/2} \ge 0 is one number for all three components. All arithmetic is exact.

Lemma 1 (one gas keeps a contact). Let one gas with ratio γ\gamma have ui=uu_i = u and pi=pp_i = p in every cell, and any densities ρi>0\rho_i > 0. After one Rusanov step, uu and pp are unchanged in every cell.

Proof. Write Gi+1/2G_{i+1/2} for the mass component of Fi+1/2F_{i+1/2}. Since ρu\rho u is uu times ρ\rho and ρu2+p=u⋅ρu+p\rho u^2 + p = u\cdot\rho u + p, the momentum component is uGi+1/2+puG_{i+1/2} + p. Since E=pγ−1+12ρu2E = \frac{p}{\gamma - 1} + \tfrac12\rho u^2 and (E+p)u=γpuγ−1+12u2⋅ρu(E + p)u = \frac{\gamma pu}{\gamma - 1} + \tfrac12u^2\cdot\rho u, the energy component is γpuγ−1+12u2Gi+1/2\frac{\gamma pu}{\gamma - 1} + \tfrac12u^2G_{i+1/2}, and the differences Ui+1−UiU_{i+1} - U_i in the dissipation term give the same factors uu and 12u2\tfrac12u^2 times the density difference. So the new state is ρi′=ρi−λ(Gi+1/2−Gi−1/2)\rho_i' = \rho_i - \lambda(G_{i+1/2} - G_{i-1/2}), (ρu)i′=uρi′(\rho u)_i' = u\rho_i', and Ei′=pγ−1+12u2ρi′E_i' = \frac{p}{\gamma - 1} + \tfrac12u^2\rho_i', because the constant parts of the flux cancel in the difference. Hence ui′=uu_i' = u and pi′=pp_i' = p. If some ρi′≤0\rho_i' \le 0 the step is not defined; under the CFL condition λs≤1\lambda s \le 1 the density update is a convex combination, so ρi′>0\rho_i' > 0. □\square

Lemma 2 (the level set moves exactly). If ϕi=xi−c\phi_i = x_i - c and every cell velocity is uu, then after L3, ϕi=xi−c−uΔt\phi_i = x_i - c - u\Delta t.

Proof. Every one-sided difference of a linear function, including the one-sided ones at the ends, equals Δx\Delta x. So L3 gives ϕi−λuΔx=ϕi−uΔt\phi_i - \lambda u\Delta x = \phi_i - u\Delta t. □\square

Theorem 1 (contacts). Let the two fluids have ui=uu_i = u and pi=pp_i = p everywhere, with any densities and with γ0≠γ1\gamma_0 \ne \gamma_1, and let ϕ\phi be linear. Then after one GFM step, ui=uu_i = u and pi=pp_i = p in every cell, and the interface has moved by uΔtu\Delta t.

Proof. In L1, every ghost state of fluid kk has velocity uu and pressure pp, because it copies them from the real state of its cell, and its density (p/s)1/γk(p/s)^{1/\gamma_k} is positive. So the array that fluid kk advances in L2 is one gas with ratio γk\gamma_k, uniform uu and pp. By Lemma 1, all of its new states have velocity uu and pressure pp for the ratio γk\gamma_k. By Lemma 2, L3 moves the zero of ϕ\phi by uΔtu\Delta t. L4 gives cell ii a state of the fluid kk that the new ϕi\phi_i assigns, and it reads that state with the same γk\gamma_k, so it has velocity uu and pressure pp. □\square

The conservative one-fluid scheme does not have this property. Its momentum and density updates still give u′=uu' = u, but in a cell next to the interface the energy flux on one side is computed with γ0\gamma_0 and on the other with γ1\gamma_1, so the constant parts γkpuγk−1\frac{\gamma_k pu}{\gamma_k - 1} do not cancel, and p′p' differs from pp by O(λpu ∣γ0γ0−1−γ1γ1−1∣)O(\lambda pu\,|\frac{\gamma_0}{\gamma_0 - 1} - \frac{\gamma_1}{\gamma_1 - 1}|) in that cell.

Setting for the pressure solve. Nodes xi=iΔxx_i = i\Delta x, i=0,…,ni = 0, \dots, n, with u0u_0 and unu_n given, the interface at α\alpha with xk≤α<xk+1x_k \le \alpha < x_{k+1}, 0<k<n−10 < k < n - 1, and θ=(α−xk)/Δx∈[0,1)\theta = (\alpha - x_k)/\Delta x \in [0, 1). The equation is (βux)x=f(\beta u_x)_x = f, with β=β±>0\beta = \beta^\pm > 0 on the two sides and jumps u(α+)−u(α−)=au(\alpha^+) - u(\alpha^-) = a, β+ux(α+)−β−ux(α−)=b\beta^+u_x(\alpha^+) - \beta^-u_x(\alpha^-) = b.

Lemma 3 (the interface flux). Let ww be a function that is linear on [xk,α][x_k, \alpha] and on [α,xk+1][\alpha, x_{k+1}], with values uku_k and uk+1u_{k+1} at the nodes, and with the two jumps aa and bb at α\alpha. Then its flux on the left side is

β−wx(α−)=β^(uk+1−uk−aΔx−b(1−θ)β+),β+wx(α+)=β^(uk+1−uk−aΔx+bθβ−),\beta^-w_x(\alpha^-) = \hat\beta\Big(\frac{u_{k+1} - u_k - a}{\Delta x} - \frac{b(1 - \theta)}{\beta^+}\Big),\qquad \beta^+w_x(\alpha^+) = \hat\beta\Big(\frac{u_{k+1} - u_k - a}{\Delta x} + \frac{b\theta}{\beta^-}\Big),

with β^=β+β−/(β+θ+β−(1−θ))\hat\beta = \beta^+\beta^-/(\beta^+\theta + \beta^-(1 - \theta)).

Proof. Let v=w(α−)v = w(\alpha^-), so w(α+)=v+aw(\alpha^+) = v + a. The slopes are (v−uk)/(θΔx)(v - u_k)/(\theta\Delta x) and (uk+1−v−a)/((1−θ)Δx)(u_{k+1} - v - a)/((1 - \theta)\Delta x), and the flux jump condition is β+uk+1−v−a(1−θ)Δx−β−v−ukθΔx=b\beta^+\frac{u_{k+1} - v - a}{(1 - \theta)\Delta x} - \beta^-\frac{v - u_k}{\theta\Delta x} = b. This is one linear equation for vv with the positive coefficient β+1−θ+β−θ\frac{\beta^+}{1 - \theta} + \frac{\beta^-}{\theta} (for θ=0\theta = 0 take v=ukv = u_k). Solving it gives v−uk=θβ+θ+β−(1−θ)(β+(uk+1−uk−a)−bΔx(1−θ))v - u_k = \frac{\theta}{\beta^+\theta + \beta^-(1 - \theta)}\big(\beta^+(u_{k+1} - u_k - a) - b\Delta x(1 - \theta)\big), and multiplying by β−/(θΔx)\beta^-/(\theta\Delta x) gives the first formula. The second is the first plus bb, and b−β^b(1−θ)/β+=bβ+θ/(β+θ+β−(1−θ))=β^bθ/β−b - \hat\beta b(1 - \theta)/\beta^+ = b\beta^+\theta/(\beta^+\theta + \beta^-(1 - \theta)) = \hat\beta b\theta/\beta^-. □\square

The rows kk and k+1k + 1 of the discretization are the flux balances (β−wx(α−)−β−uk−uk−1Δx)/Δx=fk\big(\beta^-w_x(\alpha^-) - \beta^-\frac{u_k - u_{k-1}}{\Delta x}\big)/\Delta x = f_k and (β+uk+2−uk+1Δx−β+wx(α+))/Δx=fk+1\big(\beta^+\frac{u_{k+2} - u_{k+1}}{\Delta x} - \beta^+w_x(\alpha^+)\big)/\Delta x = f_{k+1}. Moving the known terms of Lemma 3 to the right side gives exactly the β^\hat\beta face coefficient and the two right-hand side corrections on the main page.

Theorem 2 (exactness for linear pieces). If the exact solution uu is linear on [0,α)[0, \alpha) and on (α,1](\alpha, 1] (so f=0f = 0), the discrete solution equals uu at every node.

Proof. Insert the exact nodal values. In every row away from the interface, the three-point stencil of a linear function with constant β\beta is zero. In rows kk and k+1k + 1 the function ww of Lemma 3 is the exact uu, so β±wx(α±)\beta^\pm w_x(\alpha^\pm) are the exact one-sided fluxes, which equal β−ux\beta^-u_x on the left and β+ux\beta^+u_x on the right. Each flux balance is then the difference of two equal fluxes, which is 0=f0 = f. So the exact values satisfy the system, and by Theorem 3 the system has only one solution. □\square

Theorem 3 (unique solution). The matrix of the discrete system is symmetric and negative definite, so the solve has a unique solution and the Thomas algorithm runs without a zero pivot.

Proof. Every row has the form (ci+1/2(ui+1−ui)−ci−1/2(ui−ui−1))/Δx2(c_{i+1/2}(u_{i+1} - u_i) - c_{i-1/2}(u_i - u_{i-1}))/\Delta x^2 with face coefficients c>0c > 0 (β−\beta^-, β+\beta^+ or β^\hat\beta, which is positive). The off-diagonal entry between nodes ii and i+1i + 1 is ci+1/2/Δx2c_{i+1/2}/\Delta x^2 in both rows, so the matrix is symmetric. For a vector vv with v0=vn=0v_0 = v_n = 0, summation by parts gives vTAv=−∑ici+1/2(vi+1−vi)2/Δx2<0v^TAv = -\sum_{i} c_{i+1/2}(v_{i+1} - v_i)^2/\Delta x^2 < 0 unless v=0v = 0. A symmetric negative definite tridiagonal matrix has nonzero leading minors, so Gaussian elimination without pivoting, which is the Thomas algorithm, does not break down. □\square

Termination. One GFM step is a fixed number of passes over the MM cells (two sweeps for the nearest cells, two flux sweeps, one level set sweep, one selection). The time loop takes steps of at least min⁡(CFL Δx/smax⁡,T−t)\min(\text{CFL}\,\Delta x/s_{\max}, T - t) with smax⁡s_{\max} finite, so it ends after finitely many steps. The Thomas algorithm makes two passes over n−1n - 1 unknowns.

■\blacksquare

Complexity

One step costs about twice a single-fluid step: two flux sweeps over the grid, plus the extrapolation and the level set step, so Θ(M)\Theta(M) per step and Θ(NM)\Theta(NM) in all. In practice only a band of a few cells around the interface needs ghost values, so the second fluid can be computed in a narrow band. The pressure solve is a sparse symmetric system with the same pattern as the standard Poisson matrix, so the same conjugate gradient or multigrid solvers work.

Properties

  • The interface is sharp: no cell holds a mixture.
  • Contacts with uniform pressure and velocity are kept exactly, with no pressure oscillations.
  • Not conservative: mass, momentum and energy change by an amount that goes to zero with the grid, about 0.5% of the mass at 200 cells in the shock tube.
  • First order at the interface for the Euler equations and for the Poisson equation with jumps.
  • Any single-fluid scheme can be used in L2, including high-order WENO schemes.
  • The Poisson matrix is symmetric, so conjugate gradients with the usual preconditioners apply.

Variants and improvements

  • Isobaric fix. Fedkiw et al. also set the entropy of the first real cells next to the interface from their neighbours, which removes overheating errors when a shock hits a wall or an interface.
  • Real GFM and modified GFM. For strong shocks at the interface, the ghost states come from a Riemann problem at the interface instead of from the real fluid, which fixes the errors of the original method for large impedance jumps.
  • Boundary condition capturing. The Poisson form with jumps (Liu, Fedkiw and Kang) and its use for incompressible flow of two fluids with surface tension (Kang, Fedkiw and Liu).
  • Free surfaces in graphics. One fluid only, p=0p = 0 at ϕ=0\phi = 0, and the stencil uses θ\theta: the ghost pressure is pg=(θ−1)pi/θp_g = (\theta - 1)p_i/\theta. Combined with a particle level set this is the standard water solver.
  • Flames and detonations. The interface moves relative to the fluid, and the jump conditions are the Rankine-Hugoniot conditions of a deflagration, as in the graphics fire model of Nguyen, Fedkiw and Jensen.
  • Second-order versions. Symmetric second-order discretizations exist for the Dirichlet case and for some jump problems, at the cost of a more complex stencil.

When to use it

Use GFM when an interface between materials with different equations of state or properties must stay sharp, and when exact conservation across the interface matters less than the absence of oscillations: multimaterial compressible flow, bubbles and droplets, water and fire in graphics. When exact conservation of mass matters (for example over a long run of a two-phase flow), volume of fluid or conservative cut-cell methods are better. For interfaces that carry forces from elastic bodies, the immersed boundary method is the usual choice.

Pitfalls

  • Extrapolating density instead of entropy. Constant extrapolation of ρ\rho across a contact with a pressure gradient gives the wrong ghost state. Extrapolate ss and compute ρ\rho from pp and ss.
  • Expecting conservation. The method loses or gains a small amount of mass at the interface in each step. Check the total in long runs.
  • Strong shocks at the interface. Copying pp and uu from the real fluid is wrong when a strong shock crosses an interface with a large impedance jump. Use a Riemann-problem based ghost state.
  • Level set drift. The level set loses its distance property and mass over time. Reinitialize it, or use a particle level set.
  • Small θ\theta in the pressure solve. For θ→0\theta \to 0 the free-surface stencil has a large diagonal entry. Clamp θ\theta to a small minimum such as 10−310^{-3}.
  • Mixing up the sides of the jumps. aa and bb are right value minus left value. A sign error gives a solution that looks smooth but is wrong by O(1)O(1).

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.

ghost_fluid_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ghost-fluid-method/. The authors are listed in prov/73K8P0.jsonl.
"""The ghost fluid method of Fedkiw, Aslam, Merriman and Osher (1999) in one
space dimension, for two ideal gases with different ratios of specific heats,
and the ghost fluid discretization of Liu, Fedkiw and Kang (2000) for the 1D
Poisson equation (beta u')' = f with jumps [u] = a and [beta u'] = b.

Gas states are tuples (rho, rho u, E). The level set phi is negative in
fluid 0 and positive in fluid 1. Boundaries are transmissive.
"""

import math


def prim(U, g):
    rho, m, E = U
    if rho <= 0:
        raise ValueError("nonpositive density")
    u = m / rho
    return rho, u, (g - 1) * (E - 0.5 * rho * u * u)


def cons(rho, u, p, g):
    return rho, rho * u, p / (g - 1) + 0.5 * rho * u * u


def phys_flux(U, g):
    rho, u, p = prim(U, g)
    return rho * u, rho * u * u + p, (U[2] + p) * u


def speed(U, g):
    rho, u, p = prim(U, g)
    return abs(u) + math.sqrt(g * max(p, 0.0) / rho)


def rusanov(UL, UR, gl, gr):
    """Rusanov flux; gl and gr are the ratios of specific heats of the two states."""
    FL, FR = phys_flux(UL, gl), phys_flux(UR, gr)
    s = max(speed(UL, gl), speed(UR, gr))
    return tuple(0.5 * (fl + fr) - 0.5 * s * (ur - ul)
                 for fl, fr, ul, ur in zip(FL, FR, UL, UR))


def fv_step(U, gs, dx, dt):
    """One conservative Rusanov step with cell-wise gamma gs and transmissive ends."""
    m = len(U)
    E = [U[0]] + U + [U[-1]]
    G = [gs[0]] + gs + [gs[-1]]
    F = [rusanov(E[i], E[i + 1], G[i], G[i + 1]) for i in range(m + 1)]
    lam = dt / dx
    return [tuple(U[i][c] - lam * (F[i + 1][c] - F[i][c]) for c in range(3)) for i in range(m)]


def advect_level_set(phi, vel, dx, dt):
    """First-order upwind step for phi_t + u phi_x = 0 with cell velocities."""
    m = len(phi)
    out = []
    for i in range(m):
        u = vel[i]
        if u >= 0:
            d = phi[i] - phi[i - 1] if i > 0 else phi[1] - phi[0]
        else:
            d = phi[i + 1] - phi[i] if i < m - 1 else phi[-1] - phi[-2]
        out.append(phi[i] - dt / dx * u * d)
    return out


def _nearest(side, k):
    """Index of the nearest cell with side == k, for every cell (None if none)."""
    m = len(side)
    left, right = [None] * m, [None] * m
    last = None
    for i in range(m):
        if side[i] == k:
            last = i
        left[i] = last
    last = None
    for i in range(m - 1, -1, -1):
        if side[i] == k:
            last = i
        right[i] = last
    out = []
    for i in range(m):
        a, b = left[i], right[i]
        if a is None:
            out.append(b)
        elif b is None or i - a <= b - i:
            out.append(a)
        else:
            out.append(b)
    return out


def ghost_states(W, side, k, g):
    """Primitive states seen by fluid k: real cells of fluid k, ghost cells elsewhere."""
    near = _nearest(side, k)
    ext = []
    for i, (rho, u, p) in enumerate(W):
        if side[i] == k:
            ext.append((rho, u, p))
        else:
            r0, _, p0 = W[near[i]]
            s = p0 / r0 ** g                       # entropy of the nearest fluid-k cell
            ext.append(((p / s) ** (1.0 / g), u, p))
    return ext


def gfm_step(U, phi, gammas, dx, dt):
    side = [0 if v <= 0 else 1 for v in phi]
    W = [prim(U[i], gammas[side[i]]) for i in range(len(U))]
    new = {}
    for k in (0, 1):
        if k not in side:
            continue
        g = gammas[k]
        # @line L1: ghost cells of fluid k take p and u of the real fluid and the entropy of fluid k
        ext = ghost_states(W, side, k, g)
        # @line L2: one step of the single-fluid scheme for fluid k on the whole grid
        new[k] = fv_step([cons(r, u, p, g) for r, u, p in ext], [g] * len(U), dx, dt)
    # @line L3: move the level set with the fluid velocity
    phi = advect_level_set(phi, [w[1] for w in W], dx, dt)
    # @line L4: each cell keeps the new state of the fluid that the new level set gives
    U = [new[0 if phi[i] <= 0 else 1][i] for i in range(len(U))]
    return U, phi


def naive_step(U, phi, gammas, dx, dt):
    """Conservative one-fluid scheme with the gamma of each cell from the level set."""
    side = [0 if v <= 0 else 1 for v in phi]
    gs = [gammas[s] for s in side]
    vel = [prim(U[i], gs[i])[1] for i in range(len(U))]
    return fv_step(U, gs, dx, dt), advect_level_set(phi, vel, dx, dt)


def run(step, U, phi, gammas, dx, T, cfl=0.5):
    t = 0.0
    while t < T - 1e-14:
        side = [0 if v <= 0 else 1 for v in phi]
        smax = max(speed(U[i], gammas[side[i]]) for i in range(len(U)))
        dt = min(cfl * dx / smax, T - t)
        U, phi = step(U, phi, gammas, dx, dt)
        t += dt
    return U, phi


def primitives(U, phi, gammas):
    return [prim(U[i], gammas[0 if phi[i] <= 0 else 1]) for i in range(len(U))]


def gfm_poisson_1d(n, alpha, beta_minus, beta_plus, f, a, b, u_left, u_right):
    """Solve (beta u')' = f on [0, 1] with u(0), u(1) given and an interface at alpha.

    beta = beta_minus on [0, alpha) and beta_plus on (alpha, 1]. The jumps are
    u(alpha+) - u(alpha-) = a and beta u'(alpha+) - beta u'(alpha-) = b.
    Nodes x_i = i / n; returns the list of nodes and the values u_0, ..., u_n.
    """
    h = 1.0 / n
    x = [i * h for i in range(n + 1)]
    k = int(alpha / h)
    if not (0 < k < n - 1) or x[k] > alpha or alpha >= x[k + 1]:
        raise ValueError("interface must lie strictly inside the grid")
    theta = (alpha - x[k]) / h
    bhat = beta_minus * beta_plus / (beta_plus * theta + beta_minus * (1 - theta))
    face = []                                     # beta at faces i + 1/2, i = 0..n-1
    for i in range(n):
        face.append(bhat if i == k else (beta_minus if i < k else beta_plus))
    lo, di, up, rhs = [], [], [], []
    for i in range(1, n):
        lo.append(face[i - 1] / h ** 2)
        di.append(-(face[i - 1] + face[i]) / h ** 2)
        up.append(face[i] / h ** 2)
        r = f(x[i])
        if i == k:
            r += bhat * a / h ** 2 + bhat * b * (1 - theta) / (beta_plus * h)
        elif i == k + 1:
            r += -bhat * a / h ** 2 + bhat * b * theta / (beta_minus * h)
        rhs.append(r)
    rhs[0] -= lo[0] * u_left
    rhs[-1] -= up[-1] * u_right
    # Thomas algorithm (the matrix is symmetric and negative definite)
    m = n - 1
    c, d = [0.0] * m, [0.0] * m
    c[0], d[0] = up[0] / di[0], rhs[0] / di[0]
    for i in range(1, m):
        den = di[i] - lo[i] * c[i - 1]
        c[i] = up[i] / den
        d[i] = (rhs[i] - lo[i] * d[i - 1]) / den
    u = [0.0] * m
    u[-1] = d[-1]
    for i in range(m - 2, -1, -1):
        u[i] = d[i] - c[i] * u[i + 1]
    return x, [u_left] + u + [u_right]
test_ghost_fluid_method.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ghost-fluid-method/. The authors are listed in prov/73K8P0.jsonl.

import math

import pytest

from ghost_fluid_method import (cons, gfm_poisson_1d, gfm_step, ghost_states, naive_step,
                                primitives, run)

AIR, HELIUM = 1.4, 5.0 / 3.0


# ---------------------------------------------------------------- reference
def exact_riemann(WL, WR, gl, gr, s):
    """Exact solution of the Riemann problem for two ideal gases at x / t = s."""
    rl, ul, pl = WL
    rr, ur, pr = WR
    cl, cr = math.sqrt(gl * pl / rl), math.sqrt(gr * pr / rr)

    def fk(p, rk, pk, ck, g):
        if p > pk:
            A, B = 2 / ((g + 1) * rk), (g - 1) / (g + 1) * pk
            return (p - pk) * math.sqrt(A / (p + B))
        return 2 * ck / (g - 1) * ((p / pk) ** ((g - 1) / (2 * g)) - 1)

    lo, hi = 1e-12, 1e4
    for _ in range(200):
        mid = 0.5 * (lo + hi)
        if fk(mid, rl, pl, cl, gl) + fk(mid, rr, pr, cr, gr) + ur - ul > 0:
            hi = mid
        else:
            lo = mid
    ps = 0.5 * (lo + hi)
    us = 0.5 * (ul + ur) + 0.5 * (fk(ps, rr, pr, cr, gr) - fk(ps, rl, pl, cl, gl))
    if s <= us:
        g, mu = gl, (gl - 1) / (gl + 1)
        if ps > pl:
            if s <= ul - cl * math.sqrt((g + 1) / (2 * g) * ps / pl + (g - 1) / (2 * g)):
                return WL
            return rl * (ps / pl + mu) / (mu * ps / pl + 1), us, ps
        if s <= ul - cl:
            return WL
        if s >= us - cl * (ps / pl) ** ((g - 1) / (2 * g)):
            return rl * (ps / pl) ** (1 / g), us, ps
        c = 2 / (g + 1) * (cl + (g - 1) / 2 * (ul - s))
        return rl * (c / cl) ** (2 / (g - 1)), 2 / (g + 1) * (cl + (g - 1) / 2 * ul + s), \
            pl * (c / cl) ** (2 * g / (g - 1))
    g, mu = gr, (gr - 1) / (gr + 1)
    if ps > pr:
        if s >= ur + cr * math.sqrt((g + 1) / (2 * g) * ps / pr + (g - 1) / (2 * g)):
            return WR
        return rr * (ps / pr + mu) / (mu * ps / pr + 1), us, ps
    if s >= ur + cr:
        return WR
    if s <= us + cr * (ps / pr) ** ((g - 1) / (2 * g)):
        return rr * (ps / pr) ** (1 / g), us, ps
    c = 2 / (g + 1) * (cr - (g - 1) / 2 * (ur - s))
    return rr * (c / cr) ** (2 / (g - 1)), 2 / (g + 1) * (-cr + (g - 1) / 2 * ur + s), \
        pr * (c / cr) ** (2 * g / (g - 1))


def setup(m, WL, WR, x0=0.5):
    dx = 1.0 / m
    xs = [(i + 0.5) * dx for i in range(m)]
    phi = [x - x0 for x in xs]
    U = [cons(*(WL if x < x0 else WR), AIR if x < x0 else HELIUM) for x in xs]
    return xs, dx, U, phi


# ---------------------------------------------------------------- tests
def test_ghost_states_keep_pressure_velocity_and_own_entropy():
    W = [(1.0, 0.1, 1.0), (1.0, 0.1, 1.0), (0.2, 0.1, 1.0), (0.2, 0.1, 1.0)]
    side = [0, 0, 1, 1]
    ext = ghost_states(W, side, 0, AIR)
    assert ext[:2] == W[:2]
    assert all(abs(r - 1.0) < 1e-15 and u == 0.1 and p == 1.0 for r, u, p in ext[2:])
    ext = ghost_states(W, side, 1, HELIUM)
    assert all(abs(r - 0.2) < 1e-15 for r, _, _ in ext[:2])


def test_moving_contact_keeps_pressure_and_velocity():
    # Uniform p = 1 and u = 0.5, density and gamma jump: only the interface moves.
    xs, dx, U, phi = setup(100, (1.0, 0.5, 1.0), (0.1, 0.5, 1.0), x0=0.3)
    Ug, pg = run(gfm_step, U, phi, (AIR, HELIUM), dx, 0.2)
    Wg = primitives(Ug, pg, (AIR, HELIUM))
    assert max(abs(p - 1.0) for _, _, p in Wg) < 1e-12
    assert max(abs(u - 0.5) for _, u, _ in Wg) < 1e-12
    k = next(i for i, v in enumerate(pg) if v > 0)
    assert abs(xs[k] - 0.4) <= dx                    # the contact is at 0.3 + 0.5 * 0.2
    assert all(abs(r - (1.0 if i < k else 0.1)) < 1e-12 for i, (r, _, _) in enumerate(Wg))
    Un, pn = run(naive_step, U, phi, (AIR, HELIUM), dx, 0.2)
    Wn = primitives(Un, pn, (AIR, HELIUM))
    assert max(abs(p - 1.0) for _, _, p in Wn) > 0.05


def test_two_gas_shock_tube_against_the_exact_solution():
    WL, WR, T = (1.0, 0.0, 1.0), (0.125, 0.0, 0.1), 0.15
    errs = []
    for m in (100, 200):
        xs, dx, U, phi = setup(m, WL, WR)
        Ug, pg = run(gfm_step, U, phi, (AIR, HELIUM), dx, T)
        Wg = primitives(Ug, pg, (AIR, HELIUM))
        ex = [exact_riemann(WL, WR, AIR, HELIUM, (x - 0.5) / T) for x in xs]
        errs.append(sum(abs(a[0] - b[0]) for a, b in zip(Wg, ex)) * dx)
    assert errs[0] < 0.03 and errs[1] < 0.7 * errs[0]


def test_interface_position_and_pressure_at_the_contact():
    WL, WR, T = (1.0, 0.0, 1.0), (0.125, 0.0, 0.1), 0.15
    _, us, ps = exact_riemann(WL, WR, AIR, HELIUM, 0.0)
    xc = 0.5 + us * T
    xs, dx, U, phi = setup(200, WL, WR)
    Ug, pg = run(gfm_step, U, phi, (AIR, HELIUM), dx, T)
    k = next(i for i, v in enumerate(pg) if v > 0)
    assert abs(xs[k] - xc) < 0.015
    near = [i for i, x in enumerate(xs) if abs(x - xc) < 0.03]
    Wg = primitives(Ug, pg, (AIR, HELIUM))
    assert max(abs(Wg[i][2] - ps) for i in near) < 1e-3
    Un, pn = run(naive_step, U, phi, (AIR, HELIUM), dx, T)
    Wn = primitives(Un, pn, (AIR, HELIUM))
    assert max(abs(Wn[i][2] - ps) for i in near) > 0.03


def test_poisson_with_jumps_is_exact_for_piecewise_linear_solutions():
    # u = 2x on the left, 3x + 1 on the right of alpha; beta = 1 and 10.
    al = 0.437
    a = (3 * al + 1) - 2 * al
    b = 10 * 3 - 1 * 2
    x, u = gfm_poisson_1d(40, al, 1.0, 10.0, lambda s: 0.0, a, b, 0.0, 4.0)
    for xi, ui in zip(x, u):
        assert abs(ui - (2 * xi if xi < al else 3 * xi + 1)) < 1e-12


def test_poisson_with_jumps_converges():
    al, bm, bp = 0.4321, 1.0, 10.0

    def exact(s):
        return math.exp(s) if s < al else math.cos(s)

    a = math.cos(al) - math.exp(al)
    b = bp * (-math.sin(al)) - bm * math.exp(al)
    f = (lambda s: math.exp(s) if s < al else -bp * math.cos(s))
    errs = []
    for n in (20, 40, 80, 160, 320):
        x, u = gfm_poisson_1d(n, al, bm, bp, f, a, b, 1.0, math.cos(1.0))
        errs.append((n, max(abs(ui - exact(xi)) for xi, ui in zip(x, u))))
    # First order: the error is below 0.25 h on every grid; it depends on theta.
    assert all(e < 0.25 / n for n, e in errs) and errs[-1][1] < 5e-4


def test_rejects_interface_on_the_boundary():
    with pytest.raises(ValueError):
        gfm_poisson_1d(10, 0.01, 1.0, 1.0, lambda s: 0.0, 0.0, 0.0, 0.0, 0.0)

History

Fedkiw, Aslam, Merriman and Osher (1999) introduced the ghost fluid method for compressible flows with several materials, as a way to avoid the pressure oscillations of conservative capturing schemes at material interfaces, which Abgrall had studied. Liu, Fedkiw and Kang (2000) applied the idea to the Poisson equation, and Kang, Fedkiw and Liu (2000) to incompressible multiphase flow with surface tension. Fedkiw and his students then used it for water, smoke and fire in computer graphics, where its free-surface form is the standard pressure boundary condition.

References

  1. 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(2) (1999) 457-492, the ghost cells with the pressure and velocity of the real fluid and the entropy of the ghost fluid, the isobaric fix, the one-dimensional tests
  2. Xu-Dong Liu, Ronald P. Fedkiw and Myungjoo Kang, A boundary condition capturing method for Poisson's equation on irregular domains, Journal of Computational Physics 160(1) (2000) 151-178, the one-dimensional derivation with the effective coefficient, the jumps in u and in beta u_n, the convergence proof
  3. Myungjoo Kang, Ronald P. Fedkiw and Xu-Dong Liu, A boundary condition capturing method for multiphase incompressible flow, Journal of Scientific Computing 15(3) (2000) 323-360, the jumps in density and viscosity and the surface tension as a pressure jump in the projection

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 proofH1 sketch
  • a full proof of time.worst
  • 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