Algorithmresearch
Optimal Delaunay triangulation
Also called ODT smoothing, variational tetrahedral meshing.
Chen and Xu's mesh that minimises the interpolation error of |x|^2, optimised by moving vertices and retriangulating, used by Alliez and coauthors for tetrahedra.
- Solves
- Mesh generation
- Time
- O(k n^2) worst
- Space
- O(n) extra
- Where
- k = the number of sweeps; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Long Chen, Jinchao Xu, Pierre Alliez, David Cohen Steiner, Mariette Yvinec, Mathieu Desbrun, 2004
An optimal Delaunay triangulation (ODT) is a triangle or tetrahedral mesh that makes the interpolation error of the function as small as possible. Long Chen and Jinchao Xu introduced it in 2004. For fixed vertices, the best mesh is the Delaunay triangulation, which is a theorem. The method then alternates two steps: move each free vertex to the point that minimises the error over its star, and restore the Delaunay property by edge flips. Each step lowers the error, which is proved. The meshes that result are well graded and have good shapes in practice, but no angle bound is proved, and the shapes are only measured.
In plain words
Put a bowl shaped surface over the domain. Lift every mesh vertex up onto the bowl, and join the lifted points by flat triangles. The flat triangles sit above the bowl, and the volume of the gap between them and the bowl is the error of the mesh.
For a fixed set of points, the best way to join them is the Delaunay way, because it gives the lowest roof. The method then moves one point at a time to the place that makes the gap under its own small fan as small as possible, then rebuilds the Delaunay joins, and repeats. The gap never grows. Big gaps come from long edges, so the method spreads the points out evenly, and the triangles become near equilateral. A program measures their shape at the end.
The problem
The input is a convex polygon with corners in counterclockwise order, a set of fixed points on its sides, and a set of free points inside. The output is a triangulation of with the same fixed points and moved free points. The goal is a small value of
where is the piecewise linear interpolation of on . On a triangle with area and edge lengths , the error is , so is small when the triangles are small where they are many and when their edges are short for their area. The minimum over all positions is a global problem with many local minima; the method finds a local one.
The algorithm
ORIENT2D is the orientation test and INCIRCLE is the in-circle test, both exact on Fractions. For a free vertex , its star is the set of triangles that contain it, and its link is the polygon of the edges .
ODT-SMOOTH(Ω, fixed, free, k)- 1
T ← a Delaunay triangulation of the corners of Ω, fixed and free ▷ insert, then flip - 2
for sweep ← 1 to k do - 3
for each free vertex x do - 4
y* ← (1 / |Ω_x|) Σ over star triangles τ of |τ| · circumcentre(τ) - 5
for t ← 1, 1/2, 1/4, ..., 2^−29 do - 6
y ← x + t (y* − x), rounded to the grid of step 2^−20 - 7
if ORIENT2D(y, a, b) > 0 for every link edge ab and Φ(y) < Φ(x) then - 8
move x to y; break - 9
while some interior edge ij with triangles ija and jib has INCIRCLE(i, j, a, b) > 0 do - 10
flip ij to ab - 11
return T
Here over the star triangles with signed areas. It is three times the part of that depends on the free vertex. L4 is the exact minimiser of for the current star; the proof shows that it is the area-weighted mean of the circumcentres. L5 to L8 backtrack toward it: the target can lie outside the kernel of the star, where a triangle would fold over, and the grid rounding can also spoil the decrease, so both are tested exactly before a move. L9 and L10 are Lawson's flip algorithm. Points on the sides of never move.
Example
Take the square with no fixed side points and free points , and . L1 gives a Delaunay triangulation with 8 triangles and . These 7 points have 18 triangulations, found by a search of the flip graph. Their energies run from for the Delaunay one, through for the next best, up to , as Theorem 1 of the proof says.
| step | vertex | target | new position | after |
|---|---|---|---|---|
| 0 | 31.792 | |||
| 1 | 30.051 | |||
| 2 | 29.075 | |||
| 3 | 28.675 | |||
| flips | none needed | 28.675 |
Each target is in the kernel of its star, so is accepted. The next sweeps give , , , , and after 8 sweeps ; the points have settled near , and . The smallest mean ratio, from the mesh quality measures, rose from 0.261 to 0.362. Three free points in a square cannot make good triangles, so the gain is small.
On the square with 28 fixed points at unit spacing on the sides and 20 random free points, 20 sweeps lower from 70.47 to 39.41, raise the smallest angle from to and the smallest mean ratio from 0.217 to 0.718. These are measurements.
Correctness
The full proofs are in the proof file; here is the outline. By the paraboloid lifting map, the interpolant is the roof made of the lifted triangles, and a point lies inside a circumcircle exactly when its lift lies below the plane of the lifted triangle. Every roof lies on or above the lower convex envelope of the lifted points, and the Delaunay roof is equal to . So among all triangulations of a fixed vertex set, the Delaunay ones minimise , and only they do. Applied to four points in convex position, the same fact shows that each Lawson flip lowers strictly, so the flip loop of L9 stops, and it stops at a Delaunay triangulation.
For the vertex move, the signed areas of the star triangles add up to the area of the link polygon for every position . So , a convex quadratic with minimum at . On the segment from to , falls by , and points near are in the open kernel of the star. The code accepts a rounded point only after exact tests, so never increases.
What is proved is that goes down and the result is a valid Delaunay triangulation. What is not proved is a bound on angles or a global minimum. With only the four corners of on the boundary and 20 free points, fell from 202.5 to 82.3 while the smallest angle fell from to about degrees: the free points crowded the two long sides.
Proof: Delaunay minimises the interpolation error of |x|^2, and each ODT step lowers itfull
Setting. is a convex polygon. A triangulation of a finite point set that contains the corners of is a set of triangles with vertices in that cover , have disjoint interiors and meet edge to edge, and that use every point of as a vertex. Let and let be the piecewise linear function that agrees with at the vertices of . The energy is
Because is convex, on each triangle, so is the norm of the interpolation error.
Lemma 1 (one triangle). For a triangle with vertices , area and edge lengths ,
Proof. A linear function integrates to times its value at the centroid, which is the mean of the three vertex values. For the second formula, is a quadratic, and the rule is exact for quadratics. At the midpoint of the edge , . Summing over the three edges and multiplying by gives the claim.
Lemma 2 (lifting). Let and let be the affine function with at , , . Then for every point , , where and are the circumcentre and circumradius of . So the lifted point lies below the plane of the lifted triangle if and only if is strictly inside the circumcircle.
Proof. is a quadratic with leading part , so it equals for some and . It is zero at , and , so these three points are at distance from . Thus and .
This is the paraboloid lifting map, and it is the reason the in-circle test is a determinant.
Theorem 1 (Delaunay is optimal for fixed vertices). For every triangulation of , for any Delaunay triangulation of . Equality holds if and only if no point of lies strictly inside the circumcircle of a triangle of , that is, if and only if is itself a Delaunay triangulation.
Proof. Let be the lower convex envelope of the lifted points over :
On a triangle of that contains , with the barycentric coordinates of , which is one of the candidates in the minimum. So everywhere.
For a Delaunay triangulation , take a triangle of . No point of is strictly inside its circumcircle, so by Lemma 2 every lifted point lies on or above the plane . Any convex combination of lifted points then lies on or above that plane, so on . With the first part, on .
Hence . If equality holds, the integrand is continuous and nonnegative with zero integral, so on . Suppose a point were strictly inside the circumcircle of a triangle of . By Lemma 2, . Take in the interior of and small, and write as times a point plus times , where is still in . Then , a contradiction. Conversely, if no point is strictly inside any circumcircle of , the argument above for applies to and gives .
Lemma 3 (flippable edges). Let be an interior edge with triangles and , both counterclockwise. If is strictly inside the circumcircle of , then the quadrilateral is strictly convex, so the edge can be flipped to .
Proof. The chord cuts the open disk into two parts. Since is on the other side of the line from , it is in the part away from . That part is bounded by the chord and an arc from to . The rays from through and through meet the circle only at and , so the whole part lies in the open angle at between them, beyond the chord. So the segment crosses the open segment , which means that both and are counterclockwise.
Theorem 2 (a flip lowers the energy). Flipping an edge as in Lemma 3 lowers strictly.
Proof. Only the two triangles on the quadrilateral change. The four points are in convex position by Lemma 3, so both pairs of triangles cover , and the change in is the change of . Apply Theorem 1 to the point set on the convex polygon . The old pair is not Delaunay, because is inside the circumcircle of . A Delaunay triangulation of four points in convex position exists and is one of the two pairs, so it is the new pair, and the inequality of Theorem 1 is strict.
Theorem 3 (the vertex move is a descent step). Let be a vertex not on the boundary of , with star triangles , all counterclockwise, whose union is the star polygon . For a point let , the signed area, and . Put
(a) If every (that is, is in the kernel of the star), then moving to gives a valid triangulation, and changes by .
(b) , where and is constant.
(c) For and , . So if , every in lowers strictly, and for all small .
Proof. (a) If every star triangle stays counterclockwise, the triangles of the star still tile , since their outer edges are the fixed edges of the link polygon and consecutive triangles share the edges . The other triangles do not change. By Lemma 1, , and only the star terms depend on ; with they sum to .
(b) is affine in , and is the shoelace sum of the closed link polygon taken from the point , which equals for every . So , a quadratic with Hessian and gradient zero at .
(c) By (b), . The kernel is an intersection of open half-planes, so it is open and convex, and it contains .
A computation from the circumcentre formula shows that is the area-weighted mean of the circumcentres of the star triangles taken at ; the tests check this identity exactly. The implementation tries , rounds to a dyadic grid, and accepts the rounded point only if the exact tests and pass. So an accepted move lowers strictly, and a rejected vertex leaves unchanged.
Theorem 4 (the ODT loop). Each sweep of ODT-SMOOTH keeps a valid triangulation of , never increases , and ends with a Delaunay triangulation of the current points. Each call of the flip loop stops.
Proof. Moves keep validity by Theorem 3(a) and do not increase by Theorem 3(c) and the exact acceptance test. Each flip keeps validity by Lemma 3 and lowers strictly by Theorem 2. The vertex set is fixed during the flip loop and has finitely many triangulations, and no triangulation repeats because goes strictly down, so the flip loop stops. It stops only when every interior edge is locally Delaunay, and a triangulation whose edges are all locally Delaunay is a Delaunay triangulation (the Delaunay lemma, Cheng, Dey and Shewchuk, chapter 2). The number of sweeps is a parameter, so the whole method stops.
What is not proved. is not convex in all vertex positions together, so the sweeps reach a point where no single move helps, not a global minimum. measures the size of the triangles, not their shape, so no angle bound follows. In a measured run on the square with only its four corners on the boundary and 20 free points, fell from 202.5 to 82.3 and the smallest angle fell from to about degrees, as free points crowded the long boundary edges. With 28 fixed points on the sides, the smallest angle rose from to . Both are measurements.
Complexity
One vertex move costs per trial for a vertex of degree , and there are at most 30 trials, so the moves of one sweep cost in total with an adjacency structure. Lawson's flip loop can need flips in the worst case, so a sweep costs and sweeps . In practice the vertices move little after the first sweeps and only a few flips are needed, so a sweep costs close to . The simple implementation here scans the triangle list for each star and restarts the flip search after each flip, which costs more but keeps the code short. The space is . In exact arithmetic the coordinates would grow in size at each move; rounding to a dyadic grid, followed by an exact test, keeps them small.
Properties
- Optimal connectivity, proved. For fixed vertices, the Delaunay triangulation is the exact minimiser of .
- Monotone, proved. never increases from one step to the next.
- Shape not guaranteed. Shapes improve in practice, but no angle bound follows from the energy.
- Exact. Every orientation and in-circle decision uses exact arithmetic; floats only propose the next position.
- Isotropic and uniform. The energy favours equal sizes. A density weight gives a graded mesh.
Variants and improvements
- Global solve. Chen and Holst minimise the energy over all free vertices together with a sparse linear solve in each step, which converges faster than vertex by vertex sweeps.
- Tetrahedra. Alliez, Cohen-Steiner, Yvinec and Desbrun use the 3D energy, in which each vertex moves to the volume-weighted mean of the circumcentres of its tetrahedra, then retriangulate with a 3D Delaunay code. The result has few bad tetrahedra in practice, but slivers can remain, because a sliver has a small circumradius-to-edge ratio and a small error. Slivers pass a radius-edge bound, so they are removed by other means, for example sliver exudation.
- Centroidal Voronoi tessellation. A centroidal Voronoi tessellation, computed by Lloyd's algorithm, moves each point to the centroid of its Voronoi cell instead. Both energies favour well spaced points; ODT works on the triangles and CVT on the cells.
- Boundary vertices. Moving boundary points along the boundary, with a correction to the target, reduces the crowding near long boundary edges.
When to use it
Use it to improve a mesh made by Delaunay refinement or another generator, when the vertex set can change but the boundary is fixed, and when an isotropic mesh with near equilateral elements is the goal. It gives better shapes than Laplacian smoothing, because it also changes the connectivity. When the worst element matters most, follow it with optimization-based mesh smoothing, which raises the smallest quality directly. Do not use it when a proved angle bound is needed, or for an anisotropic mesh, where the energy must use a metric.
Pitfalls
- Coarse boundary. If the boundary has few points, free points crowd its long edges and the triangles there become flat. Sample the boundary at the target size first.
- Target outside the star. The target can lie outside the kernel of the star. Moving there without a test makes an inverted triangle. Backtrack and test.
- No retriangulation. Moving the vertices without the flips is not ODT. The flip step is the half of the method that has a proof of optimality.
- Inexact in-circle. With float predicates the flip loop can cycle on nearly cocircular points. Use exact predicates.
- Slivers in 3D. The 3D energy does not remove slivers on its own.
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 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
optimal_delaunay_triangulation.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimal-delaunay-triangulation/. The authors are listed in prov/CQ85FC.jsonl.
"""Optimal Delaunay triangulation (ODT) smoothing in the plane, after Chen and Xu.
The energy of a triangulation T of a convex polygon is the interpolation error
E(T) = integral over the polygon of (f_I - f), f(x) = |x|^2,
where f_I is the piecewise linear interpolant of f on T. On one triangle with
area A and edge lengths l1, l2, l3 the error is A (l1^2 + l2^2 + l3^2) / 12.
One sweep moves each interior vertex toward the minimiser of E over its star
(the area-weighted mean of the circumcentres of its triangles), with
backtracking so that the star stays valid and E goes down, and then restores
the Delaunay property by Lawson flips. Every decision is exact: coordinates are
Fractions on a dyadic grid, and orientation and in-circle tests are exact.
"""
from fractions import Fraction
from typing import Dict, List, Sequence, Tuple
from mg3geom import incircle, orient2d, to_grid
Point = Tuple[Fraction, Fraction]
Tri = Tuple[int, int, int]
def triangle_error(a: Point, b: Point, c: Point) -> Fraction:
"""The L1 error of the linear interpolant of |x|^2 on the triangle abc."""
s = sum((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2 for p, q in ((a, b), (b, c), (c, a)))
return Fraction(orient2d(a, b, c), 2) * s / 12
def energy(points: Sequence[Point], tris: Sequence[Tri]) -> Fraction:
"""E(T), the sum of the triangle errors, exact."""
return sum((triangle_error(points[i], points[j], points[k]) for i, j, k in tris), Fraction(0))
def _locate(points, tris, p):
"""Index of a triangle that contains p in its closed interior, and the
number of its edges that p lies on."""
for t, (i, j, k) in enumerate(tris):
o = [orient2d(points[i], points[j], p), orient2d(points[j], points[k], p), orient2d(points[k], points[i], p)]
if min(o) >= 0:
return t, o
raise ValueError("point outside the domain")
def lawson_flips(points: Sequence[Point], tris: List[Tri]) -> int:
"""Flip edges that are not locally Delaunay until none is left. Returns the
number of flips. The triangles are changed in place."""
flips = 0
changed = True
while changed:
changed = False
owner: Dict[Tuple[int, int], int] = {}
for t, (i, j, k) in enumerate(tris):
owner[(i, j)] = t
owner[(j, k)] = t
owner[(k, i)] = t
for (i, j), t in owner.items():
u = owner.get((j, i))
if u is None or u < t:
continue
a = [v for v in tris[t] if v not in (i, j)][0]
b = [v for v in tris[u] if v not in (i, j)][0]
if incircle(points[i], points[j], points[a], points[b]) > 0: # @line L9
# an edge that is not locally Delaunay is always flippable
tris[t] = (a, i, b) # @line L10
tris[u] = (b, j, a)
flips += 1
changed = True
break
return flips
def delaunay(points: Sequence[Point], n_corners: int) -> List[Tri]:
"""A Delaunay triangulation of the points. points[:n_corners] are the
corners of a convex polygon in counterclockwise order, and every other
point lies in the closed polygon."""
tris: List[Tri] = [(0, k, k + 1) for k in range(1, n_corners - 1)]
for v in range(n_corners, len(points)):
t, o = _locate(points, tris, points[v])
i, j, k = tris[t]
on = [e for e, s in zip(((i, j), (j, k), (k, i)), o) if s == 0]
if not on:
tris[t] = (i, j, v)
tris.extend([(j, k, v), (k, i, v)])
continue
# v lies on the edge (x, y) of triangle t: split t and its neighbour
x, y = on[0]
z = [w for w in (i, j, k) if w not in (x, y)][0]
tris[t] = (x, v, z)
tris.append((v, y, z))
for u, tri in enumerate(tris):
if u != t and y in tri and x in tri:
w = [q for q in tri if q not in (x, y)][0]
tris[u] = (y, v, w)
tris.append((v, x, w))
break
lawson_flips(points, tris)
return tris
def star_energy(x: Point, link: Sequence[Tuple[Point, Point]]) -> Fraction:
"""3 times the part of the integral of f_I that depends on the free vertex x,
for the star triangles (x, a, b): sum of area * (|x|^2 + |a|^2 + |b|^2)."""
total = Fraction(0)
for a, b in link:
area = Fraction(orient2d(x, a, b), 2)
total += area * (x[0] ** 2 + x[1] ** 2 + a[0] ** 2 + a[1] ** 2 + b[0] ** 2 + b[1] ** 2)
return total
def odt_target(link: Sequence[Tuple[Point, Point]]) -> Point:
"""The minimiser of star_energy over x, with the star kept as it is:
x* = -(1 / (2 |Omega|)) * sum of grad(area) * (|a|^2 + |b|^2).
It is the area-weighted mean of the circumcentres of the star triangles."""
omega = Fraction(0)
gx = Fraction(0)
gy = Fraction(0)
for a, b in link:
omega += Fraction(a[0] * b[1] - a[1] * b[0], 2) # area of the link polygon
s = a[0] ** 2 + a[1] ** 2 + b[0] ** 2 + b[1] ** 2
gx += Fraction(a[1] - b[1], 2) * s
gy += Fraction(b[0] - a[0], 2) * s
return (-gx / (2 * omega), -gy / (2 * omega))
def move_vertex(points: List[Point], tris: Sequence[Tri], v: int, bits: int = 20, tries: int = 30) -> bool:
"""Move the free vertex v toward odt_target with backtracking. A move is
accepted only if every star triangle stays counterclockwise and the star
energy goes strictly down, both tested exactly. Returns True if v moved."""
link = []
for i, j, k in tris:
if i == v:
link.append((points[j], points[k]))
elif j == v:
link.append((points[k], points[i]))
elif k == v:
link.append((points[i], points[j]))
x = points[v]
target = odt_target(link) # @line L4
e0 = star_energy(x, link)
t = Fraction(1)
for _ in range(tries): # @line L5
y = (to_grid(float(x[0] + t * (target[0] - x[0])), bits), # @line L6
to_grid(float(x[1] + t * (target[1] - x[1])), bits))
if y != x and all(orient2d(y, a, b) > 0 for a, b in link) and star_energy(y, link) < e0: # @line L7
points[v] = y # @line L8
return True
t /= 2
return False
def odt_smooth(corners: Sequence[Point], others: Sequence[Point], sweeps: int = 10):
"""ODT smoothing of the convex polygon `corners` (counterclockwise). The
points of `others` lie in the closed polygon; those on its sides stay fixed
and those inside are free. Returns (points, triangles, energies), where
energies[s] is E after s sweeps."""
points: List[Point] = [(Fraction(p[0]), Fraction(p[1])) for p in list(corners) + list(others)]
nc = len(corners)
tris = delaunay(points, nc) # @line L1
n = len(corners)
free = [v for v in range(nc, len(points))
if all(orient2d(corners[s], corners[(s + 1) % n], points[v]) > 0 for s in range(n))]
energies = [energy(points, tris)]
for _ in range(sweeps): # @line L2
for v in free: # @line L3
move_vertex(points, tris, v)
lawson_flips(points, tris)
energies.append(energy(points, tris))
return points, tris, energies # @line L11
test_optimal_delaunay_triangulation.py 205 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimal-delaunay-triangulation/. The authors are listed in prov/CQ85FC.jsonl.
import random
from fractions import Fraction as F
from mg3geom import incircle, orient2d, twice_area
from optimal_delaunay_triangulation import (delaunay, energy, move_vertex, odt_smooth, odt_target,
star_energy, triangle_error)
def random_inner(rng, n, size=8):
"""n distinct points with coordinates on the grid of step 1/4, strictly inside [0, size]^2."""
pts = set()
while len(pts) < n:
pts.add((F(rng.randint(1, 4 * size - 1), 4), F(rng.randint(1, 4 * size - 1), 4)))
return sorted(pts)
SQUARE = [(F(0), F(0)), (F(8), F(0)), (F(8), F(8)), (F(0), F(8))]
def check_triangulation(points, tris, corners):
"""Exact: counterclockwise triangles, each directed edge once, interior edges
twice in opposite directions, area sum equal to the polygon, Euler count."""
seen = set()
for i, j, k in tris:
assert orient2d(points[i], points[j], points[k]) > 0
for e in ((i, j), (j, k), (k, i)):
assert e not in seen
seen.add(e)
assert sum(orient2d(points[i], points[j], points[k]) for i, j, k in tris) == twice_area(corners)
hull = sum(1 for (i, j) in seen if (j, i) not in seen)
assert hull == len(corners)
assert len(tris) == 2 * len(points) - hull - 2
def is_delaunay(points, tris):
"""Global empty circle test, exact, against every point."""
for i, j, k in tris:
for p in points:
if incircle(points[i], points[j], points[k], p) > 0:
return False
return True
def test_triangle_error_against_midpoint_rule():
# the midpoint rule integrates quadratics exactly on a triangle
rng = random.Random(1)
f = lambda p: p[0] ** 2 + p[1] ** 2
for _ in range(200):
a, b, c = [(F(rng.randint(-20, 20), 3), F(rng.randint(-20, 20), 3)) for _ in range(3)]
if orient2d(a, b, c) <= 0:
continue
area = F(orient2d(a, b, c), 2)
mids = [((p[0] + q[0]) / 2, (p[1] + q[1]) / 2, (f(p) + f(q)) / 2) for p, q in ((a, b), (b, c), (c, a))]
oracle = area / 3 * sum(fi - (mx ** 2 + my ** 2) for mx, my, fi in mids)
assert triangle_error(a, b, c) == oracle
def test_target_is_weighted_mean_of_circumcentres():
rng = random.Random(2)
checked = 0
for _ in range(100):
corners = SQUARE
inner = random_inner(rng, 6)
pts = list(corners) + inner
tris = delaunay(pts, 4)
for v in range(4, len(pts)):
link = []
for i, j, k in tris:
if v in (i, j, k):
r = (i, j, k).index(v)
link.append((pts[(i, j, k)[(r + 1) % 3]], pts[(i, j, k)[(r + 2) % 3]]))
num_x = num_y = om = F(0)
for a, b in link:
x = pts[v]
area = F(orient2d(x, a, b), 2)
d = 2 * orient2d(x, a, b)
sx = x[0] ** 2 + x[1] ** 2
sa = a[0] ** 2 + a[1] ** 2
sb = b[0] ** 2 + b[1] ** 2
cx = (sx * (a[1] - b[1]) + sa * (b[1] - x[1]) + sb * (x[1] - a[1])) / d
cy = (sx * (b[0] - a[0]) + sa * (x[0] - b[0]) + sb * (a[0] - x[0])) / d
num_x += area * cx
num_y += area * cy
om += area
assert odt_target(link) == (num_x / om, num_y / om)
checked += 1
assert checked >= 500
def test_target_minimises_star_energy():
# star_energy is a convex quadratic in x; no grid point near the target beats it
rng = random.Random(3)
for _ in range(30):
pts = list(SQUARE) + random_inner(rng, 5)
tris = delaunay(pts, 4)
v = rng.randrange(4, len(pts))
link = []
for t in tris:
if v in t:
r = t.index(v)
link.append((pts[t[(r + 1) % 3]], pts[t[(r + 2) % 3]]))
x = odt_target(link)
best = star_energy(x, link)
for dx in range(-3, 4):
for dy in range(-3, 4):
y = (x[0] + F(dx, 16), x[1] + F(dy, 16))
assert star_energy(y, link) >= best
def test_delaunay_construction_is_delaunay():
rng = random.Random(4)
for _ in range(40):
inner = random_inner(rng, rng.randint(1, 15))
pts = list(SQUARE) + inner
tris = delaunay(pts, 4)
check_triangulation(pts, tris, SQUARE)
assert is_delaunay(pts, tris)
def test_energy_never_increases_and_result_is_delaunay():
rng = random.Random(5)
for _ in range(8):
inner = random_inner(rng, rng.randint(4, 12))
points, tris, energies = odt_smooth(SQUARE, inner, sweeps=6)
assert all(e1 <= e0 for e0, e1 in zip(energies, energies[1:]))
assert energies[-1] < energies[0]
assert energies[-1] == energy(points, tris)
check_triangulation(points, tris, SQUARE)
assert is_delaunay(points, tris)
def test_vertex_move_lowers_energy_exactly():
rng = random.Random(6)
moved = 0
for _ in range(20):
pts = list(SQUARE) + random_inner(rng, 8)
tris = delaunay(pts, 4)
for v in range(4, len(pts)):
e0 = energy(pts, tris)
if move_vertex(pts, tris, v):
moved += 1
assert energy(pts, tris) < e0
assert all(orient2d(pts[i], pts[j], pts[k]) > 0 for i, j, k in tris)
else:
assert energy(pts, tris) == e0
assert moved > 100
def canon(tris):
return frozenset(tuple(sorted(t)) for t in tris)
def all_triangulations(points, start):
"""Every triangulation of the point set (all points used), by breadth first
search on the flip graph, which is connected for planar point sets."""
seen = {canon(start)}
queue = [list(start)]
out = [list(start)]
while queue:
tris = queue.pop()
owner = {}
for t, (i, j, k) in enumerate(tris):
for e in ((i, j), (j, k), (k, i)):
owner[e] = t
for (i, j), t in owner.items():
u = owner.get((j, i))
if u is None or u < t:
continue
a = [v for v in tris[t] if v not in (i, j)][0]
b = [v for v in tris[u] if v not in (i, j)][0]
# flippable iff the quad i, b, j, a is strictly convex
if orient2d(points[a], points[i], points[b]) > 0 and orient2d(points[b], points[j], points[a]) > 0:
new = list(tris)
new[t] = (a, i, b)
new[u] = (b, j, a)
c = canon(new)
if c not in seen:
seen.add(c)
queue.append(new)
out.append(new)
return out
def test_delaunay_minimises_energy_among_all_triangulations():
rng = random.Random(7)
total = 0
for trial in range(25):
inner = random_inner(rng, rng.randint(2, 4), size=4)
corners = [(F(0), F(0)), (F(4), F(0)), (F(4), F(4)), (F(0), F(4))]
pts = corners + inner
dt = delaunay(pts, 4)
e_dt = energy(pts, dt)
every = all_triangulations(pts, dt)
total += len(every)
for tris in every:
e = energy(pts, tris)
assert e >= e_dt
if e == e_dt:
assert is_delaunay(pts, tris) # equality only for Delaunay triangulations
else:
assert not is_delaunay(pts, tris)
assert total > 100
History
Long Chen and Jinchao Xu introduced optimal Delaunay triangulations in 2004, in a paper in the Journal of Computational Mathematics, with the proof that for fixed vertices the Delaunay triangulation is optimal for the function , and Chen used the energy for mesh smoothing in the same year. Alliez, Cohen-Steiner, Yvinec and Desbrun applied it to tetrahedral meshing in 2005, under the name variational tetrahedral meshing. Chen and Holst gave faster local and global schemes in 2011.
References
- Long Chen and Michael Holst, Efficient mesh optimization schemes based on optimal Delaunay triangulations, Computer Methods in Applied Mechanics and Engineering 200(9-12), 2011, 967 to 984, the ODT energy, the optimality of the Delaunay triangulation for fixed vertices, and the local vertex update as the area-weighted mean of circumcentres (general locator)
- Pierre Alliez, David Cohen-Steiner, Mariette Yvinec and Mathieu Desbrun, Variational tetrahedral meshing, ACM Transactions on Graphics 24(3), 2005, 617 to 625, the ODT energy in 3D, the alternation of vertex moves and Delaunay retriangulation, and the treatment of boundary vertices (general locator)
- Siu-Wing Cheng, Tamal K. Dey and Jonathan R. Shewchuk, Delaunay Mesh Generation, CRC Press, 2013, chapter 2 (the Delaunay lemma, the lifting map and Lawson's flip algorithm)
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 CQ85FC Edit this page History Report an error Markdown