Algorithm Search⌘K

Algorithmcore

Volume of fluid method

Also called VOF method.

Tracks a free surface by the fraction of each cell filled with one fluid, advected conservatively and reconstructed as an interface.

Time
Θ(K N^2) worst
Space
Θ(N^2) extra
Where
K = the number of time steps; N = the number of cells along each side of the grid
Properties
conserves volume exactlydeterministiceulerianoperator split
Origin
Cyril W. Hirt, Billy D. Nichols, 1981

The volume of fluid (VOF) method follows the surface of a liquid on a fixed grid by storing, in each cell, the fraction FF of the cell that is filled with liquid: 1 in the liquid, 0 in the air, and a value in between in the cells that the surface cuts. Each time step moves liquid between cells through their faces, so no liquid is created or lost. In fluid animation the surface is more often tracked with a level set or with marker particles, because they give a smooth surface for rendering, and VOF is the usual choice in engineering codes. What the accurate method adds is exact conservation of the liquid volume to rounding error, the bound 0≤F≤10 \le F \le 1 by construction, and geometric fluxes that keep the surface within one or two cells instead of letting it spread.

In plain words

Think of a grid laid over a glass of water. For every square of the grid, write down how full it is with water, from 0 to 1. That table of numbers is all the method stores. To move the water, look at each wall between two squares and ask how much water crosses it in one time step. The squares far from the surface are full or empty, so that is easy. Near the surface the answer depends on where the water is inside the square, which the numbers alone do not say. The donor-acceptor rule of Hirt and Nichols guesses the shape from the neighbors: if the surface faces the flow, the water at the front leaves only after the air in front of it has gone. Water moves only from one square to the next, so the total is exact.

The problem

Given volume fractions Fij∈[0,1]F_{ij} \in [0, 1] on an N×NN \times N periodic grid of cells of side Δx=1/N\Delta x = 1/N over the unit square, and a velocity field (u,v)(u, v) with zero divergence, approximate the solution of the advection equation

∂tF+u ∂xF+v ∂yF=0\partial_tF + u\,\partial_xF + v\,\partial_yF = 0

for FF the indicator of the liquid, after KK steps of size Δt\Delta t. The output must keep ∑FijΔx2\sum F_{ij}\Delta x^2, the liquid volume, and stay in [0,1][0, 1]. The velocity is given on cell faces as u(y)u(y) on the faces normal to xx and v(x)v(x) on the faces normal to yy. Solid body rotation u=−ω(y−12)u = -\omega(y - \frac12), v=ω(x−12)v = \omega(x - \frac12) and uniform translation are of this form. The grid index ii is along xx and jj along yy.

The algorithm

  1. VOF-ADVECT(F, Δt, K, u, v)
  2. 1for k ← 0 to K - 1
  3. 2for each sweep, x then y if k is even, else y then x ▷ operator splitting
  4. 3for each face: D ← upstream cell, A ← downstream cell ▷ donor and acceptor
  5. 4c ← |w| Δt / Δx ▷ w is the face velocity, c ≤ 1
  6. 5F_AD ← F_A if the interface in D is normal to the sweep, else F_D
  7. 6q ← min(F_AD c + max((1 - F_AD) c - (1 - F_D), 0), F_D)
  8. 7F_D ← F_D - q; F_A ← F_A + q ▷ with all q from the old F
  9. 8return F

Each step is split into two one-dimensional sweeps, and the order of the sweeps alternates between steps (line L2), which removes the bias of a fixed order. In a sweep, every face has a donor cell upstream and an acceptor cell downstream (line L3). The quantity cc of line L4 is the Courant number of the face, the fraction of a cell width that crosses the face in one step.

Line L5 decides how the fluid is laid out in the donor. The donor-acceptor rule compares the change of FF across the donor in the two directions, using the neighbors on both sides. If FF changes more along the sweep, the interface is roughly normal to the flow, and the acceptor fraction FAF_A is used; this makes the flux depend on what lies downstream, so a front moves as a sharp step. If FF changes more across the sweep, the interface is parallel to the flow, and the donor fraction FDF_D is used, as in the upwind scheme.

Line L6 is the flux of Hirt and Nichols, as a fraction of the cell volume. The term FADcF_{AD}c is the guess. The term max⁡((1−FAD)c−(1−FD),0)\max((1 - F_{AD})c - (1 - F_D), 0) adds the fluid that must cross if the void that the guess sends, (1−FAD)c(1 - F_{AD})c, is more than the void the donor holds. The minimum with FDF_D stops the donor from giving more fluid than it has. Line L7 moves qq from the donor to the acceptor. All fluxes of a sweep are computed from the fractions before the sweep.

Example

A band, by hand. Take N=20N = 20, so Δx=0.05\Delta x = 0.05, and liquid in the band 0.2<x<0.50.2 < x < 0.5 for all yy. Cells i=4i = 4 to 99 are full and the rest are empty. Let u=1u = 1, v=0v = 0 and Δt=0.015\Delta t = 0.015, so c=0.3c = 0.3. In the first sweep every donor is full or empty, so q=0.3q = 0.3 for faces with a full donor and q=0q = 0 for faces with an empty one. Cell 4 gives 0.3 and gets nothing, cell 10 gets 0.3 from cell 9, and the row of cells 3 to 11 becomes

0, 0.7, 1, 1, 1, 1, 1, 0.3, 0.0,\ 0.7,\ 1,\ 1,\ 1,\ 1,\ 1,\ 0.3,\ 0.

The second step shows the difference from upwind. At the front face between cells 10 and 11, the donor has FD=0.3F_D = 0.3 and FF changes along xx, so line L5 takes the empty acceptor, FAD=0F_{AD} = 0. Line L6 gives q=min⁡(0+max⁡(0.3−0.7,0),0.3)=0q = \min(0 + \max(0.3 - 0.7, 0), 0.3) = 0: the cell holds 0.7 of void ahead of its liquid, and only 0.3 of a cell crosses the face. At the back face between cells 4 and 5, FD=0.7F_D = 0.7 and the acceptor is full, so q=min⁡(0.3,0.7)=0.3q = \min(0.3, 0.7) = 0.3. The row becomes

0, 0.4, 1, 1, 1, 1, 1, 0.6, 0,0,\ 0.4,\ 1,\ 1,\ 1,\ 1,\ 1,\ 0.6,\ 0,

the exact fractions of the band 0.23<x<0.530.23 < x < 0.53. Upwind fluxes q=cFDq = cF_D give 0,0.49,0.91,1,1,1,1,0.51,0.090, 0.49, 0.91, 1, 1, 1, 1, 0.51, 0.09 instead: liquid already leaks into cell 11 and the band spreads. The tests check that donor-acceptor moves the band exactly for 7 steps in both directions.

Rotation of a disk. A disk of radius 0.15 at (0.5,0.75)(0.5, 0.75) turns once around the center of the unit square with ω=2π\omega = 2\pi, the Courant number is at most about 0.48, and the result is compared with the start. The error is the L1L^1 distance ∑∣F−F0∣Δx2\sum|F - F_0|\Delta x^2 divided by the disk area, and a cell is counted as smeared if 0.01<F<0.990.01 < F < 0.99.

NN steps scheme relative L1L^1 error smeared cells, start and end
32 201 donor-acceptor 0.238 36, 50
32 201 upwind 1.314 36, 898
64 402 donor-acceptor 0.123 76, 153
64 402 upwind 1.041 76, 2187

Donor-acceptor keeps the surface within a band one to two cells wide, and the error halves when the grid is refined, first order. Upwind smears the disk over most of the domain; an error above 1 means that more liquid is out of place than the disk holds. Translating the same disk along the diagonal for one period at N=32N = 32 (c=0.5c = 0.5, 64 steps) gives a relative error of 0.181 with donor-acceptor, with 36 smeared cells at both ends, and 1.103 with upwind, with 540 smeared cells. In all runs the volume stayed constant to 10−1410^{-14} and every FF stayed in [0,1][0, 1].

Correctness

The proof file shows three exact facts for 0≤c≤10 \le c \le 1. First, the flux of line L6 lies between max⁡(0,c−(1−FD))\max(0, c - (1 - F_D)) and min⁡(c,FD)\min(c, F_D): the donor never gives more liquid than it holds or more void than it holds. Second, when the velocity along each line of cells is constant, as for u=u(y)u = u(y) and v=v(x)v = v(x), a sweep keeps the sum of the fractions and keeps every fraction in [0,1][0, 1], so the whole run conserves volume and stays bounded. Third, a band whose width and gap are both at least 2Δx2\Delta x is moved exactly. The accuracy for curved shapes is measured, not proved.

Proof: The donor-acceptor VOF update conserves volume, keeps 0 <= F <= 1, and moves a band exactlyfull

We use the notation of the page. The grid has N×NN \times N cells of side Δx=1/N\Delta x = 1/N and is periodic. A sweep in the xx direction treats each row of cells on its own; in row jj the face velocity is the constant w=u(yj)w = u(y_j), and the Courant number of the sweep is c=∣w∣Δt/Δxc = |w|\Delta t/\Delta x. The yy sweep is the same with the roles of the indices exchanged. For a face with donor fraction fDf_D, acceptor fraction fAf_A and chosen fraction fAD∈{fA,fD}f_{AD} \in \{f_A, f_D\}, line L6 gives the flux

q=min⁡(fADc+max⁡((1−fAD)c−(1−fD),0), fD),q = \min\bigl(f_{AD}c + \max((1 - f_{AD})c - (1 - f_D), 0),\ f_D\bigr),

measured as a fraction of the cell volume. We claim, in exact arithmetic, for 0≤c≤10 \le c \le 1 and fractions in [0,1][0, 1]:

  1. max⁡(0,c−(1−fD))≤q≤min⁡(c,fD)\max(0, c - (1 - f_D)) \le q \le \min(c, f_D).
  2. A sweep keeps the sum of the fractions, and if all fractions are in [0,1][0, 1] before the sweep, they are in [0,1][0, 1] after it. So a run of vof_advect conserves the total volume Δx2∑F\Delta x^2\sum F exactly and keeps 0≤F≤10 \le F \le 1.
  3. If the fluid is a band x0<x<x1x_0 < x < x_1 (all yy) and both the band and the gap have width at least 2Δx2\Delta x, then an xx sweep with constant velocity gives the exact volume fractions of the band moved by wΔtw\Delta t.

Claim 1. Write C=max⁡((1−fAD)c−(1−fD),0)C = \max((1 - f_{AD})c - (1 - f_D), 0) and P=fADc+CP = f_{AD}c + C, so q=min⁡(P,fD)q = \min(P, f_D).

Upper bound. Clearly q≤fDq \le f_D. Also C≤(1−fAD)cC \le (1 - f_{AD})c, because (1−fAD)c≥0(1 - f_{AD})c \ge 0 and 1−fD≥01 - f_D \ge 0. So P≤fADc+(1−fAD)c=cP \le f_{AD}c + (1 - f_{AD})c = c, and q≤cq \le c.

Lower bound. P≥0P \ge 0 and fD≥0f_D \ge 0, so q≥0q \ge 0. For the other bound we need P≥c−(1−fD)P \ge c - (1 - f_D) and fD≥c−(1−fD)f_D \ge c - (1 - f_D). The first holds because P≥fADc+(1−fAD)c−(1−fD)=c−(1−fD)P \ge f_{AD}c + (1 - f_{AD})c - (1 - f_D) = c - (1 - f_D). The second is c≤1c \le 1, the Courant condition. So q≥max⁡(0,c−(1−fD))q \ge \max(0, c - (1 - f_D)).

The claim says that the donor gives at most the fluid it holds, q≤fDq \le f_D, and at most the void it holds, c−q≤1−fDc - q \le 1 - f_D, where cc is the total volume that crosses the face.

Claim 2. In a row, ww is the same at every face, so every face of the row has the same Courant number cc and the same direction. Each cell is the donor for exactly one face (its downstream face) and the acceptor for exactly one face (its upstream face). Line L7 subtracts each flux from its donor and adds it to its acceptor, so the sum over the row does not change, and the sum over the grid does not change. For cell ii, the new value is Fi′=Fi−qout+qinF'_i = F_i - q_{\text{out}} + q_{\text{in}}. By Claim 1 applied to both faces, qout≤Fiq_{\text{out}} \le F_i and qin≥0q_{\text{in}} \ge 0, so Fi′≥0F'_i \ge 0. Also qout≥c−(1−Fi)q_{\text{out}} \ge c - (1 - F_i) and qin≤cq_{\text{in}} \le c, so Fi′≤Fi−c+1−Fi+c=1F'_i \le F_i - c + 1 - F_i + c = 1. Both fluxes are computed from the values before the sweep, so the bounds hold for all cells at once. The claim for a run follows by induction over the sweeps. A yy sweep with v=v(x)v = v(x) is the same argument with columns in place of rows. This is where the restriction u=u(y)u = u(y), v=v(x)v = v(x) is used: if the velocity changed along a row, a cell could receive more than it gives and the bound F′≤1F' \le 1 could fail.

Claim 3. Take w>0w > 0; the case w<0w < 0 is the mirror image. In the row, the fractions depend only on ii, so ∂F/∂y=0\partial F/\partial y = 0 and line L5 picks fAD=fAf_{AD} = f_A for every face. Each cell [a,a+Δx][a, a + \Delta x] is one of four kinds, and in each case we compare qq with the exact flux, which is the volume of fluid in [a+Δx−cΔx,a+Δx][a + \Delta x - c\Delta x, a + \Delta x], the part of the cell that crosses the face in time Δt\Delta t.

  • Empty donor, fD=0f_D = 0: then q=min⁡(⋅,0)=0q = \min(\cdot, 0) = 0, which is exact.
  • Full donor, fD=1f_D = 1: C=max⁡((1−fA)c,0)C = \max((1 - f_A)c, 0), so P=cP = c and q=min⁡(c,1)=cq = \min(c, 1) = c, which is exact.
  • Donor that contains the front edge x1x_1: the fluid fills [a,a+fDΔx][a, a + f_D\Delta x]. The gap is at least 2Δx2\Delta x wide, so the acceptor is empty, fAD=0f_{AD} = 0, C=max⁡(c−1+fD,0)C = \max(c - 1 + f_D, 0), and q=min⁡(max⁡(c−1+fD,0),fD)=max⁡(c−1+fD,0)q = \min(\max(c - 1 + f_D, 0), f_D) = \max(c - 1 + f_D, 0), since c≤1c \le 1. The exact flux is the length of the part of [a,a+fDΔx][a, a + f_D\Delta x] that lies beyond a+Δx−cΔxa + \Delta x - c\Delta x, divided by Δx\Delta x, which is max⁡(fD−(1−c),0)\max(f_D - (1 - c), 0). They agree.
  • Donor that contains the back edge x0x_0: the fluid fills [a+(1−fD)Δx,a+Δx][a + (1 - f_D)\Delta x, a + \Delta x]. The band is at least 2Δx2\Delta x wide, so the acceptor is full, fAD=1f_{AD} = 1, C=0C = 0, and q=min⁡(c,fD)q = \min(c, f_D). The exact flux is min⁡(c,fD)\min(c, f_D). They agree.

(If an edge falls exactly on a face, the cells on both sides are full or empty and the first two cases apply.) So every flux equals the exact one, and since the exact fluxes move the band by cΔx=wΔtc\Delta x = w\Delta t, the new fractions are those of the moved band. The moved band again has widths of at least 2Δx2\Delta x, so the claim repeats at every step; the yy sweeps with v=0v = 0 do nothing.

These are exact statements. The accuracy of the scheme for shapes that are not aligned with the grid, such as the rotating disk on the page, is measured, not proved. ■\blacksquare

Complexity

A sweep visits each of the N2N^2 faces in its direction once, and each face costs O(1)O(1): a few neighbor values for line L5 and the formula of line L6. So a step costs Θ(N2)\Theta(N^2) and a run Θ(KN2)\Theta(KN^2). The method keeps one extra copy of the grid, Θ(N2)\Theta(N^2) memory. In a flow solver the stable time step is set by c≤1c \le 1 (in practice c≤0.5c \le 0.5), so KK grows like NN for a fixed end time and a run costs Θ(N3)\Theta(N^3) in 2D. The pressure solve of the flow usually costs more than the VOF advection.

Properties

  • Exact conservation. Liquid moves only through faces, from one cell to its neighbor, so the total volume changes only by rounding.
  • Bounded when each sweep is divergence free and c≤1c \le 1. For a general velocity, splitting makes each sweep compressible and FF can leave [0,1][0, 1] slightly; codes then clip or redistribute.
  • Sharp but not smooth. The surface stays within one or two cells, but the method stores no position inside the cell, so normals and curvature must be computed from the fractions.
  • Topology changes are free. Drops merge and break without any special treatment, because only fractions are stored.
  • First-order accurate for curved interfaces with the donor-acceptor flux, as the rotation table shows. The interface becomes ragged, with small pieces of liquid left behind (flotsam).

Variants and improvements

  • PLIC. Youngs (1982) and later work reconstruct the interface in each cell as a straight line with normal from the gradient of FF, placed to cut off the volume FF, and compute the fluxes as the area of the polygon that crosses each face. This is the standard in modern VOF codes. With Youngs' normals the reconstruction is first order; with normals that reproduce every straight line, such as those of ELVIRA, it is second order for smooth interfaces.
  • SLIC. The simple line interface calculation of Noh and Woodward (1976) places a line parallel to a cell face, chosen per sweep. It is close to the donor-acceptor rule.
  • Unsplit schemes. Rider and Kothe (1998) trace the backward flux regions in two dimensions at once, which removes the splitting error and the compressible sweeps.
  • Algebraic VOF. Codes such as those with compressive interface capturing do not reconstruct a line. They advect FF with a high-resolution scheme and add a compressive term or a limiter that steepens the profile. They are simpler on unstructured meshes but less sharp.
  • Coupled methods. VOF is often combined with a level set (CLSVOF): the level set gives normals and curvature, and VOF gives conservation.
  • Surface tension enters through the continuum surface force model, with the curvature computed from FF.

When to use it

Use VOF when liquid volume must be conserved over a long run: breaking waves, sloshing, jets that break into drops, filling of molds, and boiling with many bubbles. It handles merging and breakup without bookkeeping, and it works with any grid flow solver. Use a level set when smooth normals and curvature matter more than exact volume, as in many surface tension problems, and front tracking when the interface must stay sharp and its shape must be known to high accuracy. For animation, level sets with particles are the usual choice because the rendered surface comes directly from a smooth function.

Pitfalls

  • Expecting a smooth surface. The fractions do not define a unique interface. Curvature from second differences of FF is very noisy; smooth FF first, or use height functions.
  • Courant number above 1. The bounds of the flux need c≤1c \le 1, and with split sweeps the limit applies to each sweep. In practice c≤0.5c \le 0.5 is used because the velocity changes during a step.
  • Splitting a compressible sweep. For a general divergence-free velocity, each one-dimensional sweep has a divergence, and the fractions can rise above 1. The usual fix adds a correction term F ∂xu ΔtF\,\partial_xu\,\Delta t to each sweep, or clips and redistributes the excess.
  • Fixed sweep order. Always sweeping xx first gives a bias that turns a rotating shape. Alternate the order, as on line L2.
  • Reading volume errors as success. Exact conservation does not mean accuracy: upwind also conserves the volume exactly, but the table shows that it smears the disk over the domain.
  • Too few cells per drop. A drop that covers only a few cells breaks into flotsam. Resolve the smallest feature with at least four to eight 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.

volume_of_fluid_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/volume-of-fluid-method/. The authors are listed in prov/TBCGQZ.jsonl.
"""Volume of fluid (VOF) advection with the donor-acceptor fluxes of Hirt and Nichols.

The unit square is split into N x N cells, periodic in both directions. F[i][j] is
the fraction of cell (i, j) filled with fluid; cell (i, j) has its center at
((i + 1/2) / N, (j + 1/2) / N). The velocity is given on cell faces by two functions:
u(y) on the x-faces and v(x) on the y-faces. With u depending only on y and v only
on x, each one-dimensional sweep is divergence free, so the split scheme is exactly
conservative and keeps 0 <= F <= 1 whenever the Courant number of a sweep is at most 1.
Solid body rotation u = -w (y - 1/2), v = w (x - 1/2) and uniform translation are of
this form. The sweep order alternates between steps (x then y, then y then x).
"""
from __future__ import annotations

from typing import Callable, List

Grid = List[List[float]]


def donor_acceptor_flux(fd: float, fa: float, fad: float, c: float) -> float:
    """Fluid volume, as a fraction of a cell, that leaves the donor through one face.

    fd, fa: donor and acceptor fractions; fad: the fraction used for the flux (fa when
    the interface is normal to the flow, else fd); c = |u| dt / dx with 0 <= c <= 1.
    The result lies in [max(0, c - (1 - fd)), min(c, fd)]: the donor never gives more
    fluid than it has, nor more void than it has. Cost O(1).
    """
    cf = max((1.0 - fad) * c - (1.0 - fd), 0.0)  # @line L6
    return min(fad * c + cf, fd)


def _choose(F: Grid, n: int, d: int, a: int, j: int, along_x: bool, scheme: str) -> float:
    """The fraction F_AD for a face between donor cell d and acceptor cell a."""
    if scheme == "upwind":
        return F[d][j] if along_x else F[j][d]
    if along_x:
        gx = F[(d + 1) % n][j] - F[(d - 1) % n][j]
        gy = F[d][(j + 1) % n] - F[d][(j - 1) % n]
        return F[a][j] if abs(gx) >= abs(gy) else F[d][j]  # @line L5
    gy = F[j][(d + 1) % n] - F[j][(d - 1) % n]
    gx = F[(j + 1) % n][d] - F[(j - 1) % n][d]
    return F[j][a] if abs(gy) >= abs(gx) else F[j][d]


def sweep(F: Grid, dt: float, vel: Callable[[float], float], along_x: bool,
          scheme: str = "donor-acceptor") -> Grid:
    """One conservative 1D sweep; returns a new grid. Cost O(N^2)."""
    n = len(F)
    dx = 1.0 / n
    G = [row[:] for row in F]
    for j in range(n):  # one line of cells, at y_j (x sweep) or x_j (y sweep)
        w = vel((j + 0.5) * dx)
        c = abs(w) * dt / dx  # @line L4
        if c > 1.0 + 1e-12:
            raise ValueError("Courant number above 1 in a sweep")
        if c == 0.0:
            continue
        for i in range(n):  # face between cell i and cell i + 1
            ip = (i + 1) % n
            d, a = (i, ip) if w > 0 else (ip, i)  # @line L3
            fd = F[d][j] if along_x else F[j][d]
            fa = F[a][j] if along_x else F[j][a]
            if scheme == "upwind":
                flux = fd * c
            else:
                flux = donor_acceptor_flux(fd, fa, _choose(F, n, d, a, j, along_x, scheme), c)
            if along_x:  # @line L7
                G[d][j] -= flux
                G[a][j] += flux
            else:
                G[j][d] -= flux
                G[j][a] += flux
    return G


def vof_advect(F0: Grid, dt: float, steps: int, u: Callable[[float], float],
               v: Callable[[float], float], scheme: str = "donor-acceptor") -> Grid:
    """Advect the fractions F0 for `steps` steps of size dt with face velocities u(y), v(x).

    Precondition: max |u| dt N <= 1 and max |v| dt N <= 1, 0 <= F0 <= 1.
    Cost O(steps N^2) time, O(N^2) extra space. F0 is not changed.
    """
    if scheme not in ("donor-acceptor", "upwind"):
        raise ValueError("scheme must be 'donor-acceptor' or 'upwind'")
    if dt <= 0 or steps < 0:
        raise ValueError("need dt > 0 and steps >= 0")
    F = [row[:] for row in F0]
    for k in range(steps):  # @line L1
        order = (True, False) if k % 2 == 0 else (False, True)  # @line L2
        for along_x in order:
            F = sweep(F, dt, u if along_x else v, along_x, scheme)
    return F  # @line L8


def disk_fractions(n: int, cx: float, cy: float, r: float, sub: int = 16) -> Grid:
    """Fractions of a disk by sub-sampling each cell on a sub x sub grid of points."""
    dx = 1.0 / n
    F = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            x0, y0 = i * dx, j * dx
            if (abs(x0 + 0.5 * dx - cx) - 0.75 * dx) > r or (abs(y0 + 0.5 * dx - cy) - 0.75 * dx) > r:
                continue
            inside = 0
            for a in range(sub):
                px = x0 + (a + 0.5) * dx / sub - cx
                for b in range(sub):
                    py = y0 + (b + 0.5) * dx / sub - cy
                    if px * px + py * py < r * r:
                        inside += 1
            F[i][j] = inside / (sub * sub)
    return F


def total_volume(F: Grid) -> float:
    """Sum of F times the cell area."""
    n = len(F)
    return sum(sum(row) for row in F) / (n * n)


def l1_error(F: Grid, E: Grid) -> float:
    """Sum of |F - E| times the cell area."""
    n = len(F)
    return sum(abs(a - b) for ra, rb in zip(F, E) for a, b in zip(ra, rb)) / (n * n)


def smeared_cells(F: Grid, tol: float = 0.01) -> int:
    """The number of cells with tol < F < 1 - tol."""
    return sum(1 for row in F for a in row if tol < a < 1.0 - tol)
test_volume_of_fluid_method.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/volume-of-fluid-method/. The authors are listed in prov/TBCGQZ.jsonl.
import math
import random

from volume_of_fluid_method import (
    disk_fractions,
    donor_acceptor_flux,
    l1_error,
    smeared_cells,
    total_volume,
    vof_advect,
)


def band(n, x0, x1):
    dx = 1.0 / n
    return [[max(0.0, min((i + 1) * dx, x1) - max(i * dx, x0)) / dx for _ in range(n)] for i in range(n)]


def test_flux_hand_values():
    assert donor_acceptor_flux(1.0, 1.0, 1.0, 0.3) == 0.3  # full cells
    assert abs(donor_acceptor_flux(0.5, 0.0, 0.0, 0.3)) < 1e-15  # front: the void leaves first
    assert abs(donor_acceptor_flux(0.8, 0.0, 0.0, 0.3) - 0.1) < 1e-15
    assert abs(donor_acceptor_flux(0.2, 1.0, 1.0, 0.3) - 0.2) < 1e-15  # back: only what is there
    assert abs(donor_acceptor_flux(0.5, 0.5, 0.5, 0.3) - 0.15) < 1e-15


def test_flux_bounds():
    rng = random.Random(1)
    for _ in range(2000):
        fd, fa, c = rng.random(), rng.random(), rng.random()
        fad = rng.choice((fd, fa))
        q = donor_acceptor_flux(fd, fa, fad, c)
        assert -1e-15 <= q <= min(c, fd) + 1e-15
        assert c - q <= 1.0 - fd + 1e-15  # void given <= void held


def test_band_translation_is_exact():
    n = 20
    dt = 0.3 / n
    one = vof_advect(band(n, 0.2, 0.5), dt, 1, lambda y: 1.0, lambda x: 0.0)
    assert [round(one[i][0], 12) for i in range(3, 12)] == [0.0, 0.7, 1.0, 1.0, 1.0, 1.0, 1.0, 0.3, 0.0]
    F = vof_advect(band(n, 0.2, 0.5), dt, 7, lambda y: 1.0, lambda x: 0.0)
    E = band(n, 0.2 + 7 * dt, 0.5 + 7 * dt)
    assert max(abs(a - b) for ra, rb in zip(F, E) for a, b in zip(ra, rb)) < 1e-13
    G = vof_advect(band(n, 0.2, 0.5), dt, 7, lambda y: -1.0, lambda x: 0.0)
    E = band(n, 0.2 - 7 * dt, 0.5 - 7 * dt)
    assert max(abs(a - b) for ra, rb in zip(G, E) for a, b in zip(ra, rb)) < 1e-13


def test_rotation_conserves_and_stays_bounded():
    n = 32
    w = 2 * math.pi
    F0 = disk_fractions(n, 0.5, 0.75, 0.15)
    assert abs(total_volume(F0) - math.pi * 0.15 ** 2) < 1e-3
    steps = 201
    F = vof_advect(F0, 1.0 / steps, steps, lambda y: -w * (y - 0.5), lambda x: w * (x - 0.5))
    assert abs(total_volume(F) - total_volume(F0)) < 1e-14
    assert min(min(r) for r in F) >= -1e-14 and max(max(r) for r in F) <= 1 + 1e-14
    rel = l1_error(F, F0) / total_volume(F0)
    assert abs(rel - 0.2378) < 5e-4
    U = vof_advect(F0, 1.0 / steps, steps, lambda y: -w * (y - 0.5), lambda x: w * (x - 0.5), "upwind")
    assert abs(total_volume(U) - total_volume(F0)) < 1e-14
    assert smeared_cells(F) < 60 < 800 < smeared_cells(U)


def test_courant_limit_and_bad_input():
    F0 = band(8, 0.2, 0.5)
    for args in ((0.2, 1), (0.0, 1), (0.1, -1)):
        try:
            vof_advect(F0, args[0], args[1], lambda y: 1.0, lambda x: 0.0)
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")
    try:
        vof_advect(F0, 0.1, 1, lambda y: 1.0, lambda x: 0.0, "magic")
    except ValueError:
        pass
    else:
        raise AssertionError("expected ValueError")

History

Noh and Woodward (1976) advected cell fractions with interfaces aligned to the grid in their SLIC method. Hirt and Nichols (1981) introduced the name volume of fluid, the donor-acceptor flux and the SOLA-VOF code for free-surface flows at Los Alamos; it became one of the most cited papers in computational fluid dynamics. Youngs (1982) placed a sloped line in each cell, the start of PLIC. In the 1990s, papers such as Rider and Kothe (1998) and the review of Scardovelli and Zaleski (1999) made geometric VOF with PLIC reconstruction and the continuum surface force model the standard for direct simulation of flows with interfaces.

References

  1. C. W. Hirt and B. D. Nichols, Volume of fluid (VOF) method for the dynamics of free boundaries, Journal of Computational Physics 39 (1981) 201-225, the fractional volume function, the donor-acceptor flux and the choice between the acceptor and donor fraction
  2. William J. Rider and Douglas B. Kothe, Reconstructing volume tracking, Journal of Computational Physics 141 (1998) 112-152, the review of volume tracking methods and the rotation and shear test problems
  3. Ruben Scardovelli and Stéphane Zaleski, Direct numerical simulation of free-surface and interfacial flow, Annual Review of Fluid Mechanics 31 (1999) 567-603, the section on volume of fluid methods

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