Algorithm Search⌘K

Algorithmadvanced

Least squares conformal maps

Also called LSCM.

Levy and coauthors' parameterization that minimises the violation of the Cauchy-Riemann equations over the triangles by one linear least squares solve, with free boundary.

Time
O(n^3) worstO(n^(3/2)) nested_dissection
Space
O(n^2) extraO(n log n) nested_dissection
Where
n = the number of vertices
Properties
deterministicnot exactiterative
Origin
Bruno Lévy, Sylvain Petitjean, Nicolas Ray, Jérôme Maillot, 2002

Least squares conformal maps, LSCM, flatten a triangle mesh with the topology of a disk into the plane by one linear least squares solve. A map is conformal if it keeps angles, and for a map of the plane that is the same as the Cauchy-Riemann equations. A piecewise linear map cannot satisfy them on every triangle of a curved mesh, so LSCM minimizes the sum over the triangles of the squared violation, weighted by the area. Two pinned vertices remove the similarities of the plane, which have energy zero, and the boundary is free. The energy equals twice the Dirichlet energy minus twice the area of the image, so the method is the same as the discrete conformal parameterization of Desbrun, Meyer and Alliez. It solves the mesh parameterization problem with much less distortion than a Tutte embedding, but it does not guarantee that the map is one to one.

In plain words

Draw a small circle on each triangle of the surface. A good flat map turns each circle into a circle, perhaps bigger or smaller, but not into an ellipse. Then the shape of every small part stays the same, and only its size changes.

On a curved surface this is not possible everywhere. LSCM measures for each triangle how far its circle is from a circle in the flat map, and adds up these errors. The flat map with the smallest total is what it returns.

Two points of the map are nailed down first. Without them, the whole map could turn, move or shrink to a point at no cost. The rest of the edge is free, so the outline of the flat map comes out of the shape itself.

The problem

The input is a triangle mesh MM whose triangles all have positive area and whose dual graph (triangles, joined when they share an edge) is connected. Its faces are oriented so that the outward normal follows the right-hand rule. The input also gives two distinct vertices pp and qq with target points in the plane. The output is a point Uv=uv+ivv∈CU_v = u_v + i v_v \in \mathbb{C} for each vertex, and each triangle is mapped linearly. The goal is the map that minimizes the conformal energy below, with UpU_p and UqU_q fixed. The map should have every triangle counterclockwise, but LSCM does not guarantee this.

The algorithm

Each triangle TT gets a frame: corner points q0,q1,q2∈Cq_0, q_1, q_2 \in \mathbb{C} of a triangle in the plane that is congruent to TT and has the same orientation, with area AT>0A_T > 0. For a triangle in 3D, put q0=0q_0 = 0, q1=∥x1−x0∥q_1 = \lVert x_1 - x_0 \rVert on the real axis, and q2q_2 in the upper half-plane. Write εj=qj+2−qj+1\varepsilon_j = q_{j+2} - q_{j+1}, with indices mod 3. The linear map of the frame to the images UvjU_{v_j} has ∂zˉf=isT/(4AT)\partial_{\bar z} f = i s_T / (4 A_T) with

sT=∑j=02εj Uvj,s_T = \sum_{j=0}^{2} \varepsilon_j\, U_{v_j},

and the Cauchy-Riemann equations hold on TT exactly when sT=0s_T = 0. The energy is

E(U)=∑T∣sT∣24AT=∑TAT((ux−vy)2+(uy+vx)2).E(U) = \sum_T \frac{|s_T|^2}{4 A_T} = \sum_T A_T \big((u_x - v_y)^2 + (u_y + v_x)^2\big).

Each sTs_T is a complex linear form, so it gives two real rows, the real part and the imaginary part. With the pinned values moved to the right side, EE is a weighted least squares problem in the 2(n−2)2(n - 2) free real unknowns, and the normal equations give its minimum.

  1. LSCM(M, pins)
  2. 1for each triangle T of M do (q_0, q_1, q_2), A_T ← FRAME(T)
  3. 2w_T ← 1 / (4 A_T)
  4. 3for each of the two real rows ρ of s_T = Σ_j ε_j U_{v_j} do
  5. 4split ρ into ρ_free, on the free unknowns, and the value c of the pinned terms
  6. 5N ← N + w_T ρ_freeᵀ ρ_free; r ← r − w_T c ρ_freeᵀ
  7. 6solve N x = r
  8. 7return U, with the pinned values and x

NN is symmetric and positive semidefinite, and positive definite when the pins fix the map, see the correctness section. Then Cholesky decomposition or the conjugate gradient method solves it. Each row has nonzero entries only for the vertices of one triangle, so NN has the sparsity of the mesh graph with 2×22 \times 2 blocks.

Degenerate cases. A triangle with zero area has no frame and is rejected. With fewer than two pins, or two pins on the same point, the similarities that fix the pins have energy zero, and NN is singular. A mesh whose dual graph is not connected needs two pins on each part. Two pins also give a singular NN when some development of the mesh, a map that is a rotation and translation on each triangle, takes both pins to the same point, see the pitfalls. The code raises an error when the elimination finds a zero pivot.

Example

Take the pyramid with base corners x0=(−1,−1,0)x_0 = (-1, -1, 0), x1=(1,−1,0)x_1 = (1, -1, 0), x2=(1,1,0)x_2 = (1, 1, 0), x3=(−1,1,0)x_3 = (-1, 1, 0), apex x4=(0,0,1)x_4 = (0, 0, 1), and the four 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). Pin U0=(0,0)U_0 = (0, 0) and U2=(2,2)U_2 = (2, 2). The angle at the apex in each triangle is arccos⁡(1/3)≈70.53°\arccos(1/3) \approx 70.53°, so the angles at the apex add up to 282.1°282.1°, not 360°360°. No flat map keeps all angles, and the minimum energy is not zero.

step value
L1, triangle (0,1,4)(0, 1, 4) frame q=(0,2,1+i2)q = (0, 2, 1 + i\sqrt2), AT=2A_T = \sqrt2, and the same for the other three
L2 wT=1/(42)w_T = 1 / (4\sqrt2)
L3 ε=(−1+i2, −1−i2, 2)\varepsilon = (-1 + i\sqrt2,\ -1 - i\sqrt2,\ 2), so sT=(−1+i2)U0−(1+i2)U1+2U4s_T = (-1 + i\sqrt2) U_0 - (1 + i\sqrt2) U_1 + 2 U_4
L6 U4=(1,1)U_4 = (1, 1), U1=(1+223,1−223)U_1 = (1 + \tfrac{2\sqrt2}{3}, 1 - \tfrac{2\sqrt2}{3}), U3=(1−223,1+223)U_3 = (1 - \tfrac{2\sqrt2}{3}, 1 + \tfrac{2\sqrt2}{3})
energy E=2/3≈0.471E = \sqrt2/3 \approx 0.471, ED=172/6E_D = 17\sqrt2/6, image area 82/38\sqrt2/3, and E=2ED−2⋅82/3E = 2E_D - 2 \cdot 8\sqrt2/3

The image is a rhombus with the diagonals U0U2U_0 U_2, of length 222\sqrt2, and U1U3U_1 U_3, of length 8/38/3, and the four triangles are counterclockwise. The total surface area is 424\sqrt2, so the pins also fix the scale: the image area is 2/32/3 of it.

If the mesh is planar, the energy can be zero. A planar grid with rational coordinates and two pins at distinct points maps exactly to the similarity of the plane that takes the pins to their targets, with E=0E = 0. The code of this page checks this in exact rational arithmetic.

When the arithmetic is floating point. For a mesh in 3D the frames need square roots, so the solve is in floating point. For the planar grid above, given as points in 3D, the computed map differs from the exact similarity by a relative error of 3×10−143 \times 10^{-14} on a 4×44 \times 4 grid and 7×10−137 \times 10^{-13} on an 8×88 \times 8 grid, with dense elimination on the normal equations. The normal equations square the condition number of the least squares rows, and the subtractions in the elimination lose digits by catastrophic cancellation. A QR factorization of the rows, or conjugate gradients on the sparse system, loses fewer digits. Whether a triangle of the result is flipped is the sign of ORIENT2D, the orientation test, on the computed points. Evaluate it exactly, for example with exact predicates or with the floats converted to rationals, as the tests of this page do; a sign from a float evaluation of a tiny triangle is not reliable. This is the robustness problem of geometry.

Correctness

On a triangle, ∂zˉf=isT/(4AT)\partial_{\bar z} f = i s_T / (4 A_T), so the term of TT is 4AT∣∂zˉf∣24 A_T |\partial_{\bar z} f|^2. It is zero exactly when the linear map is z↦az+bz \mapsto a z + b, a similarity that keeps the orientation. Expanding the squares gives E=2ED−2AE = 2 E_D - 2 \mathcal{A}, the Dirichlet energy minus the signed area of the image, twice. EE is a sum of squares, so the normal equations give a minimum, which is unique when the only map with E=0E = 0 and both pins at 0 is zero. A map with E=0E = 0 is a similarity on each triangle, the scale factor is the same across each edge, so it is a development times one constant. So the minimizer is unique exactly when no development takes the two pins to the same point. A planar mesh is its own development, so it is reproduced up to a similarity. The full proof is below.

Proof: LSCM minimizes twice the Dirichlet energy minus the area, and two pins make the minimizer unique unless a development maps them to one pointfull

Setting. MM is a triangle mesh whose dual graph (triangles, adjacent when they share an edge) is connected, and every triangle has positive area. Each triangle TT has a frame: corner positions q0,q1,q2∈Cq_0, q_1, q_2 \in \mathbb{C} that form a counterclockwise triangle congruent to TT, with area AT>0A_T > 0. Write εj=qj+2−qj+1\varepsilon_j = q_{j+2} - q_{j+1} (indices mod 3). A map assigns Uv∈CU_v \in \mathbb{C} to each vertex, and fTf_T is the affine map of the frame of TT with fT(qj)=Uvjf_T(q_j) = U_{v_j}. The energy is

E(U)=∑T∣sT∣24AT,sT=∑j=02εjUvj.E(U) = \sum_T \frac{|s_T|^2}{4 A_T}, \qquad s_T = \sum_{j=0}^{2} \varepsilon_j U_{v_j}.

Two distinct vertices pp and qq are pinned to given values. LSCM returns the solution of the normal equations of EE in the free values.

Claim.

  1. E(U)=∑TAT((ux−vy)2+(uy+vx)2)=2ED(U)−2 A(U)E(U) = \sum_T A_T \big((u_x - v_y)^2 + (u_y + v_x)^2\big) = 2 E_D(U) - 2\,\mathcal{A}(U), where U=u+ivU = u + iv, ED=12∑TAT(∣∇u∣2+∣∇v∣2)E_D = \frac12 \sum_T A_T (|\nabla u|^2 + |\nabla v|^2) and A(U)\mathcal{A}(U) is the signed area of the image.
  2. sT=0s_T = 0 if and only if fT(z)=az+bf_T(z) = a z + b for complex a,ba, b, that is, fTf_T is a similarity that keeps the orientation, or a constant.
  3. The minimizer with the two pins is unique if and only if there is no development of MM that maps pp and qq to the same point. A development is a map that is, on every triangle, a rotation and translation of its frame.
  4. If MM is planar, with its own coordinates as frames, and pp and qq have different positions, the minimizer is the similarity of the plane that takes pp and qq to their pins, and E=0E = 0 there.

Step 1 (the gradient of a corner function). Let φj\varphi_j be the affine function on the frame with φj(qj)=1\varphi_j(q_j) = 1 and φj=0\varphi_j = 0 on the opposite edge, from qj+1q_{j+1} to qj+2q_{j+2}. Its gradient is perpendicular to that edge, points to qjq_j, and has length 1/hj1/h_j, where hj=2AT/∣εj∣h_j = 2A_T / |\varepsilon_j| is the height. Multiplying by ii turns a complex number by +90°+90°. For a counterclockwise triangle, iεji \varepsilon_j points from the edge into the triangle. So, as a complex number ∂xφj+i ∂yφj\partial_x \varphi_j + i\, \partial_y \varphi_j, the gradient is iεj/(2AT)i \varepsilon_j / (2 A_T).

Step 2 (part 1). On TT, f=∑jUvjφjf = \sum_j U_{v_j} \varphi_j, so with ∂zˉ=12(∂x+i∂y)\partial_{\bar z} = \frac12 (\partial_x + i \partial_y),

∂zˉf=∑jUvj ∂zˉφj=i4AT∑jεjUvj=i sT4AT.\partial_{\bar z} f = \sum_j U_{v_j}\, \partial_{\bar z} \varphi_j = \frac{i}{4 A_T} \sum_j \varepsilon_j U_{v_j} = \frac{i\, s_T}{4 A_T}.

So ∣sT∣2/(4AT)=4AT∣∂zˉf∣2|s_T|^2 / (4 A_T) = 4 A_T |\partial_{\bar z} f|^2. With fx=ux+ivxf_x = u_x + i v_x and fy=uy+ivyf_y = u_y + i v_y, 2∂zˉf=(ux−vy)+i(uy+vx)2 \partial_{\bar z} f = (u_x - v_y) + i (u_y + v_x), which gives the first form. Expanding the squares, (ux−vy)2+(uy+vx)2=∣∇u∣2+∣∇v∣2−2(uxvy−uyvx)(u_x - v_y)^2 + (u_y + v_x)^2 = |\nabla u|^2 + |\nabla v|^2 - 2 (u_x v_y - u_y v_x). The last bracket is the determinant of the Jacobian of ff, and ATA_T times it is the signed area of the image of TT. Summing over TT gives E=2ED−2AE = 2 E_D - 2 \mathcal{A}.

Step 3 (part 2). An affine map of the plane is f(z)=az+czˉ+bf(z) = a z + c \bar z + b, and ∂zˉf=c\partial_{\bar z} f = c. So sT=0s_T = 0 if and only if c=0c = 0. In particular E≥0E \ge 0, and E(U)=0E(U) = 0 if and only if every fTf_T has the form aTz+bTa_T z + b_T.

Step 4 (the normal equations). EE is a sum of squares of real linear forms in the real and imaginary parts of the UvU_v, each with the weight 1/(4AT)>01/(4 A_T) > 0. With the pinned values fixed, EE is a quadratic function x⊤Nx−2r⊤x+cx^\top N x - 2 r^\top x + c of the free values xx, with NN symmetric and positive semidefinite. Its minimizers are exactly the solutions of Nx=rN x = r, which always exist for a least squares problem. The minimizer is unique if and only if NN is nonsingular, that is, if and only if the only map with E(U)=0E(U) = 0 and Up=Uq=0U_p = U_q = 0 is U=0U = 0, because the kernel of NN is the set of free values yy with y⊤Ny=0y^\top N y = 0, which is EE of the map with the pins set to 0.

Step 5 (part 3). Let U≠0U \ne 0 with E(U)=0E(U) = 0 and Up=Uq=0U_p = U_q = 0. By Step 3, fT(z)=aTz+bTf_T(z) = a_T z + b_T on each triangle. Let TT and T′T' share the edge xyxy, of length ℓ>0\ell > 0. Both frames are congruent to the 3D triangles, so ∣qyT−qxT∣=∣qyT′−qxT′∣=ℓ|q^T_y - q^T_x| = |q^{T'}_y - q^{T'}_x| = \ell, and

∣aT∣ ℓ=∣Uy−Ux∣=∣aT′∣ ℓ.|a_T|\, \ell = |U_y - U_x| = |a_{T'}|\, \ell.

So ∣aT∣=∣aT′∣|a_T| = |a_{T'}|, and since the dual graph is connected, ∣aT∣=c|a_T| = c for all TT. If c=0c = 0, every fTf_T is constant, two triangles at an edge have the same constant, so UU is one constant, and Up=0U_p = 0 gives U=0U = 0, which is false. So c>0c > 0, and U/cU / c is a rotation and a translation of the frame on each triangle: a development that maps pp and qq to 00.

Conversely, let DD be a development with D(p)=D(q)D(p) = D(q). Then U=D−D(p)U = D - D(p) has fT(z)=aTz+bTf_T(z) = a_T z + b_T with ∣aT∣=1|a_T| = 1, so E(U)=0E(U) = 0 by Step 3, Up=Uq=0U_p = U_q = 0 and U≠0U \ne 0. So the kernel is not trivial. This proves part 3.

Three cases where uniqueness follows at once. (a) If pp and qq are two vertices of one triangle, a development is one to one on that triangle, so D(p)≠D(q)D(p) \ne D(q). (b) If a development exists, the angles of the triangles around each inner vertex add up to a multiple of 2π2\pi: going around the vertex, the image of the first edge turns by each angle in turn and must come back to itself. So if some inner vertex has an angle sum that is not a multiple of 2π2\pi, no development exists, and the minimizer is unique for any two pins. (c) If two developments are given, on each triangle they differ by a rotation and translation, two triangles at an edge agree on its two distinct end points, and a rotation and translation is fixed by two distinct points. So all developments of a mesh with connected dual graph differ by one rigid motion of the plane.

Step 6 (part 4). For a planar mesh with its own coordinates as frames, the identity is a development, so by (c) every development is a rigid motion of the identity, and it maps pp and qq to different points because their positions differ. So the minimizer is unique. The similarity S(z)=az+bS(z) = a z + b with $S(x_p) = $ pin of pp and $S(x_q) = $ pin of qq exists, as xp≠xqx_p \ne x_q, and has sT=a∑jεjqj+b∑jεj=0s_T = a \sum_j \varepsilon_j q_j + b \sum_j \varepsilon_j = 0 for every TT, because ∑jεj=0\sum_j \varepsilon_j = 0 and ∑j(qj+2−qj+1)qj=0\sum_j (q_{j+2} - q_{j+1}) q_j = 0 (the six products cancel in pairs). So E(S)=0E(S) = 0, which is the minimum, and the unique minimizer is SS. With int or Fraction coordinates and pins, the normal equations have rational entries and Gaussian elimination solves them exactly, so the computed map equals SS exactly.

Termination. LSCM builds NN and rr in one pass over the triangles and solves one linear system of size 2(n−2)2(n - 2) by elimination, which stops after O(n3)O(n^3) operations. If NN is singular, by part 3 the input has a development that maps the pins to one point, and the code reports this. ■\blacksquare

Remark (Desbrun, Meyer and Alliez). Their discrete conformal parameterization minimizes ED−AE_D - \mathcal{A}, which by part 1 is E/2E / 2. So with the same pins both methods give the same map.

Complexity

For nn vertices the system has 2(n−2)2(n - 2) unknowns, and NN has about 7n7n nonzero 2×22 \times 2 blocks, one for each vertex and each edge. Building it takes O(n)O(n) time, one pass over the triangles. Dense Gaussian elimination, as in the code of this page, takes O(n3)O(n^3) time and O(n2)O(n^2) space. The sparsity graph is the mesh graph, which is planar for a disk, so a sparse Cholesky factorization with nested dissection takes O(n3/2)O(n^{3/2}) time and O(nlog⁡n)O(n \log n) space. In practice conjugate gradients with a good start, or a multigrid solver, is used for large meshes.

Properties

  • Free boundary. Only two vertices are fixed, and the shape of the boundary comes from the minimization. The natural boundary condition says that the map is conformal on the boundary triangles as far as possible.
  • Linear. One sparse symmetric positive definite solve, with no iteration and no initial guess.
  • Invariant. A similarity of the targets gives the same similarity of the result. A rigid motion or a uniform scaling of the 3D mesh does not change the result, because EE does not change when all frames are scaled by the same factor.
  • Reproduction. A planar mesh is mapped to a similar copy of itself.
  • Not injective in general. Triangles can fold, and distant parts of the boundary can overlap.
  • Area not controlled. Conformal maps of curved surfaces change the scale, and regions of high curvature, such as the tip of a cone, can shrink strongly.

Variants and improvements

  • Discrete conformal parameterization (Desbrun, Meyer and Alliez 2002). Minimizes ED−AE_D - \mathcal{A}, which is E/2E / 2, and writes EDE_D with the cotangent Laplacian. With the same pins it gives the same map.
  • Spectral conformal parameterization. Mullen and coauthors (2008) replace the pins by a constraint on the boundary and take an eigenvector of a generalized eigenvalue problem. The result does not depend on the choice of pins.
  • Angle-based flattening. ABF optimizes the angles of the flat triangles directly. It is nonlinear but gives lower angle distortion and fewer flips, and a result of ABF is often used where LSCM fails.
  • Cone singularities and boundary control. Later methods put the curvature at a few cone points or let the user fix the boundary shape or its curvature, which reduces the area distortion of a pure conformal map.
  • Solvers. For large meshes, sparse direct factorizations, preconditioned conjugate gradients and multigrid solvers replace the dense elimination of the code of this page. How much faster they are depends on the mesh and the solver; the page does not measure it.

When to use it

Use it for texture atlases and other maps where angles matter more than areas, after a mesh segmentation into charts that are close to developable. The map is fast and has a free boundary, so it suits interactive unwrapping of many small charts. Check every triangle of the result with an exact orientation test, and cut or split a chart that folds. If injectivity is required, use a Tutte embedding or a method with barriers against flips. If angle distortion is the main concern on strongly curved charts, use angle-based flattening.

Pitfalls

  • Pins that a development maps to one point. A common statement is that two pinned vertices make the minimizer unique. That is true when the mesh has no development, for example when some inner vertex has an angle sum that is not a multiple of 2π2\pi, or when the pins are two vertices of one triangle. It is false in general. A planar strip that winds once and a half around a square overlaps itself, and two vertices at the same position of the plane, one on each layer, give a singular system. The code of this page tests this case.
  • Folds. Take six triangles around a flat centre, with the rim vertices on the unit circle at heights +2+2 and −2-2 in turn. The angles at the centre add up to 806.6°806.6°, and LSCM with the pins at vertices 0 and 3 gives two triangles with ORIENT2D −0.033-0.033. Nothing in the method prevents this.
  • Pins close together. Two pins at adjacent vertices fix the scale and rotation by one short edge, and the far end of a large chart can come out badly scaled. Pins far apart, such as the two ends of the longest path of the boundary, give a better map.
  • Wrong orientation. A frame that is mirrored, because a face is oriented the wrong way, makes the term of that triangle measure an orientation-reversing map, and the result folds at that face.
  • Closed or high-genus meshes. The energy is defined, but the result is meaningless unless the mesh is first cut into a disk.

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.

least_squares_conformal_maps.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/least-squares-conformal-maps/. The authors are listed in prov/67C616.jsonl.

"""Least squares conformal maps (Levy, Petitjean, Ray and Maillot 2002).

Each triangle gets a 2D frame. For the corner positions q_0, q_1, q_2 of the
frame, as complex numbers, and the unknown images U_j = u_j + i v_j, the
Cauchy-Riemann residual of the triangle is

    s_T = sum_j eps_j U_j,   eps_j = q_(j+2) - q_(j+1),

and the energy is E = sum_T |s_T|^2 / (4 A_T). Two pinned vertices make the
minimizer unique in the usual case. The normal equations are solved by
Gaussian elimination. For a planar input with int or Fraction coordinates
the frames are the coordinates themselves, and the solve is exact.
"""

import math
from fractions import Fraction

from mp3geom import orient2d, solve


def triangle_frame(p0, p1, p2):
    """The corners of a triangle in a 2D frame with the same orientation, and its area.

    A 2D triangle is kept as it is (exact for int or Fraction). A 3D
    triangle is put in its plane with p0 at the origin and p1 on the x-axis,
    in floating point.
    """
    if len(p0) == 2:
        return (tuple(p0), tuple(p1), tuple(p2)), Fraction(orient2d(p0, p1, p2), 2)
    e1 = [float(p1[k]) - float(p0[k]) for k in range(3)]
    e2 = [float(p2[k]) - float(p0[k]) for k in range(3)]
    l1 = math.sqrt(sum(x * x for x in e1))
    x2 = sum(a * b for a, b in zip(e1, e2)) / l1
    c = (e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0])
    y2 = math.sqrt(sum(x * x for x in c)) / l1
    return ((0.0, 0.0), (l1, 0.0), (x2, y2)), l1 * y2 / 2


def residual_rows(q):
    """The real and imaginary rows of s_T: coefficients of (u_j, v_j), j = 0, 1, 2."""
    re, im = [], []
    for j in range(3):
        a, b = q[(j + 2) % 3], q[(j + 1) % 3]
        er, ei = a[0] - b[0], a[1] - b[1]        # eps_j = er + i ei
        re += [er, -ei]                          # Re(eps_j U_j) = er u_j - ei v_j
        im += [ei, er]                           # Im(eps_j U_j) = ei u_j + er v_j
    return re, im


def lscm(points, faces, pins):
    """Minimize the LSCM energy with pins = {vertex: (u, v)}. Returns {vertex: (u, v)}.

    Raises ValueError if the normal matrix is singular, which happens when
    the pins do not fix the map (see the page for when that is).
    """
    verts = sorted({v for f in faces for v in f})
    free = [v for v in verts if v not in pins]
    col = {v: k for k, v in enumerate(free)}
    exact = all(len(points[v]) == 2 and not isinstance(points[v][0], float) for v in verts)
    zero = Fraction(0) if exact else 0.0
    n = 2 * len(free)
    a = [[zero] * n for _ in range(n)]
    b = [[zero] for _ in range(n)]
    for f in faces:
        q, area = triangle_frame(*(points[v] for v in f))  # @line L1
        if area <= 0:
            raise ValueError("a triangle has no positive area")
        w = 1 / (4 * area)  # @line L2
        for row in residual_rows(q):  # @line L3
            idx, known = [], zero  # @line L4
            for j, v in enumerate(f):
                for c in range(2):
                    coef = row[2 * j + c]
                    if v in pins:
                        known += coef * pins[v][c]
                    else:
                        idx.append((2 * col[v] + c, coef))
            for r, cr in idx:  # @line L5: add w * row^T row to the normal matrix
                b[r][0] -= w * cr * known
                for s, cs in idx:
                    a[r][s] += w * cr * cs
    x = solve(a, b) if n else []  # @line L6
    out = {v: tuple(pins[v]) for v in pins}
    for v in free:
        out[v] = (x[2 * col[v]][0], x[2 * col[v] + 1][0])
    return out  # @line L7


def lscm_energy(points, faces, uv):
    """E = sum_T |s_T|^2 / (4 A_T)."""
    e = 0
    for f in faces:
        q, area = triangle_frame(*(points[v] for v in f))
        re, im = residual_rows(q)
        x = [uv[v][c] for v in f for c in range(2)]
        sr = sum(r * y for r, y in zip(re, x))
        si = sum(r * y for r, y in zip(im, x))
        e += (sr * sr + si * si) / (4 * area)
    return e


def dirichlet_energy(points, faces, uv):
    """E_D = (1/2) sum_T A_T (|grad u|^2 + |grad v|^2) of the piecewise linear map."""
    e = 0
    for f in faces:
        q, area = triangle_frame(*(points[v] for v in f))
        for c in range(2):
            gx = gy = 0
            for j, v in enumerate(f):
                a, b = q[(j + 2) % 3], q[(j + 1) % 3]
                # grad phi_j = rot90(eps_j) / (2A) = (-(a_y - b_y), a_x - b_x) / (2A)
                gx += uv[v][c] * (b[1] - a[1])
                gy += uv[v][c] * (a[0] - b[0])
            e += (gx * gx + gy * gy) / (8 * area)
    return e


def image_area(faces, uv):
    """Signed area of the image, sum over triangles of ORIENT2D / 2."""
    return sum(orient2d(uv[a], uv[b], uv[c]) for a, b, c in faces) / 2
mp3geom.py 136 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mp3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

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

Points are tuples of int, fractions.Fraction or float. The predicates are
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).
"""

from fractions import Fraction


def sub(a, b):
    return tuple(x - y for x, y in zip(a, b))


def add(a, b):
    return tuple(x + y for x, y in zip(a, b))


def scale(s, a):
    return tuple(s * x for x in a)


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def 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 orient3d(a, b, c, d):
    """((b - a) x (c - a)) . (d - a): > 0 if d is on the side of the normal of abc."""
    return dot(cross(sub(b, a), sub(c, a)), sub(d, a))


def sign(x):
    return (x > 0) - (x < 0)


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) or float. Returns the
    n rows of x. Raises ValueError if a pivot has absolute value <= tol, so
    an exact singular matrix always raises when tol is 0.
    """
    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]
        inv = 1 / pr[col] if isinstance(pr[col], float) else Fraction(1) / pr[col]
        for r in range(col + 1, n):
            f = rows[r][col]
            if f:
                f = f * inv
                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] = s / row[i] if isinstance(s, float) or isinstance(row[i], float) else Fraction(s) / row[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 neighbours(faces):
    """Map each vertex to the set of its neighbours."""
    nb = {}
    for tri in faces:
        for k in range(3):
            i, j = tri[k], tri[(k + 1) % 3]
            nb.setdefault(i, set()).add(j)
            nb.setdefault(j, set()).add(i)
    return nb


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):
    verts = {v for tri in faces for v in tri}
    edges = {frozenset((tri[k], tri[(k + 1) % 3])) for tri in faces for k in range(3)}
    return len(verts) - len(edges) + len(faces)
test_least_squares_conformal_maps.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/least-squares-conformal-maps/. The authors are listed in prov/67C616.jsonl.

import math
import random
from fractions import Fraction

import pytest

from least_squares_conformal_maps import dirichlet_energy, image_area, lscm, lscm_energy
from mp3geom import orient2d


def grid(rng, nx, ny, jitter):
    """A planar grid of (nx+1) x (ny+1) vertices with random diagonals and rational jitter."""
    while True:
        pts = {}
        for i in range(nx + 1):
            for j in range(ny + 1):
                dx = Fraction(rng.randint(-jitter, jitter), 4 * jitter + 1) if jitter else 0
                dy = Fraction(rng.randint(-jitter, jitter), 4 * jitter + 1) if jitter else 0
                pts[i * (ny + 1) + j] = (i + dx, j + dy)
        faces = []
        for i in range(nx):
            for j in range(ny):
                a, b, c, d = i * (ny + 1) + j, (i + 1) * (ny + 1) + j, (i + 1) * (ny + 1) + j + 1, i * (ny + 1) + j + 1
                faces += [(a, b, c), (a, c, d)] if rng.random() < 0.5 else [(a, b, d), (b, c, d)]
        if all(orient2d(pts[a], pts[b], pts[c]) > 0 for a, b, c in faces):
            return pts, faces


def similarity(p0, p1, t0, t1):
    """The map z -> a z + b with a p0 + b = t0 and a p1 + b = t1, in exact complex arithmetic."""
    dzr, dzi = p1[0] - p0[0], p1[1] - p0[1]
    dtr, dti = t1[0] - t0[0], t1[1] - t0[1]
    den = dzr * dzr + dzi * dzi
    ar, ai = (dtr * dzr + dti * dzi) / den, (dti * dzr - dtr * dzi) / den
    br, bi = t0[0] - (ar * p0[0] - ai * p0[1]), t0[1] - (ar * p0[1] + ai * p0[0])
    return lambda z: (ar * z[0] - ai * z[1] + br, ar * z[1] + ai * z[0] + bi)


def test_planar_mesh_is_reproduced_up_to_a_similarity_exactly() -> None:
    rng = random.Random(2002)
    for _ in range(12):
        pts, faces = grid(rng, rng.randint(1, 4), rng.randint(1, 4), 3)
        v0, v1 = rng.sample(sorted(pts), 2)
        t0 = (Fraction(rng.randint(-9, 9)), Fraction(rng.randint(-9, 9)))
        t1 = (t0[0] + rng.randint(1, 9), t0[1] + rng.randint(-9, 9))
        uv = lscm(pts, faces, {v0: t0, v1: t1})
        s = similarity(pts[v0], pts[v1], t0, t1)
        for v in pts:
            assert uv[v] == s(pts[v])
        assert lscm_energy(pts, faces, uv) == 0


def strip(turns_quarter):
    """A planar strip around a square, one quarter turn per step; it overlaps itself after 4 steps."""
    inner = [(1, 1), (-1, 1), (-1, -1), (1, -1)]
    outer = [(2, 2), (-2, 2), (-2, -2), (2, -2)]
    pts, faces = {}, []
    for t in range(turns_quarter + 1):
        pts[2 * t] = inner[t % 4]
        pts[2 * t + 1] = outer[t % 4]
    for t in range(turns_quarter):
        i0, o0, i1, o1 = 2 * t, 2 * t + 1, 2 * t + 2, 2 * t + 3
        faces += [(i0, o0, o1), (i0, o1, i1)]
    return pts, faces


def test_pins_at_one_point_of_an_immersed_strip_are_singular() -> None:
    pts, faces = strip(6)
    assert pts[0] == pts[8]
    with pytest.raises(ValueError):
        lscm(pts, faces, {0: (0, 0), 8: (1, 0)})
    uv = lscm(pts, faces, {0: (0, 0), 1: (1, 0)})
    s = similarity(pts[0], pts[1], (0, 0), (1, 0))
    assert all(uv[v] == s(pts[v]) for v in pts)


def test_folded_developable_strip_unfolds() -> None:
    rng = random.Random(5)
    flat, faces = grid(rng, 6, 2, 0)
    folded = {}
    for v, (x, y) in flat.items():
        if x <= 3:
            folded[v] = (x, y, 0)
        else:
            folded[v] = (3 + Fraction(3, 5) * (x - 3), y, Fraction(4, 5) * (x - 3))
    uv = lscm(folded, faces, {0: (0.0, 0.0), 1: (0.0, 1.0)})
    for v in flat:
        assert abs(uv[v][0] - float(flat[v][0])) < 1e-9
        assert abs(uv[v][1] - float(flat[v][1])) < 1e-9


def bump(rng, n):
    pts, faces = grid(rng, n, n, 0)
    out = {}
    for v, (x, y) in pts.items():
        r2 = (float(x) - n / 2) ** 2 + (float(y) - n / 2) ** 2
        out[v] = (float(x), float(y), 1.5 * math.exp(-r2 / 2))
    return out, faces


def test_energy_identity_and_minimality_on_a_curved_mesh() -> None:
    rng = random.Random(77)
    pts, faces = bump(rng, 4)
    pins = {0: (0.0, 0.0), 24: (4.0, 4.0)}
    uv = lscm(pts, faces, pins)
    e = lscm_energy(pts, faces, uv)
    assert e > 1e-3                                      # the bump is not developable
    for trial in range(5):
        u = {v: (rng.uniform(-3, 3), rng.uniform(-3, 3)) for v in pts}
        lhs = lscm_energy(pts, faces, u)
        rhs = 2 * dirichlet_energy(pts, faces, u) - 2 * image_area(faces, u)
        assert abs(lhs - rhs) < 1e-9 * max(1.0, abs(lhs))
    for trial in range(20):
        w = {v: (x + (0 if v in pins else rng.uniform(-1e-3, 1e-3)), y + (0 if v in pins else rng.uniform(-1e-3, 1e-3))) for v, (x, y) in uv.items()}
        assert lscm_energy(pts, faces, w) >= e - 1e-12
    assert all(exact_orient(uv, f) > 0 for f in faces)


def exact_orient(uv, f):
    """ORIENT2D of the computed float points, evaluated exactly."""
    return orient2d(*([Fraction(x) for x in uv[v]] for v in f))


def test_saddle_wheel_folds() -> None:
    # Six triangles around a flat centre, with the rim at heights +2 and -2 in turn.
    # The angle sum at the centre is above 2 pi, and LSCM folds two triangles.
    n, h = 6, 2.0
    pts = {i: (math.cos(2 * math.pi * i / n), math.sin(2 * math.pi * i / n), h * (-1) ** i) for i in range(n)}
    pts[n] = (0.0, 0.0, 0.0)
    faces = [(i, (i + 1) % n, n) for i in range(n)]
    uv = lscm(pts, faces, {0: (0.0, 0.0), 3: (1.0, 0.0)})
    signs = [exact_orient(uv, f) for f in faces]
    assert sum(s < 0 for s in signs) == 2
    assert min(signs) < -0.03                       # far from rounding level


def test_example_of_the_page() -> None:
    pts = {0: (-1, -1, 0), 1: (1, -1, 0), 2: (1, 1, 0), 3: (-1, 1, 0), 4: (0, 0, 1)}
    faces = [(0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 0, 4)]
    uv = lscm(pts, faces, {0: (0.0, 0.0), 2: (2.0, 2.0)})
    assert abs(uv[4][0] - 1) < 1e-12 and abs(uv[4][1] - 1) < 1e-12
    r = 2 * math.sqrt(2) / 3
    assert abs(uv[1][0] - (1 + r)) < 1e-12 and abs(uv[1][1] - (1 - r)) < 1e-12
    assert abs(uv[3][0] - (1 - r)) < 1e-12 and abs(uv[3][1] - (1 + r)) < 1e-12
    assert abs(lscm_energy(pts, faces, uv) - math.sqrt(2) / 3) < 1e-12
    assert abs(image_area(faces, uv) - 8 * math.sqrt(2) / 3) < 1e-12

History

Bruno Lévy, Sylvain Petitjean, Nicolas Ray and Jérôme Maillot presented LSCM at SIGGRAPH 2002, in a paper on automatic texture atlases that also segments the surface into charts and packs them. In the same year Mathieu Desbrun, Mark Meyer and Pierre Alliez derived discrete conformal parameterization from the Dirichlet energy and the area, and showed with natural boundary conditions how to free the boundary. The two energies are the same up to a factor of 2. LSCM became one of the standard unwrapping methods in modelling software, and is still the usual first choice for fast conformal charts.

References

  1. Bruno Lévy, Sylvain Petitjean, Nicolas Ray and Jérôme Maillot, Least squares conformal maps for automatic texture atlas generation, ACM Transactions on Graphics 21(3), 2002, 362 to 371, the discrete Cauchy-Riemann energy per triangle, the two pinned vertices, the free boundary, and the segmentation into charts
  2. Mathieu Desbrun, Mark Meyer and Pierre Alliez, Intrinsic parameterizations of surface meshes, Computer Graphics Forum 21(3), 2002, 209 to 218, the discrete conformal energy as the Dirichlet energy minus the area, and its natural boundary conditions
  3. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 5, Parametrization (conformal maps with free boundary)
  4. Alla Sheffer, Emil Praun and Kenneth Rose, Mesh parameterization methods and their applications, Foundations and Trends in Computer Graphics and Vision 2(2), 2006, 105 to 171, the section on conformal methods, which compares LSCM, discrete conformal parameterization and angle-based flattening

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