Algorithm Search⌘K

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.

Time
O(k n^2) worst
Space
O(n) extra
Where
k = the number of sweeps; n = the number of vertices
Properties
deterministicexactiterative
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 f(x)=∣x∣2f(x) = |x|^2 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 Ω\Omega 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 Ω\Omega with the same fixed points and moved free points. The goal is a small value of

E(T)=∫Ω(fI,T−f) dx,f(x)=∣x∣2,E(T) = \int_\Omega (f_{I,T} - f)\,dx, \qquad f(x) = |x|^2,

where fI,Tf_{I,T} is the piecewise linear interpolation of ff on TT. On a triangle with area ∣τ∣|\tau| and edge lengths ℓ1,ℓ2,ℓ3\ell_1, \ell_2, \ell_3, the error is ∣τ∣12(ℓ12+ℓ22+ℓ32)\frac{|\tau|}{12}(\ell_1^2 + \ell_2^2 + \ell_3^2), so EE 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 xx, its star is the set of triangles (x,a,b)(x, a, b) that contain it, and its link is the polygon of the edges abab.

  1. ODT-SMOOTH(Ω, fixed, free, k)
  2. 1T ← a Delaunay triangulation of the corners of Ω, fixed and free ▷ insert, then flip
  3. 2for sweep ← 1 to k do
  4. 3for each free vertex x do
  5. 4y* ← (1 / |Ω_x|) Σ over star triangles τ of |τ| · circumcentre(τ)
  6. 5for t ← 1, 1/2, 1/4, ..., 2^−29 do
  7. 6y ← x + t (y* − x), rounded to the grid of step 2^−20
  8. 7if ORIENT2D(y, a, b) > 0 for every link edge ab and Φ(y) < Φ(x) then
  9. 8move x to y; break
  10. 9while some interior edge ij with triangles ija and jib has INCIRCLE(i, j, a, b) > 0 do
  11. 10flip ij to ab
  12. 11return T

Here Φ(y)=∑τ∣τ(y)∣ (∣y∣2+∣aτ∣2+∣bτ∣2)\Phi(y) = \sum_\tau |\tau(y)|\,(|y|^2 + |a_\tau|^2 + |b_\tau|^2) over the star triangles (y,aτ,bτ)(y, a_\tau, b_\tau) with signed areas. It is three times the part of EE that depends on the free vertex. L4 is the exact minimiser of Φ\Phi 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 Ω\Omega never move.

Example

Take the square [0,4]2[0,4]^2 with no fixed side points and free points (1,1)(1,1), (3,12)(3, \frac12) and (52,3)(\frac52, 3). L1 gives a Delaunay triangulation with 8 triangles and E=763/24≈31.79E = 763/24 \approx 31.79. These 7 points have 18 triangulations, found by a search of the flip graph. Their energies run from 763/24763/24 for the Delaunay one, through 769/24769/24 for the next best, up to 4747, as Theorem 1 of the proof says.

step vertex target y∗y^* new position EE after
0 31.792
1 (1,1)(1, 1) (0.9331,1.7641)(0.9331, 1.7641) (0.9331,1.7641)(0.9331, 1.7641) 30.051
2 (3,0.5)(3, 0.5) (2.9054,1.0384)(2.9054, 1.0384) (2.9054,1.0384)(2.9054, 1.0384) 29.075
3 (2.5,3)(2.5, 3) (2.1980,3.2504)(2.1980, 3.2504) (2.1980,3.2504)(2.1980, 3.2504) 28.675
flips none needed 28.675

Each target is in the kernel of its star, so t=1t = 1 is accepted. The next sweeps give E=28.422E = 28.422, 28.38428.384, 28.38028.380, 28.37928.379, and after 8 sweeps E=28.379005E = 28.379005; the points have settled near (0.650,1.918)(0.650, 1.918), (2.732,1.268)(2.732, 1.268) and (2.082,3.350)(2.082, 3.350). 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 [0,8]2[0,8]^2 with 28 fixed points at unit spacing on the sides and 20 random free points, 20 sweeps lower EE from 70.47 to 39.41, raise the smallest angle from 7.3°7.3° to 29.1°29.1° 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 fI,Tf_{I,T} 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 gg of the lifted points, and the Delaunay roof is equal to gg. So among all triangulations of a fixed vertex set, the Delaunay ones minimise EE, and only they do. Applied to four points in convex position, the same fact shows that each Lawson flip lowers EE 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 yy. So Φ(y)=∣Ωx∣ ∣y−y∗∣2+c\Phi(y) = |\Omega_x|\,|y - y^*|^2 + c, a convex quadratic with minimum at y∗y^*. On the segment from xx to y∗y^*, Φ\Phi falls by ∣Ωx∣ t(2−t) ∣x−y∗∣2|\Omega_x|\,t(2 - t)\,|x - y^*|^2, and points near xx are in the open kernel of the star. The code accepts a rounded point only after exact tests, so EE never increases.

What is proved is that EE 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 [0,8]2[0,8]^2 on the boundary and 20 free points, EE fell from 202.5 to 82.3 while the smallest angle fell from 3.0°3.0° to about 6⋅10−66 \cdot 10^{-6} 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. Ω\Omega is a convex polygon. A triangulation TT of a finite point set V⊂ΩV \subset \Omega that contains the corners of Ω\Omega is a set of triangles with vertices in VV that cover Ω\Omega, have disjoint interiors and meet edge to edge, and that use every point of VV as a vertex. Let f(x)=∣x∣2f(x) = |x|^2 and let fI,Tf_{I,T} be the piecewise linear function that agrees with ff at the vertices of TT. The energy is

E(T)=∫Ω(fI,T(x)−f(x)) dx.E(T) = \int_\Omega \bigl(f_{I,T}(x) - f(x)\bigr)\,dx.

Because ff is convex, fI,T≥ff_{I,T} \ge f on each triangle, so E(T)E(T) is the L1L^1 norm of the interpolation error.

Lemma 1 (one triangle). For a triangle τ\tau with vertices a,b,ca, b, c, area ∣τ∣|\tau| and edge lengths ℓ1,ℓ2,ℓ3\ell_1, \ell_2, \ell_3,

∫τfI=∣τ∣3(∣a∣2+∣b∣2+∣c∣2),∫τ(fI−f)=∣τ∣12(ℓ12+ℓ22+ℓ32).\int_\tau f_{I} = \frac{|\tau|}{3}\bigl(|a|^2 + |b|^2 + |c|^2\bigr), \qquad \int_\tau (f_I - f) = \frac{|\tau|}{12}\bigl(\ell_1^2 + \ell_2^2 + \ell_3^2\bigr).

Proof. A linear function integrates to ∣τ∣|\tau| times its value at the centroid, which is the mean of the three vertex values. For the second formula, fI−ff_I - f is a quadratic, and the rule ∫τq=∣τ∣3∑edgesq(midpoint)\int_\tau q = \frac{|\tau|}{3}\sum_{\text{edges}} q(\text{midpoint}) is exact for quadratics. At the midpoint mm of the edge abab, fI(m)−f(m)=∣a∣2+∣b∣22−∣a+b2∣2=∣a−b∣24f_I(m) - f(m) = \frac{|a|^2 + |b|^2}{2} - \bigl|\frac{a+b}{2}\bigr|^2 = \frac{|a - b|^2}{4}. Summing over the three edges and multiplying by ∣τ∣/3|\tau|/3 gives the claim. □\square

Lemma 2 (lifting). Let τ=abc\tau = abc and let ℓτ\ell_\tau be the affine function with ℓτ=f\ell_\tau = f at aa, bb, cc. Then for every point pp, f(p)−ℓτ(p)=∣p−z∣2−R2f(p) - \ell_\tau(p) = |p - z|^2 - R^2, where zz and RR are the circumcentre and circumradius of τ\tau. So the lifted point (p,∣p∣2)(p, |p|^2) lies below the plane of the lifted triangle if and only if pp is strictly inside the circumcircle.

Proof. f−ℓτf - \ell_\tau is a quadratic with leading part ∣x∣2|x|^2, so it equals ∣x−z′∣2−r|x - z'|^2 - r for some z′z' and rr. It is zero at aa, bb and cc, so these three points are at distance r\sqrt r from z′z'. Thus z′=zz' = z and r=R2r = R^2. □\square

This is the paraboloid lifting map, and it is the reason the in-circle test is a 3×33 \times 3 determinant.

Theorem 1 (Delaunay is optimal for fixed vertices). For every triangulation TT of VV, E(T)≥E(D)E(T) \ge E(D) for any Delaunay triangulation DD of VV. Equality holds if and only if no point of VV lies strictly inside the circumcircle of a triangle of TT, that is, if and only if TT is itself a Delaunay triangulation.

Proof. Let gg be the lower convex envelope of the lifted points over Ω\Omega:

g(x)=min⁡{∑kλk∣vk∣2  :  vk∈V, λk≥0, ∑kλk=1, ∑kλkvk=x}.g(x) = \min\Bigl\{\sum_k \lambda_k |v_k|^2 \;:\; v_k \in V,\ \lambda_k \ge 0,\ \sum_k \lambda_k = 1,\ \sum_k \lambda_k v_k = x\Bigr\}.

On a triangle of TT that contains xx, fI,T(x)=∑λk∣vk∣2f_{I,T}(x) = \sum \lambda_k |v_k|^2 with the barycentric coordinates of xx, which is one of the candidates in the minimum. So fI,T≥gf_{I,T} \ge g everywhere.

For a Delaunay triangulation DD, take a triangle τ\tau of DD. No point of VV is strictly inside its circumcircle, so by Lemma 2 every lifted point lies on or above the plane ℓτ\ell_\tau. Any convex combination of lifted points then lies on or above that plane, so g≥ℓτ=fI,Dg \ge \ell_\tau = f_{I,D} on τ\tau. With the first part, fI,D=gf_{I,D} = g on Ω\Omega.

Hence E(T)−E(D)=∫Ω(fI,T−g)≥0E(T) - E(D) = \int_\Omega (f_{I,T} - g) \ge 0. If equality holds, the integrand is continuous and nonnegative with zero integral, so fI,T=gf_{I,T} = g on Ω\Omega. Suppose a point p∈Vp \in V were strictly inside the circumcircle of a triangle τ\tau of TT. By Lemma 2, ∣p∣2<ℓτ(p)|p|^2 < \ell_\tau(p). Take xx in the interior of τ\tau and s>0s > 0 small, and write xx as (1−s)(1 - s) times a point yy plus ss times pp, where y=(x−sp)/(1−s)y = (x - s p)/(1 - s) is still in τ\tau. Then g(x)≤(1−s)ℓτ(y)+s∣p∣2<(1−s)ℓτ(y)+sℓτ(p)=ℓτ(x)=fI,T(x)g(x) \le (1 - s)\ell_\tau(y) + s|p|^2 < (1 - s)\ell_\tau(y) + s\ell_\tau(p) = \ell_\tau(x) = f_{I,T}(x), a contradiction. Conversely, if no point is strictly inside any circumcircle of TT, the argument above for DD applies to TT and gives fI,T=gf_{I,T} = g. □\square

Lemma 3 (flippable edges). Let ijij be an interior edge with triangles ijaija and jibjib, both counterclockwise. If bb is strictly inside the circumcircle of ijaija, then the quadrilateral i,b,j,ai, b, j, a is strictly convex, so the edge can be flipped to abab.

Proof. The chord ijij cuts the open disk into two parts. Since bb is on the other side of the line ijij from aa, it is in the part away from aa. That part is bounded by the chord and an arc from ii to jj. The rays from aa through ii and through jj meet the circle only at ii and jj, so the whole part lies in the open angle at aa between them, beyond the chord. So the segment abab crosses the open segment ijij, which means that both a,i,ba, i, b and b,j,ab, j, a are counterclockwise. □\square

Theorem 2 (a flip lowers the energy). Flipping an edge ijij as in Lemma 3 lowers EE strictly.

Proof. Only the two triangles on the quadrilateral Q=i,b,j,aQ = i, b, j, a change. The four points are in convex position by Lemma 3, so both pairs of triangles cover QQ, and the change in EE is the change of ∫Q(fI−f)\int_Q (f_I - f). Apply Theorem 1 to the point set {i,j,a,b}\{i, j, a, b\} on the convex polygon QQ. The old pair is not Delaunay, because bb is inside the circumcircle of ijaija. 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. □\square

Theorem 3 (the vertex move is a descent step). Let xx be a vertex not on the boundary of Ω\Omega, with star triangles (x,aτ,bτ)(x, a_\tau, b_\tau), all counterclockwise, whose union is the star polygon Ωx\Omega_x. For a point yy let Aτ(y)=12 orient(y,aτ,bτ)A_\tau(y) = \frac12\,\mathrm{orient}(y, a_\tau, b_\tau), the signed area, and Sτ=∣aτ∣2+∣bτ∣2S_\tau = |a_\tau|^2 + |b_\tau|^2. Put

Φ(y)=∑τAτ(y)(∣y∣2+Sτ).\Phi(y) = \sum_\tau A_\tau(y)\bigl(|y|^2 + S_\tau\bigr).

(a) If every Aτ(y)>0A_\tau(y) > 0 (that is, yy is in the kernel KK of the star), then moving xx to yy gives a valid triangulation, and EE changes by 13(Φ(y)−Φ(x))\frac13\bigl(\Phi(y) - \Phi(x)\bigr).

(b) Φ(y)=∣Ωx∣ ∣y−y∗∣2+const\Phi(y) = |\Omega_x|\,|y - y^*|^2 + \text{const}, where y∗=−12∣Ωx∣∑τSτ∇Aτy^* = -\frac{1}{2|\Omega_x|}\sum_\tau S_\tau \nabla A_\tau and ∇Aτ=12(aτ,2−bτ,2, bτ,1−aτ,1)\nabla A_\tau = \frac12\bigl(a_{\tau,2} - b_{\tau,2},\ b_{\tau,1} - a_{\tau,1}\bigr) is constant.

(c) For 0<t≤10 < t \le 1 and yt=x+t(y∗−x)y_t = x + t(y^* - x), Φ(yt)−Φ(x)=−∣Ωx∣ t(2−t) ∣x−y∗∣2\Phi(y_t) - \Phi(x) = -|\Omega_x|\,t(2 - t)\,|x - y^*|^2. So if y∗≠xy^* \ne x, every yty_t in KK lowers EE strictly, and yt∈Ky_t \in K for all small tt.

Proof. (a) If every star triangle stays counterclockwise, the triangles of the star still tile Ωx\Omega_x, since their outer edges are the fixed edges of the link polygon and consecutive triangles share the edges xaτx a_\tau. The other triangles do not change. By Lemma 1, E=∑τ∣τ∣3∑v∈τ∣v∣2−∫ΩfE = \sum_\tau \frac{|\tau|}{3}\sum_{v \in \tau} |v|^2 - \int_\Omega f, and only the star terms depend on xx; with ∣τ∣=Aτ(y)|\tau| = A_\tau(y) they sum to 13Φ(y)\frac13\Phi(y).

(b) AτA_\tau is affine in yy, and ∑τAτ(y)\sum_\tau A_\tau(y) is the shoelace sum of the closed link polygon taken from the point yy, which equals ∣Ωx∣|\Omega_x| for every yy. So Φ(y)=∣Ωx∣ ∣y∣2+∑τSτAτ(y)\Phi(y) = |\Omega_x|\,|y|^2 + \sum_\tau S_\tau A_\tau(y), a quadratic with Hessian 2∣Ωx∣I2|\Omega_x| I and gradient zero at y∗y^*.

(c) By (b), Φ(yt)−Φ(x)=∣Ωx∣((1−t)2−1)∣x−y∗∣2\Phi(y_t) - \Phi(x) = |\Omega_x|\bigl((1 - t)^2 - 1\bigr)|x - y^*|^2. The kernel KK is an intersection of open half-planes, so it is open and convex, and it contains xx. □\square

A computation from the circumcentre formula shows that y∗y^* is the area-weighted mean of the circumcentres of the star triangles taken at y=xy = x; the tests check this identity exactly. The implementation tries t=1,12,14,…t = 1, \frac12, \frac14, \dots, rounds yty_t to a dyadic grid, and accepts the rounded point only if the exact tests Aτ>0A_\tau > 0 and Φ(y)<Φ(x)\Phi(y) < \Phi(x) pass. So an accepted move lowers EE strictly, and a rejected vertex leaves EE unchanged.

Theorem 4 (the ODT loop). Each sweep of ODT-SMOOTH keeps a valid triangulation of Ω\Omega, never increases EE, 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 EE by Theorem 3(c) and the exact acceptance test. Each flip keeps validity by Lemma 3 and lowers EE strictly by Theorem 2. The vertex set is fixed during the flip loop and has finitely many triangulations, and no triangulation repeats because EE 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. □\square

What is not proved. EE is not convex in all vertex positions together, so the sweeps reach a point where no single move helps, not a global minimum. EE measures the size of the triangles, not their shape, so no angle bound follows. In a measured run on the square [0,8]2[0,8]^2 with only its four corners on the boundary and 20 free points, EE fell from 202.5 to 82.3 and the smallest angle fell from 3.0°3.0° to about 6⋅10−66 \cdot 10^{-6} degrees, as free points crowded the long boundary edges. With 28 fixed points on the sides, the smallest angle rose from 7.3°7.3° to 29.1°29.1°. Both are measurements.

Complexity

One vertex move costs O(d)O(d) per trial for a vertex of degree dd, and there are at most 30 trials, so the moves of one sweep cost O(n)O(n) in total with an adjacency structure. Lawson's flip loop can need Θ(n2)\Theta(n^2) flips in the worst case, so a sweep costs O(n2)O(n^2) and kk sweeps O(kn2)O(k n^2). In practice the vertices move little after the first sweeps and only a few flips are needed, so a sweep costs close to O(n)O(n). 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 O(n)O(n). 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 EE.
  • Monotone, proved. EE 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 y∗y^* 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.

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

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

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

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

Point = Tuple


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


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


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


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


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

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


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


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


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


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


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


def mean_ratio(a: Point, b: Point, c: Point) -> float:
    """The mean ratio 4 sqrt(3) A / (sum of squared edge lengths) of a triangle,
    in floats; 1 for the equilateral triangle, 0 for a flat one, negative if the
    triangle is clockwise."""
    s = sum(float((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2) for p, q in ((a, b), (b, c), (c, a)))
    return 2.0 * math.sqrt(3.0) * float(orient2d(a, b, c)) / s
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 ∣x∣2|x|^2, 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

  1. 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)
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example