Algorithm Search⌘K

Algorithmresearch

Topological tetrahedral mesh improvement

Also called multi-face removal, aggressive tetrahedral mesh improvement.

Improves a tetrahedral mesh by edge removal, multi-face removal, flips and vertex insertion chosen to raise the worst quality, as Shewchuk and Klingner did.

Time
O(1) flipO(n) pass
Space
O(n) extra
Where
n = the number of tetrahedra
Properties
deterministicexactiterative
Origin
Bryan Matthew Klingner, Jonathan Richard Shewchuk, Barry Joe, Lori A. Freitag, Carl Ollivier Gooch, 2007

Topological tetrahedral mesh improvement changes which vertices make up the tetrahedra of a mesh, without moving the vertices, to raise the quality of the worst tetrahedra. The basic moves are the 2-3 flip, which replaces two tetrahedra on a shared triangle by three around a new edge, and its inverse, the 3-2 flip. Edge removal generalises the 3-2 flip to an edge with any number of tetrahedra around it, and multi-face removal generalises the 2-3 flip to a stack of triangles. Klingner and Shewchuk combined these moves with smoothing and vertex insertion in a hill climbing scheme that accepts a move only if it raises the worst quality nearby, and got meshes with all dihedral angles far from 0° and 180° on their tests. The validity of each flip and the termination of hill climbing are proved; the quality of the result is only measured.

In plain words

A tetrahedral mesh fills a solid with small four-cornered pieces. A bad piece is flat, like a coin, and spoils a simulation. Sometimes the corners are in good places, but they are joined the wrong way.

Look at two pieces glued on a common triangle. Their five corners can also be joined as three pieces around the line between the two far corners. That swap is a 2-3 flip, and the reverse is a 3-2 flip. It is allowed only if that line passes through the inside of the shared triangle; otherwise the new pieces would stick out or overlap.

The method tries all such swaps, and keeps a swap only if the worst of the new pieces is better than the worst of the old ones. It stops when no swap helps. Larger swaps, moving corners and adding corners help it get further. A program measures the result.

The problem

The input is a valid tetrahedral mesh: positively oriented tetrahedra with disjoint interiors that meet face to face. The goal is a mesh of the same region with the same boundary triangles, on the same vertices or on a few more, whose worst tetrahedron is as good as possible under a measure from the mesh quality measures. This page uses the mean ratio 12(3V)2/3/∑ℓ212(3V)^{2/3}/\sum \ell^2, which is 1 for the regular tetrahedron and 0 for a flat one. Klingner and Shewchuk also used the smallest sine of the six dihedral angles and a volume-length measure.

The radius-edge ratio, used by tetrahedral Delaunay refinement, is 6/4\sqrt6/4 for the regular tetrahedron, but a sliver, a flat tetrahedron whose four vertices lie near a circle, can have a small radius-edge ratio too. Slivers pass a radius-edge bound, which is why improvement works with measures that see them, such as the mean ratio or dihedral angles.

The algorithm

orient3d is six times the signed volume, computed exactly. qq is the quality. Faces and edges are scanned in a fixed order, and the first improving flip is applied.

  1. FLIP-23(abc, d, e) ▷ tetrahedra abcd and abce share abc
  2. 1if orient3d(a,b,d,e), orient3d(b,c,d,e), orient3d(c,a,d,e) do not have one strict sign then fail
  3. 2return abde, bcde, cade, each ordered so that orient3d > 0
  4. FLIP-32(de, ring abc) ▷ exactly three tetrahedra contain the interior edge de
  5. 3if orient3d(a,b,c,d) · orient3d(a,b,c,e) ≥ 0 then fail
  6. 4return abcd, abce, each ordered so that orient3d > 0
  7. IMPROVE(M)
  8. 5repeat
  9. 6for each face abc shared by two tetrahedra abcd and abce of M do
  10. 7N ← FLIP-23(abc, d, e)
  11. 8if N ≠ fail and min q(N) > min(q(abcd), q(abce)) then replace them by N; restart at L5
  12. 9for each interior edge de in exactly three tetrahedra, with ring abc, do
  13. 10N ← FLIP-32(de, abc)
  14. 11if N ≠ fail and min q(N) > min q of the three then replace them by N; restart at L5
  15. 12until no flip was applied in the pass
  16. 13return M

L1 is the exact form of the condition that the segment dede crosses the interior of the triangle abcabc. L3 asks that dd and ee are strictly on opposite sides of the plane abcabc; given that the three tetrahedra around dede are valid, this is the same crossing condition seen from the other side. L8 and L11 make the method hill climbing on the worst local quality.

Example

Take the triangle a=(0,0,0)a = (0,0,0), b=(4,0,0)b = (4,0,0), c=(2,4,0)c = (2,4,0) and the apexes d=(2,1,1)d = (2,1,1) above and e=(2,1,−1)e = (2,1,-1) below. The two tetrahedra abcdabcd and abceabce are flat: each has 6V=166V = 16 and mean ratio 0.61540.6154. The values in L1 are [abde]=−8[abde] = -8, [bcde]=−12[bcde] = -12, [cade]=−12[cade] = -12, one strict sign, because the segment dede meets the plane z=0z = 0 at (2,1,0)(2, 1, 0), inside abcabc. The flip gives three tetrahedra with 6V=8,12,126V = 8, 12, 12, which add up to 32, the old total 16+1616 + 16. Their mean ratios are 0.68720.6872, 0.70760.7076 and 0.70760.7076, so the worst rises from 0.61540.6154 to 0.68720.6872, and L8 accepts the flip.

A valid flip is not always an improvement. With c=(0,4,0)c = (0,4,0), d=(1,1,3)d = (1,1,3), e=(1,1,−2)e = (1,1,-2), the old pair has 6V=486V = 48 and 3232 and mean ratios 0.88360.8836 and 0.77750.7775; the flip is valid, with 6V=20,40,206V = 20, 40, 20 that add up to 80, but the worst new mean ratio is 0.61210.6121, so hill climbing rejects it. If ee moves to (5,5,−1)(5,5,-1), the segment dede misses the triangle, L1 fails, and the flip would make overlapping tetrahedra.

On the cube [0,3]3[0,3]^3 cut into 162 tetrahedra by the Kuhn split, with the interior vertices moved randomly by up to 1/21/2, hill climbing made 6 flips in one run and raised the worst mean ratio from 0.1250.125 to 0.1880.188, and 8 flips in another, from 0.2120.212 to 0.2630.263. In a third run it made 4 flips but the worst tetrahedron, which no single flip could reach, stayed at 0.1420.142. These are measurements.

Correctness

The full proofs are in the proof file. The key fact is a five-point identity: for any five points, the alternating sum of the signed volumes of the five tetrahedra that leave out one point is zero. Applied to a,b,c,d,ea, b, c, d, e, it says that the two old volumes add up to the three new ones, so the flip keeps the volume. Lemma 2 of the proof shows that the three new orientations are −1s-\frac1s times the barycentric coordinates of the crossing point pp of dede with the plane abcabc, times [abcd][abcd]. So they have one strict sign exactly when pp is inside abcabc, which is the validity condition. The new tetrahedra then have disjoint interiors and the same six boundary triangles as the old pair, so the rest of the mesh still fits. The 3-2 flip is the inverse.

Hill climbing stops: each accepted flip makes the sorted list of qualities lexicographically larger, and a fixed vertex set has only finitely many tetrahedral meshes, so no mesh repeats.

What is proved: every flip keeps a valid mesh of the same region with the same boundary, the worst quality never decreases, and the loop stops. What is not proved: any bound on the angles. In a measured run, a 2×2×22 \times 2 \times 2 cube mesh whose smallest dihedral angle was 34.4°34.4° was scrambled by random valid flips to a mesh with smallest dihedral angle 2.53°2.53°, and hill climbing with 2-3 and 3-2 flips alone could not raise it at all.

Proof: The 2-3 and 3-2 flips keep the volume and the validity of a tetrahedral mesh, and hill climbing with them stopsfull

Notation. [p0p1p2p3][p_0 p_1 p_2 p_3] is orient3d(p0,p1,p2,p3)\mathrm{orient3d}(p_0, p_1, p_2, p_3), six times the signed volume. A tetrahedral mesh is valid if every tetrahedron has [⋅]>0[\cdot] > 0 in its stored order, the interiors are pairwise disjoint, and every face is shared by at most two tetrahedra. A face in one tetrahedron only is a boundary face. Two meshes of the same region with the same boundary faces can replace each other inside a larger mesh, and the result is again conforming.

Lemma 1 (five points). For any points p0,…,p4p_0, \dots, p_4 in space, ∑i=04(−1)i [p0⋯pi^⋯p4]=0\sum_{i=0}^{4} (-1)^i\,[p_0 \cdots \widehat{p_i} \cdots p_4] = 0, where the hat means that pip_i is left out.

Proof. [q0q1q2q3][q_0 q_1 q_2 q_3] is, up to one fixed sign, the 4×44 \times 4 determinant with rows (1,qj)(1, q_j). Form the 5×55 \times 5 matrix with rows (1,pi,1)(1, p_i, 1). Its first and last columns are equal, so its determinant is zero. Expanding along the last column gives the alternating sum of the five 4×44 \times 4 minors, which is the claim. □\square

Lemma 2 (the crossing test). Let dd and ee lie strictly on opposite sides of the plane of the triangle abcabc, and let pp be the point where the segment dede meets that plane. Then [abde][a b d e], [bcde][b c d e] and [cade][c a d e] have one strict sign if and only if pp is in the interior of the triangle abcabc.

Proof. Write p=(1−s)d+sep = (1 - s)d + s e with 0<s<10 < s < 1. The function x↦[abdx]x \mapsto [a b d x] is affine and zero at x=dx = d, so [abdp]=s [abde][a b d p] = s\,[a b d e]. The function x↦[abxd]x \mapsto [a b x d] is affine and zero on the line abab, so on the plane of abcabc it is a fixed multiple of the signed area σab(x)\sigma_{ab}(x) of the triangle a,b,xa, b, x in that plane: [abxd]=σab(x)σab(c) [abcd][a b x d] = \frac{\sigma_{ab}(x)}{\sigma_{ab}(c)}\,[a b c d]. Since [abdp]=−[abpd][a b d p] = -[a b p d],

[abde]=−1s λc(p) [abcd],λc(p)=σab(p)σab(c).[a b d e] = -\frac{1}{s}\,\lambda_c(p)\,[a b c d], \qquad \lambda_c(p) = \frac{\sigma_{ab}(p)}{\sigma_{ab}(c)}.

The same computation for the edges bcbc and caca, with [bcad]=[cabd]=[abcd][b c a d] = [c a b d] = [a b c d] (cyclic shifts of three entries are even permutations), gives [bcde]=−1s λa(p) [abcd][b c d e] = -\frac1s\,\lambda_a(p)\,[a b c d] and [cade]=−1s λb(p) [abcd][c a d e] = -\frac1s\,\lambda_b(p)\,[a b c d]. Here λa,λb,λc\lambda_a, \lambda_b, \lambda_c are the barycentric coordinates of pp in abcabc, which sum to 1, so they cannot all be negative. Hence the three values have one strict sign if and only if all three barycentric coordinates are positive, that is, if and only if pp is inside the triangle. □\square

Theorem 3 (2-3 flip). Let abcdabcd and abceabce be two tetrahedra of a valid mesh that share the face abcabc. The flip that replaces them by abdeabde, bcdebcde and cadecade gives a valid mesh if and only if [abde][a b d e], [bcde][b c d e] and [cade][c a d e] have one strict sign, which by Lemma 2 means that the segment dede crosses the interior of abcabc. Then the three new tetrahedra, ordered positively, have the same total volume and the same boundary faces as the two old ones.

Proof. In a valid mesh, the two tetrahedra on the face abcabc lie on opposite sides of its plane, so [abcd][abcd] and [abce][abce] have opposite strict signs, and Lemma 2 applies.

Volume. Lemma 1 with (a,b,c,d,e)(a, b, c, d, e) gives [bcde]−[acde]+[abde]−[abce]+[abcd]=0[bcde] - [acde] + [abde] - [abce] + [abcd] = 0. With [acde]=−[cade][acde] = -[cade],

[abcd]−[abce]=−([abde]+[bcde]+[cade]).[abcd] - [abce] = -\bigl([abde] + [bcde] + [cade]\bigr).

The left side is the sum of the two old volumes (times 6), in absolute value, because the two terms have opposite signs. If the three new values have one sign, the right side is the sum of their absolute values. So the volume is kept.

Disjoint interiors. The point pp of Lemma 2 is inside abcabc and on the segment dede. The plane through bb, dd, ee contains pp and bb, so it meets the triangle abcabc in the line bpbp, which separates aa from cc. So abdeabde and bcdebcde lie on opposite sides of that plane. The same holds for the other two pairs.

Same region and same boundary. The three new tetrahedra lie in the convex hull BB of the five points, and so do the two old ones, which have disjoint interiors and together have the volume of BB (they form the bipyramid on abcabc, which is convex because pp is inside abcabc). The new ones have disjoint interiors and the same total volume, so their union is BB as well. The faces of abdeabde, bcdebcde, cadecade are abd,abe,bcd,bce,cad,caeabd, abe, bcd, bce, cad, cae, each once, and adeade, bdebde, cdecde, each twice. So the boundary faces are the six faces abd,abe,bcd,bce,cad,caeabd, abe, bcd, bce, cad, cae, the same as for abcdabcd and abceabce, whose shared face abcabc is interior. The rest of the mesh does not change, so the mesh stays valid.

Necessity. If the three values do not have one strict sign, then either one of them is zero, and a new tetrahedron is flat, or pp is outside the closed triangle or on its boundary, and by Lemma 2 the new tetrahedra cannot all be positive with disjoint interiors: if two had opposite signs in the cyclic order around dede, their wedges around the edge dede would overlap. □\square

Theorem 4 (3-2 flip). Let dede be an interior edge of a valid mesh that lies in exactly three tetrahedra, whose other vertices form the ring a,b,ca, b, c in the order of rotation around dede. The flip that replaces them by abcdabcd and abceabce gives a valid mesh if and only if dd and ee lie strictly on opposite sides of the plane abcabc, that is, [abcd] [abce]<0[abcd]\,[abce] < 0. The volume and the boundary faces are kept.

Proof. The three tetrahedra abdeabde, bcdebcde, cadecade fill the space around the interior edge dede in three wedges that turn the same way and make one full turn, so [abde][abde], [bcde][bcde] and [cade][cade] have one strict sign. If dd and ee are strictly on opposite sides of the plane abcabc, Lemma 2 shows that the segment dede crosses the interior of abcabc. The configuration is then exactly the result of a valid 2-3 flip of abcdabcd and abceabce, so by Theorem 3 the two meshes have the same region, the same boundary faces and the same volume, and the 3-2 flip is the inverse 2-3 flip. If dd and ee are on the same side, or one is on the plane, then abcdabcd and abceabce overlap near the face abcabc or one is flat, so the flip is invalid. □\square

Theorem 5 (hill climbing). IMPROVE keeps a valid mesh of the same region with the same boundary faces, never lowers the smallest quality, and stops after finitely many flips.

Proof. Each flip is applied only after the exact tests of Theorems 3 and 4, so validity, the region and the boundary are kept. A flip is applied only if the smallest quality of the new tetrahedra is larger than the smallest quality mm of the old ones, so the smallest quality of the whole mesh does not go down.

For termination, list the qualities of the mesh in increasing order. A flip removes a set RR of tetrahedra whose smallest quality is mm, and adds a set R′R' whose qualities are all larger than mm. The tetrahedra outside RR are the same before and after. In the sorted lists, the entries smaller than mm are the same; the old list has more entries equal to mm than the new list, since it has those of RR in addition; and the new list has an entry at that position, because it has at least ∣L∣+2|L| + 2 entries for the set LL of unchanged tetrahedra. So the new sorted list is lexicographically larger. The vertex set never changes, and a finite point set has finitely many tetrahedral meshes, since each is a set of 4-element subsets. The sorted list is a function of the mesh and strictly increases, so no mesh repeats and the loop stops. □\square

The comparisons of quality are made in floats. The argument uses only that the computed quality is a fixed function of the four points, so it holds for the computed values.

What is not proved. No bound on the dihedral angles follows. Hill climbing stops at a mesh where no single 2-3 or 3-2 flip helps the worst tetrahedra, which can still be bad. In a measured run, a 2×2×22 \times 2 \times 2 cube mesh of 48 tetrahedra with smallest dihedral angle 34.4°34.4° was scrambled by random valid flips to a mesh of 52 tetrahedra with smallest dihedral angle 2.53°2.53°; hill climbing with 2-3 and 3-2 flips made 4 flips and left the smallest angle at 2.53°2.53°. Larger moves, such as edge removal, multi-face removal, smoothing and vertex insertion, are needed, and their results too are measured, not proved.

Complexity

A flip test and a flip cost O(1)O(1) with an adjacency structure. A pass over all faces and edges costs O(n)O(n) for nn tetrahedra. The number of flips has no useful proved bound beyond the finite number of meshes, but in practice each flip is local and the number is a small multiple of the number of bad tetrahedra. Klingner and Shewchuk keep a queue of tetrahedra below a quality threshold and work only around them. Edge removal on an edge with kk tetrahedra around it chooses the best triangulation of the ring of kk vertices by dynamic programming in O(k3)O(k^3) time, and kk is small, typically below 10. The simple implementation here rescans the mesh after each flip, which costs O(n)O(n) per flip. The space is O(n)O(n).

Properties

  • Valid output, proved. Each flip passes exact orientation tests, so no tetrahedron inverts, and the boundary is kept.
  • Monotone, proved. The worst quality never decreases.
  • Terminates, proved. The sorted quality list increases.
  • No quality guarantee. The result is a local optimum of local moves; its angles are measured.
  • No moved vertices. Flips change only the connectivity. Smoothing and vertex insertion are separate steps that are combined with them.

Variants and improvements

  • Edge removal. An edge with kk tetrahedra around it, whose other vertices form a ring of kk points, is removed by replacing the kk tetrahedra by 2k−42k - 4: the ring is triangulated, and each triangle is joined to both ends of the edge. The best ring triangulation, which maximises the worst new tetrahedron, is found by dynamic programming over polygon triangulations, as in Klincsek's algorithm. The 3-2 flip is the case k=3k = 3.
  • Multi-face removal. The inverse of edge removal: a stack of triangles that separate two vertices dd and ee is removed, and the tetrahedra around the new edge dede replace those on the triangles. Shewchuk found the best set of triangles to remove by a dynamic program over a tree of candidate faces. The 2-3 flip is the case of one triangle.
  • Smoothing. Moving vertices by optimization-based mesh smoothing raises the worst dihedral angle where flips cannot. Klingner and Shewchuk alternate it with the flips.
  • Vertex insertion. Inserting a new vertex inside a bad region, and then removing the bad tetrahedra around it by flips, escapes local optima.
  • Sliver exudation. Sliver exudation instead changes the weights of a weighted Delaunay triangulation, with a proved but tiny angle bound.
  • Delaunay flips. The same flips with the in-sphere test give a 3D Delaunay flip algorithm, but in 3D flips alone cannot always reach the Delaunay triangulation from any start, unlike in the plane.

When to use it

Use it after a tetrahedral mesh generator, such as Delaunay refinement or an advancing front method, to remove slivers and flat tetrahedra before a finite element solve, especially when large dihedral angles hurt the solver. Combine it with smoothing. When the boundary may not change, apply flips only to interior faces and edges, as here. If a proved bound is needed, use a method with a theorem, but expect weaker angles than the measured ones of aggressive improvement.

Pitfalls

  • Validity in floats. A nearly flat configuration can pass a float test and produce an inverted tetrahedron. Use exact orientation tests, as here.
  • Accepting any valid flip. A valid flip can lower the quality, as in the example. Compare the worst quality of the old and new tetrahedra.
  • Boundary faces. A flip on a boundary face or edge changes the boundary. Restrict the flips, or check that the boundary triangles stay on the boundary surface.
  • Stopping too early. 2-3 and 3-2 flips alone reach poor local optima. Use edge removal, multi-face removal, smoothing and vertex insertion together.
  • Wrong measure. The radius-edge ratio does not see slivers, so improving it does not remove them.

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.

mg3geom.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the mg3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small exact tools for triangle and tetrahedral meshes, used by the mg3 pages.

Points are tuples of int, fractions.Fraction or float. Every predicate here is
exact when the coordinates are int or Fraction. A float converts to a Fraction
without rounding, so exact() followed by a predicate gives the exact sign for
the float points as they are stored. Nothing here builds a mesh; each page
builds its own.
"""

import math
from fractions import Fraction
from typing import Dict, Iterable, List, Sequence, Tuple

Point = Tuple


def exact(p: Point) -> Tuple[Fraction, ...]:
    """The point p with each coordinate converted to Fraction, without rounding."""
    return tuple(Fraction(c) for c in p)


def to_grid(x: float, bits: int = 20) -> Fraction:
    """The nearest multiple of 2**-bits to x, as a Fraction."""
    return Fraction(round(x * (1 << bits)), 1 << bits)


def orient2d(a: Point, b: Point, c: Point):
    """Twice the signed area of the triangle a, b, c; positive if counterclockwise."""
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def incircle(a: Point, b: Point, c: Point, d: Point):
    """Positive if d is inside the circle through a, b, c (a, b, c counterclockwise),
    zero if on it, negative if outside."""
    rows = []
    for p in (a, b, c):
        dx, dy = p[0] - d[0], p[1] - d[1]
        rows.append((dx, dy, dx * dx + dy * dy))
    (a0, a1, a2), (b0, b1, b2), (c0, c1, c2) = rows
    return a0 * (b1 * c2 - b2 * c1) - a1 * (b0 * c2 - b2 * c0) + a2 * (b0 * c1 - b1 * c0)


def orient3d(a: Point, b: Point, c: Point, d: Point):
    """Six times the signed volume of the tetrahedron a, b, c, d.

    Positive if d lies on the side of the plane abc toward which (b - a) x (c - a)
    points, that is, if a, b, c look clockwise from d."""
    u = (b[0] - a[0], b[1] - a[1], b[2] - a[2])
    v = (c[0] - a[0], c[1] - a[1], c[2] - a[2])
    w = (d[0] - a[0], d[1] - a[1], d[2] - a[2])
    return (u[0] * (v[1] * w[2] - v[2] * w[1])
            - u[1] * (v[0] * w[2] - v[2] * w[0])
            + u[2] * (v[0] * w[1] - v[1] * w[0]))


def twice_area(poly: Sequence[Point]):
    """Twice the signed area of a polygon by the shoelace formula."""
    n = len(poly)
    return sum(poly[i][0] * poly[(i + 1) % n][1] - poly[(i + 1) % n][0] * poly[i][1] for i in range(n))


def segments_cross(a: Point, b: Point, c: Point, d: Point) -> bool:
    """True if the open segments ab and cd cross at one point inside both."""
    return (orient2d(a, b, c) * orient2d(a, b, d) < 0
            and orient2d(c, d, a) * orient2d(c, d, b) < 0)


def edge_map(cells: Iterable[Sequence[int]]) -> Dict[Tuple[int, int], int]:
    """Map each directed edge (i, j) of a list of counterclockwise polygons
    (triangles or quads, given by vertex indices) to the index of its cell.
    Raises ValueError if a directed edge is used twice."""
    m: Dict[Tuple[int, int], int] = {}
    for k, cell in enumerate(cells):
        n = len(cell)
        for s in range(n):
            e = (cell[s], cell[(s + 1) % n])
            if e in m:
                raise ValueError("directed edge %r used twice" % (e,))
            m[e] = k
    return m


def boundary_edges(cells: Iterable[Sequence[int]]) -> List[Tuple[int, int]]:
    """The directed edges whose reverse is not an edge of any cell."""
    m = edge_map(cells)
    return [e for e in m if (e[1], e[0]) not in m]


def is_valid_planar_mesh(points: Sequence[Point], cells: Sequence[Sequence[int]]) -> bool:
    """Exact check that every cell is a strictly convex counterclockwise polygon
    and that no directed edge is used twice. With the area sum of the caller,
    this shows a conforming mesh of a simply covered region."""
    try:
        edge_map(cells)
    except ValueError:
        return False
    for cell in cells:
        n = len(cell)
        for s in range(n):
            a, b, c = points[cell[s]], points[cell[(s + 1) % n]], points[cell[(s + 2) % n]]
            if orient2d(a, b, c) <= 0:
                return False
    return True


def mean_ratio(a: Point, b: Point, c: Point) -> float:
    """The mean ratio 4 sqrt(3) A / (sum of squared edge lengths) of a triangle,
    in floats; 1 for the equilateral triangle, 0 for a flat one, negative if the
    triangle is clockwise."""
    s = sum(float((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2) for p, q in ((a, b), (b, c), (c, a)))
    return 2.0 * math.sqrt(3.0) * float(orient2d(a, b, c)) / s
topological_tetrahedral_mesh_improvement.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/topological-tetrahedral-mesh-improvement/. The authors are listed in prov/JMSVP1.jsonl.

"""2-3 and 3-2 flips of a tetrahedral mesh, and hill climbing with them.

A mesh is a list of points (tuples of Fraction) and a list of tetrahedra, each a
tuple of four vertex indices with orient3d > 0. A 2-3 flip replaces the two
tetrahedra abcd and abce on the face abc by abde, bcde and cade; a 3-2 flip is
the inverse. Every validity decision is an exact orient3d sign. The quality of
a tetrahedron (the mean ratio) is measured in floats and used only to decide
whether a valid flip is an improvement.
"""

import math
from itertools import combinations
from typing import Dict, FrozenSet, List, Optional, Sequence, Tuple

from mg3geom import orient3d

Tet = Tuple[int, int, int, int]


def positive(points, t: Sequence[int]) -> Tet:
    """The tetrahedron t with its vertices ordered so that orient3d > 0.
    Raises ValueError if it is flat."""
    a, b, c, d = t
    s = orient3d(points[a], points[b], points[c], points[d])
    if s == 0:
        raise ValueError("flat tetrahedron")
    return (a, b, c, d) if s > 0 else (b, a, c, d)


def mean_ratio(points, t: Sequence[int]) -> float:
    """12 (3V)^(2/3) / (sum of the six squared edge lengths): 1 for the regular
    tetrahedron, 0 for a flat one, negative if inverted."""
    p = [points[i] for i in t]
    v = float(orient3d(*p)) / 6.0
    s = sum(float(sum((x - y) ** 2 for x, y in zip(p[i], p[j]))) for i, j in combinations(range(4), 2))
    return math.copysign(12.0 * (3.0 * abs(v)) ** (2.0 / 3.0) / s, v)


def faces(tets: Sequence[Tet]) -> Dict[FrozenSet[int], List[int]]:
    """Map each face (a set of three vertices) to the indices of its tetrahedra."""
    out: Dict[FrozenSet[int], List[int]] = {}
    for k, t in enumerate(tets):
        for f in combinations(t, 3):
            out.setdefault(frozenset(f), []).append(k)
    return out


def flip23(points, tets: Sequence[Tet], face: FrozenSet[int]) -> Optional[List[Tet]]:
    """The three tetrahedra that replace the two on `face`, or None if the flip
    is invalid. Valid iff the segment between the two apexes crosses the
    interior of the face, that is, iff the three new tetrahedra have orient3d
    of one strict sign."""
    owners = [t for t in tets if face <= set(t)]
    if len(owners) != 2:
        return None
    a, b, c = sorted(face)
    d = [v for v in owners[0] if v not in face][0]
    e = [v for v in owners[1] if v not in face][0]
    P = points
    signs = [orient3d(P[x], P[y], P[d], P[e]) for x, y in ((a, b), (b, c), (c, a))]
    if not (all(s > 0 for s in signs) or all(s < 0 for s in signs)):  # @line L1
        return None
    return [positive(P, (x, y, d, e)) for x, y in ((a, b), (b, c), (c, a))]  # @line L2


def degree3_edges(tets: Sequence[Tet]):
    """Edges (d, e) in exactly three tetrahedra whose other vertices form a
    closed ring a, b, c; these are the interior edges of degree 3. Yields
    (edge, ring, indices of the three tetrahedra)."""
    around: Dict[Tuple[int, int], List[int]] = {}
    for k, t in enumerate(tets):
        for d, e in combinations(sorted(t), 2):
            around.setdefault((d, e), []).append(k)
    for (d, e), ks in around.items():
        if len(ks) != 3:
            continue
        links = [tuple(v for v in tets[k] if v not in (d, e)) for k in ks]
        verts = [v for l in links for v in l]
        ring = sorted(set(verts))
        if len(ring) == 3 and all(verts.count(v) == 2 for v in ring):
            yield (d, e), tuple(ring), ks


def flip32(points, edge: Tuple[int, int], ring: Tuple[int, int, int]) -> Optional[List[Tet]]:
    """The two tetrahedra abcd and abce that replace the three around the
    interior edge de of degree 3, or None if invalid. Valid iff d and e lie
    strictly on opposite sides of the plane abc."""
    d, e = edge
    a, b, c = ring
    P = points
    sd = orient3d(P[a], P[b], P[c], P[d])
    se = orient3d(P[a], P[b], P[c], P[e])
    if sd * se >= 0:  # @line L3
        return None
    return [positive(P, (a, b, c, d)), positive(P, (a, b, c, e))]  # @line L4


def improve(points, tets: Sequence[Tet], max_flips: int = 10000):
    """Hill climbing: apply a 2-3 or 3-2 flip whenever it is valid and raises
    the smallest quality of the tetrahedra it touches; stop when none does.
    Returns (tets, number of 2-3 flips, number of 3-2 flips)."""
    tets = list(tets)
    n23 = n32 = 0
    for _ in range(max_flips):  # @line L5
        done = False
        for face, ks in faces(tets).items():  # @line L6
            if len(ks) != 2:
                continue
            new = flip23(points, tets, face)  # @line L7
            if new is None:
                continue
            old_q = min(mean_ratio(points, tets[k]) for k in ks)
            if min(mean_ratio(points, t) for t in new) > old_q:  # @line L8
                tets = [t for k, t in enumerate(tets) if k not in ks] + new
                n23 += 1
                done = True
                break
        if not done:
            for edge, ring, ks in degree3_edges(tets):  # @line L9
                new = flip32(points, edge, ring)  # @line L10
                if new is None:
                    continue
                old_q = min(mean_ratio(points, tets[k]) for k in ks)
                if min(mean_ratio(points, t) for t in new) > old_q:  # @line L11
                    tets = [t for k, t in enumerate(tets) if k not in ks] + new
                    n32 += 1
                    done = True
                    break
        if not done:  # @line L12
            break
    return tets, n23, n32  # @line L13


def kuhn_cube_mesh(n: int) -> Tuple[List[Tuple[int, int, int]], List[Tet]]:
    """The n x n x n grid of unit cubes, each split into 6 tetrahedra along its
    main diagonal (the Kuhn or Freudenthal split, conforming across cubes)."""
    idx = lambda i, j, k: (k * (n + 1) + j) * (n + 1) + i
    pts = [(i, j, k) for k in range(n + 1) for j in range(n + 1) for i in range(n + 1)]
    tets = []
    for k in range(n):
        for j in range(n):
            for i in range(n):
                for perm in ((0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)):
                    cur = [i, j, k]
                    path = [idx(*cur)]
                    for axis in perm:
                        cur[axis] += 1
                        path.append(idx(*cur))
                    tets.append(positive(pts, path))
    return pts, tets
test_topological_tetrahedral_mesh_improvement.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/topological-tetrahedral-mesh-improvement/. The authors are listed in prov/JMSVP1.jsonl.

import random
from collections import Counter
from fractions import Fraction as F
from itertools import combinations

from mg3geom import orient3d
from topological_tetrahedral_mesh_improvement import (degree3_edges, faces, flip23, flip32, improve, kuhn_cube_mesh,
                                                      mean_ratio, positive)


def volume6(points, tets):
    return sum(orient3d(*[points[i] for i in t]) for t in tets)


def boundary_faces(tets):
    c = Counter(frozenset(f) for t in tets for f in combinations(t, 3))
    assert all(v <= 2 for v in c.values())     # no face in three tetrahedra
    return {f for f, v in c.items() if v == 1}


def det3(m):
    return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
            + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]))


def segment_crosses_triangle(d, e, a, b, c):
    """Independent test by barycentric coordinates: solve
    d + s (e - d) = a + u (b - a) + v (c - a) with Cramer's rule in Fractions,
    and ask for 0 < s < 1, u > 0, v > 0, u + v < 1."""
    cols = [[e[i] - d[i] for i in range(3)], [a[i] - b[i] for i in range(3)], [a[i] - c[i] for i in range(3)]]
    rhs = [a[i] - d[i] for i in range(3)]
    m = [[cols[j][i] for j in range(3)] for i in range(3)]
    den = det3(m)
    if den == 0:
        return False
    sol = []
    for j in range(3):
        mj = [row[:] for row in m]
        for i in range(3):
            mj[i][j] = rhs[i]
        sol.append(F(det3(mj), den))
    s, u, v = sol
    return 0 < s < 1 and u > 0 and v > 0 and u + v < 1


def test_one_23_flip_and_back():
    P = [(0, 0, 0), (4, 0, 0), (0, 4, 0), (1, 1, 3), (1, 1, -2)]
    a, b, c, d, e = range(5)
    old = [positive(P, (a, b, c, d)), positive(P, (a, b, c, e))]
    new = flip23(P, old, frozenset((a, b, c)))
    assert new is not None and len(new) == 3
    assert all(orient3d(*[P[i] for i in t]) > 0 for t in new)
    assert volume6(P, new) == volume6(P, old) == 80     # 6 V: 16 * 3 + 16 * 2
    assert boundary_faces(new) == boundary_faces(old)
    (edge, ring, ks), = list(degree3_edges(new))
    assert set(edge) == {d, e} and set(ring) == {a, b, c}
    back = flip32(P, edge, ring)
    assert {frozenset(t) for t in back} == {frozenset(t) for t in old}


def test_invalid_23_flip():
    P = [(0, 0, 0), (4, 0, 0), (0, 4, 0), (1, 1, 3), (5, 5, -1)]
    old = [positive(P, (0, 1, 2, 3)), positive(P, (0, 1, 2, 4))]
    assert flip23(P, old, frozenset((0, 1, 2))) is None
    assert not segment_crosses_triangle(P[3], P[4], P[0], P[1], P[2])


def test_five_point_volume_identity():
    rng = random.Random(1)
    for _ in range(500):
        p = [tuple(F(rng.randint(-9, 9), rng.randint(1, 4)) for _ in range(3)) for _ in range(5)]
        s = sum((-1) ** i * orient3d(*[p[j] for j in range(5) if j != i]) for i in range(5))
        assert s == 0


def test_23_validity_matches_barycentric_test():
    rng = random.Random(2)
    seen = Counter()
    while sum(seen.values()) < 600:
        P = [tuple(rng.randint(-4, 4) for _ in range(3)) for _ in range(5)]
        sd, se = orient3d(P[0], P[1], P[2], P[3]), orient3d(P[0], P[1], P[2], P[4])
        if sd * se >= 0:
            continue      # abcd and abce must lie on opposite sides of abc
        old = [positive(P, (0, 1, 2, 3)), positive(P, (0, 1, 2, 4))]
        try:
            new = flip23(P, old, frozenset((0, 1, 2)))
        except ValueError:
            new = None
        ok = segment_crosses_triangle(P[3], P[4], P[0], P[1], P[2])
        assert (new is not None) == ok
        if new is not None:
            assert volume6(P, new) == volume6(P, old)
            assert all(orient3d(*[P[i] for i in t]) > 0 for t in new)
            assert boundary_faces(new) == boundary_faces(old)
        seen[ok] += 1
    assert seen[True] > 50 and seen[False] > 50


def test_32_validity_matches_barycentric_test():
    rng = random.Random(3)
    seen = Counter()
    while sum(seen.values()) < 600:
        P = [tuple(rng.randint(-4, 4) for _ in range(3)) for _ in range(5)]
        a, b, c, d, e = range(5)
        s = [orient3d(P[x], P[y], P[d], P[e]) for x, y in ((a, b), (b, c), (c, a))]
        if not (all(v > 0 for v in s) or all(v < 0 for v in s)):
            continue      # the three tetrahedra around de must form a valid ring
        three = [positive(P, (x, y, d, e)) for x, y in ((a, b), (b, c), (c, a))]
        (edge, ring, ks), = list(degree3_edges(three))
        try:
            new = flip32(P, edge, ring)
        except ValueError:
            new = None
        ok = segment_crosses_triangle(P[d], P[e], P[a], P[b], P[c])
        assert (new is not None) == ok
        if new is not None:
            assert volume6(P, new) == volume6(P, three)
            assert boundary_faces(new) == boundary_faces(three)
        seen[ok] += 1
    assert seen[True] > 50 and seen[False] > 50


def perturbed_cube(seed, n=2, amount=F(3, 8)):
    """The Kuhn mesh of [0, n]^3 with interior vertices moved randomly on a
    grid of step 1/16, redrawn until every tetrahedron stays positive."""
    rng = random.Random(seed)
    pts, tets = kuhn_cube_mesh(n)
    base = [tuple(F(x) for x in p) for p in pts]
    while True:
        P = []
        for p in base:
            if all(0 < x < n for x in p):
                k = int(amount * 16)
                P.append(tuple(x + F(rng.randint(-k, k), 16) for x in p))
            else:
                P.append(p)
        if all(orient3d(*[P[i] for i in t]) > 0 for t in tets):
            return P, tets


def test_hill_climbing_keeps_a_valid_mesh_and_raises_the_worst_quality():
    flips = 0
    for n, seed in ((2, 0), (3, 1), (3, 2)):
        P, tets = perturbed_cube(seed, n=n, amount=F(1, 2))
        before = min(mean_ratio(P, t) for t in tets)
        out, n23, n32 = improve(P, tets)
        flips += n23 + n32
        assert all(orient3d(*[P[i] for i in t]) > 0 for t in out)
        assert volume6(P, out) == 6 * n ** 3                  # the cube [0, n]^3
        assert boundary_faces(out) == boundary_faces(tets)    # same boundary, conforming
        assert min(mean_ratio(P, t) for t in out) >= before
        assert len(out) == len(tets) + n23 - n32
    assert flips >= 10


def test_each_flip_raises_the_sorted_quality_vector():
    # the termination argument: each accepted flip makes the ascending list of
    # qualities lexicographically larger, so no mesh repeats
    P, tets = perturbed_cube(1, n=3, amount=F(1, 2))
    prev = sorted(mean_ratio(P, t) for t in tets)
    k = 1
    while True:
        out, n23, n32 = improve(P, tets, max_flips=k)
        if n23 + n32 < k:
            break
        cur = sorted(mean_ratio(P, t) for t in out)
        assert cur > prev
        prev = cur
        k += 1
    assert k > 2

History

Barry Joe studied local transformations of tetrahedral meshes, including the 2-3 and 3-2 flips, to raise a quality measure in 1995. Freitag and Ollivier-Gooch combined face and edge swapping with optimisation-based smoothing in 1997 and measured which combinations work best. Shewchuk described edge removal and multi-face removal with dynamic programming in a 2002 manuscript, and Klingner and Shewchuk combined them with smoothing and vertex insertion in a hill climbing scheme in 2007; with their best settings, all dihedral angles of their test meshes lay between 31°31° and 149°149°, a measured result.

References

  1. Bryan Matthew Klingner and Jonathan Richard Shewchuk, Aggressive tetrahedral mesh improvement, Proceedings of the 16th International Meshing Roundtable, Springer, 2007, 3 to 23, edge removal, multi-face removal, the smoothing and vertex insertion steps, the hill climbing schedule and the measured dihedral angles (general locator)
  2. Barry Joe, Construction of three-dimensional improved-quality triangulations using local transformations, SIAM Journal on Scientific Computing 16(6), 1995, 1292 to 1307, the local transformations of tetrahedral meshes, including the 2-3 and 3-2 flips, applied to raise a quality measure (general locator)
  3. Siu-Wing Cheng, Tamal K. Dey and Jonathan R. Shewchuk, Delaunay Mesh Generation, CRC Press, 2013, chapter 4 (bistellar flips of tetrahedra and their validity 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.flip
  • a full proof of time.pass
  • 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