Algorithm Search⌘K

Algorithmresearch

Discrete conformal maps by conformal equivalence

Also called discrete Yamabe flow, Springborn-Schroder-Pinkall conformal maps.

Springborn, Schroder and Pinkall's maps that scale edge lengths by vertex factors found by minimising a convex energy, to reach target angle sums.

Time
O(k n^3) worstO(k n^(3/2)) nested_dissection
Space
O(n^2) extraO(n log n) nested_dissection
Where
k = the number of Newton steps; n = the number of vertices
Properties
deterministicnot exactiterative
Origin
Boris Springborn, Peter Schröder, Ulrich Pinkall, 2008

Two edge-length metrics on the same triangle mesh are discretely conformally equivalent if each vertex ii has a number uiu_i, its logarithmic scale factor, such that every edge length is multiplied by e(ui+uj)/2e^{(u_i + u_j)/2}. Springborn, Schröder and Pinkall showed that the scale factors that give prescribed angle sums at the vertices are the minimizer of a convex energy, whose gradient is the angle error and whose Hessian is the cotangent Laplacian of the new metric. Newton's method then finds them in a few steps. With target angle sums 2π2\pi at the inner vertices the new metric is flat, and laying out its triangles gives a mesh parameterization that is conformal in this discrete sense.

In plain words

A conformal flattening may only grow or shrink each small region, never shear it. On a triangle mesh this becomes a rule: give each corner point a growth number, and scale each edge by the average growth of its two ends.

The task is to pick the growth numbers so that the corners around each inner point add up to a full turn, because then the triangles fit flat in the plane.

There is a hill-shaped quantity whose lowest point is exactly such a choice, and a hill of this shape has only one lowest point. So a standard downhill method with good steps finds it in a few rounds, and it cannot be caught in a wrong hollow. If the lowest point needs a triangle that is squashed flat, there is no answer for this mesh.

The problem

The input is a connected triangle mesh MM with nn vertices, edge lengths ℓij\ell_{ij} that satisfy the strict triangle inequality in every triangle, a set FF of free vertices with a target angle sum Θi>0\Theta_i > 0 for each i∈Fi \in F, and the value ui=0u_i = 0 at the other vertices, which must be at least one vertex. The faces are oriented so that the outward normal follows the right-hand rule.

The output is u∈Rnu \in \mathbb{R}^n such that the new lengths ℓ~ij=e(ui+uj)/2ℓij\tilde\ell_{ij} = e^{(u_i + u_j)/2} \ell_{ij} satisfy the triangle inequalities and the sum of the corner angles at each i∈Fi \in F is Θi\Theta_i. The usual targets are:

  • Flattening a disk. Θi=2π\Theta_i = 2\pi at the inner vertices and ub=0u_b = 0 on the boundary, so that the boundary keeps its lengths. Or Θb=π−k~b\Theta_b = \pi - \tilde k_b at the boundary vertices too, for turning angles k~b\tilde k_b of the outline that add up to 2π2\pi, with one vertex fixed.
  • Closed surfaces. Targets at all vertices but one, which add up, with the angle sum of the fixed vertex, to 2π(V−χ)2\pi(V - \chi), where χ=V−E+F=2−2g\chi = V - E + F = 2 - 2g is the Euler characteristic. This is the discrete Gauss-Bonnet theorem.

Length cross ratios. An inner edge ijij with the triangles ijkijk and jiljil has the length cross ratio ℓilℓjk/(ℓljℓki)\ell_{il}\ell_{jk} / (\ell_{lj}\ell_{ki}). A change of the lengths by vertex factors keeps it, because each of i,j,k,li, j, k, l is an end of one edge in the numerator and one in the denominator, so the factors cancel. Springborn, Schröder and Pinkall show the converse: two metrics with the same length cross ratios on all inner edges are conformally equivalent. The length cross ratio is the absolute value of the complex cross ratio of the four points, which Möbius transformations keep.

The corner angles come from the lengths by the law of cosines, so the problem is about lengths only. The vertex positions are not needed, and a flat result is laid out afterwards.

The algorithm

For a triangle with new lengths ℓ~\tilde\ell, let x=log⁡ℓ~x = \log\tilde\ell for each side and α\alpha the corner angle opposite it. Let Λ(α)=−∫0αlog⁡∣2sin⁡t∣ dt\Lambda(\alpha) = -\int_0^\alpha \log\lvert 2\sin t \rvert \, dt be Milnor's Lobachevsky function. The energy is

E(u)=∑t(2ft(u)−π(ui+uj+uk))+∑i∈FΘiui,ft=∑corners of t(α xopposite+Λ(α)),E(u) = \sum_{t} \Big( 2 f_t(u) - \pi (u_i + u_j + u_k) \Big) + \sum_{i \in F} \Theta_i u_i, \qquad f_t = \sum_{\text{corners of } t} \big( \alpha\, x_{\text{opposite}} + \Lambda(\alpha) \big),

where i,j,ki, j, k are the corners of the triangle tt. Its gradient is ∂E/∂ui=Θi−∑α\partial E / \partial u_i = \Theta_i - \sum \alpha, the target minus the angle sum at ii, and its Hessian is the cotangent Laplacian Hij=−12(cot⁡αij+cot⁡βij)H_{ij} = -\frac12(\cot\alpha_{ij} + \cot\beta_{ij}), Hii=−∑j≠iHijH_{ii} = -\sum_{j \ne i} H_{ij}, of the new lengths. A triangle whose new lengths break the triangle inequality is given the angles π\pi, 0, 0, with π\pi opposite the longest side. This extends EE to a convex function on all of Rn\mathbb{R}^n with a continuous gradient.

  1. DiscreteConformal(M, ℓ, Θ, F, ε)
  2. 1u ← 0
  3. 2repeat at most K times
  4. 3ℓ̃_ij ← e^{(u_i + u_j)/2} ℓ_ij; angles of each triangle from ℓ̃, or (π, 0, 0) if it is degenerate
  5. 4g_i ← Θ_i − (sum of the angles at i), for i ∈ F ▷ the gradient of E
  6. 5if max_i |g_i| < ε then
  7. 6if some triangle is degenerate then fail ▷ no solution with this triangulation
  8. 7return u
  9. 8H ← the cotangent Laplacian of ℓ̃, rows and columns in F ▷ the Hessian of E
  10. 9solve H d = −g; if H is singular then d ← −g
  11. 10t ← 1; while E(u + t d) > E(u) + c t (g · d) do t ← t/2 ▷ backtracking, c = 10^{-4}
  12. 11u_F ← u_F + t d
  13. 12fail ▷ no convergence in K steps

Line L3 is the only place where the lengths enter. Line L8 skips degenerate triangles: their angles are constant, so they add nothing to the Hessian. Line L9 is a Newton step for minimizing EE, the Newton method applied to the gradient equation g=0g = 0. Line L10 is a backtracking line search: it halves the step until EE drops by a fixed fraction of the drop that the slope predicts, so the energy decreases at every step. Near the minimum the full step is taken, and Newton's method then converges quadratically. The code of this page takes the full step without the test when the predicted drop is below the rounding level of EE, because the energy values can no longer tell the steps apart there.

Layout. For a disk with flat targets, place one triangle in the plane with its new lengths, then place each neighbour across a shared edge, in the order of a traversal of the triangles. The angle sums 2π2\pi at the inner vertices make the triangles around each inner vertex close up, so on a disk the result does not depend on the order. A closed surface or a surface of higher genus is first cut to a disk along a cut graph, and the targets at the cut vertices are set so that the copies match.

Example

Take the pyramid of the BFF page: base corners (±1,±1,0)(\pm1, \pm1, 0) numbered 00 to 33 counterclockwise from (−1,−1,0)(-1, -1, 0), apex 44 at (0,0,1)(0, 0, 1), side triangles (0,1,4)(0, 1, 4), (1,2,4)(1, 2, 4), (2,3,4)(2, 3, 4), (3,0,4)(3, 0, 4). The base edges have length 2, the side edges 3\sqrt3. The only free vertex is the apex, with Θ4=2π\Theta_4 = 2\pi, and u=0u = 0 on the boundary. The apex angles are 70.53°70.53° each, so the angle sum is 282.1°282.1° and the apex has the defect 77.88°=1.359377.88° = 1.3593.

step u4u_4 g4=2π−angle sumg_4 = 2\pi - \text{angle sum} H44H_{44} E(u)E(u)
0 00 1.35931.3593 2.82842.8284 23.23230323.232303
1 −0.4806020-0.4806020 −0.3124-0.3124 4.32534.3253 22.95243922.952439
2 −0.4083658-0.4083658 −1.16×10−2-1.16 \times 10^{-2} 4.01164.0116 22.94087122.940871
3 −0.4054693-0.4054693 −1.68×10−5-1.68 \times 10^{-5} 4.00004.0000 22.94085422.940854
4 −0.4054651-0.4054651 −3.5×10−11-3.5 \times 10^{-11} 4.00004.0000 22.94085422.940854
5 −0.4054651-0.4054651 9×10−169 \times 10^{-16} 4.00004.0000 22.94085422.940854

Each line search takes the full step, and the code returns after step 5. The limit is u4=log⁡(2/3)=−0.4054651u_4 = \log(2/3) = -0.4054651: the side edges become eu4/23=2e^{u_4/2}\sqrt3 = \sqrt2, the apex angles become 90°90°, and the layout is a square of side 2 with the apex at its centre. The angle error is roughly squared at each step from step 1 on. The first step is the linear solve of boundary first flattening, whose u4=−0.4806u_4 = -0.4806 is the linearization of this problem; Newton's method continues to the exact discrete answer.

A target with no solution. If Θ4≥4π\Theta_4 \ge 4\pi, the side triangles must have apex angles of π\pi, which only degenerate triangles have, when eu4/23≤1e^{u_4/2}\sqrt3 \le 1. For Θ4=4π\Theta_4 = 4\pi the code stops at line L6, and for Θ4=4.5π\Theta_4 = 4.5\pi the energy decreases without bound and it stops at line L12. For Θ4=3.9π\Theta_4 = 3.9\pi the first Newton step lands in the degenerate region, line L9 takes gradient steps out of it, and the code returns u4=−1.0971u_4 = -1.0971 with all triangles valid.

Measured on finer meshes. On 5 random disks of 37 vertices, 54 triangles and 18 boundary vertices (a hexagonal grid with jitter, lifted to a random quadratic surface, seeds 0 to 4), with ε=10−12\varepsilon = 10^{-12}:

target Newton steps largest angle error flipped triangles in the layout range of uu
2π2\pi inside, u=0u = 0 on the boundary 3 to 4 9.5×10−149.5 \times 10^{-14} 0 −0.22-0.22 to 0.470.47
rectangle: π/2\pi/2 at 4 boundary vertices, π\pi at the others 5 to 11 5.3×10−145.3 \times 10^{-14} 0 −2.14-2.14 to 2.162.16

The flips were checked with ORIENT2D, the orientation test, evaluated exactly on the float coordinates converted to rationals. A float evaluation of that sign is not reliable for tiny triangles, because of catastrophic cancellation; exact predicates avoid it. This is the robustness problem of geometry. The large range of uu for the rectangle shows the area distortion near its corners. These numbers are measurements on these meshes, not bounds.

Correctness

The proof in proofs/correctness.md shows the following.

  1. For a triangle, ∂ft/∂x=α\partial f_t / \partial x = \alpha, the angle opposite that side. This follows from the law of sines and the angle sum π\pi. Then ∂E/∂ui=Θi−∑α\partial E / \partial u_i = \Theta_i - \sum \alpha at ii.
  2. The Hessian of EE is the cotangent Laplacian of the new lengths, which is positive semidefinite with the constants as its kernel. With at least one vertex fixed, it is positive definite on the free vertices.
  3. With the angles (π,0,0)(\pi, 0, 0) for degenerate triangles, EE is a convex function on all of Rn\mathbb{R}^n with a continuous gradient.
  4. Key invariant. uu gives the target angle sums with valid triangles if and only if uu minimizes EE and all its triangles are valid, and such a uu is unique.
  5. Every uu that the code returns has all triangles valid and angle errors below ε\varepsilon, and the code stops after at most KK steps.

So when the code returns, the result is correct up to ε\varepsilon, and it is the only answer. What can fail is existence. The proof does not show that Newton's method reaches the minimum from every start, and with a fixed triangulation the minimum may have degenerate triangles, or EE may have no minimum at all, as in the pyramid with Θ4≥4π\Theta_4 \ge 4\pi. Gu, Luo, Sun and Wu changed the definition so that the triangulation changes by Delaunay edge flips as uu changes, and proved that then a metric with the given curvature exists and is unique up to scale, for every target that satisfies the Gauss-Bonnet condition. That result is cited here, not proved.

Proof: The discrete conformal energy is convex with the angle error as its gradient, its minimizer with valid triangles is the unique solution, and a returned answer is correctfull

Setting. MM is a connected triangle mesh with vertices 1,…,n1, \dots, n and edge lengths ℓ\ell that satisfy the strict triangle inequality in every triangle. FF is the set of free vertices, it is not all of the vertices, and the other vertices keep a fixed value uiu_i. For u∈Rnu \in \mathbb{R}^n the new lengths are ℓ~ij=e(ui+uj)/2ℓij\tilde\ell_{ij} = e^{(u_i + u_j)/2} \ell_{ij}, and x=log⁡ℓ~x = \log\tilde\ell on each side. A triangle is valid if its new lengths satisfy the strict triangle inequality. A valid triangle has the angles of the law of cosines; a triangle that is not valid has the angle π\pi opposite its longest side and 0 at the other two corners. Λ(α)=−∫0αlog⁡∣2sin⁡t∣ dt\Lambda(\alpha) = -\int_0^\alpha \log\lvert 2\sin t\rvert\,dt, so Λ′(α)=−log⁡(2sin⁡α)\Lambda'(\alpha) = -\log(2\sin\alpha) for 0<α<π0 < \alpha < \pi, and Λ(0)=Λ(π)=0\Lambda(0) = \Lambda(\pi) = 0. EE is the energy of the page, a function of uFu_F. The algorithm and its lines L1 to L12 are as on the page.

Claim.

  1. For a valid triangle with sides x1,x2,x3x_1, x_2, x_3 (logarithms of lengths) and opposite angles α1,α2,α3\alpha_1, \alpha_2, \alpha_3, the function f=∑mαmxm+∑mΛ(αm)f = \sum_m \alpha_m x_m + \sum_m \Lambda(\alpha_m) has ∂f/∂xm=αm\partial f / \partial x_m = \alpha_m. For {a,b,c}={1,2,3}\{a, b, c\} = \{1, 2, 3\}, ∂αa/∂xa=cot⁡αb+cot⁡αc\partial\alpha_a / \partial x_a = \cot\alpha_b + \cot\alpha_c and ∂αa/∂xb=−cot⁡αc\partial\alpha_a / \partial x_b = -\cot\alpha_c.
  2. ∂E/∂ui=Θi−∑α\partial E / \partial u_i = \Theta_i - \sum\alpha, the target minus the angle sum at ii, for every uu. Where all triangles at ii are valid or strictly not valid, the second derivatives of EE are the entries of the cotangent Laplacian HH of the new lengths, built from the valid triangles only.
  3. HH is positive semidefinite. If all triangles are valid, HH restricted to F×FF \times F is positive definite.
  4. EE is convex on RF\mathbb{R}^F and has a continuous gradient.
  5. Key invariant. uu has all triangles valid and the angle sum Θi\Theta_i at every i∈Fi \in F if and only if uu minimizes EE and all its triangles are valid. There is at most one such uu.
  6. (Correctness and termination.) In exact arithmetic, each search of line L10 stops, each step that line L11 takes lowers EE, the loop ends after at most KK steps, and a returned uu has all triangles valid and all angle errors below ε\varepsilon.

Step 1 (part 1). In a valid triangle, the law of sines gives ℓ~m/(2sin⁡αm)=R\tilde\ell_m / (2\sin\alpha_m) = R, the circumradius, for each mm, so xm−log⁡(2sin⁡αm)=log⁡Rx_m - \log(2\sin\alpha_m) = \log R for each mm. Then

df=∑mαm dxm+∑m(xm+Λ′(αm)) dαm=∑mαm dxm+log⁡R∑mdαm=∑mαm dxm,df = \sum_m \alpha_m\, dx_m + \sum_m \big(x_m + \Lambda'(\alpha_m)\big)\, d\alpha_m = \sum_m \alpha_m\, dx_m + \log R \sum_m d\alpha_m = \sum_m \alpha_m\, dx_m,

because the angles add up to π\pi, so ∑mdαm=0\sum_m d\alpha_m = 0. For the angle derivatives, write lm=exml_m = e^{x_m} and change xcx_c alone. The law of cosines lc2=la2+lb2−2lalbcos⁡αcl_c^2 = l_a^2 + l_b^2 - 2 l_a l_b \cos\alpha_c gives 2lc2 dxc=2lalbsin⁡αc dαc2 l_c^2\, dx_c = 2 l_a l_b \sin\alpha_c\, d\alpha_c, so ∂αc/∂xc=lc2/(lalbsin⁡αc)=lc2/(2A)\partial\alpha_c / \partial x_c = l_c^2 / (l_a l_b \sin\alpha_c) = l_c^2 / (2A), with AA the area. The height hh from the corner cc splits the side lcl_c into hcot⁡αah\cot\alpha_a and hcot⁡αbh\cot\alpha_b, and 2A=lch2A = l_c h, so lc2/(2A)=cot⁡αa+cot⁡αbl_c^2 / (2A) = \cot\alpha_a + \cot\alpha_b. The law of cosines at the corner aa, la2=lb2+lc2−2lblccos⁡αal_a^2 = l_b^2 + l_c^2 - 2 l_b l_c\cos\alpha_a, gives 0=2lc2 dxc−2lblccos⁡αa dxc+2lblcsin⁡αa dαa0 = 2 l_c^2\, dx_c - 2 l_b l_c \cos\alpha_a\, dx_c + 2 l_b l_c \sin\alpha_a\, d\alpha_a. So ∂αa/∂xc=(lbcos⁡αa−lc)/(lbsin⁡αa)\partial\alpha_a / \partial x_c = (l_b\cos\alpha_a - l_c) / (l_b \sin\alpha_a). Since lc=lbcos⁡αa+lacos⁡αbl_c = l_b\cos\alpha_a + l_a\cos\alpha_b, the numerator is −lacos⁡αb-l_a\cos\alpha_b, and by the law of sines la/(lbsin⁡αa)=1/sin⁡αbl_a / (l_b\sin\alpha_a) = 1 / \sin\alpha_b, so ∂αa/∂xc=−cot⁡αb\partial\alpha_a / \partial x_c = -\cot\alpha_b. The other cases follow by renaming.

Step 2 (the extended triangle function). Let T⊂R3T \subset \mathbb{R}^3 be the open set of valid xx, and extend ff to all of R3\mathbb{R}^3 with the angles of the setting. Outside TT, say ex1≥ex2+ex3e^{x_1} \ge e^{x_2} + e^{x_3}, the angles are (π,0,0)(\pi, 0, 0) and f=πx1f = \pi x_1, so ∇f=(π,0,0)=α\nabla f = (\pi, 0, 0) = \alpha in the interior of that set. The angles are continuous on R3\mathbb{R}^3: as l1→l2+l3l_1 \to l_2 + l_3 from inside TT, cos⁡α1=(l22+l32−l12)/(2l2l3)→−1\cos\alpha_1 = (l_2^2 + l_3^2 - l_1^2) / (2 l_2 l_3) \to -1, so α1→π\alpha_1 \to \pi and the other two go to 0. So ff is continuous.

Take a line x(s)=x+syx(s) = x + s y and φ(s)=f(x(s))\varphi(s) = f(x(s)). The line meets the boundary of TT where ex1+sy1−ex2+sy2−ex3+sy3=0e^{x_1 + s y_1} - e^{x_2 + s y_2} - e^{x_3 + s y_3} = 0 or one of the two similar equations holds. A real exponential sum ∑m=1pcmeλms\sum_{m=1}^{p} c_m e^{\lambda_m s} with distinct λm\lambda_m and not all cm=0c_m = 0 has at most p−1p - 1 real zeros. For p=1p = 1 it has none. For larger pp, multiply by e−λ1se^{-\lambda_1 s}, which keeps the zeros. The derivative is an exponential sum with p−1p - 1 terms cm(λm−λ1)e(λm−λ1)sc_m (\lambda_m - \lambda_1) e^{(\lambda_m - \lambda_1)s}. If these are all 0, the sum is c1eλ1sc_1 e^{\lambda_1 s} with c1≠0c_1 \ne 0, which has no zeros. Otherwise the derivative has at most p−2p - 2 zeros, and by Rolle's theorem the function has at most p−1p - 1. So, after equal exponents are merged, each equation either holds on the whole line or at most at 2 points. If it holds on the whole line, the line stays in the boundary set where the angles are constant, and φ\varphi is linear with φ′=α⋅y\varphi' = \alpha \cdot y. Otherwise φ\varphi is continuous, and away from finitely many points it is differentiable with φ′(s)=α(x(s))⋅y\varphi'(s) = \alpha(x(s)) \cdot y, which is continuous in ss. By the mean value theorem, φ\varphi is then differentiable at the finitely many points too, with the same formula. So every directional derivative of ff is α⋅y\alpha \cdot y, and these are continuous, so ff is C1C^1 with ∇f=α\nabla f = \alpha.

Step 3 (part 2). In a triangle tt with corners i,j,ki, j, k, the vertex value uiu_i enters the sides opposite jj and opposite kk, each with the factor 12\frac12, and no other side. By Step 2,

∂∂ui(2ft−π(ui+uj+uk))=2⋅12(αj+αk)−π=−αi,\frac{\partial}{\partial u_i}\Big(2 f_t - \pi(u_i + u_j + u_k)\Big) = 2 \cdot \tfrac12 (\alpha_j + \alpha_k) - \pi = -\alpha_i,

since the angles of tt add up to π\pi, also for a triangle that is not valid. Adding over the triangles at ii and the term Θiui\Theta_i u_i gives ∂E/∂ui=Θi−∑α\partial E / \partial u_i = \Theta_i - \sum\alpha.

Inside a region where tt stays valid, ∂αi/∂uj\partial\alpha_i / \partial u_j for j≠ij \ne i is 12\frac12 times the sum of ∂αi/∂x\partial\alpha_i / \partial x over the two sides at jj, the side opposite ii and the side opposite kk. By part 1 this is 12((cot⁡αj+cot⁡αk)−cot⁡αj)=12cot⁡αk\frac12\big((\cot\alpha_j + \cot\alpha_k) - \cot\alpha_j\big) = \frac12\cot\alpha_k. So ∂2E/∂ui∂uj\partial^2 E / \partial u_i \partial u_j gets −12cot⁡αk-\frac12\cot\alpha_k from tt, where αk\alpha_k is the angle opposite the edge ijij. In the same way, ∂αi/∂ui=12(−cot⁡αk−cot⁡αj)\partial\alpha_i / \partial u_i = \frac12(-\cot\alpha_k - \cot\alpha_j), so the diagonal entry gets 12(cot⁡αj+cot⁡αk)\frac12(\cot\alpha_j + \cot\alpha_k), minus the sum of the two off-diagonal entries. These are the entries of the cotangent Laplacian of tt. Where tt stays strictly not valid, its angles are constant and it adds nothing.

Step 4 (part 3). For a valid triangle tt, its new lengths form a triangle in the plane. For a function vv on its corners, extended linearly over it, Step 3 of the proof on the BFF page gives v⊤Htv=12∑cot⁡θ (va−vb)2=At∥∇v∥2≥0v^\top H_t v = \frac12 \sum \cot\theta\, (v_a - v_b)^2 = A_t \lVert\nabla v\rVert^2 \ge 0, summed over the three edges abab of tt with opposite angle θ\theta, and this is 0 only if vv is constant on tt. HH is the sum of the HtH_t over the valid triangles, so it is positive semidefinite. If all triangles are valid and v⊤Hv=0v^\top H v = 0 for some vv that is 0 outside FF, then vv is constant on each triangle, hence on the connected mesh, and it is 0 at a vertex outside FF, so v=0v = 0. So HFFH_{FF} is positive definite.

Step 5 (part 4). Each new side xx is an affine function of uu, so a line u(s)=u+svu(s) = u + s v in RF\mathbb{R}^F gives a line in the sides of each triangle. Let ψ(s)=E(u(s))\psi(s) = E(u(s)). By Steps 2 and 3, ψ\psi is C1C^1 with ψ′(s)=∇E(u(s))⋅v\psi'(s) = \nabla E(u(s)) \cdot v, so ∇E\nabla E is continuous. By Step 2 there are finitely many points of the line where a triangle changes between valid and not valid. Between two such points, every triangle is valid throughout, not valid throughout, or on the boundary throughout with constant angles, so ψ\psi is twice differentiable there with ψ′′=v⊤Hv≥0\psi'' = v^\top H v \ge 0 by Step 4. So ψ′\psi' does not decrease on each of these intervals, and since ψ′\psi' is continuous on the whole line, it does not decrease on the whole line. A C1C^1 function of one variable with a nondecreasing derivative is convex. This holds on every line, so EE is convex.

Step 6 (part 5). For a convex C1C^1 function, uu is a minimizer if and only if ∇E(u)=0\nabla E(u) = 0. By part 2, ∇E(u)=0\nabla E(u) = 0 says exactly that the angle sum at every i∈Fi \in F is Θi\Theta_i. This proves the equivalence.

For uniqueness, let u∗u^* be a minimizer with all triangles valid and u′u' any other minimizer, v=u′−u∗≠0v = u' - u^* \ne 0. By convexity, ψ(s)=E(u∗+sv)\psi(s) = E(u^* + s v) is convex and has its minimum at s=0s = 0 and s=1s = 1, so ψ\psi is constant on [0,1][0, 1]. Validity is a strict inequality, so all triangles stay valid for ss in some [0,δ)[0, \delta), and there ψ′′(s)=v⊤HFFv>0\psi''(s) = v^\top H_{FF} v > 0 by Step 4 for ss near 0, which contradicts ψ\psi being constant. So u∗u^* is the only minimizer.

On a closed mesh with one fixed vertex ff and targets with ∑i∈FΘi+Θf=π⋅(number of triangles)\sum_{i \in F} \Theta_i + \Theta_f = \pi \cdot (\text{number of triangles}), the condition of the discrete Gauss-Bonnet theorem, the angle sum at ff is also Θf\Theta_f at the solution, because the angle sums of all vertices add up to π\pi times the number of triangles.

Step 7 (part 6). Line L5 returns only when all ∣gi∣<ε\lvert g_i\rvert < \varepsilon, and line L6 returns uu only when all triangles are valid. For line L10, let g≠0g \ne 0 be the gradient at line L9. If HFFH_{FF} is not singular, it is positive definite by Step 4 (positive semidefinite and nonsingular), so the slope g⋅d=−g⊤HFF−1g<0g \cdot d = -g^\top H_{FF}^{-1} g < 0. If it is singular, d=−gd = -g and g⋅d=−∥g∥2<0g \cdot d = -\lVert g \rVert^2 < 0. Since EE is C1C^1, E(u+td)=E(u)+t g⋅d+o(t)E(u + t d) = E(u) + t\, g \cdot d + o(t), and since c<1c < 1, E(u+td)≤E(u)+c t g⋅dE(u + t d) \le E(u) + c\, t\, g \cdot d for all small enough t>0t > 0. So the halving stops, and the accepted step lowers EE by at least c t ∣g⋅d∣>0c\, t\, \lvert g \cdot d \rvert > 0. The loop of line L2 runs at most KK times, and each pass does a bounded amount of work, so the algorithm terminates.

The code of the page adds two guards for floating point: it stops the halving at t<10−12t < 10^{-12}, and it takes the full step without the test when ∣g⋅d∣\lvert g \cdot d\rvert is below 10−12max⁡(1,∣E∣)10^{-12} \max(1, \lvert E \rvert), where rounding makes the test meaningless. Neither guard changes what a returned uu satisfies, because the checks of lines L5 and L6 are made on the final uu.

What is not claimed. The proof does not show that a solution with valid triangles exists, and it need not: on the pyramid of the page, no uu gives the apex an angle sum of 4π4\pi or more with valid triangles. It does not show that Newton's method reaches the minimizer from every start, or bound the number of steps. Near a minimizer with valid triangles, HFFH_{FF} is positive definite and EE is smooth, and the standard theory of Newton's method with backtracking then gives quadratic convergence once the iterates are close; this is cited, not proved here. ■\blacksquare

Complexity

For nn vertices, lines L3, L4 and L8 take O(n)O(n) time, and each evaluation of EE in line L10 also takes O(n)O(n). Line L9 is a solve with a sparse symmetric positive definite matrix. Dense elimination, as in the code of this page, takes O(n3)O(n^3) time and O(n2)O(n^2) space per step. Sparse Cholesky factorization with nested dissection on the planar mesh graph takes O(n3/2)O(n^{3/2}) time and O(nlog⁡n)O(n \log n) space per step. The matrix changes with uu, so each step factors it again. For kk Newton steps the total is O(kn3)O(k n^3) dense or O(kn3/2)O(k n^{3/2}) sparse, plus the line searches. The number of steps is not bounded by the proof; on the meshes above it was 3 to 11.

Properties

  • Proved. The energy is convex, with the angle error as its gradient and the cotangent Laplacian as its Hessian.
  • Proved. A solution with valid triangles is unique and is the minimizer of EE, and a returned uu has angle errors below ε\varepsilon.
  • Proved. The energy does not increase in a step that passes the test of line L10.
  • Exact discrete conformality. The result is exactly conformally equivalent to the input in the discrete sense, not an approximation of it, and the angle sums are met up to ε\varepsilon.
  • Measured. 3 to 11 Newton steps and no flipped triangles on the 10 runs above.
  • Not guaranteed. With a fixed triangulation, a solution may not exist. Without edge flips the code then fails at line L6 or line L12.

Variants and improvements

  • Delaunay flips. Gu, Luo, Sun and Wu let the triangulation follow uu, flipping an edge when it stops being Delaunay in the current metric. With this change, existence holds for every target that satisfies Gauss-Bonnet. The flipped edges are intrinsic: they are straight in the current metric, not in the input surface.
  • Curvature flow. Luo proposed in 2004 to move uu by a flow that, written with these targets, is u˙i=∑α−Θi\dot u_i = \sum\alpha - \Theta_i, a gradient descent on the same energy. Newton's method on EE reaches the same point in far fewer steps.
  • Hyperbolic and spherical targets. The same notion with hyperbolic or spherical triangles gives uniformization of surfaces of genus at least 2, or of the sphere. Bobenko, Pinkall and Springborn related the energy to volumes of ideal hyperbolic polyhedra.
  • Cone singularities. Targets other than 2π2\pi at a few inner vertices, the cones, take up the curvature and reduce the area distortion. The layout then needs cuts through the cones.
  • Linear methods. Boundary first flattening solves a linearized form of the same problem in one step. LSCM gives another linear conformal map with a free boundary.

When to use it

Use it when the angle sums at the vertices must be met exactly, for example a flat metric with chosen cone angles for seamless texture maps, or a polygon outline with exact corner angles. It is a good choice for meshes of good quality, where the minimum has valid triangles and Newton's method needs few steps. For meshes with very bad triangles or extreme targets, use the version with Delaunay flips. If a fast approximate map is enough, BFF or LSCM needs one linear solve instead of several.

Pitfalls

  • A line search near the minimum. Near the minimum, the drop of EE in a Newton step is about the square of the angle error, and it soon falls below the rounding error of EE itself. The test of line L10 then compares rounding noise and can reject every step, so the method stalls at an angle error far above ε\varepsilon. A first version of the code of this page did this on the disks above with ε=10−12\varepsilon = 10^{-12}, although pure Newton steps reached 2×10−152 \times 10^{-15}. Take the full Newton step when the predicted drop is below the rounding level of EE.
  • No fixed vertex. On a closed mesh, EE is unchanged when the same constant is added to all uiu_i, if the targets satisfy Gauss-Bonnet, and the Hessian is singular. Fix one vertex. If the targets do not satisfy Gauss-Bonnet, EE decreases without bound along the constants and there is no solution.
  • Wrong Lobachevsky function. Integrating log⁡∣2sin⁡t∣\log\lvert 2\sin t\rvert with a plain quadrature rule loses accuracy at the singularity at 0. Use a series, for example Λ(x)=x−xlog⁡(2x)+∑n≥1ζ(2n)n(2n+1)x2n+1π2n\Lambda(x) = x - x\log(2x) + \sum_{n \ge 1} \frac{\zeta(2n)}{n(2n+1)} \frac{x^{2n+1}}{\pi^{2n}} on (0,π/2](0, \pi/2], and the symmetries Λ(−x)=−Λ(x)\Lambda(-x) = -\Lambda(x) and Λ(x+π)=Λ(x)\Lambda(x + \pi) = \Lambda(x).
  • Cotangents of degenerate triangles. A degenerate triangle has a zero angle, whose cotangent is infinite. Skip it in the Hessian, and give it the angles (π,0,0)(\pi, 0, 0) in the gradient, or the function is not convex and Newton's method can jump to nonsense.
  • Laying out a surface that is not a disk. The layout across shared edges needs a disk. On a cylinder or a surface with handles, the triangles met along two different paths need not agree, even with angle sums 2π2\pi, because going around a loop can rotate and scale the layout.

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.

discrete_conformal_equivalence.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/discrete-conformal-equivalence/. The authors are listed in prov/VG00WC.jsonl.

"""Discrete conformal maps by conformal equivalence (Springborn, Schroder and Pinkall 2008).

Two metrics on the same triangle mesh are discretely conformally equivalent
if there are vertex values u with  l~_ij = exp((u_i + u_j) / 2) l_ij  on every
edge. Given target angle sums Theta_i at the free vertices, the code finds u
by Newton's method with a backtracking line search on the convex energy

    E(u) = sum_t ( 2 f_t(u) - pi (u_i + u_j + u_k) ) + sum_i Theta_i u_i,
    f_t = sum_corners ( alpha x_opposite + Lob(alpha) ),   x = log l~,

where Lob is Milnor's Lobachevsky function. The gradient of E is
Theta_i - (angle sum at i), and its Hessian is the cotangent Laplacian of the
new metric. A triangle whose new lengths break the triangle inequality gets
the angles (pi, 0, 0), which extends E to a convex C^1 function on all of R^n.
"""

import math

from mx2geom import corner_angle, solve, undirected_edges

# zeta(2n) for n = 1..4 in closed form; larger n by direct sums (error far below 1e-16 after scaling).
_ZETA = [0.0, math.pi ** 2 / 6, math.pi ** 4 / 90, math.pi ** 6 / 945, math.pi ** 8 / 9450]
for _n in range(5, 60):
    _ZETA.append(sum(k ** (-2.0 * _n) for k in range(1, 40)))


def lobachevsky(x):
    """Milnor's Lobachevsky function  Lob(x) = -integral_0^x log|2 sin t| dt  (odd, period pi)."""
    x = math.fmod(x, math.pi)
    if x < 0:
        x += math.pi
    sign = 1.0
    if x > math.pi / 2:
        x, sign = math.pi - x, -1.0
    if x == 0.0:
        return 0.0
    # log(2 sin t) = log(2 t) - sum_n zeta(2n) t^(2n) / (n pi^(2n)), integrated from 0 to x.
    s = x * math.log(2 * x) - x
    r = (x / math.pi) ** 2
    p = r
    for n in range(1, 60):
        term = _ZETA[n] * p * x / (n * (2 * n + 1))
        s -= term
        if term < 1e-18:
            break
        p *= r
    return -sign * s


def triangle_angles(l0, l1, l2):
    """Angles opposite the sides l0, l1, l2, and True; (pi, 0, 0)-type angles and False if degenerate."""
    if l0 >= l1 + l2:
        return (math.pi, 0.0, 0.0), False
    if l1 >= l0 + l2:
        return (0.0, math.pi, 0.0), False
    if l2 >= l0 + l1:
        return (0.0, 0.0, math.pi), False
    return (corner_angle(l0, l1, l2), corner_angle(l1, l2, l0), corner_angle(l2, l0, l1)), True


def edge_lengths(vertices, faces):
    """The length of every edge (a sorted vertex pair) of a mesh with vertex positions."""
    return {e: math.dist(vertices[e[0]], vertices[e[1]]) for e in undirected_edges(faces)}


def new_lengths(lengths, u):
    """The lengths exp((u_i + u_j) / 2) l_ij of the conformally equivalent metric."""
    return {e: math.exp((u[e[0]] + u[e[1]]) / 2) * l for e, l in lengths.items()}


def _key(i, j):
    return (i, j) if i < j else (j, i)


def corner_data(faces, lengths, u):
    """For each face: the new lengths opposite its corners, the angles, and whether it is a valid triangle."""
    nl = new_lengths(lengths, u)  # @line L3
    out = []
    for a, b, c in faces:
        ls = (nl[_key(b, c)], nl[_key(c, a)], nl[_key(a, b)])
        ang, ok = triangle_angles(*ls)
        out.append((ls, ang, ok))
    return out


def energy(faces, lengths, u, theta):
    """E(u) for the target angle sums theta (a dict from vertex to target)."""
    total = 0.0
    for (a, b, c), (ls, ang, ok) in zip(faces, corner_data(faces, lengths, u)):
        f = sum(al * math.log(l) + lobachevsky(al) for al, l in zip(ang, ls))
        total += 2 * f - math.pi * (u[a] + u[b] + u[c])
    return total + sum(t * u[i] for i, t in theta.items())


def angle_sums(faces, lengths, u, n):
    """The sum of the corner angles at each of the n vertices in the metric with scale factors u."""
    s = [0.0] * n
    for tri, (ls, ang, ok) in zip(faces, corner_data(faces, lengths, u)):
        for k in range(3):
            s[tri[k]] += ang[k]
    return s


def gradient_and_hessian(faces, lengths, u, theta, free):
    """Gradient Theta_i - angle sum and Hessian (cotangent Laplacian of the new metric) on the free vertices."""
    n = len(u)
    idx = {v: k for k, v in enumerate(free)}
    h = [[0.0] * len(free) for _ in free]
    s = [0.0] * n
    for tri, (ls, ang, ok) in zip(faces, corner_data(faces, lengths, u)):
        for k in range(3):
            s[tri[k]] += ang[k]
            if not ok:
                continue
            w = 0.5 / math.tan(ang[k])  # @line L8
            i, j = tri[(k + 1) % 3], tri[(k + 2) % 3]
            for x, y, val in ((i, i, w), (j, j, w), (i, j, -w), (j, i, -w)):
                if x in idx and y in idx:
                    h[idx[x]][idx[y]] += val
    g = [theta[v] - s[v] for v in free]  # @line L4
    return g, h


def conformal_scale_factors(faces, lengths, theta, n, u0=None, tol=1e-12, max_steps=100):
    """Newton's method with backtracking for the u that gives the angle sums theta at the free vertices.

    theta maps each free vertex to its target angle sum; the other vertices keep u fixed (u0, default 0).
    Returns (u, steps). Raises ValueError if the minimum makes a triangle degenerate (no solution
    without changing the triangulation) or if Newton does not converge in max_steps steps.
    """
    u = list(u0) if u0 is not None else [0.0] * n  # @line L1
    free = sorted(theta)
    for step in range(max_steps):  # @line L2
        g, h = gradient_and_hessian(faces, lengths, u, theta, free)
        if max(abs(x) for x in g) < tol:  # @line L5
            if not all(ok for _, _, ok in corner_data(faces, lengths, u)):
                raise ValueError("the minimum has a degenerate triangle")  # @line L6
            return u, step  # @line L7
        try:
            d = [x[0] for x in solve(h, [[-x] for x in g], 1e-14)]  # @line L9
        except ValueError:
            # Degenerate triangles make H singular; step down the gradient instead.
            d = [-x for x in g]
        e0 = energy(faces, lengths, u, theta)
        slope = sum(gi * di for gi, di in zip(g, d))
        t = 1.0
        # When the predicted decrease is at the level of rounding, energy values cannot rank
        # the steps, and the full Newton step is taken.
        exact_enough = -slope < 1e-12 * max(1.0, abs(e0))
        while True:  # @line L10
            trial = list(u)
            for v, dv in zip(free, d):
                trial[v] += t * dv
            if exact_enough or energy(faces, lengths, trial, theta) <= e0 + 1e-4 * t * slope or t < 1e-12:
                break
            t /= 2
        u = trial  # @line L11
    raise ValueError("Newton did not converge")  # @line L12


def layout(faces, lengths, u):
    """Lay out a disk with the new lengths: place one triangle, then the others across shared edges."""
    nl = new_lengths(lengths, u)
    pos = {}
    a, b, c = faces[0]
    pos[a] = (0.0, 0.0)
    pos[b] = (nl[_key(a, b)], 0.0)
    pos[c] = _third(pos[a], pos[b], nl[_key(a, c)], nl[_key(b, c)])
    by_edge = {}
    for f, tri in enumerate(faces):
        for k in range(3):
            by_edge[(tri[k], tri[(k + 1) % 3])] = f
    done = {0}
    queue = [0]
    while queue:
        f = queue.pop()
        tri = faces[f]
        for k in range(3):
            i, j = tri[k], tri[(k + 1) % 3]
            g = by_edge.get((j, i))
            if g is None or g in done:
                continue
            done.add(g)
            other = [v for v in faces[g] if v not in (i, j)][0]
            if other not in pos:
                # Triangle (j, i, other) is counterclockwise.
                pos[other] = _third(pos[j], pos[i], nl[_key(j, other)], nl[_key(i, other)])
            queue.append(g)
    return pos


def _third(p, q, lp, lq):
    """The point r left of the directed segment pq with |r - p| = lp and |r - q| = lq."""
    d = math.dist(p, q)
    x = (lp * lp - lq * lq + d * d) / (2 * d)
    y = math.sqrt(max(0.0, lp * lp - x * x))
    ex, ey = (q[0] - p[0]) / d, (q[1] - p[1]) / d
    return (p[0] + x * ex - y * ey, p[1] + x * ey + y * ex)
mx2geom.py 150 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mx2 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small tools for triangle meshes, used by the mx2 pages.

Points are tuples of int, fractions.Fraction or float. ORIENT2D is exact
when the coordinates are int or Fraction. A mesh is a list of faces, each a
tuple of three vertex indices, oriented so that the outward normal follows
the right-hand rule (counterclockwise seen from outside).
"""

import math
from fractions import Fraction


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


def exact_orient2d(a, b, c):
    """ORIENT2D with the float coordinates converted to rationals first, so the sign is exact."""
    return orient2d(*[tuple(Fraction(x) for x in p) for p in (a, b, c)])


def solve(a, b, tol=0.0):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a list of n rows of length n, b is a list of n rows of length m
    (m right-hand sides). Entries are Fraction (exact), float or complex.
    Raises ValueError if a pivot has absolute value <= tol.
    """
    n = len(a)
    m = len(b[0]) if n else 0
    rows = [list(a[i]) + list(b[i]) for i in range(n)]
    for col in range(n):
        piv = max(range(col, n), key=lambda r: abs(rows[r][col]))
        if abs(rows[piv][col]) <= tol:
            raise ValueError("singular matrix")
        rows[col], rows[piv] = rows[piv], rows[col]
        pr = rows[col]
        for r in range(col + 1, n):
            f = rows[r][col]
            if f:
                f = Fraction(f) / pr[col] if isinstance(f, int) and isinstance(pr[col], int) else f / pr[col]
                row = rows[r]
                for k in range(col, n + m):
                    if pr[k]:
                        row[k] -= f * pr[k]
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        row = rows[i]
        for k in range(m):
            s = row[n + k]
            for j in range(i + 1, n):
                if row[j]:
                    s -= row[j] * x[j][k]
            x[i][k] = Fraction(s) / row[i] if isinstance(s, int) and isinstance(row[i], int) else s / row[i]
    return x


def cholesky(a):
    """The lower triangular factor l with a = l l^T of a symmetric positive definite float matrix."""
    n = len(a)
    l = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(l[i][k] * l[j][k] for k in range(j))
            if i == j:
                if s <= 0:
                    raise ValueError("matrix is not positive definite")
                l[i][i] = math.sqrt(s)
            else:
                l[i][j] = s / l[j][j]
    return l


def cholesky_solve(l, b):
    """Solve l l^T x = b for one right-hand side b, a list of floats."""
    n = len(l)
    y = [0.0] * n
    for i in range(n):
        y[i] = (b[i] - sum(l[i][k] * y[k] for k in range(i))) / l[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(l[k][i] * x[k] for k in range(i + 1, n))) / l[i][i]
    return x


def directed_edges(faces):
    """Map each directed edge (i, j) to (face index, corner of i). Raises on a repeated directed edge."""
    out = {}
    for f, tri in enumerate(faces):
        for k in range(3):
            e = (tri[k], tri[(k + 1) % 3])
            if e in out:
                raise ValueError("directed edge %r used twice: not an oriented manifold" % (e,))
            out[e] = (f, k)
    return out


def undirected_edges(faces):
    """The sorted list of edges, each a sorted pair of vertex indices."""
    return sorted({tuple(sorted((tri[k], tri[(k + 1) % 3]))) for tri in faces for k in range(3)})


def boundary_loop(faces):
    """The boundary of an oriented disk as one vertex loop, in the order of the face orientation."""
    de = directed_edges(faces)
    nxt = {}
    for i, j in de:
        if (j, i) not in de:
            if i in nxt:
                raise ValueError("boundary vertex %r is not manifold" % (i,))
            nxt[i] = j
    if not nxt:
        raise ValueError("the mesh has no boundary")
    start = min(nxt)
    loop = [start]
    while True:
        v = nxt[loop[-1]]
        if v == start:
            break
        loop.append(v)
    if len(loop) != len(nxt):
        raise ValueError("the boundary has more than one loop")
    return loop


def euler_characteristic(faces):
    """V - E + F of the mesh, counting only the vertices used by faces."""
    verts = {v for tri in faces for v in tri}
    return len(verts) - len(undirected_edges(faces)) + len(faces)


def length(p, q):
    return math.sqrt(sum((float(a) - float(b)) ** 2 for a, b in zip(p, q)))


def corner_angle(a, b, c):
    """The angle opposite the side of length a in a triangle with sides a, b, c (law of cosines)."""
    x = (b * b + c * c - a * a) / (2 * b * c)
    return math.acos(max(-1.0, min(1.0, x)))


def triangle_frame(p0, p1, p2):
    """Corners of a congruent counterclockwise 2D triangle: p0 at 0, p1 on the positive x-axis."""
    l01, l12, l20 = length(p0, p1), length(p1, p2), length(p2, p0)
    a0 = corner_angle(l12, l01, l20)
    return (0.0, 0.0), (l01, 0.0), (l20 * math.cos(a0), l20 * math.sin(a0))
test_discrete_conformal_equivalence.py 192 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/discrete-conformal-equivalence/. The authors are listed in prov/VG00WC.jsonl.

import math
import random

import pytest

from discrete_conformal_equivalence import (
    angle_sums,
    conformal_scale_factors,
    edge_lengths,
    energy,
    gradient_and_hessian,
    layout,
    lobachevsky,
    new_lengths,
)
from mx2geom import boundary_loop, exact_orient2d


def hex_disk(r, rng, bend, jitter=0.15):
    """A hexagonal patch of the triangular lattice, jittered and lifted to z = a x^2 + b y^2 + c x y."""
    pts, index = [], {}
    for i in range(-r, r + 1):
        for j in range(-r, r + 1):
            if abs(i + j) <= r:
                index[(i, j)] = len(pts)
                pts.append((i + 0.5 * j + rng.uniform(-jitter, jitter), j * math.sqrt(3) / 2 + rng.uniform(-jitter, jitter)))
    a, b, c = [rng.uniform(-bend, bend) for _ in range(3)]
    verts = [(x, y, a * x * x + b * y * y + c * x * y) for x, y in pts]
    faces = []
    for (i, j), v in index.items():
        if (i + 1, j) in index and (i, j + 1) in index:
            faces.append((v, index[(i + 1, j)], index[(i, j + 1)]))
        if (i + 1, j) in index and (i + 1, j - 1) in index:
            faces.append((v, index[(i + 1, j - 1)], index[(i + 1, j)]))
    return verts, faces


def disk_problem(seed, r=3, bend=0.5):
    rng = random.Random(seed)
    v, f = hex_disk(r, rng, bend)
    lengths = edge_lengths(v, f)
    loop = boundary_loop(f)
    inner = [x for x in range(len(v)) if x not in loop]
    return v, f, lengths, loop, inner


PYRAMID_V = [(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0), (0, 0, 1)]
PYRAMID_F = [(0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 0, 4)]
OCTA_V = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
OCTA_F = [(0, 2, 4), (2, 1, 4), (1, 3, 4), (3, 0, 4), (2, 0, 5), (1, 2, 5), (3, 1, 5), (0, 3, 5)]


def lob_quadrature(x, n=2000):
    """-integral_0^x log(2 sin t) dt for 0 < x < pi: the log(2 t) part exactly, log(sin t / t) by Simpson."""
    h = x / n

    def smooth(t):
        return math.log(math.sin(t) / t) if t > 0 else 0.0

    s = smooth(0.0) + smooth(x) + sum((4 if k % 2 else 2) * smooth(k * h) for k in range(1, n))
    return -(x * math.log(2 * x) - x) - s * h / 3


def test_lobachevsky_function():
    # Lob(pi/6) = Cl2(pi/3) / 2 and Lob(pi/4) = G / 2 (Catalan's constant).
    assert abs(lobachevsky(math.pi / 6) - 0.5 * 1.0149416064096536) < 1e-15
    assert abs(lobachevsky(math.pi / 4) - 0.5 * 0.915965594177219) < 1e-15
    for x in (0.3, 1.0, 1.5, 2.0, 3.0):
        assert abs(lobachevsky(x) - lob_quadrature(x)) < 1e-10
        assert abs(lobachevsky(-x) + lobachevsky(x)) < 1e-15
        assert abs(lobachevsky(x + math.pi) - lobachevsky(x)) < 1e-12
    assert lobachevsky(0.0) == 0.0 and abs(lobachevsky(math.pi / 2)) < 1e-15


def test_gradient_and_hessian_match_finite_differences():
    for seed in range(3):
        v, f, lengths, loop, inner = disk_problem(seed, r=2)
        rng = random.Random(100 + seed)
        theta = {i: 2 * math.pi + rng.uniform(-0.3, 0.3) for i in inner}
        u = [rng.uniform(-0.2, 0.2) for _ in v]
        g, h = gradient_and_hessian(f, lengths, u, theta, inner)
        eps = 1e-5
        for k, i in enumerate(inner):
            up, um = list(u), list(u)
            up[i] += eps
            um[i] -= eps
            fd = (energy(f, lengths, up, theta) - energy(f, lengths, um, theta)) / (2 * eps)
            assert abs(g[k] - fd) < 1e-7
            gp, _ = gradient_and_hessian(f, lengths, up, theta, inner)
            gm, _ = gradient_and_hessian(f, lengths, um, theta, inner)
            # g is the gradient of E, so its derivative is the Hessian H.
            for c in range(len(inner)):
                assert abs(h[c][k] - (gp[c] - gm[c]) / (2 * eps)) < 1e-6


def test_energy_is_convex_along_lines_through_degenerate_triangles():
    v, f, lengths, loop, inner = disk_problem(5, r=2)
    theta = {i: 2 * math.pi for i in inner}
    rng = random.Random(7)
    for _ in range(10):
        d = [rng.uniform(-1, 1) if i in theta else 0.0 for i in range(len(v))]
        values = [energy(f, lengths, [s * x for x in d], theta) for s in [k / 10 for k in range(-40, 41)]]
        for a, b, c in zip(values, values[1:], values[2:]):
            assert a - 2 * b + c > -1e-9


def test_target_angle_sums_are_met_on_disks():
    for seed in range(5):
        v, f, lengths, loop, inner = disk_problem(seed)
        theta = {i: 2 * math.pi for i in inner}
        u, steps = conformal_scale_factors(f, lengths, theta, len(v))
        s = angle_sums(f, lengths, u, len(v))
        assert max(abs(s[i] - 2 * math.pi) for i in inner) < 1e-11
        assert all(u[b] == 0.0 for b in loop)
        assert steps <= 10


def test_rectangle_target_lays_out_as_a_rectangle_without_flips():
    for seed in range(3):
        v, f, lengths, loop, inner = disk_problem(seed)
        m = len(loop)
        corners = {loop[(c * m) // 4] for c in range(4)}
        theta = {i: 2 * math.pi for i in inner}
        for b in loop:
            theta[b] = math.pi / 2 if b in corners else math.pi
        fixed = loop[1]
        del theta[fixed]
        u, _ = conformal_scale_factors(f, lengths, theta, len(v))
        s = angle_sums(f, lengths, u, len(v))
        # The fixed vertex gets its angle for free, by the discrete Gauss-Bonnet theorem.
        assert abs(s[fixed] - math.pi) < 1e-10
        pos = layout(f, lengths, u)
        nl = new_lengths(lengths, u)
        for (i, j), l in nl.items():
            assert abs(math.dist(pos[i], pos[j]) - l) < 1e-9
        for x, y, z in f:
            assert exact_orient2d(pos[x], pos[y], pos[z]) > 0
        for t in range(m):
            p0, p1, p2 = pos[loop[t - 1]], pos[loop[t]], pos[loop[(t + 1) % m]]
            d0 = (p1[0] - p0[0], p1[1] - p0[1])
            d1 = (p2[0] - p1[0], p2[1] - p1[1])
            turn = math.atan2(d0[0] * d1[1] - d0[1] * d1[0], d0[0] * d1[0] + d0[1] * d1[1])
            assert abs(turn - (math.pi / 2 if loop[t] in corners else 0.0)) < 1e-9


def test_closed_octahedron_reaches_targets_that_satisfy_gauss_bonnet():
    for seed in range(3):
        rng = random.Random(seed)
        v = [tuple(c * rng.uniform(0.6, 1.5) for c in p) for p in OCTA_V]
        lengths = edge_lengths(v, OCTA_F)
        theta = {i: 4 * math.pi / 3 for i in range(1, 6)}
        u, _ = conformal_scale_factors(OCTA_F, lengths, theta, 6)
        s = angle_sums(OCTA_F, lengths, u, 6)
        assert max(abs(x - 4 * math.pi / 3) for x in s) < 1e-11


def test_minimum_is_unique_from_different_starts():
    v, f, lengths, loop, inner = disk_problem(2)
    theta = {i: 2 * math.pi for i in inner}
    u1, _ = conformal_scale_factors(f, lengths, theta, len(v))
    rng = random.Random(9)
    for _ in range(3):
        start = [rng.uniform(-0.5, 0.5) if i in theta else 0.0 for i in range(len(v))]
        u2, _ = conformal_scale_factors(f, lengths, theta, len(v), u0=start)
        assert max(abs(a - b) for a, b in zip(u1, u2)) < 1e-10


def test_pyramid_example():
    lengths = edge_lengths(PYRAMID_V, PYRAMID_F)
    u, steps = conformal_scale_factors(PYRAMID_F, lengths, {4: 2 * math.pi}, 5)
    assert abs(u[4] - math.log(2 / 3)) < 1e-12
    assert steps == 5  # five Newton steps, then the stop test passes
    pos = layout(PYRAMID_F, lengths, u)
    for i in range(4):
        assert abs(math.dist(pos[i], pos[(i + 1) % 4]) - 2) < 1e-12
        assert abs(math.dist(pos[i], pos[4]) - math.sqrt(2)) < 1e-12


def test_targets_without_a_valid_solution_raise():
    lengths = edge_lengths(PYRAMID_V, PYRAMID_F)
    # 3.9 pi is reached with valid triangles, after gradient steps through degenerate ones.
    u, _ = conformal_scale_factors(PYRAMID_F, lengths, {4: 3.9 * math.pi}, 5)
    assert abs(angle_sums(PYRAMID_F, lengths, u, 5)[4] - 3.9 * math.pi) < 1e-11
    # 4 pi needs all four apex angles equal to pi: only degenerate triangles reach it.
    with pytest.raises(ValueError):
        conformal_scale_factors(PYRAMID_F, lengths, {4: 4 * math.pi}, 5)
    # Above 4 pi the angle sum is never reached and E has no minimum.
    with pytest.raises(ValueError):
        conformal_scale_factors(PYRAMID_F, lengths, {4: 4.5 * math.pi}, 5)

History

The notion that two metrics on a triangulation are conformally equivalent when the edge lengths change by vertex factors is older than the algorithm. Feng Luo studied it in 2004 together with a curvature flow on the scale factors. Boris Springborn, Peter Schröder and Ulrich Pinkall gave the convex energy with the Lobachevsky function in ACM Transactions on Graphics in 2008, solved it by Newton's method, and used it for conformal maps with cone singularities. Bobenko, Pinkall and Springborn related it in 2015 to ideal hyperbolic polyhedra and extended the energy to all scale factors. Gu, Luo, Sun and Wu proved a discrete uniformization theorem in 2018, with Delaunay flips as part of the definition, which settled the existence question.

References

  1. Boris Springborn, Peter Schröder and Ulrich Pinkall, Conformal equivalence of triangle meshes, ACM Transactions on Graphics 27(3), Article 77, 2008, the definition of discrete conformal equivalence, the energy with the Lobachevsky function, its gradient and Hessian, and the Newton solver
  2. Alexander I. Bobenko, Ulrich Pinkall and Boris A. Springborn, Discrete conformal maps and ideal hyperbolic polyhedra, Geometry and Topology 19(4), 2155-2215, 2015, the variational principle, and the extension of the energy to a convex function on all of the space of scale factors
  3. Xianfeng David Gu, Feng Luo, Jian Sun and Tianqi Wu, A discrete uniformization theorem for polyhedral surfaces, Journal of Differential Geometry 109(2), 223-256, 2018, the changed definition with Delaunay edge flips, and existence and uniqueness of a metric with given curvature

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.nested_dissection
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of space.nested_dissection
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