Algorithm Search⌘K

Algorithmadvanced

Front tracking method

Also called Unverdi-Tryggvason method.

Represents the interface by a moving surface mesh that carries surface tension and is coupled to a fixed grid for the flow.

Time
Θ(K (M + S)) worst
Space
Θ(M + N^2) extra
Where
K = the number of time steps; M = the number of front points; N = the number of grid cells along each side; S = the cost of one step of the grid flow solver
Properties
deterministiclagrangian interfacesharp interfacezero net tension force
Origin
Salih O. Unverdi, Gretar Tryggvason, 1992

The front tracking method computes flows of two fluids, such as bubbles in a liquid, by keeping two separate meshes: a fixed grid on which the Navier-Stokes equations are solved, and a moving mesh of connected points that is the interface itself (a curve in 2D, a triangulated surface in 3D). The interface points move with the fluid velocity, interpolated from the grid. In return, the interface computes the surface tension from its own geometry and spreads it onto the grid as a force, with the smoothed delta function of the immersed boundary method. Since the interface is explicit, its position, normal and curvature are known to high accuracy, and the interface stays sharp. The price is bookkeeping: the front must be refined as it stretches, and drops that merge or break up need special treatment.

In plain words

Imagine a bubble rising in water, drawn as a ring of beads joined by threads. The water is computed on a fixed grid of squares, as usual. In each step, every thread pulls on the beads at its two ends with a force equal to the surface tension, so a curved ring is pulled inward, harder where it bends more. These pulls are passed to the nearby grid squares as forces on the water. The flow solver then finds the new water velocity. Each bead reads the velocity from the nearby grid squares and moves with it. When threads become too long, a new bead is put in the middle; when beads come too close, one is taken out. The beads always show exactly where the bubble surface is.

The problem

Solve the incompressible Navier-Stokes equations for two immiscible fluids separated by a moving interface Γ\Gamma, with density ρ\rho and viscosity μ\mu that jump across Γ\Gamma, and a surface tension force σκn\sigma\kappa n concentrated on Γ\Gamma, where σ\sigma is the surface tension coefficient, κ\kappa the curvature and nn the normal. In the one-fluid form used by front tracking this is

ρ(∂tu+u⋅∇u)=−∇p+∇⋅μ(∇u+∇uT)+∫Γσκn δ(x−X(s)) ds,∇⋅u=0,\rho(\partial_tu + u \cdot \nabla u) = -\nabla p + \nabla \cdot \mu(\nabla u + \nabla u^T) + \int_\Gamma\sigma\kappa n\,\delta(x - X(s))\,ds, \qquad \nabla \cdot u = 0,

and the interface moves with the fluid, dX/dt=u(X)dX/dt = u(X). The output is the velocity on the grid and the position of the interface after KK steps. On this page the grid is N×NN \times N cell centers of spacing h=1/Nh = 1/N in the periodic unit square, and the front is a closed polygon X1,…,XMX_1, \dots, X_M in counterclockwise order.

The algorithm

  1. FRONT-TRACKING(X, u, Δt, K)
  2. 1for k ← 1 to K
  3. 2F_k ← σ (t_{k+1/2} - t_{k-1/2}) for every front point k ▷ surface tension
  4. 3f ← Σ_k F_k δ_h(x - X_k) ▷ spread to the grid
  5. 4u ← FLOW-STEP(u, f, Δt) ▷ ρ and μ from the front
  6. 5U_k ← Σ_ij u_ij δ_h(x_ij - X_k) h² ▷ interpolate to the front
  7. 6X_k ← X_k + Δt U_k ▷ midpoint rule in the code
  8. 7split elements longer than l_max, drop points closer than l_min
  9. 8return X, u

Surface tension (line L2). With tk+1/2t_{k+1/2} the unit tangent of the element from XkX_k to Xk+1X_{k+1}, the force on point kk is σ(tk+1/2−tk−1/2)\sigma(t_{k+1/2} - t_{k-1/2}): each element pulls its two end points toward each other with the tension σ\sigma. Since dt/ds=κndt/ds = \kappa n, this is the integral of σκn\sigma\kappa n over the half elements on both sides of the point. This is the form described by Tryggvason and co-workers (2001), and its forces on a closed front add up to exactly zero.

Front to grid and back (lines L3 and L5). The smoothed delta function is δh(x,y)=ϕ(x/h)ϕ(y/h)/h2\delta_h(x, y) = \phi(x/h)\phi(y/h)/h^2 with Peskin's 4-point kernel

ϕ(r)=18(3−2∣r∣+1+4∣r∣−4r2) for ∣r∣≤1,ϕ(r)=18(5−2∣r∣−−7+12∣r∣−4r2) for 1≤∣r∣≤2,\phi(r) = \tfrac18\bigl(3 - 2|r| + \sqrt{1 + 4|r| - 4r^2}\bigr) \text{ for } |r| \le 1, \qquad \phi(r) = \tfrac18\bigl(5 - 2|r| - \sqrt{-7 + 12|r| - 4r^2}\bigr) \text{ for } 1 \le |r| \le 2,

and ϕ=0\phi = 0 beyond. The same weights are used in both directions, so spreading and interpolation are adjoint, and each front point touches a block of 4×44 \times 4 grid points.

The flow step (line L4). Any grid solver can be used; Unverdi and Tryggvason used a conservative finite difference method on a fixed grid, and a projection method on a staggered grid, as in the MAC method, is the usual choice. The density and viscosity on the grid come from an indicator function II, which is 1 in one fluid and 0 in the other. To find it, the jump of II times the normal is spread from the front like a force, giving a grid approximation GG of ∇I\nabla I, and the Poisson equation ∇2I=∇⋅G\nabla^2I = \nabla \cdot G is solved. The code on this page takes the flow step as a parameter, and the tests use a prescribed velocity, so they check the front part of the method on its own.

Restructuring (line L7). In a stretching flow the elements grow, and in a compressing flow they shrink. The code splits each element longer than lmax⁡l_{\max} into equal parts and then drops points that are closer than lmin⁡l_{\min} to the previous kept point. In 3D the front is a triangulation, and the same job is done by splitting, collapsing and flipping edges.

Example

A corner, by hand. For the unit square with corners (0,0),(1,0),(1,1),(0,1)(0, 0), (1, 0), (1, 1), (0, 1) and σ=1\sigma = 1, the point (1,0)(1, 0) has tk−1/2=(1,0)t_{k-1/2} = (1, 0) and tk+1/2=(0,1)t_{k+1/2} = (0, 1), so its force is (−1,1)(-1, 1), pointing into the square with length 2=2sin⁡(π/4)\sqrt2 = 2\sin(\pi/4). The four forces add up to zero. For a regular polygon with MM points on a circle of radius RR, each force has length 2σsin⁡(π/M)2\sigma\sin(\pi/M) and points to the center; divided by the element length 2Rsin⁡(π/M)2R\sin(\pi/M) it is σ/R\sigma/R, the force per length of the Young-Laplace law.

The Laplace pressure jump. In a drop at rest the pressure balances the surface tension, ∇p=f\nabla p = f, so the jump of pp across the interface is the integral of the spread force across it. In 2D the exact jump is σ/R\sigma/R. For a circle of radius R=0.25R = 0.25 centered on a cell center, with σ=1\sigma = 1, integrating fxf_x along the grid row through the center gave:

NN MM front spacing / hh Δp R/σ\Delta p\,R/\sigma
32 64 0.79 1.0155
32 128 0.39 0.9989
64 128 0.79 1.0159
64 256 0.39 0.9990

The error depends on the front spacing compared with hh, not on hh itself: with about two front points per grid cell, the jump is within 0.1%. In all cases the total spread force was zero to 10−1610^{-16}.

Advection. A circle of radius 0.15 at (0.5,0.75)(0.5, 0.75) with 64 points turns once in the prescribed rotation u=−2π(y−12)u = -2\pi(y - \frac12), v=2π(x−12)v = 2\pi(x - \frac12), interpolated from a 32×3232 \times 32 grid. Since the kernel reproduces linear fields, only the time step matters:

steps 50 100 200
max point error 0.0066 0.0017 0.00041
area change 3.1⋅10−33.1 \cdot 10^{-3} 3.9⋅10−43.9 \cdot 10^{-4} 4.9⋅10−54.9 \cdot 10^{-5}

The point error falls as Δt2\Delta t^2, as for the midpoint rule. The area is not kept exactly: the front has no built-in volume conservation, which is the main difference from the volume of fluid method. In the shear flow u=y−12u = y - \frac12, a circle of radius 0.2 with 40 points was stretched for t=2t = 2 with lmin⁡=0.01l_{\min} = 0.01 and lmax⁡=0.03l_{\max} = 0.03. The first restructuring split every element into two, and the front ended with 110 points, all elements between 0.013 and 0.027 long. No point was dropped, so the area stayed the same to 3⋅10−153 \cdot 10^{-15}.

Correctness

The proof file shows four exact facts. The forces of line L2 on a closed front have zero sum and zero torque, because each element pulls its two end points with equal and opposite forces along the element. Peskin's kernel has ∑jϕ(r−j)=1\sum_j\phi(r - j) = 1 and ∑j(r−j)ϕ(r−j)=0\sum_j(r - j)\phi(r - j) = 0 for every rr. So spreading keeps the total force and the total torque, and the grid flow gets no net momentum or angular momentum from surface tension, while interpolation is exact for linear velocity fields. Splitting elements does not change the front. The accuracy of the coupled method, with a real flow solver, is a matter of measurement; Tryggvason and co-workers (2001) report the tests.

Proof: The front forces of front tracking have zero sum and zero torque, and the transfer to the grid keeps bothfull

We use the notation of the page. The front is a closed polygon with points X1,…,XMX_1, \dots, X_M, indices taken mod MM, and tk+1/2=(Xk+1−Xk)/∣Xk+1−Xk∣t_{k+1/2} = (X_{k+1} - X_k)/|X_{k+1} - X_k|. Line L2 gives the force Fk=σ(tk+1/2−tk−1/2)F_k = \sigma(t_{k+1/2} - t_{k-1/2}) on point kk. The 1D kernel is Peskin's

ϕ(r)={(3−2∣r∣+1+4∣r∣−4r2)/8,∣r∣≤1,(5−2∣r∣−−7+12∣r∣−4r2)/8,1≤∣r∣≤2,0,∣r∣≥2,\phi(r) = \begin{cases} \bigl(3 - 2|r| + \sqrt{1 + 4|r| - 4r^2}\bigr)/8, & |r| \le 1, \\ \bigl(5 - 2|r| - \sqrt{-7 + 12|r| - 4r^2}\bigr)/8, & 1 \le |r| \le 2, \\ 0, & |r| \ge 2, \end{cases}

and δh(x,y)=ϕ(x/h)ϕ(y/h)/h2\delta_h(x, y) = \phi(x/h)\phi(y/h)/h^2. We claim, in exact arithmetic:

  1. ∑kFk=0\sum_kF_k = 0 and ∑kXk×Fk=0\sum_kX_k \times F_k = 0, where a×b=axby−aybxa \times b = a_xb_y - a_yb_x.
  2. For every real rr, ∑jϕ(r−j)=1\sum_j\phi(r - j) = 1 and ∑j(r−j)ϕ(r−j)=0\sum_j(r - j)\phi(r - j) = 0, with jj over the integers.
  3. If the kernel stencils of the front points do not wrap around the periodic box, the grid force f=∑kFkδh(x−Xk)f = \sum_kF_k\delta_h(x - X_k) of line L3 has ∑ijfijh2=∑kFk\sum_{ij}f_{ij}h^2 = \sum_kF_k and ∑ijxij×fijh2=∑kXk×Fk\sum_{ij}x_{ij} \times f_{ij}h^2 = \sum_kX_k \times F_k. So surface tension gives the grid flow no net force and no net torque. Also, line L5 interpolates every linear velocity field exactly.
  4. The splitting part of the regrid (line L7) does not change the polygon, so it keeps the enclosed area and the shape.

Claim 1. The sum telescopes: ∑k(tk+1/2−tk−1/2)=0\sum_k(t_{k+1/2} - t_{k-1/2}) = 0 for a closed front. For the torque, reorder the sum by elements:

∑kXk×(tk+1/2−tk−1/2)=∑kXk×tk+1/2−∑kXk+1×tk+1/2=−∑k(Xk+1−Xk)×tk+1/2.\sum_kX_k \times (t_{k+1/2} - t_{k-1/2}) = \sum_kX_k \times t_{k+1/2} - \sum_kX_{k+1} \times t_{k+1/2} = -\sum_k(X_{k+1} - X_k) \times t_{k+1/2}.

Each term is the cross product of the element with its own direction, which is 00. The same argument shows that the force is that of a tension σ\sigma pulling along each element on its two end points: each element pulls its end points toward each other with equal and opposite forces, so the forces are internal to the front.

Claim 2. Both sums are periodic in rr with period 1, so take 0≤r<10 \le r < 1. The only integers with ∣r−j∣<2|r - j| < 2 are j=−1,0,1,2j = -1, 0, 1, 2, at distances 1+r1 + r, rr, 1−r1 - r and 2−r2 - r. Put s=1+4r−4r2s = \sqrt{1 + 4r - 4r^2}. Expanding the expression under each square root gives s2s^2 in all four cases: for example, −7+12(1+r)−4(1+r)2=1+4r−4r2-7 + 12(1 + r) - 4(1 + r)^2 = 1 + 4r - 4r^2. So

8ϕ(r)=3−2r+s,8ϕ(1−r)=1+2r+s,8ϕ(1+r)=3−2r−s,8ϕ(2−r)=1+2r−s.8\phi(r) = 3 - 2r + s, \quad 8\phi(1 - r) = 1 + 2r + s, \quad 8\phi(1 + r) = 3 - 2r - s, \quad 8\phi(2 - r) = 1 + 2r - s.

These add up to 8, which is the first identity. For the second,

8∑j(r−j)ϕ(r−j)=(1+r)(3−2r−s)+r(3−2r+s)+(r−1)(1+2r+s)+(r−2)(1+2r−s).8\sum_j(r - j)\phi(r - j) = (1 + r)(3 - 2r - s) + r(3 - 2r + s) + (r - 1)(1 + 2r + s) + (r - 2)(1 + 2r - s).

The coefficient of ss is −(1+r)+r+(r−1)−(r−2)=0-(1 + r) + r + (r - 1) - (r - 2) = 0. The rest is (−2r2+r+3)+(3r−2r2)+(2r2−r−1)+(2r2−3r−2)=0(-2r^2 + r + 3) + (3r - 2r^2) + (2r^2 - r - 1) + (2r^2 - 3r - 2) = 0.

Claim 3. Write the 2D weight of grid point (i,j)(i, j) for front point kk as wij=ϕ(ξi)ϕ(ηj)w_{ij} = \phi(\xi_i)\phi(\eta_j), with ξi=(xi−Xk,x)/h\xi_i = (x_i - X_{k,x})/h and ηj=(yj−Xk,y)/h\eta_j = (y_j - X_{k,y})/h. The cell centers are hh apart, so the ξi\xi_i are a shifted copy of the integers, and since ϕ\phi is even, Claim 2 gives ∑ijwij=1\sum_{ij}w_{ij} = 1, ∑ijxiwij=Xk,x\sum_{ij}x_iw_{ij} = X_{k,x} and ∑ijyjwij=Xk,y\sum_{ij}y_jw_{ij} = X_{k,y} (the first moment identity says that the weighted mean of the grid points is the front point). Then ∑ijfijh2=∑kFk∑ijwij=∑kFk\sum_{ij}f_{ij}h^2 = \sum_kF_k\sum_{ij}w_{ij} = \sum_kF_k, and

∑ijxij×fijh2=∑k(∑ijwijxij)×Fk=∑kXk×Fk.\sum_{ij}x_{ij} \times f_{ij}h^2 = \sum_k\Bigl(\sum_{ij}w_{ij}x_{ij}\Bigr) \times F_k = \sum_kX_k \times F_k.

With Claim 1, both are zero. For interpolation, Uk=∑ijwiju(xij)U_k = \sum_{ij}w_{ij}u(x_{ij}), and for u(x)=a+Bxu(x) = a + Bx the same identities give Uk=a+BXkU_k = a + BX_k. If a stencil wraps around the box, the coordinates xijx_{ij} jump by 1 and the moment identities fail; the code assumes the front stays away from the boundary, or a velocity that is periodic.

Claim 4. A split element is replaced by points on the segment between its end points, so the polygon, as a set, is the same. The dropping step removes a point, which replaces two elements by one, and in general changes the area; the page measures this change. ■\blacksquare

Complexity

Lines L2, L3, L5 and L6 cost Θ(M)\Theta(M), with a constant of 16 grid points per front point for each transfer. Restructuring costs Θ(M)\Theta(M). So a step costs Θ(M+S)\Theta(M + S), where SS is the cost of the flow step, and a run Θ(K(M+S))\Theta(K(M + S)). With M=Θ(N)M = \Theta(N) points on a 2D grid, the front is cheap compared with the grid solve: a fast Poisson solver gives S=Θ(N2log⁡N)S = \Theta(N^2\log N) in 2D. Memory is Θ(M+N2)\Theta(M + N^2). The indicator function needs one more Poisson solve per step.

Properties

  • Sharp interface. The fluid properties jump over a few grid cells, set by the width of δh\delta_h, and the interface position is known to the accuracy of the front points, not of the grid.
  • Accurate curvature. The surface tension comes from the front geometry, which is smooth, so the force is much less noisy than curvature computed from volume fractions.
  • Zero net force from surface tension, exactly, as the proof shows. This rules out the self-propulsion of a drop by its own surface tension.
  • Volume is kept only approximately. The enclosed area changes with the time-stepping error and with each dropped point, as the advection table shows. Long runs correct it.
  • Topology changes are not automatic. Two drops that touch do not merge until the code finds the close fronts and reconnects them.

Variants and improvements

  • Level contour reconstruction. Shin and Juric rebuild the front from a contour of the indicator function every few steps, which makes merging and breakup automatic in 3D and removes most of the restructuring code.
  • Mass correction. Codes move the front points a little along the normal after each step to restore the volume of each drop.
  • Hybrid methods. The front can be combined with a level set or with the volume of fluid method, using the front for curvature and the other method for topology and conservation.
  • Other force forms. Surface tension can be computed per element with the curvature of a fitted curve, which is more accurate for coarse fronts but no longer sums to exactly zero.
  • Front tracking for shocks. In compressible gas dynamics, front tracking of Glimm and co-workers follows shocks and contact discontinuities as moving curves. It has the same name but solves the jump conditions at the front, not a one-fluid equation.

When to use it

Use front tracking for flows where the interface shape and the surface tension must be very accurate and the topology does not change often: rising bubbles, drops in shear, deformable cells and capsules, and flows with surfactants that live on the interface. It is also the natural choice when quantities are carried on the interface, because the front points can store them. For flows with much breakup and merging, such as atomization, the volume of fluid method or a level set is simpler. For surface tension on those methods, see the continuum surface force model.

Pitfalls

  • Unresolved front. With front points much farther apart than hh, the spread force has gaps; the Laplace table shows 1.6% error at 0.79 points per cell. Keep the front spacing near h/2h/2 to hh.
  • Over-refined front. Front points much closer than h/4h/4 add work and give short elements whose tangents are noisy. Drop them, as line L7 does.
  • Volume drift. The front is not conservative. Monitor the volume of each drop and correct it.
  • Merging and breakup. Two fronts that come within a few grid cells interact through the smoothed fields, but do not join. Decide when they should, and reconnect them.
  • Periodic wrap. The moment identities of the kernel use the true coordinates of the grid points. When a front crosses a periodic boundary, shift the coordinates before spreading.
  • Parasitic currents. Even with exact force balance, the pressure on the grid cannot balance a smoothed force exactly, so a drop at rest shows small spurious velocities. They are much smaller than with curvature from volume fractions, but they are there.

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.

front_tracking_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/front-tracking-method/. The authors are listed in prov/7VRC33.jsonl.
"""The front part of the front tracking method of Unverdi and Tryggvason in 2D.

The front is a closed polygon of marker points X[k] = (x, y), in counterclockwise
order, inside the periodic unit square. The flow lives on an n x n grid of cell
centers ((i + 1/2) h, (j + 1/2) h), h = 1/n; grid arrays are indexed g[i][j] with i
along x. Front and grid are linked by the 4-point delta function of Peskin. The flow
solver itself is a parameter of `front_track`: it receives the grid force density and
returns the new grid velocity. The tests use a prescribed velocity.
"""
from __future__ import annotations

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

Grid = List[List[float]]
Point = Tuple[float, float]
FlowStep = Callable[[Grid, Grid, Grid, Grid, float], Tuple[Grid, Grid]]


def peskin_phi(r: float) -> float:
    """Peskin's 4-point kernel: sum_j phi(r - j) = 1, sum_j (r - j) phi(r - j) = 0. O(1)."""
    a = abs(r)
    if a <= 1.0:
        return (3.0 - 2.0 * a + math.sqrt(1.0 + 4.0 * a - 4.0 * a * a)) / 8.0
    if a < 2.0:
        return (5.0 - 2.0 * a - math.sqrt(max(0.0, -7.0 + 12.0 * a - 4.0 * a * a))) / 8.0
    return 0.0


def _stencil(p: float, n: int) -> List[Tuple[int, float]]:
    """Grid indices (mod n) and 1D weights of the 4 cell centers nearest to p (a coordinate)."""
    s = p * n - 0.5  # position in units of h, relative to the first cell center
    base = math.floor(s) - 1
    return [((base + t) % n, peskin_phi(s - (base + t))) for t in range(4)]


def tension_forces(X: Sequence[Point], sigma: float) -> List[Point]:
    """Surface tension force on each front point: sigma (t_{k+1/2} - t_{k-1/2}).

    t_{k+1/2} is the unit tangent of the element from point k to point k + 1. For a
    closed front the forces add up to zero and have zero total torque. Cost O(M).
    """
    m = len(X)
    if m < 3:
        raise ValueError("a closed front needs at least 3 points")
    t = []
    for k in range(m):
        dx = X[(k + 1) % m][0] - X[k][0]
        dy = X[(k + 1) % m][1] - X[k][1]
        ln = math.hypot(dx, dy)
        if ln == 0.0:
            raise ValueError("two front points coincide")
        t.append((dx / ln, dy / ln))
    return [(sigma * (t[k][0] - t[k - 1][0]), sigma * (t[k][1] - t[k - 1][1])) for k in range(m)]  # @line L2


def spread(X: Sequence[Point], F: Sequence[Point], n: int) -> Tuple[Grid, Grid]:
    """Force density on the grid: f(x) = sum_k F_k delta_h(x - X_k). Keeps sum f h^2 = sum F."""
    fx = [[0.0] * n for _ in range(n)]
    fy = [[0.0] * n for _ in range(n)]
    inv = float(n * n)  # 1 / h^2
    for (px, py), (gx, gy) in zip(X, F):
        sx, sy = _stencil(px, n), _stencil(py, n)
        for i, wi in sx:
            for j, wj in sy:
                w = wi * wj * inv
                fx[i][j] += w * gx  # @line L3
                fy[i][j] += w * gy
    return fx, fy


def interpolate(u: Grid, v: Grid, X: Sequence[Point]) -> List[Point]:
    """Front velocities U_k = sum_ij u_ij delta_h(x_ij - X_k) h^2. Exact for linear u."""
    n = len(u)
    out = []
    for px, py in X:
        sx, sy = _stencil(px, n), _stencil(py, n)
        a = b = 0.0
        for i, wi in sx:
            for j, wj in sy:
                a += wi * wj * u[i][j]  # @line L5
                b += wi * wj * v[i][j]
        out.append((a, b))
    return out


def regrid(X: Sequence[Point], lmin: float, lmax: float) -> List[Point]:
    """Split elements longer than lmax at their midpoints, then drop points whose
    element to the next kept point is shorter than lmin. Needs 0 < lmin < lmax / 2."""
    if not 0.0 < lmin < 0.5 * lmax:
        raise ValueError("need 0 < lmin < lmax / 2")
    out: List[Point] = []
    m = len(X)
    for k in range(m):
        p, q = X[k], X[(k + 1) % m]
        ln = math.hypot(q[0] - p[0], q[1] - p[1])
        parts = max(1, math.ceil(ln / lmax))
        for s in range(parts):  # @line L7
            out.append((p[0] + (q[0] - p[0]) * s / parts, p[1] + (q[1] - p[1]) * s / parts))
    kept = [out[0]]
    for p in out[1:]:
        if math.hypot(p[0] - kept[-1][0], p[1] - kept[-1][1]) >= lmin:
            kept.append(p)
    while len(kept) > 3 and math.hypot(kept[0][0] - kept[-1][0], kept[0][1] - kept[-1][1]) < lmin:
        kept.pop()
    return kept


def front_track(X0: Sequence[Point], u: Grid, v: Grid, dt: float, steps: int, sigma: float,
                flow_step: FlowStep, lmin: float, lmax: float) -> Tuple[List[Point], Grid, Grid]:
    """Run `steps` steps of front tracking. Precondition: X0 is a closed front inside the
    unit square, dt > 0, the flow step keeps the front points away from the boundary.

    Each step costs O(M) for the front plus the cost of the flow step, with M front points.
    The front moves by the midpoint rule with the new grid velocity.
    """
    if dt <= 0 or steps < 0:
        raise ValueError("need dt > 0 and steps >= 0")
    X = list(X0)
    n = len(u)
    for _ in range(steps):  # @line L1
        F = tension_forces(X, sigma)
        fx, fy = spread(X, F, n)
        u, v = flow_step(u, v, fx, fy, dt)  # @line L4
        U = interpolate(u, v, X)
        mid = [(x + 0.5 * dt * a, y + 0.5 * dt * b) for (x, y), (a, b) in zip(X, U)]
        Um = interpolate(u, v, mid)
        X = [(x + dt * a, y + dt * b) for (x, y), (a, b) in zip(X, Um)]  # @line L6
        X = regrid(X, lmin, lmax)
    return X, u, v  # @line L8


def circle_front(cx: float, cy: float, r: float, m: int) -> List[Point]:
    """m points on a circle, counterclockwise."""
    return [(cx + r * math.cos(2 * math.pi * k / m), cy + r * math.sin(2 * math.pi * k / m)) for k in range(m)]


def enclosed_area(X: Sequence[Point]) -> float:
    """Signed area of the front polygon (positive for counterclockwise)."""
    m = len(X)
    return 0.5 * sum(X[k][0] * X[(k + 1) % m][1] - X[(k + 1) % m][0] * X[k][1] for k in range(m))


def grid_field(n: int, fu: Callable[[float, float], float]) -> Grid:
    """Sample a function at the cell centers."""
    h = 1.0 / n
    return [[fu((i + 0.5) * h, (j + 0.5) * h) for j in range(n)] for i in range(n)]
test_front_tracking_method.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/front-tracking-method/. The authors are listed in prov/7VRC33.jsonl.
import math
import random

from front_tracking_method import (
    circle_front,
    enclosed_area,
    front_track,
    grid_field,
    interpolate,
    peskin_phi,
    regrid,
    spread,
    tension_forces,
)


def frozen(u, v, fx, fy, dt):
    return u, v


def test_peskin_kernel_moments():
    rng = random.Random(1)
    for _ in range(200):
        r = rng.uniform(-3.0, 3.0)
        w = [peskin_phi(r - j) for j in range(-6, 7)]
        assert abs(sum(w) - 1.0) < 1e-14
        assert abs(sum((r - j) * peskin_phi(r - j) for j in range(-6, 7))) < 1e-14
        assert abs(sum(a * a for a in w) - 0.375) < 1e-14
    assert peskin_phi(2.0) == 0.0 and abs(peskin_phi(0.0) - 0.5) < 1e-15


def test_tension_forces_hand_and_balance():
    sq = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
    F = tension_forces(sq, 1.0)
    assert F[1] == (-1.0, 1.0)  # inward at the corner (1, 0), length sqrt(2) = 2 sin(pi/4)
    rng = random.Random(2)
    for _ in range(50):
        m = rng.randrange(5, 40)
        X = [(0.5 + (0.2 + 0.1 * rng.random()) * math.cos(2 * math.pi * k / m),
              0.5 + (0.2 + 0.1 * rng.random()) * math.sin(2 * math.pi * k / m)) for k in range(m)]
        F = tension_forces(X, 0.7)
        assert abs(sum(f[0] for f in F)) < 1e-14 and abs(sum(f[1] for f in F)) < 1e-14
        torque = sum(x * f[1] - y * f[0] for (x, y), f in zip(X, F))
        assert abs(torque) < 1e-14
        fx, fy = spread(X, F, 16)
        assert abs(sum(map(sum, fx)) / 256) < 1e-13 and abs(sum(map(sum, fy)) / 256) < 1e-13


def test_spread_and_interpolate():
    n = 16
    fx, fy = spread([(0.3141, 0.2718)], [(2.0, -1.0)], n)
    assert abs(sum(map(sum, fx)) / n ** 2 - 2.0) < 1e-14 and abs(sum(map(sum, fy)) / n ** 2 + 1.0) < 1e-14
    u = grid_field(n, lambda x, y: 1.5 * x - 0.5 * y + 0.25)
    v = grid_field(n, lambda x, y: -0.3 * x + 2.0 * y)
    for (a, b), (x, y) in zip(interpolate(u, v, [(0.3, 0.4), (0.55, 0.61), (0.5, 0.5)]), [(0.3, 0.4), (0.55, 0.61), (0.5, 0.5)]):
        assert abs(a - (1.5 * x - 0.5 * y + 0.25)) < 1e-14 and abs(b - (-0.3 * x + 2.0 * y)) < 1e-14


def test_laplace_pressure_jump():
    n, m, r, sigma = 32, 128, 0.25, 1.0
    c = (n // 2 + 0.5) / n
    fx, fy = spread(circle_front(c, c, r, m), tension_forces(circle_front(c, c, r, m), sigma), n)
    dp = -sum(fx[i][n // 2] for i in range(n // 2, n)) / n  # integral of grad p = f across the front
    assert abs(dp - sigma / r) < 0.01 * sigma / r  # measured 3.9957 against 4


def test_rotation_second_order():
    w = 2 * math.pi
    n = 32
    u = grid_field(n, lambda x, y: -w * (y - 0.5))
    v = grid_field(n, lambda x, y: w * (x - 0.5))
    X0 = circle_front(0.5, 0.75, 0.15, 64)
    errs = []
    for steps in (50, 100):
        X, _, _ = front_track(X0, u, v, 1.0 / steps, steps, 0.0, frozen, 0.002, 0.03)
        assert len(X) == 64
        errs.append(max(math.hypot(a[0] - b[0], a[1] - b[1]) for a, b in zip(X, X0)))
    assert errs[1] < 1.8e-3 and 3.8 < errs[0] / errs[1] < 4.2


def test_shear_regrid():
    n = 32
    u = grid_field(n, lambda x, y: y - 0.5)
    v = grid_field(n, lambda x, y: 0.0)
    X0 = circle_front(0.5, 0.5, 0.2, 40)
    X, _, _ = front_track(X0, u, v, 0.05, 40, 0.0, frozen, 0.01, 0.03)
    m = len(X)
    lengths = [math.hypot(X[(k + 1) % m][0] - X[k][0], X[(k + 1) % m][1] - X[k][1]) for k in range(m)]
    assert m > 40 and min(lengths) >= 0.01 and max(lengths) <= 0.04
    assert abs(enclosed_area(X) / enclosed_area(X0) - 1.0) < 2e-3
    sq = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
    assert enclosed_area(regrid(sq, 0.1, 0.3)) == 1.0 and len(regrid(sq, 0.1, 0.3)) == 16


def test_bad_input():
    for f in (lambda: tension_forces([(0.0, 0.0), (1.0, 0.0)], 1.0),
              lambda: tension_forces([(0.0, 0.0), (0.0, 0.0), (1.0, 1.0)], 1.0),
              lambda: regrid(circle_front(0.5, 0.5, 0.2, 8), 0.2, 0.3),
              lambda: front_track(circle_front(0.5, 0.5, 0.2, 8), [[0.0]], [[0.0]], 0.0, 1, 1.0, frozen, 0.01, 0.03)):
        try:
            f()
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")

History

The immersed boundary method of Peskin, built in the 1970s for heart valves, gave the idea of a Lagrangian structure that spreads its forces onto a fixed grid with a smoothed delta function. Unverdi and Tryggvason (1992) used this idea for the interface between two fluids, with a front of connected points, an indicator function found from the front, and the one-fluid Navier-Stokes equations on a fixed grid. Tryggvason and co-workers developed the method for bubbly flows, boiling, solidification and flows with surfactants, and their review (Tryggvason et al. 2001) describes it in detail. Peskin (2002) reviewed the immersed boundary method and the construction of its delta functions.

References

  1. Salih O. Unverdi and Gretar Tryggvason, A front-tracking method for viscous, incompressible, multi-fluid flows, Journal of Computational Physics 100 (1992) 25-37, the front of connected marker points, the transfer between front and grid, and the indicator function
  2. G. Tryggvason, B. Bunner, A. Esmaeeli, D. Juric, N. Al-Rawahi, W. Tauber, J. Han, S. Nas and Y.-J. Jan, A front-tracking method for the computations of multiphase flow, Journal of Computational Physics 169 (2001) 708-759, the surface tension on front elements, the restructuring of the front and the validation tests
  3. Charles S. Peskin, The immersed boundary method, Acta Numerica 11 (2002) 479-517, the construction of the 4-point delta function from its moment conditions

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