Techniqueresearch
Protecting balls for sharp features
Also called weighted protecting balls.
Cheng, Dey and Ramos's weighted points around sharp edges and corners, so Delaunay refinement of piecewise smooth complexes terminates with the right topology.
Protecting balls make Delaunay refinement work on domains with sharp edges and corners at any angle. Before refinement starts, every corner and every sharp curve of the domain is covered by a chain of balls. Each ball becomes a weighted point of a weighted Delaunay triangulation, the regular triangulation dual to the power diagram. Refinement then runs as for smooth surfaces, as in Delaunay surface meshing, with unweighted points. Two things follow from the weights and from simple conditions on the balls. The restricted Delaunay edges along each sharp curve are exactly the pairs of neighboring balls, whatever unweighted points are added. And a refinement point taken on a Voronoi edge never lands inside a ball. The second fact keeps refinement from closing in on a small angle forever. Cheng, Dey and Ramos introduced the weighted version for piecewise smooth complexes in 2007; the journal version appeared in 2010. Cheng, Dey and Ray had used weighted balls for polyhedra with small angles in 2005, and protecting balls without weights are older still.
In plain words
A Delaunay mesher puts new points in the middle of empty spaces. Near a sharp edge where two surfaces meet at a small angle, the empty spaces get thinner and thinner, so it keeps adding points closer and closer to the edge and never stops.
The fix is to fence off the sharp edges first. Lay a string of beads along each edge, each bead overlapping its neighbors, and give each bead a weight equal to its size squared. In the weighted Voronoi diagram, a bead claims the part of the edge it covers more strongly than any ordinary point can. Two things follow. The edge stays meshed as the string of beads, with no point allowed to cut into it. And the mesher never finds an empty space inside a bead, so it never puts a point there. The rest of the domain is meshed as usual.
When it applies
- The domain is a piecewise smooth complex: vertices, curves, surface patches and volumes, each smooth, glued along their boundaries. Polyhedra, CAD models with sharp edges and non-manifold surfaces are all of this kind.
- Two patches may meet at a curve, or two curves at a vertex, at an angle that is arbitrarily small. Without protection, Delaunay refinement need not terminate there. The termination proofs of Ruppert's algorithm and of tetrahedral Delaunay refinement assume that the input has no small angles.
- The sharp curves must be kept as curves of the mesh, which is usually what a CAD user wants.
- The mesher can maintain a weighted Delaunay triangulation and find where Voronoi edges and facets meet the curves and patches. CGAL's 3D mesh generator works this way.
The template
The protection properties, in the form used by this page for straight sharp edges, are three. Neighbors along a curve form a chain with centers on the curve, ending at the vertex balls.
- (a) Neighbors overlap, and neither contains the other's center: .
- (b) Balls that are not neighbors are disjoint.
- (c) No ball meets a piece of a chain unless it is centered at or .
Cheng, Dey and Levine (2007) state the properties for curved edges as follows. Neighbors overlap significantly without containing each other's centers. No three balls have a common point. And for a constant , every ball with up to 8 times the protecting radius meets its curve in one open arc and each incident patch in a disk, with normals turning by at most inside it. Their construction takes the radius . Here is the distance at which the normal has turned by , and is the distance to the nearest point where a sphere around touches a curve or patch tangentially.
The layout below is for straight sharp edges. It is the one in the implementation. For a segment of length , let be its distance to the segments that share no endpoint with it. Let be the sine of the smallest angle between and another segment at , capped at 90 degrees, and let be the same at . Let be the size factor, by default.
PROTECT(vertices, segments, c)- 1
for each vertex v: r_v ← c · min(distance to the segments not at v, half the shortest segment at v) - 2
for each segment e = uv: ρ_e(s) ← c · min(H_e, s σ_u, (L − s) σ_v), for the point at distance s from u - 3
s_a ← the s with s = r_u + ρ_e(s)/2, and s_b ← the s with L − s = r_v + ρ_e(s)/2 - 4
put centers from s_a to s_b at equal steps of Φ/m in φ(s) = ∫ ds / ρ_e(s), with m = ⌈Φ/1.4⌉; one center at the midpoint if Φ ≤ 0.7 - 5
r_x ← min(ρ_e(x), 0.9 · the distance to the nearer neighbor center of x on e) - 6
check (a), (b) and (c) exactly; fail if any is violated - 7
return every ball B(x, r_x) as the weighted point (x, r_x²)
The meshing that follows is outside the template. Run Delaunay refinement with these weighted points and unweighted new points. Cheng, Dey and Levine's DelPSC inserts a point where a Voronoi edge meets a patch, either when the triangles around a vertex do not form a disk or when a restricted triangle is larger than a resolution . It inserts the orthocenter of a tetrahedron when the radius-edge ratio exceeds , unless that would delete a restricted triangle.
Power distance is . An unweighted point has . The restricted pairs of a curve are the pairs of sites whose power cells share a point of the curve: the restricted Delaunay edges of restricted Delaunay triangulation, counted with their degenerate cases.
Claim 1 (proved here: the chain is restricted, for any unweighted points). Let (a) and (c) hold, and let be any finite set of unweighted points, anywhere. In the power diagram of the balls and , the restricted pairs of each segment are exactly the neighbors of its chain.
Proof. Take neighbors and a point of . Since , either or , so . For , . For a ball other than , (c) gives , so . So on only and can be nearest. Along the line, is affine, because the squared terms cancel. At it is and at it is positive, both by (a). So it has exactly one zero on : is nearest before it and after. Walking from to , the nearest site runs through in order, and two sites share a point of the segment exactly when they are neighbors.
Claim 2 (proved here: Voronoi edges avoid the balls). Let (b) hold and let every segment carry at least one ball besides its vertex balls. If a point has three or more nearest sites in power, then lies in no open ball.
Proof. Let be the smallest power at . If one of the nearest sites is unweighted, . Otherwise all of them are balls. If , lies inside three open balls, which then meet pairwise. By (b) they would be pairwise neighbors in a chain. That is impossible: neighbors are consecutive in a chain or a vertex and its first ball, and since each segment has a ball inside it, no three are pairwise neighbors. So , and for every ball .
Claim 2 is the reason for the weights. DelPSC inserts points where Voronoi edges meet patches and at orthocenters of tetrahedra, which have four nearest sites. By Claim 2 none of them is inside a protecting ball, so the point set stays admissible: the weighted points plus unweighted points outside the balls. This is Lemma 3 of Cheng, Dey and Levine. With weight zero on the same centers, Voronoi edges do pass through the balls. The tests place an unweighted point just outside two neighboring balls. The point equidistant from it and the two centers then lies deep inside a ball, and those three are its nearest sites.
Claim 3 (proved here: the layout gives (b) and (c) when ). Ignore the rounding of the centers to rationals. With , the balls of lines L1 to L5 satisfy (b) and (c).
Proof. For on at distance from , let be another segment. If shares no endpoint with , then . If meets at at angle , then when degrees, and otherwise. So for every other segment , and the same holds for for not at . For balls and on different segments, . The same bound covers a vertex ball and a ball on a segment not at that vertex. A ball meets no piece of another segment, because . On one segment, line L5 keeps every radius below the gap to each neighbor. Line L3 puts the first center past the vertex ball, . So a ball never reaches its neighbor's center, balls two apart are disjoint, and no ball meets a piece of its own segment that it does not end. Two vertex balls on the same segment have .
The bound is tight. At the 10 degree corner of the example below, two balls at distance from the corner, one on each edge, are apart. Each has radius . So (b) fails as soon as . The test finds that passes the exact check and fails it. Property (a) is not proved for this layout, because it depends on how fast changes between neighbors. Line L6 checks it, with (b) and (c), in exact rational arithmetic.
Claim 4 (proved here: number of balls). Segment gets at most balls besides its vertex balls, where
Proof. Line L4 places centers with , or one. Next, . Integrating over with and gives the bound. Here is computed by a numerical integral, and the bound is for that value.
So the count grows like times a logarithm at a small angle, not like . This is the graded shrinking that the weights allow near a corner.
What the papers prove, and of which kind. Cheng, Dey and Ramos prove termination and a homeomorphism. Termination is proved with no bound on the number of points. The homeomorphism is an existence theorem: the output is homeomorphic to the domain once the sample is dense enough, with no explicit threshold. Cheng, Dey and Levine's DelPSC keeps only the disk test. For it they state three properties. Termination is their Theorem 1. T1 says every sharp curve is meshed as the chain of its protecting balls, for every ; it follows from their Lemma 1, which is Claim 1 for curved edges. T2 says every patch is meshed as a manifold, for every . T3 says there exists a for which the output is homeomorphic to the domain, again with no value given. They skip the proof of T2 in that paper.
Proved constants and measured ones. The proved conditions are very cautious, much more so than what works in practice. The radius with is under 1 percent of the distance at which the normal turns by . Cheng, Dey and Levine write that the properties "can be satisfied in practice by using sufficiently small balls around the non-smooth edges". The topology theorem gives only the existence of some . Their experiments set to 10 percent of the smallest side of the bounding box and , and on their eleven models they report the right topology, with 1340 to 19810 vertices in 4.8 to 170.9 seconds. The same holds here, on a small scale. The proof of Claim 3 needs . Yet with , where the exact check fails, the chains of the example were still the restricted pairs against 60 random admissible points, with a size factor 2.4 times the proved limit. At they were not.
Classic examples
A corner of 10 degrees. Take , , and , with the segments , , and . The angle is degrees, and is at right angles to the other two. With , PROTECT makes 98 balls and the exact check passes.
| segment | length | at its ends | balls inside | smallest radius | largest radius | bound of Claim 4 |
|---|---|---|---|---|---|---|
| 1000.0 | 0.174, 0.996 | 38 | 5.56 | 35.34 | 47.1 | |
| 1000.3 | 0.174, 0.996 | 38 | 5.56 | 35.36 | 47.1 | |
| 174.6 | 0.996, 0.996 | 9 | 6.21 | 21.13 | 14.4 | |
| 1000.0 | 1, 1 | 9 | 35.71 | 121.0 | 16.8 |
The vertex balls have radius 125 at and , a quarter of half of 1000, and 21.83 at and , a quarter of half of . Along , from the corner, each radius is 6.15 percent larger than the one before. Along , which meets nothing at a small angle, the step is 32.4 percent. The thin wedge between and is fenced off by two chains of small balls that never touch each other. Adding unweighted points anywhere does not change the chains, as Claim 1 says. Without weights, an unweighted point near the middle of a piece takes part of the edge from its two neighbors. The tests check both.
Polyhedra with small angles. The sharp edges of a polyhedron are straight segments, which is the case above. Cheng, Dey and Ray (2005) protected them with weighted balls and refined the rest by weighted Delaunay refinement.
Piecewise smooth complexes. Curved sharp edges, as in CAD models and non-manifold surfaces, need the normal conditions as well. Cheng, Dey and Ramos proved termination and topology for any input angles. Cheng, Dey and Levine made it practical with the single disk test.
CGAL. CGAL's 3D mesh generator protects the 1-dimensional features with balls that become weighted points. Its manual requires that no two balls centered on different features intersect, and that no three balls intersect. The user parameter edge_size bounds the distance between consecutive centers.
Variations
- Unweighted protection. Murphy, Mount and Gable (2001) and Cohen-Steiner, Colin de Verdière and Yvinec (2002, journal 2004) protect the edges of a polyhedron with balls that carry no weights, to get a conforming Delaunay tetrahedralization.
- Cheaper predicates. Dey and Levine (2009) give a version of the piecewise smooth mesher without the expensive predicates of the 2007 algorithm, as their title says.
- Larger balls. The proved conditions are sufficient, not necessary. In the example, chains survived random points with a size factor of 1.2, far above the proved . A mesher can start with large balls and shrink only those that fail a check.
Pitfalls
- The weights must stay. An unweighted Delaunay triangulation of the same centers lets Voronoi edges pass inside the balls, and a refinement point inserted there breaks the chain.
- Protection does not make the elements good. DelPSC refines tetrahedra by radius-edge ratio with , and a radius-edge bound does not remove slivers, the flat sliver tetrahedra. Near the balls, tetrahedra are not refined at all when the orthocenter would delete a restricted triangle. Small angles in the input stay small angles in the mesh.
- The size of the balls is set by the smallest angle and the nearest other feature. A pair of sharp edges that nearly touch forces tiny balls along their whole length, and the count grows like .
- The layout of this page computes in floating point and then checks exactly. A check that fails raises an error, rather than returning balls that are not safe.
- The ball conditions for curved edges need normal deviation and tangency distances, which are expensive to compute. DelPSC computes them once, before refinement.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/protecting-balls/. The authors are listed in prov/EADV10.jsonl.
"""Protecting balls for the sharp edges of a domain, turned into weighted points.
The sharp features are a 1-complex in R^3: vertices with integer coordinates
and straight segments that meet only at shared endpoints, at any angle, however
small. PROTECT puts a ball on every vertex and a chain of balls along every
segment, with radii that shrink near a vertex where two segments meet at a
small angle. Each ball B(x, r) becomes the weighted point (x, r^2).
The layout is computed in floating point, then the centers (rational points of
the segments) and radii (rationals) are fixed, and the protection properties
are checked exactly with Fraction arithmetic:
(a) adjacent balls of a chain overlap and neither contains the other's center:
max(r_p, r_q) < |pq| < r_p + r_q;
(b) balls that are not adjacent are disjoint;
(c) no ball meets a piece [p, q] of a chain unless it is centered at p or q.
restricted_pairs computes, exactly, which pairs of sites have power cells that
meet at a point of a segment, using the lower envelope of affine functions;
restricted_pairs_brute does the same from scratch in O(n^2). With (a) and (c),
the pairs on each segment are exactly the consecutive balls of its chain, for
any set of unweighted points added to the sites.
"""
import math
from fractions import Fraction
from typing import Dict, List, Optional, Sequence, Set, Tuple
Point = Sequence
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):
d = sub(a, b)
return dot(d, d)
def point_seg_dist2(p: Point, a: Point, b: Point):
"""Squared distance from p to the closed segment ab. Exact for int or Fraction input."""
d = sub(b, a)
dd = dot(d, d)
t = dot(sub(p, a), d)
if t <= 0:
return dist2(p, a)
if t >= dd:
return dist2(p, b)
if isinstance(t, float) or isinstance(dd, float):
tt = t / dd
else:
tt = Fraction(t) / dd
q = tuple(ai + tt * di for ai, di in zip(a, d))
return dist2(p, q)
def seg_seg_dist2(a: Point, b: Point, c: Point, d: Point) -> Fraction:
"""Exact squared distance between closed segments ab and cd (integer or rational input)."""
best = min(point_seg_dist2(a, c, d), point_seg_dist2(b, c, d), point_seg_dist2(c, a, b), point_seg_dist2(d, a, b))
u, v, w = sub(b, a), sub(d, c), sub(a, c)
A, B, C = dot(u, u), dot(u, v), dot(v, v)
den = A * C - B * B
if den != 0:
D, E = dot(u, w), dot(v, w)
s = Fraction(B * E - C * D, 1) / den
t = Fraction(A * E - B * D, 1) / den
if 0 <= s <= 1 and 0 <= t <= 1:
p = tuple(ai + s * ui for ai, ui in zip(a, u))
q = tuple(ci + t * vi for ci, vi in zip(c, v))
best = min(best, dist2(p, q))
return Fraction(best)
class Ball:
"""A protecting ball B(center, r); vertex is set for a vertex ball, seg for a segment ball."""
__slots__ = ("center", "r", "vertex", "seg")
def __init__(self, center: tuple, r: Fraction, vertex: Optional[int] = None, seg: Optional[int] = None):
self.center = center
self.r = r
self.vertex = vertex
self.seg = seg
def weighted(self) -> Tuple[tuple, Fraction]:
return self.center, self.r * self.r
class Protection:
"""The balls, and for each segment the chain of ball indices from its first to its second endpoint."""
def __init__(self, points, segments, c, balls, chains):
self.points = points
self.segments = segments
self.c = c
self.balls: List[Ball] = balls
self.chains: List[List[int]] = chains
def adjacent_pairs(self) -> Set[Tuple[int, int]]:
out = set()
for ch in self.chains:
for i, j in zip(ch, ch[1:]):
out.add((min(i, j), max(i, j)))
return out
def weighted_points(self) -> List[Tuple[tuple, Fraction]]:
return [b.weighted() for b in self.balls]
def check_complex(points: Sequence[Point], segments: Sequence[Tuple[int, int]]) -> None:
"""Raise ValueError unless the segments form a proper 1-complex on the given vertices."""
n = len(points)
seen = set()
used = set()
for i, j in segments:
if not (0 <= i < n and 0 <= j < n) or i == j:
raise ValueError("bad segment")
key = (min(i, j), max(i, j))
if key in seen:
raise ValueError("duplicate segment")
seen.add(key)
used.update(key)
if len(used) != n:
raise ValueError("every vertex must be an endpoint of a segment")
for k, (i, j) in enumerate(segments):
for l in range(k + 1, len(segments)):
p, q = segments[l]
shared = {i, j} & {p, q}
if not shared:
if seg_seg_dist2(points[i], points[j], points[p], points[q]) == 0:
raise ValueError("segments cross")
else:
(s,) = shared
a = sub(points[j if s == i else i], points[s])
b = sub(points[q if s == p else p], points[s])
if cross(a, b) == (0, 0, 0) and dot(a, b) > 0:
raise ValueError("segments overlap")
def _fseg_dist(p, a, b) -> float:
return math.sqrt(float(point_seg_dist2(tuple(map(float, p)), tuple(map(float, a)), tuple(map(float, b)))))
def _fsegseg(a, b, c, d) -> float:
return math.sqrt(float(seg_seg_dist2(a, b, c, d)))
def _sin_min_angle(points, segments, e: int, end: int) -> float:
"""sin of the smallest angle at vertex `end` between segment e and the other segments there, capped at 90 degrees."""
i, j = segments[e]
other = j if end == i else i
a = sub(points[other], points[end])
best = 1.0
for k, (p, q) in enumerate(segments):
if k == e or end not in (p, q):
continue
b = sub(points[q if end == p else p], points[end])
if dot(a, b) <= 0:
continue
s = math.sqrt(dot(cross(a, b), cross(a, b)) / (dot(a, a) * dot(b, b)))
best = min(best, s)
return best
def _dyadic(x: float, bits: int) -> Fraction:
"""x rounded down to a multiple of 2^-bits, so a radius never grows."""
return Fraction(math.floor(x * (1 << bits)), 1 << bits)
class _Rho:
"""rho(s) = c min(H, s su, (L - s) sv) on [0, L], and phi(s) = integral of ds / rho."""
def __init__(self, c, H, su, sv, L):
self.c, self.H, self.su, self.sv, self.L = c, H, su, sv, L
def __call__(self, s: float) -> float:
return self.c * min(self.H, s * self.su, (self.L - s) * self.sv)
def phi(self, s0: float, s1: float, steps: int = 400) -> float:
# the integrand is 1 / (piecewise linear), smooth between breakpoints; a fine
# midpoint rule on a geometric grid is accurate far beyond what is needed
tot = 0.0
h = (s1 - s0) / steps
for k in range(steps):
tot += h / self(s0 + (k + 0.5) * h)
return tot
def _solve(fn, x0: float) -> float:
x = x0
for _ in range(100):
x = fn(x)
return x
def protect(points: Sequence[Point], segments: Sequence[Tuple[int, int]], c: float = 0.25, check: bool = True) -> Protection:
"""Protecting balls for the sharp segments; raises ValueError if the exact check fails.
The ball size factor c must be below 1/2 for the properties to be guaranteed.
check=False skips the exact check, to measure what happens with larger balls.
"""
if not 0 < c:
raise ValueError("c must be positive")
check_complex(points, segments)
n = len(points)
inc: Dict[int, List[int]] = {v: [] for v in range(n)}
for k, (i, j) in enumerate(segments):
inc[i].append(k)
inc[j].append(k)
length = [math.sqrt(dist2(points[i], points[j])) for i, j in segments]
balls: List[Ball] = []
rv: List[float] = []
for v in range(n):
H = min((_fseg_dist(points[v], points[p], points[q]) for p, q in segments if v not in (p, q)), default=math.inf)
r = c * min(H, min(length[k] for k in inc[v]) / 2) # @line L1
R = _dyadic(r, 24)
balls.append(Ball(tuple(Fraction(x) for x in points[v]), R, vertex=v))
rv.append(float(R))
chains: List[List[int]] = []
for e, (u, v) in enumerate(segments):
L = length[e]
H = min(
(_fsegseg(points[u], points[v], points[p], points[q]) for p, q in segments if not {u, v} & {p, q}),
default=math.inf,
)
rho = _Rho(c, H, _sin_min_angle(points, segments, e, u), _sin_min_angle(points, segments, e, v), L) # @line L2
sa = _solve(lambda s: rv[u] + rho(s) / 2, rv[u]) # @line L3
sb = _solve(lambda s: L - rv[v] - rho(s) / 2, L - rv[v])
Phi = rho.phi(sa, sb)
if Phi <= 0.7: # @line L4
pos = [(sa + sb) / 2]
else:
m = math.ceil(Phi / 1.4)
pos = [sa]
for k in range(1, m):
# next center one m-th of Phi further along in phi
lo, hi = pos[-1], sb
for _ in range(50):
mid = (lo + hi) / 2
if rho.phi(pos[-1], mid, 40) < Phi / m:
lo = mid
else:
hi = mid
pos.append((lo + hi) / 2)
pos.append(sb)
ts = [_dyadic(s / L, 32) for s in pos]
d = sub(points[v], points[u])
chain = [u]
full = [0.0] + [float(t) * L for t in ts] + [L]
for k, t in enumerate(ts):
s = full[k + 1]
gap = min(s - full[k], full[k + 2] - s)
r = min(rho(s), 0.9 * gap) # @line L5
center = tuple(Fraction(a) + t * di for a, di in zip(points[u], d))
balls.append(Ball(center, _dyadic(r, 24), seg=e))
chain.append(len(balls) - 1)
chain.append(v)
chains.append(chain)
prot = Protection(points, segments, c, balls, chains)
bad = violations(prot) if check else [] # @line L6
if bad:
raise ValueError("protection check failed: %s" % (bad[:3],))
return prot # @line L7
def violations(prot: Protection) -> List[tuple]:
"""Every failure of the protection properties (a), (b), (c), checked exactly."""
balls = prot.balls
adj = prot.adjacent_pairs()
bad = []
for i, j in sorted(adj):
d2 = dist2(balls[i].center, balls[j].center)
ri, rj = balls[i].r, balls[j].r
if not (max(ri, rj) ** 2 < d2 < (ri + rj) ** 2):
bad.append(("a", i, j))
for i in range(len(balls)):
for j in range(i + 1, len(balls)):
if (i, j) in adj:
continue
if dist2(balls[i].center, balls[j].center) <= (balls[i].r + balls[j].r) ** 2:
bad.append(("b", i, j))
for ch in prot.chains:
for p, q in zip(ch, ch[1:]):
a, b = balls[p].center, balls[q].center
for k, ball in enumerate(balls):
if k in (p, q):
continue
if point_seg_dist2(ball.center, a, b) <= ball.r ** 2:
bad.append(("c", k, p, q))
for ch in prot.chains:
if len(ch) < 3:
bad.append(("chain", ch))
return bad
def _lines(a: Point, b: Point, sites: Sequence[Tuple[Point, Fraction]]) -> List[Tuple[Fraction, Fraction]]:
"""Power distance from x(t) = a + t (b - a) to each site, minus the common term |b - a|^2 t^2."""
d = sub(b, a)
out = []
for s, w in sites:
e = sub(a, s)
out.append((Fraction(2 * dot(d, e)), Fraction(dot(e, e) - w)))
return out
def restricted_pairs(a: Point, b: Point, sites: Sequence[Tuple[Point, Fraction]]) -> Set[Tuple[int, int]]:
"""Pairs {i, j} of sites whose power cells share a point of the segment ab (lower envelope, exact)."""
lines = _lines(a, b, sites)
groups: Dict[Tuple[Fraction, Fraction], List[int]] = {}
for i, ln in enumerate(lines):
groups.setdefault(ln, []).append(i)
# lower envelope of the distinct lines: slopes decreasing, keep the lowest intercept per slope
best: Dict[Fraction, Fraction] = {}
for m, q in groups:
if m not in best or q < best[m]:
best[m] = q
order = sorted(best.items(), key=lambda mq: -mq[0])
def meet(l1, l2) -> Fraction:
return (l2[1] - l1[1]) / (l1[0] - l2[0])
hull: List[Tuple[Fraction, Fraction]] = []
for ln in order:
while len(hull) >= 2 and meet(hull[-2], ln) < meet(hull[-2], hull[-1]):
hull.pop()
hull.append(ln)
# interval of t where each hull line is minimal, clipped to [0, 1]
iv = []
for k, ln in enumerate(hull):
lo = meet(hull[k - 1], ln) if k > 0 else None
hi = meet(ln, hull[k + 1]) if k + 1 < len(hull) else None
lo2 = Fraction(0) if lo is None else max(lo, Fraction(0))
hi2 = Fraction(1) if hi is None else min(hi, Fraction(1))
if lo2 <= hi2:
iv.append((lo2, hi2, groups[ln]))
out = set()
for x in range(len(iv)):
for i in iv[x][2]:
for j in iv[x][2]:
if i < j:
out.add((i, j))
for y in range(x + 1, len(iv)):
if max(iv[x][0], iv[y][0]) <= min(iv[x][1], iv[y][1]):
for i in iv[x][2]:
for j in iv[y][2]:
out.add((min(i, j), max(i, j)))
return out
def restricted_pairs_brute(a: Point, b: Point, sites: Sequence[Tuple[Point, Fraction]]) -> Set[Tuple[int, int]]:
"""Same as restricted_pairs, from the definition: the set where site i is nearest is an interval."""
lines = _lines(a, b, sites)
ivs = []
for i, (mi, qi) in enumerate(lines):
lo, hi = Fraction(0), Fraction(1)
for j, (mj, qj) in enumerate(lines):
if j == i:
continue
# need mi t + qi <= mj t + qj, that is (mi - mj) t <= qj - qi
k, rhs = mi - mj, qj - qi
if k == 0:
if rhs < 0:
lo, hi = Fraction(1), Fraction(0)
elif k > 0:
hi = min(hi, rhs / k)
else:
lo = max(lo, rhs / k)
ivs.append((lo, hi))
out = set()
for i in range(len(lines)):
for j in range(i + 1, len(lines)):
lo = max(ivs[i][0], ivs[j][0])
hi = min(ivs[i][1], ivs[j][1])
if lo <= hi:
out.add((i, j))
return out
def nearest_power(x: Point, sites: Sequence[Tuple[Point, Fraction]]) -> Tuple[Fraction, List[int]]:
"""The smallest power distance from x to the sites, and every site that attains it."""
best, arg = None, []
for i, (s, w) in enumerate(sites):
p = dist2(x, s) - w
if best is None or p < best:
best, arg = p, [i]
elif p == best:
arg.append(i)
return best, arg
test_protecting_balls.py 386 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/protecting-balls/. The authors are listed in prov/EADV10.jsonl.
import math
import random
from fractions import Fraction as F
from itertools import combinations
import pytest
from protecting_balls import (
Ball,
Protection,
_fsegseg,
_sin_min_angle,
check_complex,
dist2,
nearest_power,
point_seg_dist2,
protect,
restricted_pairs,
restricted_pairs_brute,
seg_seg_dist2,
sub,
violations,
)
# a triangle with a 10 degree angle at O, and a segment OC at right angles to it
P = [(0, 0, 0), (1000, 0, 0), (985, 174, 0), (0, 0, 1000)]
S = [(0, 1), (0, 2), (1, 2), (0, 3)]
@pytest.fixture(scope="module")
def example():
return protect(P, S)
def chain_pairs(prot, e):
ch = prot.chains[e]
return {(min(i, j), max(i, j)) for i, j in zip(ch, ch[1:])}
def rand_complex(rng, nv=5, ne=6, span=1000, far=150):
while True:
pts = [tuple(rng.randint(-span, span) for _ in range(3)) for _ in range(nv)]
segs = set()
while len(segs) < ne:
i, j = rng.sample(range(nv), 2)
segs.add((min(i, j), max(i, j)))
segs = sorted(segs)
if len({x for s in segs for x in s}) < nv:
continue
try:
check_complex(pts, segs)
except ValueError:
continue
if all(
seg_seg_dist2(pts[a], pts[b], pts[p], pts[q]) >= far * far
for k, (a, b) in enumerate(segs)
for (p, q) in segs[k + 1 :]
if not {a, b} & {p, q}
):
return pts, segs
def admissible_points(rng, prot, k, lo=-100, hi=1100):
out = []
while len(out) < k:
x = tuple(rng.randint(lo, hi) for _ in range(3))
if all(dist2(x, b.center) >= b.r**2 for b in prot.balls):
out.append((x, F(0)))
return out
def near_curve_points(rng, prot, k):
"""Unweighted points just outside the balls, next to the pieces of the chains."""
out = []
pieces = [(p, q) for ch in prot.chains for p, q in zip(ch, ch[1:])]
while len(out) < k:
p, q = rng.choice(pieces)
a, b = prot.balls[p].center, prot.balls[q].center
t = F(rng.randint(1, 99), 100)
m = tuple(x + t * (y - x) for x, y in zip(a, b))
off = tuple(F(rng.randint(-40, 40)) for _ in range(3))
x = tuple(mi + oi for mi, oi in zip(m, off))
if all(dist2(x, bb.center) >= bb.r**2 for bb in prot.balls):
out.append((x, F(0)))
return out
# --- exact geometry -----------------------------------------------------------
def test_seg_seg_distance_against_sampling():
rng = random.Random(1)
for _ in range(40):
a, b, c, d = (tuple(rng.randint(-20, 20) for _ in range(3)) for _ in range(4))
exact = float(seg_seg_dist2(a, b, c, d))
best = min(
dist2(tuple(x + i / 40 * (y - x) for x, y in zip(a, b)), tuple(x + j / 40 * (y - x) for x, y in zip(c, d)))
for i in range(41)
for j in range(41)
)
assert exact <= best + 1e-9
assert math.sqrt(best) - math.sqrt(exact) <= 2.0
def test_point_seg_distance():
assert point_seg_dist2((0, 5, 0), (-3, 0, 0), (3, 0, 0)) == 25
assert point_seg_dist2((7, 0, 0), (-3, 0, 0), (3, 0, 0)) == 16
assert point_seg_dist2((1, 1, 1), (0, 0, 0), (2, 2, 0)) == 1
# --- the restricted pairs on a segment -------------------------------------------
def test_restricted_pairs_matches_brute_force():
rng = random.Random(2)
for trial in range(150):
a = tuple(rng.randint(-50, 50) for _ in range(3))
b = tuple(rng.randint(-50, 50) for _ in range(3))
if a == b:
continue
sites = []
for _ in range(rng.randint(1, 12)):
s = tuple(rng.randint(-60, 60) for _ in range(3))
w = F(rng.choice([0, 0, rng.randint(0, 900)]))
sites.append((s, w))
# degenerate inputs: a site mirrored across the line has the same power
# function along it, and a repeated site ties everywhere
if trial % 3 == 0 and sites:
s, w = sites[0]
d = sub(b, a)
e = sub(s, a)
t = F(sum(x * y for x, y in zip(e, d)), sum(x * x for x in d))
foot = tuple(ai + t * di for ai, di in zip(a, d))
sites.append((tuple(2 * f - x for f, x in zip(foot, s)), w))
if trial % 5 == 0 and sites:
sites.append(sites[-1])
assert restricted_pairs(a, b, sites) == restricted_pairs_brute(a, b, sites)
def test_restricted_pairs_three_way_tie():
# three unweighted sites equidistant from the midpoint (5, 0, 0) of the segment
a, b = (0, 0, 0), (10, 0, 0)
sites = [((0, 0, 0), F(0)), ((10, 0, 0), F(0)), ((5, 5, 0), F(0))]
got = restricted_pairs(a, b, sites)
assert got == restricted_pairs_brute(a, b, sites) == {(0, 1), (0, 2), (1, 2)}
# --- the protection -------------------------------------------------------------------
def test_example(example):
prot = example
assert violations(prot) == []
assert [len(ch) - 2 for ch in prot.chains] == [38, 38, 9, 9]
assert [float(b.r) for b in prot.balls[:4]] == pytest.approx([125.0, 21.8307, 21.8307, 125.0], abs=1e-3)
ch = prot.chains[0]
radii = [float(prot.balls[i].r) for i in ch[1:-1]]
assert radii[0] == pytest.approx(5.56, abs=0.01)
assert max(radii) == pytest.approx(35.34, abs=0.01)
# near the 10 degree corner the radii grow by about 6 percent per ball
assert radii[1] / radii[0] == pytest.approx(1.0615, abs=1e-3)
# on OC, at right angles to everything, they grow by about a third
oc = [float(prot.balls[i].r) for i in prot.chains[3][1:-1]]
assert oc[1] / oc[0] == pytest.approx(1.324, abs=1e-3)
for e, (u, v) in enumerate(S):
assert prot.chains[e][0] == u and prot.chains[e][-1] == v
for i in prot.chains[e][1:-1]:
assert prot.balls[i].seg == e
def test_centers_lie_on_their_segments(example):
for e, (u, v) in enumerate(S):
for i in example.chains[e]:
assert point_seg_dist2(example.balls[i].center, P[u], P[v]) == 0
def test_random_complexes_pass_the_exact_check():
rng = random.Random(3)
for c in (0.3, 0.45):
pts, segs = rand_complex(rng, nv=4, ne=5)
prot = protect(pts, segs, c) # raises if the exact check fails
assert violations(prot) == []
def test_violations_detects_each_property(example):
balls = [Ball(b.center, b.r, b.vertex, b.seg) for b in example.balls]
ch = example.chains[3]
i, j = ch[2], ch[3]
# (a): shrink two neighbors until they no longer overlap
small = list(balls)
small[i] = Ball(balls[i].center, balls[i].r / 4, seg=3)
small[j] = Ball(balls[j].center, balls[j].r / 4, seg=3)
kinds = {v[0] for v in violations(Protection(P, S, 0.25, small, example.chains))}
assert "a" in kinds
# (b) and (c): grow one ball over its neighbor's neighbor
big = list(balls)
big[i] = Ball(balls[i].center, balls[i].r * 3, seg=3)
kinds = {v[0] for v in violations(Protection(P, S, 0.25, big, example.chains))}
assert {"a", "b", "c"} <= kinds
def test_c_below_one_half_is_needed_for_the_check():
# two balls on OA and OB at the same distance from O are
# 2 sin(5 degrees) s apart, and both have radius about c sin(10 degrees) s
assert violations(protect(P, S, 0.5, check=False)) == []
with pytest.raises(ValueError):
protect(P, S, 0.55)
def test_ball_count_bound():
rng = random.Random(4)
cases = [(P, S, protect(P, S))]
pts, segs = rand_complex(rng)
cases.append((pts, segs, protect(pts, segs, 0.4, check=False)))
for pts, segs, prot in cases:
c = prot.c
for e, (u, v) in enumerate(segs):
L = math.sqrt(dist2(pts[u], pts[v]))
H = min((_fsegseg(pts[u], pts[v], pts[p], pts[q]) for p, q in segs if not {u, v} & {p, q}), default=math.inf)
su, sv = _sin_min_angle(pts, segs, e, u), _sin_min_angle(pts, segs, e, v)
ru, rv = float(prot.balls[u].r), float(prot.balls[v].r)
phi_bound = (L / H + math.log(L / ru) / su + math.log(L / rv) / sv) / c
assert len(prot.chains[e]) - 2 <= phi_bound / 1.4 + 2
# --- what the protection buys ------------------------------------------------------------
def test_chain_is_restricted_for_any_unweighted_points(example):
rng = random.Random(5)
sites = example.weighted_points()
extra = admissible_points(rng, example, 40) + near_curve_points(rng, example, 40)
allsites = sites + extra
for e, (u, v) in enumerate(S):
got = restricted_pairs(P[u], P[v], allsites)
assert got == chain_pairs(example, e)
# the brute force agrees on one segment
assert restricted_pairs_brute(P[2], P[1], allsites) == restricted_pairs(P[1], P[2], allsites)
def test_chain_holds_even_for_points_inside_balls(example):
# the proof only uses that an unweighted point has power >= 0 everywhere
rng = random.Random(6)
pieces = [(p, q) for ch in example.chains for p, q in zip(ch, ch[1:])]
extra = []
for _ in range(30):
p, q = rng.choice(pieces)
a, b = example.balls[p].center, example.balls[q].center
t = F(rng.randint(0, 100), 100)
extra.append((tuple(x + t * (y - x) + rng.randint(-2, 2) for x, y in zip(a, b)), F(0)))
allsites = example.weighted_points() + extra
for e, (u, v) in enumerate(S):
assert restricted_pairs(P[u], P[v], allsites) == chain_pairs(example, e)
def test_chain_on_random_complex():
rng = random.Random(7)
pts, segs = rand_complex(rng, nv=4, ne=5)
prot = protect(pts, segs, 0.45)
allsites = prot.weighted_points() + admissible_points(rng, prot, 15, -1100, 1100) + near_curve_points(rng, prot, 15)
for e, (u, v) in enumerate(segs):
assert restricted_pairs(pts[u], pts[v], allsites) == chain_pairs(prot, e)
def middle_piece(prot, e):
"""The middle piece [p, q] of chain e, its midpoint m, a normal n, and D = |pq|^2."""
ch = prot.chains[e]
p, q = ch[len(ch) // 2], ch[len(ch) // 2 + 1]
a, b = prot.balls[p].center, prot.balls[q].center
m = tuple((x + y) / 2 for x, y in zip(a, b))
d = sub(b, a)
n = (-d[1], d[0], F(0)) if (d[0], d[1]) != (0, 0) else (F(1), F(0), F(0))
return p, q, a, b, m, n, dist2(a, b)
def test_without_weights_a_point_in_the_balls_breaks_the_chain(example):
# same centers with weight 0: an unweighted point close to the middle of a
# piece takes a part of the edge, so p and q are no longer joined; with the
# weights the same point changes nothing
zero = [(b.center, F(0)) for b in example.balls]
weighted = example.weighted_points()
for e, (u, v) in enumerate(S):
p, q, a, b, m, n, D = middle_piece(example, e)
s = tuple(mi + F(1, 64) * ni for mi, ni in zip(m, n))
assert dist2(s, a) < example.balls[p].r ** 2 # inside the protecting ball
unw = restricted_pairs(P[u], P[v], zero + [(s, F(0))])
assert (min(p, q), max(p, q)) not in unw
assert any(len(zero) in pair for pair in unw)
assert restricted_pairs(P[u], P[v], weighted + [(s, F(0))]) == chain_pairs(example, e)
def test_voronoi_points_inside_balls_only_without_weights(example):
# put an unweighted point s just outside the balls, above the middle of a piece.
# Without weights the point equidistant from p, q and s lies deep inside B_p, and
# p, q, s are its nearest sites: a Voronoi edge passes through the protecting
# ball, and a refinement step could insert a point there. With weights, the
# point of equal power to p, q and s has power |z - s|^2 >= 0 to all three.
weighted = example.weighted_points()
zero = [(b.center, F(0)) for b in example.balls]
for e in range(len(S)):
p, q, a, b, m, n, D = middle_piece(example, e)
N = sum(x * x for x in n)
rp, rq = example.balls[p].r, example.balls[q].r
# smallest t on a fine grid with s outside both balls of the piece
step = F(math.sqrt(float(D / N))).limit_denominator(1000) / 1024
t0 = math.sqrt(max(0.0, float((max(rp, rq) ** 2 - D / 4) / N)))
t = F(math.floor(t0 / float(step)) - 2) * step
while True:
s = tuple(mi + t * ni for mi, ni in zip(m, n))
if t > 0 and all(dist2(s, bb.center) >= bb.r**2 for bb in example.balls):
break
t += step
# unweighted: z = m + y n with |z - p| = |z - s|
y = (t * t * N - D / 4) / (2 * t * N)
z = tuple(mi + y * ni for mi, ni in zip(m, n))
best, arg = nearest_power(z, zero + [(s, F(0))])
assert sorted(arg) == sorted([p, q, len(zero)])
assert dist2(z, a) < rp**2
# weighted: z' = a + alpha (b - a) + beta n with equal power to p, q and s
alpha = F(1, 2) + (rp**2 - rq**2) / (2 * D)
beta = (t * t * N + rp**2 + D / 4 - alpha * D) / (2 * t * N)
zw = tuple(ai + alpha * (bi - ai) + beta * ni for ai, bi, ni in zip(a, b, n))
pw = [dist2(zw, c) - w for c, w in (weighted[p], weighted[q], (s, F(0)))]
assert pw[0] == pw[1] == pw[2] >= 0
best, arg = nearest_power(zw, weighted + [(s, F(0))])
if len(arg) >= 3:
assert best >= 0
def test_no_point_is_in_three_balls(example):
# property (b): only neighbors in a chain overlap, so a point with negative
# power to its nearest sites has at most two of them, and they are neighbors
rng = random.Random(8)
sites = example.weighted_points()
adj = example.adjacent_pairs()
pieces = [(p, q) for ch in example.chains for p, q in zip(ch, ch[1:])]
for _ in range(300):
p, q = rng.choice(pieces)
a, b = example.balls[p].center, example.balls[q].center
t = F(rng.randint(0, 64), 64)
x = tuple(xa + t * (xb - xa) + F(rng.randint(-64, 64), 16) for xa, xb in zip(a, b))
inside = [i for i, (c, w) in enumerate(sites) if dist2(x, c) < w]
assert len(inside) <= 2
if len(inside) == 2:
assert tuple(inside) in adj
best, arg = nearest_power(x, sites + [(x, F(0))])
if best < 0:
assert len(arg) <= 2
def test_larger_balls_measured():
# the exact check needs c < 1/2; with c = 1.2 it fails, yet on this example the
# chains are still the restricted pairs for these random points
rng = random.Random(9)
prot = protect(P, S, 1.2, check=False)
assert violations(prot)
allsites = prot.weighted_points() + admissible_points(rng, prot, 60)
for e, (u, v) in enumerate(S):
assert restricted_pairs(P[u], P[v], allsites) == chain_pairs(prot, e)
# with c = 1.6 they are not
prot = protect(P, S, 1.6, check=False)
allsites = prot.weighted_points() + admissible_points(rng, prot, 60)
assert any(restricted_pairs(P[u], P[v], allsites) != chain_pairs(prot, e) for e, (u, v) in enumerate(S))
@pytest.mark.parametrize(
"pts,segs",
[
([(0, 0, 0), (10, 0, 0), (0, 10, 0), (10, 10, 0)], [(0, 3), (1, 2)]), # crossing
([(0, 0, 0), (10, 0, 0), (20, 0, 0)], [(0, 1), (0, 2)]), # overlapping
([(0, 0, 0), (10, 0, 0), (5, 5, 5)], [(0, 1)]), # isolated vertex
([(0, 0, 0), (10, 0, 0)], [(0, 1), (1, 0)]), # duplicate
([(0, 0, 0), (10, 0, 0)], [(0, 0)]), # loop
],
)
def test_bad_input(pts, segs):
with pytest.raises(ValueError):
protect(pts, segs)
def test_bad_c():
with pytest.raises(ValueError):
protect(P, S, 0)
Exercises
- Show that Claim 1 fails without (c). Find a ball, two neighbors and and a point of where the third ball is nearest.
- For two segments meeting at angle , find the largest for which balls at equal distance from the corner, one on each segment, are disjoint. Check it against the 0.502 of the example.
- Prove that a point of the power diagram with an unweighted nearest site has nonnegative power to every site, and use it to show that DelPSC's orthocenters are never inside a ball.
- With and , how many balls does Claim 4 allow from out to distance 500? Compare with the 38 balls of .
References
- Siu-Wing Cheng, Tamal K. Dey and Edgar A. Ramos, Delaunay refinement for piecewise smooth complexes, Discrete and Computational Geometry 43(1), 2010, 121 to 166 (conference version in SODA 2007), protection of the vertices and curves by balls that become weighted points, the refinement by four kinds of violations, termination and the homeomorphism for a small enough sample (general locator)
- Siu-Wing Cheng, Tamal K. Dey and Joshua A. Levine, A practical Delaunay meshing algorithm for a large class of domains, Proceedings of the 16th International Meshing Roundtable, 2007, 477 to 494, Section 3 (the protection properties with omega at most 0.076 and R at most 8 radii, weighted points, admissible point sets, Lemma 1), Section 4.1 (algorithm DelPSC), Section 4.2 (the radius omega/8 times min of d_x and d'_x, the march with steps of 5/6 of a radius, the two last balls of equal radius), Section 5 (Lemma 3, Theorem 1, properties T1 to T3, Theorem 2), Section 6 (Table 1, rho_0 = 1.4 and lambda at 10 percent of the bounding box)
- Siu-Wing Cheng, Tamal K. Dey and Tathagata Ray, Weighted Delaunay refinement for polyhedra with small angles, Proceedings of the 14th International Meshing Roundtable, 2005, 325 to 342, protecting balls turned into weighted points for polyhedral input with small angles (general locator)
- Siu-Wing Cheng, Tamal K. Dey, Edgar A. Ramos and Tathagata Ray, Quality meshing of polyhedra with small angles, International Journal of Computational Geometry and Applications 15(4), 2005, 421 to 461, protection of small input angles by balls in Delaunay refinement of polyhedra (general locator)
- Siu-Wing Cheng, Tamal K. Dey and Jonathan Richard Shewchuk, Delaunay Mesh Generation, CRC Press, 2013, Chapter 15, Meshing piecewise smooth complexes, pages 349 to 384 (general locator)
- Tamal K. Dey and Joshua A. Levine, Delaunay meshing of piecewise smooth complexes without expensive predicates, Algorithms 2(4), 2009, 1327 to 1349, protection and refinement with only the disk test and Voronoi edge intersections (general locator)
- Clement Jamin, Pierre Alliez, Mariette Yvinec and Jean-Daniel Boissonnat, CGALmesh, a generic framework for Delaunay mesh generation, ACM Transactions on Mathematical Software 41(4), 2015, the protection of 1-dimensional features in the CGAL 3D mesh generator (general locator)
- CGAL 3D Mesh Generation user manual, the section on protection of 1-dimensional features (balls become weighted points, no two balls on different features intersect, no three balls intersect, the parameter edge_size bounds the distance between consecutive centers)
- Michael Murphy, David M. Mount and Carl W. Gable, A point-placement strategy for conforming Delaunay tetrahedralization, International Journal of Computational Geometry and Applications 11(6), 2001, 669 to 682, balls around input vertices and edges, without weights, to get a conforming Delaunay tetrahedralization (general locator)
- David Cohen-Steiner, Eric Colin de Verdiere and Mariette Yvinec, Conforming Delaunay triangulations in 3D, Computational Geometry 28(2 to 3), 2004, 217 to 233, protecting balls on the edges of a piecewise linear complex, without weights (general locator)
- Herbert Edelsbrunner and Nimish R. Shah, Triangulating topological spaces, International Journal of Computational Geometry and Applications 7(4), 1997, 365 to 378, the closed ball property, used in its extended form for the homeomorphism (general locator)
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag EADV10 Edit this page History Report an error Markdown