Algorithm Search⌘K

Algorithmadvanced

Piecewise linear interface calculation

Also called PLIC.

Reconstructs the interface in each cell as a plane with normal from the volume fraction gradient, placed so it cuts off the cell's fraction.

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 exactlydeterministiceuleriangeometric fluxesreconstruction keeps volume
Origin
David L. Youngs, 1982

Piecewise linear interface calculation (PLIC) is the reconstruction step of the volume of fluid method. The grid stores only the fraction FF of each cell filled with liquid, and PLIC turns these numbers into a surface: in each cell that is partly full it draws a straight line (a plane in 3D) with its normal taken from the change of FF across the neighbors, and slides the line until it cuts off exactly the fraction FF. The fluxes between cells are then areas of polygons, not guesses. The result is a sharp interface at most one cell thick, with the liquid volume kept to rounding error.

In plain words

Look at one cell of the grid that is 30% full of water. The number 30% does not say where the water is in the cell. The neighbors do: if the cells to the left are full and the cells to the right are empty, the water is on the left. PLIC finds the direction in which FF falls fastest, from a block of 3 by 3 cells, and takes that as the direction out of the water. It draws a line across the cell at right angles to that direction and moves it until the water side has exactly 30% of the cell. To move water to the next cell, it cuts out the strip that crosses the face and measures the water in it. That amount moves. Since water only moves from one cell to the next, none is lost.

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, and a divergence-free velocity, advect FF by ∂tF+u ∂xF+v ∂yF=0\partial_tF + u\,\partial_xF + v\,\partial_yF = 0 for KK steps of size Δt\Delta t, keeping the total volume ∑FijΔx2\sum F_{ij}\Delta x^2 and the bounds 0≤F≤10 \le F \le 1, and keeping the interface sharp. As on the VOF page, the face velocity is u(y)u(y) on the faces normal to xx and v(x)v(x) on the faces normal to yy, which covers solid body rotation and translation and makes each split sweep divergence free.

The reconstruction subproblem is this. In the cell coordinates (x,y)∈[0,1]2(x, y) \in [0, 1]^2, given a normal n=(nx,ny)≠0n = (n_x, n_y) \ne 0 that points out of the fluid and a fraction ff, find β\beta so that the part of the cell with nxx+nyy≤βn_xx + n_yy \le \beta has area ff.

The algorithm

  1. PLIC-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
  4. 3for each mixed cell: n ← -∇F by Youngs' 3 × 3 stencil
  5. 4β ← the line constant with area{n·x ≤ β} = F, in closed form
  6. 5for each face: D ← upstream cell, A ← downstream cell, c ← |w| Δt / Δx
  7. 6q ← area of the fluid polygon of D in the strip of width c at the face
  8. 7F_D ← F_D - q; F_A ← F_A + q ▷ with all q from the old F
  9. 8return F

The normal (line L3). Youngs' stencil differences the fractions across the cell in each direction, with weights 1, 2, 1 across the other direction:

nx=−[(Fi+1,j+1+2Fi+1,j+Fi+1,j−1)−(Fi−1,j+1+2Fi−1,j+Fi−1,j−1)],n_x = -\bigl[(F_{i+1,j+1} + 2F_{i+1,j} + F_{i+1,j-1}) - (F_{i-1,j+1} + 2F_{i-1,j} + F_{i-1,j-1})\bigr],

and nyn_y is the same with the roles of ii and jj exchanged. The common factor 1/(8Δx)1/(8\Delta x) does not matter, since only the direction is used.

The line constant (line L4). Reflect the cell so that both components are nonnegative and scale them so that m1+m2=1m_1 + m_2 = 1 with m1≤m2m_1 \le m_2. The area cut off by m1x+m2y≤am_1x + m_2y \le a is

A(a)={a2/(2m1m2),0≤a≤m1,(a−m1/2)/m2,m1≤a≤m2,1−(1−a)2/(2m1m2),m2≤a≤1,A(a) = \begin{cases} a^2/(2m_1m_2), & 0 \le a \le m_1, \\ (a - m_1/2)/m_2, & m_1 \le a \le m_2, \\ 1 - (1 - a)^2/(2m_1m_2), & m_2 \le a \le 1, \end{cases}

the closed form of Scardovelli and Zaleski (2000). It is easy to invert: for f≤12f \le \frac12, a=2m1m2fa = \sqrt{2m_1m_2f} if f≤m1/(2m2)f \le m_1/(2m_2) and a=m2f+m1/2a = m_2f + m_1/2 otherwise, and f>12f > \frac12 follows from A(1−a)=1−A(a)A(1 - a) = 1 - A(a). Undoing the scaling and the reflection gives β=(∣nx∣+∣ny∣) a+min⁡(nx,0)+min⁡(ny,0)\beta = (|n_x| + |n_y|)\,a + \min(n_x, 0) + \min(n_y, 0). In 3D the same idea gives a closed form with a cubic, and on other cell shapes an iteration is used.

The flux (line L6). For a face on the right of the donor, the fluid that crosses in one step is the fluid in the strip 1−c≤x≤11 - c \le x \le 1 of the donor. The code clips the strip rectangle with the half-plane n⋅x≤βn \cdot x \le \beta (the Sutherland-Hodgman step) and takes the area of the result by the shoelace formula. Full and empty cells use q=cFq = cF. Lines L5 and L7 and the alternating sweeps are as on the VOF page.

Example

A line constant, by hand. Let n=(1,2)n = (1, 2) and f=0.3f = 0.3. Then m1=13m_1 = \frac13, m2=23m_2 = \frac23 and m1/(2m2)=0.25<0.3m_1/(2m_2) = 0.25 < 0.3, so a=23⋅0.3+16=0.3667a = \frac23 \cdot 0.3 + \frac16 = 0.3667 and β=3a=1.1\beta = 3a = 1.1. Check: the line x+2y=1.1x + 2y = 1.1 meets the side x=0x = 0 at y=0.55y = 0.55 and the side x=1x = 1 at y=0.05y = 0.05, so the fluid below it is a trapezoid of area 12(0.55+0.05)=0.3\frac12(0.55 + 0.05) = 0.3.

A flux, by hand. Let a cell have f=18f = \frac18 and n=(1,1)n = (1, 1), so the fluid is the triangle x+y≤12x + y \le \frac12 in the lower left corner. With c=0.3c = 0.3 the strip 0.7≤x≤10.7 \le x \le 1 at the right face holds no fluid, so q=0q = 0; the upwind flux cFcF would move 0.0375. With c=0.6c = 0.6 the strip 0.4≤x≤10.4 \le x \le 1 cuts off the corner 0.4≤x≤0.50.4 \le x \le 0.5 of the triangle, a triangle with legs 0.1, so q=0.005q = 0.005, against 0.075 for upwind.

Rotation of a disk. The same test as on the VOF page: a disk of radius 0.15 at (0.5,0.75)(0.5, 0.75) turns once with ω=2π\omega = 2\pi, at a Courant number of at most about 0.48. The error is ∑∣F−F0∣Δx2\sum|F - F_0|\Delta x^2 divided by the disk area, and a cell is smeared if 0.01<F<0.990.01 < F < 0.99.

NN steps method relative L1L^1 error smeared cells, start and end
32 201 donor-acceptor 0.238 36, 50
32 201 PLIC (Youngs) 0.018 36, 36
64 402 donor-acceptor 0.123 76, 153
64 402 PLIC (Youngs) 0.0058 76, 74

PLIC is 13 to 21 times more accurate, the interface stays exactly one cell thick, and the error falls by a factor of 3.2 when the grid is refined. Translating the same disk along the diagonal for one period at N=32N = 32 (c=0.5c = 0.5) gives a relative error of 0.0091, against 0.181 for donor-acceptor. In all runs the volume stayed constant to 10−1610^{-16} and every FF stayed in [0,1][0, 1]. The run at N=64N = 64 took about 2 s in pure Python.

Correctness

The proof file shows three exact facts. The line constant of line L4 cuts off exactly the area FF, for every normal and every F∈[0,1]F \in [0, 1], so the reconstruction keeps the volume of every cell. The geometric flux lies in [max⁡(0,c−(1−F)),min⁡(c,F)][\max(0, c - (1 - F)), \min(c, F)], since the strip is part of the cell; with divergence-free sweeps this gives exact conservation and 0≤F≤10 \le F \le 1, as for donor-acceptor. A band at least two cells wide is moved exactly, because the stencil then finds the exact normal. The tests also check the closed form against the polygon area to 10−1410^{-14} on 3000 random cases.

Proof: The PLIC reconstruction keeps the volume, and the PLIC update conserves volume, keeps 0 <= F <= 1, and moves a band exactlyfull

We use the notation of the page. In cell coordinates (x,y)∈[0,1]2(x, y) \in [0, 1]^2 the reconstructed fluid is {nxx+nyy≤β}\{n_xx + n_yy \le \beta\}, and a sweep has the constant Courant number c=∣w∣Δt/Δx≤1c = |w|\Delta t/\Delta x \le 1 along each line of cells. We claim, in exact arithmetic:

  1. For (nx,ny)≠0(n_x, n_y) \ne 0 and 0≤f≤10 \le f \le 1, the line constant β\beta of line L4 cuts off exactly the area ff of the unit square.
  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 conserves the total volume exactly and keeps 0≤F≤10 \le F \le 1.
  3. If the fluid is a band x0<x<x1x_0 < x < x_1 and both the band and the gap have width at least 2Δx2\Delta x, an xx sweep moves the band exactly by wΔtw\Delta t.

Claim 1. First reduce to nonnegative components. If nx<0n_x < 0, put x′=1−xx' = 1 - x; then nxx=∣nx∣x′+nxn_xx = |n_x|x' + n_x. Doing the same for yy gives nxx+nyy=∣nx∣x′+∣ny∣y′+min⁡(nx,0)+min⁡(ny,0)n_xx + n_yy = |n_x|x' + |n_y|y' + \min(n_x, 0) + \min(n_y, 0), and the map (x,y)↦(x′,y′)(x, y) \mapsto (x', y') maps the square to itself and keeps areas. Divide by s=∣nx∣+∣ny∣>0s = |n_x| + |n_y| > 0 and swap the axes if needed, which also keeps areas. The set becomes {m1x+m2y≤a}\{m_1x + m_2y \le a\} with 0≤m1≤m20 \le m_1 \le m_2, m1+m2=1m_1 + m_2 = 1 and β=sa+min⁡(nx,0)+min⁡(ny,0)\beta = sa + \min(n_x, 0) + \min(n_y, 0), as in the code. So it is enough to show that the aa of the code gives area ff for this set.

Let A(a)A(a) be the area of {m1x+m2y≤a}∩[0,1]2\{m_1x + m_2y \le a\} \cap [0, 1]^2. For m1>0m_1 > 0 and 0≤a≤m10 \le a \le m_1, the set is the triangle with legs a/m1a/m_1 and a/m2a/m_2, so A(a)=a2/(2m1m2)A(a) = a^2/(2m_1m_2). For m1≤a≤m2m_1 \le a \le m_2, the line crosses the sides x=0x = 0 and x=1x = 1 at y=a/m2y = a/m_2 and y=(a−m1)/m2y = (a - m_1)/m_2, both in [0,1][0, 1], so the set is a trapezoid of area (a−m1/2)/m2(a - m_1/2)/m_2. (If m1=0m_1 = 0, only this case occurs and A(a)=aA(a) = a.) The set and its complement are mapped to each other by (x,y)↦(1−x,1−y)(x, y) \mapsto (1 - x, 1 - y), which takes m1x+m2y≤am_1x + m_2y \le a to m1x+m2y≥1−am_1x + m_2y \ge 1 - a. So A(1−a)=1−A(a)A(1 - a) = 1 - A(a), which covers a≥m2a \ge m_2.

The code puts g=min⁡(f,1−f)≤12g = \min(f, 1 - f) \le \frac12. If g≤m1/(2m2)=A(m1)g \le m_1/(2m_2) = A(m_1), it takes a=2m1m2g≤m1a = \sqrt{2m_1m_2g} \le m_1, and A(a)=gA(a) = g by the first case. Otherwise it takes a=m2g+m1/2a = m_2g + m_1/2, which is at least m1m_1 because g>m1/(2m2)g > m_1/(2m_2) and at most 12≤m2\frac12 \le m_2 because g≤12g \le \frac12, so A(a)=gA(a) = g by the second case. If f≤12f \le \frac12, then g=fg = f and we are done. If f>12f > \frac12, then g=1−fg = 1 - f, the code replaces aa by 1−a1 - a, and the symmetry gives A(1−a)=1−g=fA(1 - a) = 1 - g = f.

Claim 2. The flux qq of line L6 is the area of the fluid polygon inside the strip of width cc next to the face. Since the strip is part of the cell, q≤cq \le c; since the polygon has area ff by Claim 1, q≤fq \le f; and the void in the strip, c−qc - q, is at most the void in the cell, 1−f1 - f. Full and empty cells use q=cfq = cf, which is 00 or cc and satisfies the same bounds. The code also clamps qq to [max⁡(0,c−(1−f)),min⁡(c,f)][\max(0, c - (1 - f)), \min(c, f)], so the bounds hold even after rounding. From here the proof is that of the volume of fluid page: each cell is the donor of exactly one face and the acceptor of exactly one face of its line, line L7 moves each flux from donor to acceptor, so the sum is kept, and for a cell F′=F−qout+qinF' = F - q_{\text{out}} + q_{\text{in}} with 0≤F−qout0 \le F - q_{\text{out}} and F−qout+qin≤F−(c−1+F)+c=1F - q_{\text{out}} + q_{\text{in}} \le F - (c - 1 + F) + c = 1. Induction over the sweeps gives the claim for a run.

Claim 3. Take w>0w > 0. The fractions do not depend on jj, so in Youngs' stencil the yy difference is 00 and ny=0n_y = 0, and nx=−4(Fi+1−Fi−1)n_x = -4(F_{i+1} - F_{i-1}). Full and empty donors give the exact fluxes cc and 00. Consider the cell [a,a+Δx][a, a + \Delta x] that contains the front edge x1x_1 in its interior. Its left neighbor ends at a>x1−Δx≥x0+Δxa > x_1 - \Delta x \ge x_0 + \Delta x, so it lies inside the band and is full; its right neighbor starts at a+Δxa + \Delta x and ends at a+2Δx≤x1+2Δxa + 2\Delta x \le x_1 + 2\Delta x, which is inside the gap, so it is empty. So nx>0n_x > 0, and by Claim 1 the fluid of the cell is reconstructed as {x≤f}\{x \le f\} in cell coordinates, which is exactly the fluid of the band in this cell. The same argument at the back edge gives nx<0n_x < 0 and the set {x≥1−f}\{x \ge 1 - f\}, again exact. So the reconstructed fluid equals the true fluid in every cell, and the strip areas are the exact fluxes. The new fractions are those of the band moved by cΔx=wΔtc\Delta x = w\Delta t, which again has widths of at least 2Δx2\Delta x, so the claim repeats. The yy sweeps with v=0v = 0 do nothing. ■\blacksquare

Complexity

Each mixed cell costs O(1)O(1): a 9-point stencil, a square root, and the clipping of a 4-vertex polygon. Full and empty cells cost a multiplication. So a sweep costs Θ(N2)\Theta(N^2) and a run Θ(KN2)\Theta(KN^2), with Θ(N2)\Theta(N^2) memory; the constant is several times that of donor-acceptor, but only the O(N)O(N) mixed cells pay it. In 3D the polyhedron clipping is more costly, and it is often the most expensive part of the VOF step.

Properties

  • Exact volume. Each reconstruction holds exactly the fraction FF of its cell, and the fluxes move volume between neighbors, so the total is kept to rounding.
  • Sharp. The interface stays one cell thick, as the rotation table shows.
  • Not continuous. The lines of neighboring cells do not meet in general. The interface is a set of separate segments, which is enough for fluxes but not for curvature.
  • Order of the normal. Youngs' normal does not reproduce a straight line at every angle, so the reconstruction is first order in the sense of Pilliod and Puckett (2004). Methods that fit the line to the 3×33 \times 3 block, such as ELVIRA, reproduce every straight line and are second order.
  • Bounded for divergence-free sweeps with c≤1c \le 1, as for donor-acceptor.

Variants and improvements

  • Better normals. ELVIRA of Pilliod and Puckett (2004) tries several candidate normals from the 3×33 \times 3 block and keeps the one whose extended line best matches the neighbor fractions; LVIRA minimizes the same error by iteration. Mixed Youngs-centered schemes are used in 3D codes.
  • Unsplit advection. Rider and Kothe (1998) trace the region that crosses each face in a step back along the velocity and intersect it with the reconstruction, which removes the splitting error.
  • Lagrangian-explicit sweeps. Some codes move the reconstructed line with the flow in each sweep instead of cutting strips, and combine the two kinds of sweeps so that the volume is kept for any divergence-free velocity.
  • Moment of fluid. The cell stores the centroid of the fluid as well as its volume, which fixes the normal without the neighbors and resolves thin films.
  • Curvature. The PLIC lines are not used for curvature. Codes compute it from height functions, sums of FF along columns, or from a coupled level set, and add surface tension by the continuum surface force model.

When to use it

Use PLIC whenever a VOF code needs a sharp interface: breaking waves, jets, sprays and bubbly flows with surface tension. It is the standard reconstruction in geometric VOF codes. Algebraic VOF schemes, which compress the profile of FF without a line, are simpler on unstructured meshes and are used where some smearing is acceptable. If smooth normals and curvature are the main need, a level set or front tracking is easier.

Pitfalls

  • Isolated and thin features. A filament thinner than a cell has fluid on both sides of the cell, which one line cannot represent. Youngs' stencil then gives a poor normal, and the filament breaks into small pieces.
  • A zero normal. A mixed cell with symmetric neighbors gives ∇F=0\nabla F = 0. Fall back to an upwind flux, as the code does.
  • Rounding at the limits. Fractions such as 10−1510^{-15} or 1−10−151 - 10^{-15} give lines at the edge of the cell. Treat them as empty or full, and clamp the flux to its exact bounds.
  • Splitting error. With a general divergence-free velocity, each split sweep has a divergence, and FF can leave [0,1][0, 1] unless the sweep includes a divergence correction.
  • Normal sign. The normal must point out of the fluid, n=−∇Fn = -\nabla F. With the other sign the line cuts off the void instead of the fluid, and the volume of the cell is still right, so the error does not show in a volume check. The band test catches it.

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.

piecewise_linear_interface_calculation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/piecewise-linear-interface-calculation/. The authors are listed in prov/AZM3X0.jsonl.
"""PLIC volume of fluid advection in 2D: Youngs normals, the closed-form line constant
of Scardovelli and Zaleski, and geometric fluxes in split sweeps.

The unit square has N x N periodic cells; F[i][j] is the fluid fraction of cell (i, j),
with i along x and j along y. In each mixed cell the interface is the line
nx * x + ny * y = beta in the cell coordinates (x, y) in [0, 1]^2, with the fluid on
the side nx * x + ny * y <= beta. The normal (nx, ny) = -grad F points out of the fluid.
The face velocities are u(y) on the x-faces and v(x) on the y-faces, so every sweep has
a constant velocity along each line of cells and is divergence free.
"""
from __future__ import annotations

import math
from typing import Callable, List, Sequence, Tuple

Grid = List[List[float]]
Point = Tuple[float, float]
EPS = 1e-12


def youngs_normal(F: Grid, i: int, j: int) -> Tuple[float, float]:
    """-grad F at cell (i, j) by the 3 x 3 stencil of Youngs (weights 1, 2, 1). Cost O(1).

    The result is not normalized; it is (0, 0) if the stencil sees no change.
    """
    n = len(F)
    ip, im, jp, jm = (i + 1) % n, (i - 1) % n, (j + 1) % n, (j - 1) % n
    gx = (F[ip][jp] + 2.0 * F[ip][j] + F[ip][jm]) - (F[im][jp] + 2.0 * F[im][j] + F[im][jm])
    gy = (F[ip][jp] + 2.0 * F[i][jp] + F[im][jp]) - (F[ip][jm] + 2.0 * F[i][jm] + F[im][jm])
    return -gx, -gy  # @line L3


def line_constant(nx: float, ny: float, f: float) -> float:
    """beta such that the part of the unit square with nx x + ny y <= beta has area f.

    Closed form: with m1 <= m2 the absolute components scaled to m1 + m2 = 1, the area
    of {m1 x + m2 y <= a} is a^2 / (2 m1 m2) for a <= m1, (a - m1/2) / m2 for
    m1 <= a <= m2, and 1 - (1 - a)^2 / (2 m1 m2) for a >= m2. Needs (nx, ny) != 0 and
    0 <= f <= 1. Cost O(1).
    """
    s = abs(nx) + abs(ny)
    if s == 0.0:
        raise ValueError("zero normal")
    if not 0.0 <= f <= 1.0:
        raise ValueError("fraction outside [0, 1]")
    m1, m2 = sorted((abs(nx) / s, abs(ny) / s))
    g = min(f, 1.0 - f)  # symmetry: solve for the smaller of fluid and void
    if g <= m1 / (2.0 * m2):
        a = math.sqrt(2.0 * m1 * m2 * g)
    else:
        a = m2 * g + 0.5 * m1
    if f > 0.5:
        a = 1.0 - a
    return s * a + min(nx, 0.0) + min(ny, 0.0)  # @line L4


def clip(poly: Sequence[Point], nx: float, ny: float, beta: float) -> List[Point]:
    """The part of a convex polygon with nx x + ny y <= beta (Sutherland-Hodgman). O(len)."""
    out: List[Point] = []
    k = len(poly)
    for t in range(k):
        p, q = poly[t], poly[(t + 1) % k]
        dp = nx * p[0] + ny * p[1] - beta
        dq = nx * q[0] + ny * q[1] - beta
        if dp <= 0.0:
            out.append(p)
        if (dp < 0.0 < dq) or (dq < 0.0 < dp):
            s = dp / (dp - dq)
            out.append((p[0] + s * (q[0] - p[0]), p[1] + s * (q[1] - p[1])))
    return out


def area(poly: Sequence[Point]) -> float:
    """Area of a simple polygon by the shoelace formula."""
    k = len(poly)
    return 0.5 * abs(sum(poly[t][0] * poly[(t + 1) % k][1] - poly[(t + 1) % k][0] * poly[t][1] for t in range(k)))


def strip_flux(nx: float, ny: float, beta: float, c: float, forward: bool) -> float:
    """Fluid area in the strip of width c at the right face (forward) or the left face."""
    lo, hi = (1.0 - c, 1.0) if forward else (0.0, c)
    rect = [(lo, 0.0), (hi, 0.0), (hi, 1.0), (lo, 1.0)]
    return area(clip(rect, nx, ny, beta))  # @line L6


def plic_flux(F: Grid, d: int, j: int, c: float, forward: bool, along_x: bool) -> float:
    """Fluid volume (fraction of a cell) leaving donor cell d of line j through one face.

    For an x sweep the donor is cell (d, j); for a y sweep it is cell (j, d). The result
    is kept in [max(0, c - (1 - f)), min(c, f)], the bounds the exact geometry satisfies.
    """
    i, k = (d, j) if along_x else (j, d)
    f = F[i][k]
    if f <= EPS or f >= 1.0 - EPS:
        q = c * f
    else:
        nx, ny = youngs_normal(F, i, k)
        if nx == 0.0 and ny == 0.0:
            q = c * f
        else:
            if not along_x:  # work in coordinates with the sweep along the first axis
                nx, ny = ny, nx
            beta = line_constant(nx, ny, f)
            q = strip_flux(nx, ny, beta, c, forward)
    return min(max(q, c - (1.0 - f), 0.0), c, f)


def sweep(F: Grid, dt: float, vel: Callable[[float], float], along_x: bool) -> Grid:
    """One conservative 1D sweep with geometric fluxes; 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):
        w = vel((j + 0.5) * dx)
        c = abs(w) * dt / dx
        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 L5
            q = plic_flux(F, d, j, c, w > 0, along_x)
            if along_x:  # @line L7
                G[d][j] -= q
                G[a][j] += q
            else:
                G[j][d] -= q
                G[j][a] += q
    return G


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

    Precondition: max |u| dt N <= 1, max |v| dt N <= 1 and 0 <= F0 <= 1. Volume is kept
    exactly and 0 <= F <= 1 is kept. Cost O(steps N^2) time, O(N^2) extra space.
    """
    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)
    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_piecewise_linear_interface_calculation.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/piecewise-linear-interface-calculation/. The authors are listed in prov/AZM3X0.jsonl.
import math
import random

from piecewise_linear_interface_calculation import (
    area,
    clip,
    disk_fractions,
    l1_error,
    line_constant,
    plic_advect,
    plic_flux,
    smeared_cells,
    strip_flux,
    total_volume,
    youngs_normal,
)

SQUARE = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]


def band(n, x0, x1, along_x=True):
    dx = 1.0 / n
    prof = [max(0.0, min((i + 1) * dx, x1) - max(i * dx, x0)) / dx for i in range(n)]
    return [[prof[i] if along_x else prof[j] for j in range(n)] for i in range(n)]


def test_line_constant_hand_values():
    assert abs(line_constant(1.0, 1.0, 0.125) - 0.5) < 1e-15  # triangle x + y <= 1/2
    assert abs(line_constant(1.0, 2.0, 0.3) - 1.1) < 1e-15  # middle case, a = 0.36667
    assert abs(line_constant(1.0, 0.0, 0.3) - 0.3) < 1e-15  # vertical line x = 0.3
    assert abs(line_constant(-1.0, 0.0, 0.3) - (-0.7)) < 1e-15  # fluid on the right: x >= 0.7
    assert abs(strip_flux(1.0, 1.0, 0.5, 0.6, True) - 0.005) < 1e-15
    assert strip_flux(1.0, 1.0, 0.5, 0.3, True) == 0.0


def test_reconstruction_keeps_the_volume():
    rng = random.Random(3)
    for _ in range(3000):
        nx, ny, f = rng.uniform(-1, 1), rng.uniform(-1, 1), rng.random()
        if rng.random() < 0.1:
            nx = 0.0
        b = line_constant(nx, ny, f)
        assert abs(area(clip(SQUARE, nx, ny, b)) - f) < 1e-14


def test_youngs_normal_directions():
    F = band(8, 0.2, 0.55)  # fluid on the left of x = 0.55 in cell 4
    nx, ny = youngs_normal(F, 4, 3)
    assert nx > 0 and ny == 0.0
    n = 8
    H = [[1.0 if i + j < n else (0.5 if i + j == n else 0.0) for j in range(n)] for i in range(n)]
    nx, ny = youngs_normal(H, 4, 4)
    assert nx > 0 and abs(nx - ny) < 1e-15  # the 45 degree normal is found exactly


def test_flux_bounds():
    rng = random.Random(5)
    n = 6
    for _ in range(300):
        F = [[rng.random() for _ in range(n)] for _ in range(n)]
        c = rng.random()
        d, j = rng.randrange(n), rng.randrange(n)
        for fwd in (True, False):
            for ax in (True, False):
                f = F[d][j] if ax else F[j][d]
                q = plic_flux(F, d, j, c, fwd, ax)
                assert max(0.0, c - (1.0 - f)) <= q <= min(c, f)


def test_band_translation_is_exact():
    n = 20
    dt = 0.3 / n
    for ax in (True, False):
        for s in (1.0, -1.0):
            u = (lambda y: s) if ax else (lambda y: 0.0)
            v = (lambda x: 0.0) if ax else (lambda x: s)
            F = plic_advect(band(n, 0.21, 0.52, ax), dt, 9, u, v)
            E = band(n, 0.21 + 9 * s * dt, 0.52 + 9 * s * dt, ax)
            assert max(abs(a - b) for ra, rb in zip(F, E) for a, b in zip(ra, rb)) < 1e-13


def test_rotation_is_sharp_and_conservative():
    n = 32
    w = 2 * math.pi
    F0 = disk_fractions(n, 0.5, 0.75, 0.15)
    steps = 201
    F = plic_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) >= 0.0 and max(max(r) for r in F) <= 1.0
    rel = l1_error(F, F0) / total_volume(F0)
    assert abs(rel - 0.0184) < 5e-4  # donor-acceptor gives 0.2378 on the same run
    assert smeared_cells(F) == smeared_cells(F0) == 36


def test_bad_input():
    for args in ((0.0, 0.0, 0.5), (1.0, 0.0, 1.5), (1.0, 0.0, -0.1)):
        try:
            line_constant(*args)
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")
    for dt, steps in ((0.2, 1), (0.0, 1), (0.1, -1)):
        try:
            plic_advect(band(8, 0.2, 0.5), dt, steps, lambda y: 1.0, lambda x: 0.0)
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")

History

The SLIC method of Noh and Woodward (1976) used lines aligned with the grid. Youngs (1982) gave the first widely used method with a sloped line in each cell and a normal from the 3×33 \times 3 block, for multi-material flows with large distortion. Rider and Kothe (1998) and Scardovelli and Zaleski (1999) reviewed the field and made PLIC with geometric fluxes the standard. Scardovelli and Zaleski (2000) published the closed-form link between the line position and the volume fraction, which replaced iterative searches, and Pilliod and Puckett (2004) showed which normals give second-order reconstructions.

References

  1. D. L. Youngs, Time-dependent multi-material flow with large fluid distortion, in K. W. Morton and M. J. Baines (eds.), Numerical Methods for Fluid Dynamics, Academic Press, 1982, 273-285, the straight-line interface in each mixed cell and its normal from the neighboring volume fractions
  2. Ruben Scardovelli and Stéphane Zaleski, Analytical relations connecting linear interfaces and volume fractions in rectangular grids, Journal of Computational Physics 164 (2000) 228-237, the closed-form relations between the line constant and the volume fraction
  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 review of VOF interface reconstruction and advection
  4. James E. Pilliod and Elbridge G. Puckett, Second-order accurate volume-of-fluid algorithms for tracking material interfaces, Journal of Computational Physics 199 (2004) 465-502, the LVIRA and ELVIRA normals and the comparison of reconstruction orders
  5. William J. Rider and Douglas B. Kothe, Reconstructing volume tracking, Journal of Computational Physics 141 (1998) 112-152

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