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.
- Solves
- Mesh parameterization
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 has a number , its logarithmic scale factor, such that every edge length is multiplied by . 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 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 with vertices, edge lengths that satisfy the strict triangle inequality in every triangle, a set of free vertices with a target angle sum for each , and the value 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 such that the new lengths satisfy the triangle inequalities and the sum of the corner angles at each is . The usual targets are:
- Flattening a disk. at the inner vertices and on the boundary, so that the boundary keeps its lengths. Or at the boundary vertices too, for turning angles of the outline that add up to , with one vertex fixed.
- Closed surfaces. Targets at all vertices but one, which add up, with the angle sum of the fixed vertex, to , where is the Euler characteristic. This is the discrete Gauss-Bonnet theorem.
Length cross ratios. An inner edge with the triangles and has the length cross ratio . A change of the lengths by vertex factors keeps it, because each of 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 , let for each side and the corner angle opposite it. Let be Milnor's Lobachevsky function. The energy is
where are the corners of the triangle . Its gradient is , the target minus the angle sum at , and its Hessian is the cotangent Laplacian , , of the new lengths. A triangle whose new lengths break the triangle inequality is given the angles , 0, 0, with opposite the longest side. This extends to a convex function on all of with a continuous gradient.
DiscreteConformal(M, ℓ, Θ, F, ε)- 1
u ← 0 - 2
repeat at most K times - 3
ℓ̃_ij ← e^{(u_i + u_j)/2} ℓ_ij; angles of each triangle from ℓ̃, or (π, 0, 0) if it is degenerate - 4
g_i ← Θ_i − (sum of the angles at i), for i ∈ F ▷ the gradient of E - 5
if max_i |g_i| < ε then - 6
if some triangle is degenerate then fail ▷ no solution with this triangulation - 7
return u - 8
H ← the cotangent Laplacian of ℓ̃, rows and columns in F ▷ the Hessian of E - 9
solve H d = −g; if H is singular then d ← −g - 10
t ← 1; while E(u + t d) > E(u) + c t (g · d) do t ← t/2 ▷ backtracking, c = 10^{-4} - 11
u_F ← u_F + t d - 12
fail ▷ 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 , the Newton method applied to the gradient equation . Line L10 is a backtracking line search: it halves the step until 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 , 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 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 numbered to counterclockwise from , apex at , side triangles , , , . The base edges have length 2, the side edges . The only free vertex is the apex, with , and on the boundary. The apex angles are each, so the angle sum is and the apex has the defect .
| step | ||||
|---|---|---|---|---|
| 0 | ||||
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
Each line search takes the full step, and the code returns after step 5. The limit is : the side edges become , the apex angles become , 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 is the linearization of this problem; Newton's method continues to the exact discrete answer.
A target with no solution. If , the side triangles must have apex angles of , which only degenerate triangles have, when . For the code stops at line L6, and for the energy decreases without bound and it stops at line L12. For the first Newton step lands in the degenerate region, line L9 takes gradient steps out of it, and the code returns 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 :
| target | Newton steps | largest angle error | flipped triangles in the layout | range of |
|---|---|---|---|---|
| inside, on the boundary | 3 to 4 | 0 | to | |
| rectangle: at 4 boundary vertices, at the others | 5 to 11 | 0 | to |
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 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.
- For a triangle, , the angle opposite that side. This follows from the law of sines and the angle sum . Then at .
- The Hessian of 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.
- With the angles for degenerate triangles, is a convex function on all of with a continuous gradient.
- Key invariant. gives the target angle sums with valid triangles if and only if minimizes and all its triangles are valid, and such a is unique.
- Every that the code returns has all triangles valid and angle errors below , and the code stops after at most steps.
So when the code returns, the result is correct up to , 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 may have no minimum at all, as in the pyramid with . Gu, Luo, Sun and Wu changed the definition so that the triangulation changes by Delaunay edge flips as 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. is a connected triangle mesh with vertices and edge lengths that satisfy the strict triangle inequality in every triangle. is the set of free vertices, it is not all of the vertices, and the other vertices keep a fixed value . For the new lengths are , and 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 opposite its longest side and 0 at the other two corners. , so for , and . is the energy of the page, a function of . The algorithm and its lines L1 to L12 are as on the page.
Claim.
- For a valid triangle with sides (logarithms of lengths) and opposite angles , the function has . For , and .
- , the target minus the angle sum at , for every . Where all triangles at are valid or strictly not valid, the second derivatives of are the entries of the cotangent Laplacian of the new lengths, built from the valid triangles only.
- is positive semidefinite. If all triangles are valid, restricted to is positive definite.
- is convex on and has a continuous gradient.
- Key invariant. has all triangles valid and the angle sum at every if and only if minimizes and all its triangles are valid. There is at most one such .
- (Correctness and termination.) In exact arithmetic, each search of line L10 stops, each step that line L11 takes lowers , the loop ends after at most steps, and a returned has all triangles valid and all angle errors below .
Step 1 (part 1). In a valid triangle, the law of sines gives , the circumradius, for each , so for each . Then
because the angles add up to , so . For the angle derivatives, write and change alone. The law of cosines gives , so , with the area. The height from the corner splits the side into and , and , so . The law of cosines at the corner , , gives . So . Since , the numerator is , and by the law of sines , so . The other cases follow by renaming.
Step 2 (the extended triangle function). Let be the open set of valid , and extend to all of with the angles of the setting. Outside , say , the angles are and , so in the interior of that set. The angles are continuous on : as from inside , , so and the other two go to 0. So is continuous.
Take a line and . The line meets the boundary of where or one of the two similar equations holds. A real exponential sum with distinct and not all has at most real zeros. For it has none. For larger , multiply by , which keeps the zeros. The derivative is an exponential sum with terms . If these are all 0, the sum is with , which has no zeros. Otherwise the derivative has at most zeros, and by Rolle's theorem the function has at most . 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 is linear with . Otherwise is continuous, and away from finitely many points it is differentiable with , which is continuous in . By the mean value theorem, is then differentiable at the finitely many points too, with the same formula. So every directional derivative of is , and these are continuous, so is with .
Step 3 (part 2). In a triangle with corners , the vertex value enters the sides opposite and opposite , each with the factor , and no other side. By Step 2,
since the angles of add up to , also for a triangle that is not valid. Adding over the triangles at and the term gives .
Inside a region where stays valid, for is times the sum of over the two sides at , the side opposite and the side opposite . By part 1 this is . So gets from , where is the angle opposite the edge . In the same way, , so the diagonal entry gets , minus the sum of the two off-diagonal entries. These are the entries of the cotangent Laplacian of . Where stays strictly not valid, its angles are constant and it adds nothing.
Step 4 (part 3). For a valid triangle , its new lengths form a triangle in the plane. For a function on its corners, extended linearly over it, Step 3 of the proof on the BFF page gives , summed over the three edges of with opposite angle , and this is 0 only if is constant on . is the sum of the over the valid triangles, so it is positive semidefinite. If all triangles are valid and for some that is 0 outside , then is constant on each triangle, hence on the connected mesh, and it is 0 at a vertex outside , so . So is positive definite.
Step 5 (part 4). Each new side is an affine function of , so a line in gives a line in the sides of each triangle. Let . By Steps 2 and 3, is with , so 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 is twice differentiable there with by Step 4. So does not decrease on each of these intervals, and since is continuous on the whole line, it does not decrease on the whole line. A function of one variable with a nondecreasing derivative is convex. This holds on every line, so is convex.
Step 6 (part 5). For a convex function, is a minimizer if and only if . By part 2, says exactly that the angle sum at every is . This proves the equivalence.
For uniqueness, let be a minimizer with all triangles valid and any other minimizer, . By convexity, is convex and has its minimum at and , so is constant on . Validity is a strict inequality, so all triangles stay valid for in some , and there by Step 4 for near 0, which contradicts being constant. So is the only minimizer.
On a closed mesh with one fixed vertex and targets with , the condition of the discrete Gauss-Bonnet theorem, the angle sum at is also at the solution, because the angle sums of all vertices add up to times the number of triangles.
Step 7 (part 6). Line L5 returns only when all , and line L6 returns only when all triangles are valid. For line L10, let be the gradient at line L9. If is not singular, it is positive definite by Step 4 (positive semidefinite and nonsingular), so the slope . If it is singular, and . Since is , , and since , for all small enough . So the halving stops, and the accepted step lowers by at least . The loop of line L2 runs at most 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 , and it takes the full step without the test when is below , where rounding makes the test meaningless. Neither guard changes what a returned satisfies, because the checks of lines L5 and L6 are made on the final .
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 gives the apex an angle sum of 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, is positive definite and 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.
Complexity
For vertices, lines L3, L4 and L8 take time, and each evaluation of in line L10 also takes . Line L9 is a solve with a sparse symmetric positive definite matrix. Dense elimination, as in the code of this page, takes time and space per step. Sparse Cholesky factorization with nested dissection on the planar mesh graph takes time and space per step. The matrix changes with , so each step factors it again. For Newton steps the total is dense or 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 , and a returned has angle errors below .
- 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 .
- 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 , 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 by a flow that, written with these targets, is , a gradient descent on the same energy. Newton's method on 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 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 in a Newton step is about the square of the angle error, and it soon falls below the rounding error of 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 . A first version of the code of this page did this on the disks above with , although pure Newton steps reached . Take the full Newton step when the predicted drop is below the rounding level of .
- No fixed vertex. On a closed mesh, is unchanged when the same constant is added to all , if the targets satisfy Gauss-Bonnet, and the Hessian is singular. Fix one vertex. If the targets do not satisfy Gauss-Bonnet, decreases without bound along the constants and there is no solution.
- Wrong Lobachevsky function. Integrating with a plain quadrature rule loses accuracy at the singularity at 0. Use a series, for example on , and the symmetries and .
- 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 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 , 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VG00WC Edit this page History Report an error Markdown