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.
- Solves
- Advection equation
- 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
- Model
- Real RAM
- Properties
- conserves volume exactlydeterministiceulerianoperator split
- Evidence
- Proof sketchCode in 1 languages
- 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 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 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 on an periodic grid of cells of side over the unit square, and a velocity field with zero divergence, approximate the solution of the advection equation
for the indicator of the liquid, after steps of size . The output must keep , the liquid volume, and stay in . The velocity is given on cell faces as on the faces normal to and on the faces normal to . Solid body rotation , and uniform translation are of this form. The grid index is along and along .
The algorithm
VOF-ADVECT(F, Δt, K, u, v)- 1
for k ← 0 to K - 1 - 2
for each sweep, x then y if k is even, else y then x ▷ operator splitting - 3
for each face: D ← upstream cell, A ← downstream cell ▷ donor and acceptor - 4
c ← |w| Δt / Δx ▷ w is the face velocity, c ≤ 1 - 5
F_AD ← F_A if the interface in D is normal to the sweep, else F_D - 6
q ← min(F_AD c + max((1 - F_AD) c - (1 - F_D), 0), F_D) - 7
F_D ← F_D - q; F_A ← F_A + q ▷ with all q from the old F - 8
return 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 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 across the donor in the two directions, using the neighbors on both sides. If changes more along the sweep, the interface is roughly normal to the flow, and the acceptor fraction is used; this makes the flux depend on what lies downstream, so a front moves as a sharp step. If changes more across the sweep, the interface is parallel to the flow, and the donor fraction 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 is the guess. The term adds the fluid that must cross if the void that the guess sends, , is more than the void the donor holds. The minimum with stops the donor from giving more fluid than it has. Line L7 moves 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 , so , and liquid in the band for all . Cells to are full and the rest are empty. Let , and , so . In the first sweep every donor is full or empty, so for faces with a full donor and 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
The second step shows the difference from upwind. At the front face between cells 10 and 11, the donor has and changes along , so line L5 takes the empty acceptor, . Line L6 gives : 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, and the acceptor is full, so . The row becomes
the exact fractions of the band . Upwind fluxes give 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 turns once around the center of the unit square with , the Courant number is at most about 0.48, and the result is compared with the start. The error is the distance divided by the disk area, and a cell is counted as smeared if .
| steps | scheme | relative 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 (, 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 and every stayed in .
Correctness
The proof file shows three exact facts for . First, the flux of line L6 lies between and : 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 and , a sweep keeps the sum of the fractions and keeps every fraction in , so the whole run conserves volume and stays bounded. Third, a band whose width and gap are both at least 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 cells of side and is periodic. A sweep in the direction treats each row of cells on its own; in row the face velocity is the constant , and the Courant number of the sweep is . The sweep is the same with the roles of the indices exchanged. For a face with donor fraction , acceptor fraction and chosen fraction , line L6 gives the flux
measured as a fraction of the cell volume. We claim, in exact arithmetic, for and fractions in :
- .
- A sweep keeps the sum of the fractions, and if all fractions are in before the sweep, they are in after it. So a run of
vof_advectconserves the total volume exactly and keeps . - If the fluid is a band (all ) and both the band and the gap have width at least , then an sweep with constant velocity gives the exact volume fractions of the band moved by .
Claim 1. Write and , so .
Upper bound. Clearly . Also , because and . So , and .
Lower bound. and , so . For the other bound we need and . The first holds because . The second is , the Courant condition. So .
The claim says that the donor gives at most the fluid it holds, , and at most the void it holds, , where is the total volume that crosses the face.
Claim 2. In a row, is the same at every face, so every face of the row has the same Courant number 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 , the new value is . By Claim 1 applied to both faces, and , so . Also and , so . 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 sweep with is the same argument with columns in place of rows. This is where the restriction , is used: if the velocity changed along a row, a cell could receive more than it gives and the bound could fail.
Claim 3. Take ; the case is the mirror image. In the row, the fractions depend only on , so and line L5 picks for every face. Each cell is one of four kinds, and in each case we compare with the exact flux, which is the volume of fluid in , the part of the cell that crosses the face in time .
- Empty donor, : then , which is exact.
- Full donor, : , so and , which is exact.
- Donor that contains the front edge : the fluid fills . The gap is at least wide, so the acceptor is empty, , , and , since . The exact flux is the length of the part of that lies beyond , divided by , which is . They agree.
- Donor that contains the back edge : the fluid fills . The band is at least wide, so the acceptor is full, , , and . The exact flux is . 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 , the new fractions are those of the moved band. The moved band again has widths of at least , so the claim repeats at every step; the sweeps with 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.
Complexity
A sweep visits each of the faces in its direction once, and each face costs : a few neighbor values for line L5 and the formula of line L6. So a step costs and a run . The method keeps one extra copy of the grid, memory. In a flow solver the stable time step is set by (in practice ), so grows like for a fixed end time and a run costs 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 . For a general velocity, splitting makes each sweep compressible and can leave 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 , placed to cut off the volume , 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 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 .
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 is very noisy; smooth first, or use height functions.
- Courant number above 1. The bounds of the flux need , and with split sweeps the limit applies to each sweep. In practice 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 to each sweep, or clips and redistributes the excess.
- Fixed sweep order. Always sweeping 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag TBCGQZ Edit this page History Report an error Markdown