Algorithmresearch
Sliver exudation
Also called Cheng-Dey-Edelsbrunner sliver removal.
Removes slivers from a Delaunay tetrahedral mesh by giving each vertex a small weight, so that the weighted Delaunay triangulation of the same points avoids them.
- Solves
- Mesh generation
- Time
- O(n) worst
- Space
- O(n) extra
- Where
- n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Siu Wing Cheng, Tamal K. Dey, Herbert Edelsbrunner, Michael A. Facello, Shang Hua Teng, 1999
Sliver exudation removes slivers from a Delaunay tetrahedral mesh without moving any vertex or adding one. It gives each vertex a weight , the squared radius of a small sphere around , and replaces the Delaunay triangulation by the weighted Delaunay (regular) triangulation of the same points. Cheng, Dey, Edelsbrunner, Facello and Teng proved that if the Delaunay mesh has bounded radius-edge ratio, as tetrahedral Delaunay refinement produces, then weights exist that make every tetrahedron fat, and the weights can be found one vertex at a time. The proof gives a positive constant that the authors call "miserably tiny", while in practice the method raises the smallest dihedral angle to about .
In plain words
A Delaunay mesh with good radius-edge ratios can still contain slivers: flat tetrahedra whose four vertices lie near a circle. A sliver is fragile. If one of its vertices gets a weight, its orthosphere (the sphere that is orthogonal to the four weighted spheres) moves, and some other vertex falls inside it, so the sliver leaves the triangulation. Sliver exudation visits each vertex once. It removes the vertex, looks at the finitely many weights at which the triangulation around it changes, tries one weight between each pair, and keeps the weight whose star has the largest smallest dihedral angle. The weight stays below , where is the distance to the nearest other vertex, so the spheres stay disjoint and no vertex disappears.
The problem
The input is a finite point set in whose Delaunay triangulation has the Ratio Property : every tetrahedron has circumradius and shortest edge with . The output is a weight for each point , and the weighted Delaunay triangulation of the weighted points, chosen so that no tetrahedron is a sliver.
Two weighted points and have power distance . Four weighted points in general position have a unique orthosphere with for each of them; with zero weights it is the circumsphere. A weighted point conflicts with the tetrahedron if its power distance to the orthosphere is negative. The weighted Delaunay triangulation has a tetrahedron on four weighted points exactly when no other weighted point conflicts with it. Its sizes are measured, as in the paper, by , the volume over the cube of the shortest edge. A tetrahedron is a sliver when is small though its ratio is bounded.
The weights must satisfy the Weight Property for a constant : for every two points , . Then the spheres are disjoint, and every point remains a vertex.
This page makes three kinds of claim.
- Existence theorem, cited. The Sliver Theorem (Section 6.5 of the paper): "Assume Del S has Ratio Property . Then there is a constant and a weight assignment defining a set of spheres with Weight Property such that for all tetrahedra pqrs" of the weighted Delaunay triangulation. The theorem is stated for periodic point sets , which have no boundary. The paper gives no number for ; its Section 8.1 says "the estimate for provided by the Sliver Theorem is miserably tiny" and leaves open how it depends on and . Claim 7 (Section 5.1) adds that the weighted triangulation has orthoradius over shortest edge for a constant that depends only on and , also without a number.
- Proved here. The power test that the implementation uses, and the fact that pumping never lowers the smallest dihedral angle of the mesh. Also a lemma that turns the theorem into a dihedral angle bound with explicit dependence: every dihedral angle of the weighted triangulation of the theorem satisfies . For the factor is , so the bound is a tiny multiple of a tiny constant. See
proofs/correctness.md. - Measured, no guarantee. Edelsbrunner and Guoy write that the proved constant is "positive but miserably small" and that the constant reached in practice is "much larger and possibly around 5°". On a mesh of more than 76,000 tetrahedra they moved every dihedral angle above except one, which was above , next to the boundary. Labelle and Shewchuk note that the provable bounds of Delaunay methods with sliver removal are below and probably below a millionth of a degree. In the example below the smallest angle rises from to .
A radius-edge bound alone does not remove slivers: a sliver can have as low as . That is why sliver exudation exists, and why it needs the Ratio Property only as a hypothesis, not as the goal.
The algorithm
Fix the weights of all vertices except , and let be the weighted Delaunay triangulation without . For each tetrahedron of the critical weight is the power distance from (at weight ) to the orthosphere of . The weighted point conflicts with exactly when . So the triangulation with at weight is with the tetrahedra removed and joined to the boundary of the hole, and it changes only when crosses a critical weight.
SLIVER-EXUDATION(S, Ω0)- 1
T ← the Delaunay triangulation of S; every weight is 0 - 2
for each vertex u, once, in any order: - 3
T_u ← the weighted Delaunay triangulation of S without u - 4
for each tetrahedron t of T_u: w_t ← power distance from (u, 0) to the orthosphere of t - 5
W ← (Ω0 d_u)^2, where d_u is the distance from u to its nearest other point - 6
candidates ← 0 and one weight strictly between each two consecutive critical weights in [0, W] - 7
for each candidate w: star(w) ← u joined to the boundary of {t in T_u : w_t < w}; ζ(w) ← its smallest dihedral angle - 8
w* ← the candidate of largest ζ, keeping 0 on ties - 9
w_u ← w*; T ← (T_u minus the removed tetrahedra) plus star(w*) - 10
return T and the weights - 11
conflict test: (e, w_e) conflicts with abcd iff -det[p - e, |p - e|^2 - w_p + w_e] (rows p = a, b, c, d) has the sign of orient3d(a, b, c, d)
The test of L11 is the weighted form of the insphere test: with all weights it is the insphere determinant. The paper's own rule (Section 7.1) picks the weight that maximizes the smallest in the star; Edelsbrunner and Guoy's implementation, and this one, maximize the smallest dihedral angle instead. Edelsbrunner and Guoy evaluate the star at each critical weight as it grows; here a weight strictly between two critical weights is used, so no four weighted points are ever on a common orthosphere.
The paper treats periodic sets. The implementation puts the points in a box whose 8 corners are part of the input and keep weight ; only the points strictly inside are pumped. Coordinates and weights are integers, so every orientation and power test is exact integer arithmetic, and the critical weights are exact fractions. L3 rebuilds the triangulation without by Bowyer-Watson insertion with the power test.
Example
The input is 27 points near the grid points for , each coordinate moved by a random integer in (seed 2), inside the box , with . The steps come from the implementation, and the test file checks them.
| Step | Vertex | What happens |
|---|---|---|
| L1 | 35 vertices, 151 tetrahedra; smallest dihedral angle , 9 tetrahedra below and 17 below | |
| the worst is a sliver on , , , , with angles and and radius-edge ratio | ||
| pump 2 | weight of at most ; the smallest angle in its star rises from to | |
| pump 7 | weight ; star from to | |
| pump 19 | weight of at most ; star from to ; the worst sliver is gone and the mesh minimum rises to | |
| pump 23 | weight , chosen among 14 candidates; star from to ; the mesh minimum rises to | |
| end | 139 tetrahedra; smallest angle , none below and 6 below ; 11 of the 27 points got a positive weight, the largest with |
Sixteen of the 27 pumps keep weight , because no weight improves their star. The number of tetrahedra drops, as Edelsbrunner and Guoy also observe, because a sliver and its neighbors are replaced by fewer tetrahedra. With seed 1 and moves up to , the minimum rises from to , and the worst remaining tetrahedron has a box corner as a vertex, which is never pumped: near the boundary the method has little room, as the paper's boundary-free setting suggests.
Correctness
The power test. Lift each weighted point to in . The four lifted vertices of a tetrahedron lie on the graph of an affine function , where is the orthosphere, and the power distance of to the orthosphere is . Column operations turn the determinant of L11 into times , so the test returns , positive exactly in conflict. The full proof is in proofs/correctness.md, and the tests compare the test with an orthosphere computed by exact Gaussian elimination on 300 random weighted configurations.
Each pump keeps the triangulation regular. By the lifting, the weighted Delaunay triangulation is the projection of the lower convex hull of the lifted points, and adding removes exactly the facets whose hyperplane passes above , which are the tetrahedra with , and cones to the horizon. The tests check that the final mesh has no conflict between any tetrahedron and any weighted point, that the volumes sum to the box, and that it equals a triangulation rebuilt from scratch with the final weights.
The smallest dihedral angle never decreases. Weight is always a candidate, and at weight the star is the current star of . A larger weight only removes more tetrahedra of . So the new mesh consists of tetrahedra of the old mesh and the new star, whose smallest angle is at least that of the old star. The tests check this after every pump.
The guarantee. The Sliver Theorem is cited, not proved here. Its proof shows that for each vertex the weights at which the star contains a sliver cover only part of the interval , and picks a weight outside them; the Ratio Property bounds how many tetrahedra can ever appear in the star. The bound , with the longest over the shortest edge, and under the Weight Property, are proved in proofs/correctness.md and checked on every tetrahedron of the tests.
Proof: The power test is exact, pumping keeps the triangulation regular and never lowers the smallest dihedral angle, and the Sliver Theorem gives a dihedral angle boundfull
Claim. Assume general position: no five lifted weighted points lie on a common hyperplane, and no candidate weight equals a critical weight.
- The test of L11 returns , where is the power distance from to the orthosphere of the four weighted points . So it is positive exactly when conflicts with the tetrahedron, and with all weights it is the insphere test. The critical weight of L4 is the power distance from to the orthosphere, and conflicts with exactly when .
- For each weight , the set is the weighted Delaunay triangulation with at weight , as long as is a vertex of it.
- The smallest dihedral angle of the mesh after the pump of L9 is at least the one before.
- Every tetrahedron with shortest edge , longest edge and volume has every dihedral angle with , where and .
- If the weights have the Weight Property , every tetrahedron of the weighted Delaunay triangulation with orthoradius has .
- Hence, for the weights of the Sliver Theorem, every dihedral angle of the weighted Delaunay triangulation satisfies .
What is cited. Part 6 uses the Sliver Theorem (Section 6.5 of Cheng, Dey, Edelsbrunner, Facello and Teng, J. ACM 2000), which gives , and their Claim 7 (Section 5.1), which gives ; neither proof is repeated, and the paper gives no number for or . Part 2 uses the standard fact that the weighted Delaunay triangulation is the projection of the lower convex hull of the lifted points (Chapter 7 of Cheng, Dey and Shewchuk) and the beneath-beyond rule for adding a point to a convex hull. The fact that every point stays a vertex under the Weight Property is from the paper (Section 4.2).
Step 1: the lifting. Lift a weighted point to in with . The orthosphere of satisfies , which expands to . So the four lifted points lie on the graph of the affine function . For any weighted point ,
so the power distance of to the orthosphere is the height of above that graph. Conflict, , means that lies below the hyperplane through .
Step 2: the determinant (part 1). Let be the matrix with rows for . Since
subtracting times column from column 4, for , gives rows with the same determinant. Now for the four vertices, and . Subtracting times column from column 4 gives rows . Factor out : the determinant of the rows is, after subtracting the first row from the others, the determinant of the rows , which by expansion along the last column is . So
The implementation returns times the sign of orient3d, which is : positive exactly when . With all weights , is the insphere matrix and the orthosphere is the circumsphere. For the critical weight, put : the implementation divides by orient3d and gets . With weight the power distance is , negative exactly when .
Step 3: the star (part 2). The weighted Delaunay triangulation of a set of weighted points is the vertical projection of the lower convex hull of their lifts, by Step 1: a tetrahedron is in it exactly when no lifted point lies below the hyperplane through its four lifted vertices. Adding the point to a lower convex hull removes exactly the facets whose hyperplane passes above , the facets visible from below, and joins to the boundary of that region (beneath-beyond). By Step 2 these facets are the tetrahedra of with . So the new triangulation is without them, plus joined to the boundary faces of the removed region, which is of L7. If is not a critical weight, every is either below or above , so no tetrahedron is degenerate, and the triangulation is the same for all in one open interval between consecutive critical weights. Hence L6 tries every triangulation that a weight in can give, except those at the critical weights themselves.
Step 4: monotonicity (part 3). By induction, before is pumped the mesh is the weighted Delaunay triangulation with , because each pump installs the triangulation for the chosen weight (Step 3) and has not been pumped yet. Write . Then . Let be the smallest dihedral angle of ; in particular , since . The chosen weight satisfies by L8, since is a candidate. Every with also has , so and . The new mesh is . Its tetrahedra of the first kind belong to and have angles at least ; those of the second kind have angles at least .
Step 5: angle, volume and edges (part 4). Let be the dihedral angle at edge , between the faces and of areas and . The vertex of off is at distance from the line of , and at distance from the plane of . So
A triangle with all sides at most has area at most : if is its longest side, the third corner is within of both ends of , so its height over is at most , and increases in for , so it is largest at . Thus , and with ,
Step 6: the Weight Property bounds the longest edge (part 5). Let be vertices of a tetrahedron of the weighted Delaunay triangulation, with orthosphere . Then , and the Weight Property gives , and likewise for . By the triangle inequality,
Taking at the ends of the longest edge, , that is . Since the left side is positive, so in particular .
Step 7: the dihedral bound (part 6). Under the hypotheses of the Sliver Theorem, its weights give for every tetrahedron, and Claim 7 gives . By Step 6, , so . By Step 5,
For the factor equals . The bound is positive but inherits the unknown and, by the paper's own account, tiny ; it is far below the seen in practice.
What is not proved. Part 6 is about the weights of the theorem. That the rule of L8, which maximizes the smallest dihedral angle rather than the smallest , reaches weights at least as good is not proved here. The implementation also has a boundary, which the theorem excludes. The tests check parts 1 to 5 exactly or to floating point precision on every tetrahedron of two examples.
Complexity
Under the Ratio Property the star of every vertex has constant size (Cheng et al.), so a pump looks at a constant number of critical weights and takes constant time once the vertex is located, and the whole method runs in time after the Delaunay triangulation is built, as Edelsbrunner and Guoy note. The paper states when the triangulation is included. Space is .
The implementation is simpler: it rebuilds the triangulation without from scratch for each pump, with linear scans, so a pump costs and the run . For the 35 points of the example the whole run takes about half a second.
Properties
- No new vertices, no moved vertices. Only the connectivity changes, through the weights.
- Monotone. The smallest dihedral angle of the mesh never decreases, and the smallest angle of each pumped star does not decrease either.
- Every vertex once, in any order. Edelsbrunner and Guoy note that one pass suffices.
- Existence guarantee, no explicit constant. for periodic inputs with bounded ratio; the paper does not compute .
- Weak at the boundary. The theorem has no boundary. Edelsbrunner and Guoy name the boundary as the main limitation in practice.
- Exact here. Integer coordinates and weights; all signs are exact.
Variants and improvements
- Refinement with pumping. Cheng and Dey (SIAM J. Computing, 2003) mix pumping with Delaunay refinement for polyhedral domains, giving the first deterministic method with boundaries; Chapter 11 of Cheng, Dey and Shewchuk presents it as refinement for sliver exudation.
- Random perturbation. Chew (1997) and Li and Teng (2001) remove slivers by choosing each new vertex at random in a small region around the circumcenter, with probabilistic arguments and, again, very small constants.
- Lattice methods. Isosurface stuffing proves dihedral angles of at least , a far better constant, by giving up the Delaunay property and sharp features.
- Mesh improvement. Topological improvement and optimization-based smoothing have no guarantee but reach or more in practice.
- Weighted features. Protecting balls use the same weighted Delaunay machinery to keep sharp edges in the mesh.
When to use it
Use it as a last step after tetrahedral Delaunay refinement when slivers remain, the vertices must not move, and a weighted Delaunay mesh is acceptable for the solver. It works best in the interior of the domain. If the target is a specific dihedral angle such as or more, use mesh improvement instead or after it, because the proved constant gives no such assurance.
Pitfalls
- Expecting a usable constant. The theorem gives only existence; the measured is what to expect.
- Weights too large. Above two spheres can overlap and a vertex can become redundant and vanish from the triangulation.
- Ignoring the boundary. Near the boundary the star is cut off and pumping has few options; Edelsbrunner and Guoy also bound weights so that boundary triangles stay in the mesh.
- Inexact power tests. The critical weights are close together for a sliver, and a floating point comparison can choose a weight on a critical value, where four weighted points are coplanar in the lifted space.
- Confusing the measures. The paper's sliver measure is a volume ratio, not a dihedral angle; the dihedral bound needs a second step.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the mg2 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small exact geometric tools used by the mg2 pages.
Points are tuples of int or fractions.Fraction. Every predicate returns an
exact value when the coordinates are int or Fraction, so its sign is the true
sign. A float converts to a Fraction without rounding (exact()), so the sign
is then exact for the float point as it is stored. The angle functions return
floats and are used only to report or to compare with a stated bound.
"""
import math
from fractions import Fraction
from typing import 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 sub(a: Point, b: Point) -> tuple:
return tuple(x - y for x, y in zip(a, b))
def dot(a: Point, b: Point):
return sum(x * y for x, y in zip(a, b))
def cross(a: Point, b: Point) -> tuple:
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def dist2(a: Point, b: Point):
return sum((x - y) * (x - y) for x, y in zip(a, b))
def det3(r0: Sequence, r1: Sequence, r2: Sequence):
return dot(r0, cross(r1, r2))
def det4(m: Sequence[Sequence]):
"""Determinant of a 4 by 4 matrix by cofactor expansion along the first row."""
total = 0
for j in range(4):
minor = [[m[i][k] for k in range(4) if k != j] for i in range(1, 4)]
term = m[0][j] * det3(minor[0], minor[1], minor[2])
total += term if j % 2 == 0 else -term
return total
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 orient3d(a: Point, b: Point, c: Point, d: Point):
"""Six times the signed volume of the tetrahedron a, b, c, d.
It is det[b - a, c - a, d - a]: positive when d lies on the side of the
plane abc from which a, b, c appear clockwise.
"""
return det3(sub(b, a), sub(c, a), sub(d, a))
def insphere(a: Point, b: Point, c: Point, d: Point, e: Point):
"""Positive if e lies inside the sphere through a, b, c, d, zero on it.
The value is det of the rows (p - e, |p - e|^2) for p = a, b, c, d,
divided by nothing, times the sign of orient3d(a, b, c, d), so the result
does not depend on the order of a, b, c, d. The tetrahedron must not be flat.
"""
rows = []
for p in (a, b, c, d):
v = sub(p, e)
rows.append([v[0], v[1], v[2], dot(v, v)])
o = orient3d(a, b, c, d)
if o == 0:
raise ValueError("flat tetrahedron")
val = -det4(rows)
return val if o > 0 else -val
def circumcenter3(a: Point, b: Point, c: Point, d: Point) -> tuple:
"""Exact circumcenter of a tetrahedron, by Cramer's rule on 2 (p - a) . x = |p - a|^2."""
u, v, w = sub(b, a), sub(c, a), sub(d, a)
det = det3(u, v, w)
if det == 0:
raise ValueError("flat tetrahedron")
bu, bv, bw = Fraction(dot(u, u)), Fraction(dot(v, v)), Fraction(dot(w, w))
# x = (bu (v x w) + bv (w x u) + bw (u x v)) / (2 det)
cvw, cwu, cuv = cross(v, w), cross(w, u), cross(u, v)
x = tuple((bu * cvw[k] + bv * cwu[k] + bw * cuv[k]) / (2 * det) for k in range(3))
return tuple(a[k] + x[k] for k in range(3))
def tri_circumcenter3(a: Point, b: Point, c: Point) -> tuple:
"""Exact circumcenter of a triangle in space (the center of its smallest circumscribed sphere)."""
u, v = sub(b, a), sub(c, a)
n = cross(u, v)
nn = Fraction(dot(n, n))
if nn == 0:
raise ValueError("flat triangle")
t1 = cross(n, u)
t2 = cross(v, n)
uu, vv = dot(u, u), dot(v, v)
# x = (|u|^2 (v x n) + |v|^2 (n x u)) / (2 |n|^2)
return tuple(a[k] + (uu * t2[k] + vv * t1[k]) / (2 * nn) for k in range(3))
def radius_edge2(a: Point, b: Point, c: Point, d: Point) -> Fraction:
"""Exact square of the radius-edge ratio R / l_min of a tetrahedron."""
cc = circumcenter3(a, b, c, d)
r2 = dist2(cc, a)
pts = (a, b, c, d)
lmin2 = min(dist2(pts[i], pts[j]) for i in range(4) for j in range(i + 1, 4))
return Fraction(r2) / Fraction(lmin2)
def _angle(u: Sequence[float], v: Sequence[float]) -> float:
nu = math.sqrt(sum(x * x for x in u))
nv = math.sqrt(sum(x * x for x in v))
c = sum(x * y for x, y in zip(u, v)) / (nu * nv)
return math.degrees(math.acos(max(-1.0, min(1.0, c))))
def triangle_angles_deg(a: Point, b: Point, c: Point) -> list:
"""The three plane angles of a triangle in degrees, in 2D or 3D (floats)."""
p = [tuple(float(x) for x in q) for q in (a, b, c)]
out = []
for i in range(3):
o, s, t = p[i], p[(i + 1) % 3], p[(i + 2) % 3]
out.append(_angle(sub(s, o), sub(t, o)))
return out
def dihedral_angles_deg(a: Point, b: Point, c: Point, d: Point) -> list:
"""The six dihedral angles of a tetrahedron in degrees (floats).
The angle at edge pq is the angle between the two faces pqr and pqs,
measured inside the tetrahedron.
"""
p = [tuple(float(x) for x in q) for q in (a, b, c, d)]
out = []
for i in range(4):
for j in range(i + 1, 4):
k, m = [t for t in range(4) if t not in (i, j)]
e = sub(p[j], p[i])
ee = dot(e, e)
# components of p_k - p_i and p_m - p_i orthogonal to the edge
u = sub(p[k], p[i])
v = sub(p[m], p[i])
u = tuple(u[t] - dot(u, e) / ee * e[t] for t in range(3))
v = tuple(v[t] - dot(v, e) / ee * e[t] for t in range(3))
out.append(_angle(u, v))
return out
sliver_exudation.py 204 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sliver-exudation/. The authors are listed in prov/4WRSY6.jsonl.
"""Sliver exudation (Cheng, Dey, Edelsbrunner, Facello and Teng, 2000).
Each vertex u in turn is "pumped": its weight (the square U^2 of the radius of
a sphere centered at u) is chosen among the weights for which the weighted
Delaunay (regular) triangulation is free of the worst tetrahedra around u.
The weight is kept at most (OMEGA * d_u)^2, where d_u is the distance from u to
its nearest neighbor and OMEGA < 1/2, so the spheres stay disjoint and every
point stays a vertex. As in Edelsbrunner and Guoy's implementation, the weight
chosen is the one that maximizes the smallest dihedral angle of the star of u.
The paper treats periodic point sets, which have no boundary. Here the points
lie in an axis-aligned box whose 8 corners are part of the input; the corners
keep weight 0, and only the points strictly inside are pumped.
Coordinates and weights are integers, so every power (weighted insphere) test
is exact integer arithmetic. A chosen weight is an integer strictly between two
consecutive critical weights, so no degenerate configuration is ever chosen.
"""
import math
from fractions import Fraction
from typing import Dict, List, Optional, Sequence, Set, Tuple
from mg2geom import det4, dihedral_angles_deg, dist2, orient3d, sub
Tet = Tuple[int, int, int, int]
Face = Tuple[int, int, int]
OMEGA = Fraction(9, 20) # Edelsbrunner and Guoy use 0.45; any constant in (0, 1/2) is allowed
def power_test(a, b, c, d, e, wa=0, wb=0, wc=0, wd=0, we=0):
"""Positive if the weighted point (e, we) conflicts with the orthosphere of abcd.
The value is -det of the rows (p - e, |p - e|^2 - w_p + w_e) for p = a, b, c,
d, times the sign of orient3d(a, b, c, d). It equals -pi * |orient3d|, where
pi = |e - z|^2 - Z^2 - w_e is the power distance from (e, we) to the
orthosphere (z, Z^2) of the four weighted points. So it is positive exactly
when pi < 0, and with all weights 0 it is the ordinary insphere test.
"""
rows = []
for p, w in ((a, wa), (b, wb), (c, wc), (d, wd)):
v = sub(p, e)
rows.append([v[0], v[1], v[2], v[0] * v[0] + v[1] * v[1] + v[2] * v[2] - w + we])
o = orient3d(a, b, c, d)
if o == 0:
raise ValueError("flat tetrahedron")
val = -det4(rows)
return val if o > 0 else -val # @line L11
def critical_weight(a, b, c, d, u, wa=0, wb=0, wc=0, wd=0) -> Fraction:
"""The power pi_t(u) = |u - z|^2 - Z^2 of the point u to the orthosphere of abcd.
The weighted point (u, w) conflicts with the tetrahedron exactly when w > pi_t(u).
"""
rows = []
for p, w in ((a, wa), (b, wb), (c, wc), (d, wd)):
v = sub(p, u)
rows.append([v[0], v[1], v[2], v[0] * v[0] + v[1] * v[1] + v[2] * v[2] - w])
return Fraction(det4(rows), orient3d(a, b, c, d))
def faces_of(t: Tet) -> List[Face]:
return [tuple(sorted(t[:i] + t[i + 1 :])) for i in range(4)]
def min_dihedral(pts, tets) -> float:
return min(min(dihedral_angles_deg(*[pts[v] for v in t])) for t in tets)
class Exuder:
def __init__(self, side: int, inner: Sequence[Sequence[int]], omega: Fraction = OMEGA):
if side <= 0:
raise ValueError("side must be positive")
self.omega = Fraction(omega)
if not 0 < self.omega < Fraction(1, 2):
raise ValueError("omega must lie in (0, 1/2)")
corners = [(x, y, z) for x in (0, side) for y in (0, side) for z in (0, side)]
self.pts: List[tuple] = corners + [tuple(int(c) for c in p) for p in inner]
if len(set(self.pts)) != len(self.pts):
raise ValueError("repeated point")
for p in self.pts[8:]:
if not all(0 < c < side for c in p):
raise ValueError("inner points must lie strictly inside the box")
self.side = side
self.w: List[int] = [0] * len(self.pts)
self.tets: Set[Tet] = self.triangulate(range(len(self.pts))) # @line L1
self.log: List[tuple] = []
# weighted Delaunay triangulation by Bowyer-Watson insertion with the power test
def conflicts(self, t: Tet, v: int) -> bool:
P, W = self.pts, self.w
return power_test(*[P[x] for x in t], P[v], *[W[x] for x in t], W[v]) > 0
def triangulate(self, verts) -> Set[Tet]:
"""The regular triangulation of the given vertices with the current weights.
The 8 corners are always included and start as 6 tetrahedra around the
diagonal; they are cospherical with equal weights, so this is regular.
"""
P = self.pts
tets: Set[Tet] = set()
face_tets: Dict[Face, Set[Tet]] = {}
def add(t):
if orient3d(*[P[x] for x in t]) < 0:
t = (t[1], t[0], t[2], t[3])
if orient3d(*[P[x] for x in t]) == 0:
raise AssertionError("flat tetrahedron: the cavity is not star-shaped")
tets.add(t)
for f in faces_of(t):
face_tets.setdefault(f, set()).add(t)
def remove(t):
tets.discard(t)
for f in faces_of(t):
face_tets[f].discard(t)
if not face_tets[f]:
del face_tets[f]
for path in ((1, 3), (1, 5), (2, 3), (2, 6), (4, 5), (4, 6)):
add((0, path[0], path[1], 7))
for v in verts:
if v < 8:
continue
start = next(t for t in tets if self.conflicts(t, v))
cavity, stack = {start}, [start]
while stack:
t = stack.pop()
for f in faces_of(t):
for s in face_tets[f]:
if s not in cavity and self.conflicts(s, v):
cavity.add(s)
stack.append(s)
boundary = [f for t in cavity for f in faces_of(t) if not any(s in cavity for s in face_tets[f] if s != t)]
for t in cavity:
remove(t)
for f in boundary:
add(f + (v,))
return tets
def nearest2(self, u: int) -> int:
return min(dist2(self.pts[u], q) for i, q in enumerate(self.pts) if i != u)
def star(self, rest: Set[Tet], crit: Dict[Tet, Fraction], u: int, w) -> Tuple[Set[Tet], List[Tet]]:
"""The cavity {t in rest : crit[t] < w} and the cone from u over its boundary."""
cavity = {t for t in rest if crit[t] < w}
count: Dict[Face, int] = {}
for t in cavity:
for f in faces_of(t):
count[f] = count.get(f, 0) + 1
cone = []
for f, m in count.items():
if m == 1:
t = f + (u,)
o = orient3d(*[self.pts[x] for x in t])
if o == 0:
raise AssertionError("flat tetrahedron in the star")
cone.append(t if o > 0 else (t[1], t[0], t[2], t[3]))
return cavity, cone
def pump(self, u: int) -> int:
P = self.pts
rest = self.triangulate([v for v in range(len(P)) if v != u]) # @line L3
crit = {t: critical_weight(*[P[x] for x in t], P[u], *[self.w[x] for x in t]) for t in rest} # @line L4
wmax = math.floor(self.omega**2 * self.nearest2(u)) # @line L5
cuts = sorted({c for c in crit.values() if 0 < c < wmax})
# the current weight 0, and one integer strictly inside each interval
cands = [0] # @line L6
for lo, hi in zip([Fraction(0)] + cuts, cuts + [Fraction(wmax + 1)]):
m = math.floor((lo + hi) / 2)
for x in (m, m + 1, math.floor(lo) + 1):
if lo < x < hi and x <= wmax:
cands.append(x)
break
best = None
for w in cands:
if w != 0 and w in crit.values():
continue
cavity, cone = self.star(rest, crit, u, w) # @line L7
zeta = min_dihedral(P, cone)
if best is None or zeta > best[0]: # @line L8
best = (zeta, w, cavity, cone)
zeta0 = min_dihedral(P, self.star(rest, crit, u, 0)[1])
_, w, cavity, cone = best
self.w[u] = w # @line L9
self.tets = (rest - cavity) | set(cone)
self.log.append((u, w, wmax, len(cands), zeta0, best[0]))
return w
def run(self) -> None:
for u in range(8, len(self.pts)): # @line L2
self.pump(u)
def sliver_exudation(side: int, inner: Sequence[Sequence[int]], omega: Fraction = OMEGA) -> Exuder:
"""Pump every inner point once; return the Exuder with fields pts, w (weights) and tets."""
e = Exuder(side, inner, omega)
e.run()
return e # @line L10
test_sliver_exudation.py 311 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sliver-exudation/. The authors are listed in prov/4WRSY6.jsonl.
import math
import random
from fractions import Fraction as F
from functools import lru_cache
import pytest
from mg2geom import circumcenter3, dihedral_angles_deg, dist2, insphere, orient3d, sub
from sliver_exudation import OMEGA, Exuder, critical_weight, faces_of, min_dihedral, power_test, sliver_exudation
S = 1000
def jittered_grid(seed, g, jit):
"""g^3 points near the grid points (i, j, k) * S, each coordinate moved by at most jit."""
r = random.Random(seed)
return [
(i * S + r.randint(-jit, jit), j * S + r.randint(-jit, jit), k * S + r.randint(-jit, jit))
for i in range(1, g + 1)
for j in range(1, g + 1)
for k in range(1, g + 1)
]
EXAMPLE = (2, 3, 100) # seed, g, jitter: 27 inner points in a box of side 4000
OTHER = (1, 3, 150)
@lru_cache(maxsize=None)
def pumped(case):
"""Run the pumps one at a time and record the global minimum dihedral angle after each."""
seed, g, jit = case
e = Exuder((g + 1) * S, jittered_grid(seed, g, jit))
before = (frozenset(e.tets), min_dihedral(e.pts, e.tets))
mins = [before[1]]
for u in range(8, len(e.pts)):
e.pump(u)
mins.append(min_dihedral(e.pts, e.tets))
return e, before, mins
# brute-force orthosphere: center z and squared radius Z2 with |p - z|^2 - Z2 = w_p for the four points
def orthosphere(pts, ws):
a, wa = pts[0], ws[0]
rows, rhs = [], []
for p, w in zip(pts[1:], ws[1:]):
rows.append([F(2 * (p[k] - a[k])) for k in range(3)])
rhs.append(F(sum(p[k] ** 2 - a[k] ** 2 for k in range(3)) - w + wa))
# Gaussian elimination in exact arithmetic
m = [rows[i] + [rhs[i]] for i in range(3)]
for c in range(3):
piv = next(i for i in range(c, 3) if m[i][c] != 0)
m[c], m[piv] = m[piv], m[c]
for i in range(3):
if i != c and m[i][c] != 0:
f = m[i][c] / m[c][c]
m[i] = [x - f * y for x, y in zip(m[i], m[c])]
z = tuple(m[i][3] / m[i][i] for i in range(3))
return z, dist2(a, z) - wa
def random_weighted(r, n):
pts = [tuple(r.randint(-20, 20) for _ in range(3)) for _ in range(n)]
ws = [r.randint(0, 60) for _ in range(n)]
return pts, ws
def test_power_test_matches_brute_force_orthosphere():
r = random.Random(7)
checked = signs = 0
while checked < 300:
pts, ws = random_weighted(r, 5)
if orient3d(*pts[:4]) == 0:
continue
z, Z2 = orthosphere(pts[:4], ws[:4])
pi = dist2(pts[4], z) - Z2 - ws[4]
val = power_test(*pts, *ws)
assert (val > 0) == (pi < 0) and (val == 0) == (pi == 0)
assert val == -pi * abs(orient3d(*pts[:4]))
assert critical_weight(*pts, *ws[:4]) == dist2(pts[4], z) - Z2
# the order of the four points does not matter
perm = [1, 0, 2, 3]
assert power_test(*[pts[i] for i in perm], pts[4], *[ws[i] for i in perm], ws[4]) == val
checked += 1
signs += val > 0
assert 0 < signs < 300
def test_power_test_with_zero_weights_is_insphere():
r = random.Random(8)
n = 0
while n < 200:
pts = [tuple(r.randint(-9, 9) for _ in range(3)) for _ in range(5)]
if orient3d(*pts[:4]) == 0:
continue
assert power_test(*pts) == insphere(*pts)
n += 1
def test_power_test_on_a_cube():
c = [(x, y, z) for x in (0, 2) for y in (0, 2) for z in (0, 2)]
t = (c[0], c[1], c[2], c[4])
assert power_test(*t, (1, 1, 1)) > 0 # the center of the circumsphere
assert power_test(*t, c[7]) == 0 # cospherical
assert power_test(*t, (1, 1, 1), we=0) > 0
# a center weight equal to its power distance makes it orthogonal: zero; more is a conflict, less is not
pi = critical_weight(*t, (1, 1, 1))
assert pi == dist2((1, 1, 1), (1, 1, 1)) - 3 == -3
assert power_test(*t, (1, 1, 1), we=-3) == 0
assert power_test(*t, (1, 1, 1), we=-4) < 0
# (1, 1, 3) lies outside the circumsphere, power 4 - 3 = 1: a weight above 1 makes it conflict
assert critical_weight(*t, (1, 1, 3)) == 1
assert power_test(*t, (1, 1, 3)) < 0
assert power_test(*t, (1, 1, 3), we=1) == 0
assert power_test(*t, (1, 1, 3), we=2) > 0
# a weight on the corner (0, 0, 2) pulls the orthosphere away from it, so (1, 1, 3) needs a larger weight
assert critical_weight(*t, (1, 1, 3), 0, 4, 0, 0) > 1
assert power_test(*t, (1, 1, 3), 0, 4, 0, 0, we=2) < 0
def test_flat_tetrahedron_raises():
with pytest.raises(ValueError):
power_test((0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 0, 1))
def check_regular(e):
"""Every tetrahedron has positive volume and no weighted point conflicts with it."""
P, W = e.pts, e.w
vol = 0
for t in e.tets:
o = orient3d(*[P[x] for x in t])
assert o > 0
vol += o
for v in range(len(P)):
if v not in t:
assert power_test(*[P[x] for x in t], P[v], *[W[x] for x in t], W[v]) <= 0
assert vol == 6 * e.side**3
# every point is a vertex, and every face is shared by two tetrahedra or lies on the box
assert {v for t in e.tets for v in t} == set(range(len(P)))
count = {}
for t in e.tets:
for f in faces_of(t):
count[f] = count.get(f, 0) + 1
for f, m in count.items():
if m == 1:
assert any(all(P[v][k] in (0, e.side) and P[v][k] == P[f[0]][k] for v in f) for k in range(3))
else:
assert m == 2
@pytest.mark.parametrize("case", [EXAMPLE, OTHER])
def test_initial_triangulation_is_delaunay(case):
seed, g, jit = case
e = Exuder((g + 1) * S, jittered_grid(seed, g, jit))
assert all(w == 0 for w in e.w)
check_regular(e)
@pytest.mark.parametrize("case", [EXAMPLE, OTHER])
def test_final_triangulation_is_regular_and_unique(case):
e, _, _ = pumped(case)
check_regular(e)
fresh = e.triangulate(range(len(e.pts)))
assert {tuple(sorted(t)) for t in fresh} == {tuple(sorted(t)) for t in e.tets}
@pytest.mark.parametrize("case", [EXAMPLE, OTHER])
def test_weight_property(case):
e, _, _ = pumped(case)
P = e.pts
for u in range(len(P)):
assert e.w[u] >= 0
for v in range(len(P)):
if v != u:
# U <= OMEGA |uv|, so the spheres of radius sqrt(w) are disjoint
assert e.w[u] <= OMEGA**2 * dist2(P[u], P[v])
assert math.sqrt(e.w[u]) + math.sqrt(e.w[v]) < math.sqrt(dist2(P[u], P[v]))
assert all(e.w[u] == 0 for u in range(8))
@pytest.mark.parametrize("case", [EXAMPLE, OTHER])
def test_minimum_dihedral_never_decreases(case):
e, before, mins = pumped(case)
assert len(e.log) == len(e.pts) - 8
for u, w, wmax, ncand, zeta0, best in e.log:
assert 0 <= w <= wmax and ncand >= 1
assert best >= zeta0
for a, b in zip(mins, mins[1:]):
assert b >= a
assert mins[-1] > mins[0]
def test_star_matches_fresh_triangulation():
"""The star computed from critical weights equals Bowyer-Watson from scratch with that weight."""
r = random.Random(3)
e = Exuder(3 * S, jittered_grid(5, 2, 150))
P = e.pts
for u in range(8, len(P)):
rest = e.triangulate([v for v in range(len(P)) if v != u])
crit = {t: critical_weight(*[P[x] for x in t], P[u], *[e.w[x] for x in t]) for t in rest}
wmax = math.floor(OMEGA**2 * e.nearest2(u))
for w in [0, wmax] + [r.randint(0, wmax) for _ in range(4)]:
if w in crit.values():
continue
cavity, cone = e.star(rest, crit, u, w)
e.w[u] = w
fresh = e.triangulate(range(len(P)))
e.w[u] = 0
assert {tuple(sorted(t)) for t in (rest - cavity) | set(cone)} == {tuple(sorted(t)) for t in fresh}
e.pump(u)
@pytest.mark.parametrize("u", [9, 18, 21, 26, 30])
def test_pump_finds_the_best_star(u):
"""Brute force: try the midpoint of every interval between critical weights, and many integers."""
e = Exuder(4 * S, jittered_grid(*EXAMPLE))
P = e.pts
rest = e.triangulate([v for v in range(len(P)) if v != u])
crit = {t: critical_weight(*[P[x] for x in t], P[u]) for t in rest}
wmax = math.floor(OMEGA**2 * e.nearest2(u))
cuts = sorted({c for c in crit.values() if 0 < c < wmax})
trial = [F(0)] + [(lo + hi) / 2 for lo, hi in zip([F(0)] + cuts, cuts + [F(wmax)])]
trial += [F(w) for w in range(1, wmax + 1, 499)]
best = max(min_dihedral(P, e.star(rest, crit, u, w)[1]) for w in trial if w not in crit.values())
e.pump(u)
# the current weight 0, and at most one integer in each of the len(cuts) + 1 intervals
assert e.log[-1][3] <= len(cuts) + 2
assert e.log[-1][5] == pytest.approx(best, abs=1e-9)
def test_example_numbers():
e, before, mins = pumped(EXAMPLE)
P = e.pts
tets0, min0 = before
lo0 = [min(dihedral_angles_deg(*[P[v] for v in t])) for t in tets0]
lo1 = [min(dihedral_angles_deg(*[P[v] for v in t])) for t in e.tets]
assert (len(tets0), len(e.tets)) == (151, 139)
assert round(min0, 2) == 0.14 and round(mins[-1], 2) == 5.20
assert (sum(a < 5 for a in lo0), sum(a < 5 for a in lo1)) == (9, 0)
assert (sum(a < 10 for a in lo0), sum(a < 10 for a in lo1)) == (17, 6)
assert sum(1 for w in e.w if w) == 11
# the worst sliver: four vertices near the face x = 3000, angles 0.14 and 179.78 degrees
worst = min(tets0, key=lambda t: min(dihedral_angles_deg(*[P[v] for v in t])))
assert sorted(worst) == [26, 27, 29, 30]
ang = dihedral_angles_deg(*[P[v] for v in worst])
assert round(max(ang), 2) == 179.78
# its radius-edge ratio is small: the ratio does not see it
cc = circumcenter3(*[P[v] for v in worst])
lmin = min(dist2(P[a], P[b]) for a in worst for b in worst if a < b)
assert dist2(cc, P[worst[0]]) / lmin < 9
# the pump of vertex 26 removes it
row = next(x for x in e.log if x[0] == 26)
assert row[1] == 44845 and round(row[4], 2) == 0.14 and round(row[5], 2) == 5.47
# the global minimum rises at the pumps of 26 and 30 only
assert [i + 8 for i in range(len(mins) - 1) if mins[i + 1] > mins[i]] == [26, 30]
def test_second_example_worst_touches_a_corner():
e, _, mins = pumped(OTHER)
assert round(mins[0], 2) == 1.54 and round(mins[-1], 2) == 3.03
worst = min(e.tets, key=lambda t: min(dihedral_angles_deg(*[e.pts[v] for v in t])))
assert min(worst) < 8
def test_dihedral_lower_bound_from_volume_and_edge_ratio():
"""sin(theta) >= 8 Sigma / lambda^4 with Sigma = V / L^3 and lambda = D / L, on every tetrahedron."""
for case in (EXAMPLE, OTHER):
e, before, _ = pumped(case)
P = e.pts
for t in set(before[0]) | e.tets:
q = [P[v] for v in t]
V = F(abs(orient3d(*q)), 6)
e2 = [dist2(q[a], q[b]) for a in range(4) for b in range(a + 1, 4)]
L, D = math.sqrt(min(e2)), math.sqrt(max(e2))
bound = 8 * float(V) * L / D**4 # 8 (V / L^3) / (D / L)^4
theta = min(dihedral_angles_deg(*q))
assert math.sin(math.radians(theta)) >= bound * (1 - 1e-9)
@pytest.mark.parametrize("case", [EXAMPLE, OTHER])
def test_longest_edge_bounded_by_orthoradius(case):
"""With the Weight Property, D^2 (1 - 4 OMEGA^2) <= 4 Z^2 for every tetrahedron of the output."""
e, _, _ = pumped(case)
P, W = e.pts, e.w
for t in e.tets:
q, ws = [P[v] for v in t], [W[v] for v in t]
z, Z2 = orthosphere(q, ws)
assert Z2 > 0
for p, w in zip(q, ws):
assert dist2(p, z) - Z2 == w
D2 = max(dist2(q[a], q[b]) for a in range(4) for b in range(a + 1, 4))
assert D2 * (1 - 4 * OMEGA**2) <= 4 * Z2
def test_entry_point_and_bad_input():
e = sliver_exudation(2 * S, [(1000, 1000, 1000)])
assert len(e.tets) == 12 and e.w[8] <= OMEGA**2 * 3 * 10**6
check_regular(e)
with pytest.raises(ValueError):
Exuder(0, [])
with pytest.raises(ValueError):
Exuder(10, [(5, 5, 5)], omega=F(1, 2))
with pytest.raises(ValueError):
Exuder(10, [(5, 5, 5), (5, 5, 5)])
with pytest.raises(ValueError):
Exuder(10, [(0, 5, 5)])
with pytest.raises(ValueError):
Exuder(10, [(5, 5, 11)])
History
Slivers were known as the weak point of three-dimensional Delaunay refinement through the 1990s: Shewchuk's 1998 analysis bounds only the radius-edge ratio, and Chew's 1997 method removes slivers by random choice with a weak guarantee. Cheng, Dey, Edelsbrunner, Facello and Teng presented sliver exudation at SoCG 1999 and in the Journal of the ACM in 2000, with the first proof that weights alone can remove slivers. Edelsbrunner and Guoy tested it in 2002 and found the minimum angle reaches about in practice. Cheng and Dey combined it with refinement for domains with boundaries, and the material forms Chapters 10 and 11 of Cheng, Dey and Shewchuk's Delaunay Mesh Generation (2013).
References
- Siu-Wing Cheng, Tamal K. Dey, Herbert Edelsbrunner, Michael A. Facello and Shang-Hua Teng, Sliver exudation, Journal of the ACM 47(5), 2000, 883 to 904, Section 2.4 (Ratio Property), Section 4.2 (Weight Property), Section 4.5 (the measure Sigma), Section 5.1 (periodic point sets and Claim 7, the Weighted Ratio Property), Section 6.5 (the Sliver Theorem), Section 7.1 (pumping and the skyline), Section 8.1 (the constant is "miserably tiny")
- Siu-Wing Cheng, Tamal K. Dey, Herbert Edelsbrunner, Michael A. Facello and Shang-Hua Teng, Sliver exudation, Proceedings of the 15th Annual Symposium on Computational Geometry, 1999, 1 to 13, the conference version (general locator)
- Herbert Edelsbrunner and Damrong Guoy, An experimental study of sliver exudation, Engineering with Computers 18(3), 2002, 229 to 240, Section 3 (function Pump with the bound 0.45 d_u, the O(n) running time, the remark that the proved constant is "positive but miserably small" and around 5 degrees in practice), Section 4 (experiments), Section 5 (the boundary as the main limitation)
- Siu-Wing Cheng, Tamal K. Dey and Jonathan Richard Shewchuk, Delaunay Mesh Generation, CRC Press, 2013, Chapter 7 (weighted Delaunay triangulations, pages 169 to 184), Chapter 10 (sliver exudation, pages 223 to 246), Chapter 11 (refinement for sliver exudation, pages 247 to 260)
- Siu-Wing Cheng and Tamal K. Dey, Quality meshing with weighted Delaunay refinement, SIAM Journal on Computing 33(1), 2003, 69 to 93, Section 5 (pumping mixed with refinement for polyhedral domains, Lemma 5.1 on the orthoradius-edge ratio)
- François Labelle and Jonathan Richard Shewchuk, Isosurface stuffing, fast tetrahedral meshes with good dihedral angles, ACM Transactions on Graphics 26(3), 2007, article 57, Section 2, the remark that the provable angle bounds of Delaunay methods with sliver removal are below 0.1 degree and probably below a millionth of a degree
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 4WRSY6 Edit this page History Report an error Markdown