Algorithm Search⌘K

Algorithmadvanced

As-rigid-as-possible parameterization

Also called ARAP parameterization, local-global parameterization.

Liu and coauthors' flattening that alternates fitting a rotation to each triangle and a global Poisson solve, which gives low stretch with a free boundary.

Time
O(n^3 + k n^2) worstO(n^(3/2) + k n log n) nested_dissection
Space
O(n^2) extraO(n log n) nested_dissection
Where
k = the number of iterations; n = the number of vertices
Properties
deterministicnot exactiterative
Origin
Ligang Liu, Lei Zhang, Yin Xu, Craig Gotsman, Steven J. Gortler, 2008

As-rigid-as-possible parameterization, ARAP, flattens a triangle mesh with the topology of a disk into the plane so that each triangle keeps its shape and its size as well as possible. For each triangle it measures how far the linear map of that triangle is from a rotation, and it minimizes the sum of these errors, weighted by the area. It alternates two exact steps: a local step that fits the best rotation to each triangle, and a global step that solves one linear system for all the vertices with the rotations fixed. Each step can only lower the energy, and the matrix of the global step never changes, so it is factored once. It solves the mesh parameterization problem with much less area distortion than a conformal map, and the boundary is free.

In plain words

Cut the surface into its triangles and lay each one flat on the table. Each flat triangle has the right shape and size, but they no longer fit together. Now push and pull the corners so that the triangles join again, while each one stays as close as possible to its own flat copy.

After the push, the triangles have turned a little. So look again at each triangle and find how its flat copy must turn to match it best. Then push and pull the corners again toward the turned copies. Repeat these two steps.

Each round can only make the total error smaller, never larger. On a gently curved patch the result is a flat map in which most triangles are close to their true size, and the edge of the map takes whatever shape fits best.

The problem

The input is a triangle mesh MM with nn vertices whose triangles all have positive area, whose dual graph (triangles, joined when they share an edge) is connected, and whose faces are oriented so that the outward normal follows the right-hand rule. The input also has a start map: a point uv∈R2u_v \in \mathbb{R}^2 for each vertex. The output is a new map uu of lower distortion. Each triangle tt has a frame: a counterclockwise triangle in the plane congruent to tt, with area AtA_t. The map uu sends the frame of tt to the image triangle by a linear map plus a translation, and Jt(u)J_t(u) is the 2×22 \times 2 Jacobian of that linear map. The ARAP energy is

E(u,R)=∑tAt∥Jt(u)−Rt∥F2,E^(u)=min⁡RE(u,R),E(u, R) = \sum_t A_t \lVert J_t(u) - R_t \rVert_F^2, \qquad \hat E(u) = \min_{R} E(u, R),

where each RtR_t is a rotation of the plane and ∥⋅∥F\lVert \cdot \rVert_F is the Frobenius norm. E^(u)=0\hat E(u) = 0 exactly when each triangle is mapped by a rotation and a translation, that is, when the map keeps all lengths. The goal is a map with small E^\hat E. The energy is not convex, and the algorithm finds a local minimum, not the global one.

The algorithm

The energy of one triangle has a second form, with the edges. Write eij=qi−qje_{ij} = q_i - q_j for the edge from corner jj to corner ii of the frame, and θij\theta_{ij} for the angle of the frame opposite that edge. Then

At∥Jt−Rt∥F2=12∑(i,j)∈tcot⁡θij ∥(ui−uj)−Rteij∥2,A_t \lVert J_t - R_t \rVert_F^2 = \frac12 \sum_{(i,j) \in t} \cot \theta_{ij}\, \big\lVert (u_i - u_j) - R_t e_{ij} \big\rVert^2,

see the proof. So for fixed rotations, EE is a quadratic function of uu, and its normal equations have the cotangent Laplacian LL of the mesh as their matrix: Lu=b(R)L u = b(R), one system for the xx coordinates and one for the yy coordinates. EE does not change when uu moves by a translation, so one vertex pp is pinned.

  1. ARAP-PARAMETERIZATION(M, u, iterations)
  2. 1for each triangle t do compute its frame, A_t and the cotangents of its angles
  3. 2L ← the cotangent Laplacian without the row and column of the pinned vertex p
  4. 3factor L once (Cholesky)
  5. 4repeat iterations times
  6. 5for each triangle t do ▷ local step
  7. 6J ← J_t(u); R_t ← the rotation by the angle atan2(J₂₁ − J₁₂, J₁₁ + J₂₂)
  8. 7b ← Σ over the edges (i, j) of each t of ½ cot θ_ij · R_t e_ij, added to row i and subtracted from row j
  9. 8solve L u = b for x and for y, with u_p fixed ▷ global step
  10. 9return u

Line L6 is the closest rotation to JJ in the Frobenius norm. For RR the rotation by θ\theta, tr⁡(R⊤J)=cos⁡θ (J11+J22)+sin⁡θ (J21−J12)\operatorname{tr}(R^\top J) = \cos\theta\,(J_{11} + J_{22}) + \sin\theta\,(J_{21} - J_{12}), and ∥J−R∥F2=∥J∥F2+2−2tr⁡(R⊤J)\lVert J - R \rVert_F^2 = \lVert J \rVert_F^2 + 2 - 2 \operatorname{tr}(R^\top J), so the best θ\theta is the angle of the vector (J11+J22,J21−J12)(J_{11} + J_{22}, J_{21} - J_{12}). This is the same rotation as the usual UV⊤U V^\top from the singular value decomposition J=UΣV⊤J = U \Sigma V^\top, with the sign of the last column of UU changed when det⁡(UV⊤)<0\det(U V^\top) < 0, as in the Kabsch algorithm. If both entries of the vector are 0, every rotation is optimal, and the code takes the identity.

Line L7 builds the right side. For each edge, the target of ui−uju_i - u_j is the turned frame edge RteijR_t e_{ij}. Line L8 then gives the map in which all the image edges are as close to their targets as possible, in the weighted least squares sense. The pinned vertex moves its terms to the right side.

Start map. The code of this page starts from a Tutte embedding with uniform weights and the boundary on a circle, which has no flipped triangle. A map from least squares conformal maps is also a common start.

Degenerate cases. A triangle with zero area has no frame and is rejected. An obtuse angle gives a negative cotangent, which is correct and must be kept, see the pitfalls. A mesh whose dual graph is not connected needs one pinned vertex on each part, or LL is singular.

Example

Take the pyramid of the LSCM page: 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). The base edges have length 2 and the side edges have length 3≈1.732\sqrt3 \approx 1.732. The angles at the apex add up to 282.1°282.1°, so no flat map keeps all lengths. Vertex 0 is pinned.

step value
L1 each frame is (0,0),(2,0),(1,2)(0, 0), (2, 0), (1, \sqrt2) with At=2A_t = \sqrt2; the cotangents are 0.70710.7071 at the base corners and 0.35360.3536 at the apex
start Tutte: u0=(1,0)u_0 = (1, 0), u1=(0,1)u_1 = (0, 1), u2=(−1,0)u_2 = (-1, 0), u3=(0,−1)u_3 = (0, -1), u4=(0,0)u_4 = (0, 0); E^=1.899495\hat E = 1.899495
L6, triangle (0,1,4)(0, 1, 4) J=(−0.5−0.35360.5−0.3536)J = \begin{pmatrix} -0.5 & -0.3536 \\ 0.5 & -0.3536 \end{pmatrix}, the vector (−0.8536,0.8536)(-0.8536, 0.8536), so RtR_t turns by 135°135°
L6, the other three −135°-135°, −45°-45° and 45°45°
L8 u4=(−0.6095,0)u_4 = (-0.6095, 0), u1=(−0.6095,1.6095)u_1 = (-0.6095, 1.6095), u2=(−2.2190,0)u_2 = (-2.2190, 0), u3=(−0.6095,−1.6095)u_3 = (-0.6095, -1.6095); E^=0.323521\hat E = 0.323521
second round no change: the map is a fixed point

The result is a square of side 2.27612.2761 with the apex at its centre. Each base edge is 13.8%13.8\% too long and each side edge 1.60951.6095 is 7.1%7.1\% too short. A conformal map keeps the angles instead and lets the size change; on the LSCM page the same pyramid has an image with only 2/32/3 of the surface area.

The pyramid is symmetric, so one round reaches the fixed point. Move the apex to (0.5,0.25,1)(0.5, 0.25, 1) and the energies after 0, 1, 2, 3 and 4 rounds are 2.0886392.088639, 0.4539430.453943, 0.4272590.427259, 0.4201780.420178 and 0.4183150.418315. After 11 rounds the energy is 0.4176510.417651 and does not change in the sixth digit. The energy never increases, as the proof says.

Floating point and flips. The frames need square roots, so the computation is in floating point. Whether a triangle of the result is flipped is the sign of ORIENT2D, the orientation test, on the computed points. For tiny triangles a float evaluation of that sign is not reliable, because of catastrophic cancellation. The tests of this page convert the float coordinates to rationals and evaluate ORIENT2D exactly; exact predicates do the same faster. This is the robustness problem of geometry. On 8 random disks of 37 vertices and 54 triangles (a hexagonal grid with jitter, lifted to a random quadratic surface, seeds 0 to 7, 25 rounds), the tests found no flipped triangle. This is a measurement, not a theorem.

Correctness

The proof in proofs/correctness.md shows four facts.

  1. The local step is exact: line L6 gives a rotation that minimizes At∥Jt−R∥F2A_t \lVert J_t - R \rVert_F^2 over all rotations RR.
  2. The global step is exact: with the rotations fixed, EE is a convex quadratic function of uu with the pinned value fixed, its matrix is the cotangent Laplacian without one row and column, and that matrix is positive definite. So line L8 gives the unique minimizer.
  3. Key invariant. The energies never increase: E^(uk+1)≤E(uk+1,Rk+1)≤E(uk,Rk+1)=E^(uk)\hat E(u_{k+1}) \le E(u_{k+1}, R_{k+1}) \le E(u_k, R_{k+1}) = \hat E(u_k), where Rk+1R_{k+1} are the rotations of round k+1k + 1.
  4. The energies form a sequence that does not increase and is bounded below by 0, so they converge. A stop rule "stop when the decrease is below ε\varepsilon" stops after at most ⌈E^(u0)/ε⌉+1\lceil \hat E(u_0) / \varepsilon \rceil + 1 rounds.

The proof does not show that the maps uku_k converge to a global minimum, or that the result has no flipped triangle.

Proof: The local and global steps of ARAP parameterization are exact, so the energy never increasesfull

Setting. MM is a triangle mesh with a connected dual graph, and every triangle tt has a frame: corner points q1,q2,q3∈R2q_1, q_2, q_3 \in \mathbb{R}^2 of a counterclockwise triangle congruent to tt, with area At>0A_t > 0. A map assigns uv∈R2u_v \in \mathbb{R}^2 to each vertex. On the frame of tt, let φk\varphi_k be the affine function with φk(qk)=1\varphi_k(q_k) = 1 that is 0 on the opposite edge, and gk=∇φkg_k = \nabla \varphi_k, a column vector. The Jacobian of the affine map of the frame to the image is

Jt(u)=∑k=13uvk gk⊤,J_t(u) = \sum_{k=1}^{3} u_{v_k}\, g_k^\top,

a linear function of uu. The energy is E(u,R)=∑tAt∥Jt(u)−Rt∥F2E(u, R) = \sum_t A_t \lVert J_t(u) - R_t \rVert_F^2 for rotations RtR_t, and E^(u)=min⁡RE(u,R)\hat E(u) = \min_R E(u, R). A vertex pp is pinned. Round kk of the algorithm computes R(k+1)R^{(k+1)} from u(k)u^{(k)} by the local step and then u(k+1)u^{(k+1)} from R(k+1)R^{(k+1)} by the global step, with up(k+1)=up(k)u^{(k+1)}_p = u^{(k)}_p.

Claim.

  1. (Edge form.) At∥Jt(u)−R∥F2=12∑cot⁡θm∥(uk−ul)−R(qk−ql)∥2A_t \lVert J_t(u) - R \rVert_F^2 = \frac12 \sum \cot \theta_m \lVert (u_k - u_l) - R (q_k - q_l) \rVert^2, summed over the three edges {k,l}\{k, l\} of tt, with θm\theta_m the angle of the frame at the third corner mm.
  2. (Local step.) For J=Jt(u)J = J_t(u), the rotation by the angle of the vector (J11+J22,J21−J12)(J_{11} + J_{22}, J_{21} - J_{12}) minimizes ∥J−R∥F2\lVert J - R \rVert_F^2 over all rotations RR.
  3. (Global step.) For fixed rotations and a fixed upu_p, E(⋅,R)E(\cdot, R) has exactly one minimizer, and it is the solution of a linear system whose matrix is the cotangent Laplacian of MM with the row and column of pp removed. That matrix is positive definite.
  4. (Monotone energy.) E^(u(k+1))≤E^(u(k))\hat E(u^{(k+1)}) \le \hat E(u^{(k)}) for all kk.
  5. (Termination.) The values E^(u(k))\hat E(u^{(k)}) converge. For every ε>0\varepsilon > 0, the rule "stop after the first round that lowers E^\hat E by less than ε\varepsilon" stops after at most ⌈E^(u(0))/ε⌉+1\lceil \hat E(u^{(0)}) / \varepsilon \rceil + 1 rounds.

Step 1 (facts about the corner gradients). The functions φk\varphi_k add up to 1, and ∑kφk(x) qk=x\sum_k \varphi_k(x)\, q_k = x for every point xx of the plane, because both sides are affine and agree at the three corners. Taking gradients, ∑kgk=0\sum_k g_k = 0 and ∑kqkgk⊤=I\sum_k q_k g_k^\top = I. The vector gkg_k is perpendicular to the edge opposite qkq_k, points into the triangle, and has length 1/hk1/h_k, where hk=2At/∥ek∥h_k = 2A_t / \lVert e_k \rVert is the height on that edge of length ∥ek∥\lVert e_k \rVert. For k≠lk \ne l and the third corner mm, the edges opposite qkq_k and qlq_l meet at qmq_m with the angle θm\theta_m between them, so their inward normals make the angle π−θm\pi - \theta_m. Hence

gk⋅gl=−∥ek∥∥el∥cos⁡θm4At2,2At=∥ek∥∥el∥sin⁡θm,g_k \cdot g_l = -\frac{\lVert e_k \rVert \lVert e_l \rVert \cos \theta_m}{4 A_t^2}, \qquad 2 A_t = \lVert e_k \rVert \lVert e_l \rVert \sin \theta_m,

and so At gk⋅gl=−12cot⁡θmA_t\, g_k \cdot g_l = -\tfrac12 \cot \theta_m.

Step 2 (part 1). First take R=0R = 0. With ∥J∥F2=tr⁡(J⊤J)\lVert J \rVert_F^2 = \operatorname{tr}(J^\top J),

∥Jt(w)∥F2=∑k,l(wk⋅wl)(gk⋅gl).\lVert J_t(w) \rVert_F^2 = \sum_{k, l} (w_k \cdot w_l)(g_k \cdot g_l).

Since ∑lgl=0\sum_l g_l = 0, gk⋅gk=−∑l≠kgk⋅glg_k \cdot g_k = -\sum_{l \ne k} g_k \cdot g_l. Put this in, and group the terms of each pair k≠lk \ne l: ∣wk∣2+∣wl∣2−2wk⋅wl=∥wk−wl∥2|w_k|^2 + |w_l|^2 - 2 w_k \cdot w_l = \lVert w_k - w_l \rVert^2, so

∥Jt(w)∥F2=−∑{k,l}(gk⋅gl)∥wk−wl∥2.\lVert J_t(w) \rVert_F^2 = -\sum_{\{k, l\}} (g_k \cdot g_l) \lVert w_k - w_l \rVert^2.

Multiply by AtA_t and use Step 1: At∥Jt(w)∥F2=12∑{k,l}cot⁡θm∥wk−wl∥2A_t \lVert J_t(w) \rVert_F^2 = \frac12 \sum_{\{k,l\}} \cot\theta_m \lVert w_k - w_l \rVert^2. Now take any rotation RR and put wk=uk−Rqkw_k = u_k - R q_k. By Step 1, Jt(w)=Jt(u)−R∑kqkgk⊤=Jt(u)−RJ_t(w) = J_t(u) - R \sum_k q_k g_k^\top = J_t(u) - R, and wk−wl=(uk−ul)−R(qk−ql)w_k - w_l = (u_k - u_l) - R(q_k - q_l). This is part 1.

Step 3 (part 2). For a rotation RR, R⊤R=IR^\top R = I, so ∥J−R∥F2=∥J∥F2−2tr⁡(R⊤J)+2\lVert J - R \rVert_F^2 = \lVert J \rVert_F^2 - 2 \operatorname{tr}(R^\top J) + 2. Minimizing it is the same as maximizing tr⁡(R⊤J)\operatorname{tr}(R^\top J). For RR the rotation by θ\theta, with entries R11=R22=cos⁡θR_{11} = R_{22} = \cos\theta, R21=−R12=sin⁡θR_{21} = -R_{12} = \sin\theta,

tr⁡(R⊤J)=∑a,bRabJab=cos⁡θ (J11+J22)+sin⁡θ (J21−J12)=(cos⁡θ,sin⁡θ)⋅(α,β),\operatorname{tr}(R^\top J) = \sum_{a, b} R_{ab} J_{ab} = \cos\theta\, (J_{11} + J_{22}) + \sin\theta\, (J_{21} - J_{12}) = (\cos\theta, \sin\theta) \cdot (\alpha, \beta),

with α=J11+J22\alpha = J_{11} + J_{22} and β=J21−J12\beta = J_{21} - J_{12}. By the Cauchy-Schwarz inequality this is at most α2+β2\sqrt{\alpha^2 + \beta^2}, with equality when (cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta) is the unit vector in the direction of (α,β)(\alpha, \beta). If α=β=0\alpha = \beta = 0, the value is 0 for every θ\theta, and every rotation is a minimizer.

Step 4 (part 3). Fix the rotations. By part 1, E(u,R)E(u, R) is a sum of terms 12cot⁡θm∥(uk−ul)−d∥2\frac12 \cot\theta_m \lVert (u_k - u_l) - d \rVert^2 with constant vectors dd, so it is a quadratic polynomial in the free values uvu_v, v≠pv \ne p, of the form Q(u)−(linear)+constQ(u) - (\text{linear}) + \text{const}, where Q(u)=∑tAt∥Jt(u)∥F2=∑t12∑{k,l}cot⁡θm∥uk−ul∥2Q(u) = \sum_t A_t \lVert J_t(u) \rVert_F^2 = \sum_t \frac12 \sum_{\{k,l\}} \cot\theta_m \lVert u_k - u_l \rVert^2. The xx and yy coordinates do not mix in QQ, and for each coordinate the matrix of QQ is the cotangent Laplacian LL, with the off-diagonal entry −12(cot⁡αij+cot⁡βij)-\frac12(\cot\alpha_{ij} + \cot\beta_{ij}) for an edge ijij with the opposite angles αij\alpha_{ij} and βij\beta_{ij} (βij\beta_{ij} absent on the boundary). Fix up=0u_p = 0 in QQ, which removes the row and column of pp. Q(u)≥0Q(u) \ge 0 always. If Q(u)=0Q(u) = 0 then Jt(u)=0J_t(u) = 0 on every triangle, so uu is constant on every triangle; two triangles that share an edge share two vertices, so the constants agree, and because the dual graph is connected, uu is one constant, which is up=0u_p = 0. So QQ is positive definite on the free values. A quadratic function with a positive definite quadratic part has exactly one minimizer, the unique zero of its gradient, and the gradient is zero exactly when the free values solve L′u=bL' u = b, with L′L' the reduced Laplacian. This is part 3. Since E(u+c,R)=E(u,R)E(u + c, R) = E(u, R) for a translation cc (it does not change any JtJ_t), pinning upu_p at any value does not change the minimum value over all maps.

Step 5 (part 4). The local step of round kk takes Rt(k+1)R^{(k+1)}_t as in part 2 for Jt(u(k))J_t(u^{(k)}), so it minimizes each term separately and E(u(k),R(k+1))=min⁡RE(u(k),R)=E^(u(k))E(u^{(k)}, R^{(k+1)}) = \min_R E(u^{(k)}, R) = \hat E(u^{(k)}). The global step takes the minimizer of E(⋅,R(k+1))E(\cdot, R^{(k+1)}) with upu_p fixed, and u(k)u^{(k)} is one of the candidates, so E(u(k+1),R(k+1))≤E(u(k),R(k+1))E(u^{(k+1)}, R^{(k+1)}) \le E(u^{(k)}, R^{(k+1)}). Finally E^(u(k+1))\hat E(u^{(k+1)}) is a minimum over all rotations, so it is at most the value at R(k+1)R^{(k+1)}. Together,

E^(u(k+1))≤E(u(k+1),R(k+1))≤E(u(k),R(k+1))=E^(u(k)).\hat E(u^{(k+1)}) \le E(u^{(k+1)}, R^{(k+1)}) \le E(u^{(k)}, R^{(k+1)}) = \hat E(u^{(k)}).

Step 6 (part 5). The sequence E^(u(k))\hat E(u^{(k)}) does not increase (Step 5) and is at least 0, so it converges. Suppose the first NN rounds each lower E^\hat E by at least ε\varepsilon. Then 0≤E^(u(N))≤E^(u(0))−Nε0 \le \hat E(u^{(N)}) \le \hat E(u^{(0)}) - N \varepsilon, so N≤E^(u(0))/εN \le \hat E(u^{(0)}) / \varepsilon. So some round among the first ⌈E^(u(0))/ε⌉+1\lceil \hat E(u^{(0)}) / \varepsilon \rceil + 1 lowers E^\hat E by less than ε\varepsilon, and the rule stops there. Each round does a finite amount of work: one pass over the triangles and two solves with a matrix factored once.

What is not claimed. The energy is not convex in uu, because the set of rotations is not convex, so the limit of the values need not be the global minimum, and the proof says nothing about the convergence of the maps themselves. Nothing in the energy forbids a triangle with det⁡Jt<0\det J_t < 0, so the result is not proved to be free of flips. ■\blacksquare

Complexity

For nn vertices and kk rounds, the local step takes O(n)O(n) time per round, with a constant amount of work per triangle. The matrix LL does not depend on the rotations, so it is factored once and each round needs only two triangular solves. With dense Cholesky, as in the code of this page, the factorization takes O(n3)O(n^3) time and O(n2)O(n^2) space, and each round O(n2)O(n^2) time. The sparsity graph of LL 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, and each round O(nlog⁡n)O(n \log n) time. In practice a few tens of rounds are used; the number needed for a given accuracy is not bounded by the proof.

Properties

  • Proved. The local step is optimal for each triangle, the global step is optimal for the given rotations, the energy does not increase, and the energy values converge.
  • Proved. If the mesh is planar, its own coordinates are a map with E^=0\hat E = 0, the global minimum, and a start at that map stays there.
  • Measured. On 3 planar disks of 37 vertices (seeds 0 to 2), the code started from Tutte reaches E^<10−20\hat E < 10^{-20} within 100 rounds, and all edge lengths agree with the input to 10−910^{-9}. On 8 curved disks (seeds 0 to 7), no triangle flipped.
  • Not guaranteed. The result can have flipped triangles or a boundary that overlaps itself, and it can stop in a local minimum.
  • Free boundary. Only one vertex is pinned, and it only fixes the translation.
  • Invariant. A rigid motion of the 3D mesh does not change the result, because the frames do not change.

Variants and improvements

  • As-similar-as-possible (ASAP). Liu and coauthors also replace the rotations by similarities, a rotation times a scale. Then the energy is quadratic in uu and in the similarities together, and its minimum is a conformal map like LSCM.
  • Hybrid model. The same paper mixes the two with a parameter that weights angle keeping against area keeping, with a local step that solves a cubic equation.
  • ARAP deformation. As-rigid-as-possible deformation uses the same two steps in 3D, with 3×33 \times 3 rotations from an SVD and handles moved by the user.
  • Other energies. Later methods use the same scheme of local fits and one fixed sparse matrix for energies that go to infinity when a triangle collapses, such as the symmetric Dirichlet energy, and so keep every triangle unflipped. This is the usual fix when injectivity is required.
  • Boundary control. Boundary first flattening fixes the boundary lengths or angles first and gives a conformal map with that boundary.

When to use it

Use it for texture charts where the size of each triangle matters, for example to keep the texel density even, or to cut cloth or sheet material from a flat pattern. It needs a good start map and a mesh cut into a disk, and the rounds cost more than one linear solve of LSCM. Check every triangle of the result with an exact orientation test. If a flip-free result is required, use a method with a barrier against flips, or a Tutte embedding with its fixed boundary. If only angles matter, a conformal map is cheaper.

Pitfalls

  • Clamping the cotangents. A common change sets negative cotangents to 0 at line L2 to make the matrix an M-matrix. That changes the energy: the edge form above is only equal to At∥Jt−Rt∥F2A_t \lVert J_t - R_t \rVert_F^2 with the true signed cotangents. With clamped weights the global step no longer minimizes EE, and the proof that the energy does not increase fails.
  • A reflection instead of a rotation. Taking Rt=UV⊤R_t = U V^\top from the SVD at line L6 without the sign fix gives a reflection when det⁡J<0\det J < 0. The energy then rewards a flipped triangle, and flips stay in the map.
  • No pinned vertex. Without the pin at line L2, LL is singular, because a translation of uu does not change the energy. A dense or Cholesky solver then fails, and an iterative solver can drift.
  • Rebuilding the matrix each round. LL depends only on the 3D mesh. Factoring it inside the loop, at line L8, makes each round cost a full factorization.
  • A start map with flips. The local step only picks rotations, and nothing in the energy forbids a flipped triangle. A start with folds, for example a conformal map of a strongly curved chart, can keep them to the end.
  • Float signs. Reading flips from a float evaluation of ORIENT2D can report a tiny triangle with the wrong orientation. Use exact predicates.

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.

arap_parameterization.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/arap-parameterization/. The authors are listed in prov/7SBDXS.jsonl.

"""As-rigid-as-possible parameterization (Liu, Zhang, Xu, Gotsman and Gortler 2008).

Each triangle t gets a congruent 2D frame. For a map u of the vertices to
the plane, J_t is the 2 x 2 Jacobian of the linear map from the frame of t
to its image. The energy is

    E(u, R) = sum_t A_t || J_t - R_t ||_F^2,

with R_t a rotation. The local step sets each R_t to the rotation closest to
J_t. The global step fixes the R_t and solves a linear least squares problem
in u, with the cotangent Laplacian of the mesh as its matrix. One vertex is
pinned, because E does not change when u is translated.
"""

import math

from mx2geom import boundary_loop, cholesky, cholesky_solve, length, solve, triangle_frame, undirected_edges


def tutte_start(vertices, faces):
    """A uniform-weight Tutte map with the boundary on the unit circle by arc length (no flips)."""
    loop = boundary_loop(faces)
    nxt = {loop[k]: loop[(k + 1) % len(loop)] for k in range(len(loop))}
    total = sum(length(vertices[v], vertices[nxt[v]]) for v in loop)
    pos, s = {}, 0.0
    for v in loop:
        t = 2 * math.pi * s / total
        pos[v] = (math.cos(t), math.sin(t))
        s += length(vertices[v], vertices[nxt[v]])
    nb = {}
    for i, j in undirected_edges(faces):
        nb.setdefault(i, set()).add(j)
        nb.setdefault(j, set()).add(i)
    inner = [v for v in sorted(nb) if v not in pos]
    idx = {v: k for k, v in enumerate(inner)}
    a = [[0.0] * len(inner) for _ in inner]
    b = [[0.0, 0.0] for _ in inner]
    for v in inner:
        r = idx[v]
        a[r][r] = float(len(nb[v]))
        for w in nb[v]:
            if w in idx:
                a[r][idx[w]] -= 1.0
            else:
                b[r][0] += pos[w][0]
                b[r][1] += pos[w][1]
    x = solve(a, b) if inner else []
    for v in inner:
        pos[v] = (x[idx[v]][0], x[idx[v]][1])
    return [pos[v] for v in range(len(vertices))]


def frames(vertices, faces):
    """For each face: the 2D frame corners, the area, and the cotangent of the angle at each corner."""
    out = []
    for a, b, c in faces:
        q = triangle_frame(vertices[a], vertices[b], vertices[c])
        area = 0.5 * ((q[1][0] - q[0][0]) * (q[2][1] - q[0][1]) - (q[1][1] - q[0][1]) * (q[2][0] - q[0][0]))
        if area <= 0:
            raise ValueError("degenerate triangle")
        cots = []
        for k in range(3):
            p, r, s = q[k], q[(k + 1) % 3], q[(k + 2) % 3]
            ux, uy, vx, vy = r[0] - p[0], r[1] - p[1], s[0] - p[0], s[1] - p[1]
            cots.append((ux * vx + uy * vy) / (ux * vy - uy * vx))
        out.append((q, area, cots))
    return out


def jacobian(q, area, w):
    """The Jacobian of the linear map from the frame q to the image points w, as ((a, b), (c, d))."""
    # Gradients of the three corner functions, from the edge opposite each corner.
    j = [[0.0, 0.0], [0.0, 0.0]]
    for k in range(3):
        e = (q[(k + 2) % 3][0] - q[(k + 1) % 3][0], q[(k + 2) % 3][1] - q[(k + 1) % 3][1])
        g = (-e[1] / (2 * area), e[0] / (2 * area))
        for r in range(2):
            j[r][0] += w[k][r] * g[0]
            j[r][1] += w[k][r] * g[1]
    return j


def closest_rotation(j):
    """The rotation R that maximizes trace(R^T J), the closest rotation to J in the Frobenius norm."""
    c, s = j[0][0] + j[1][1], j[1][0] - j[0][1]
    if c == 0 and s == 0:
        return ((1.0, 0.0), (0.0, 1.0))
    r = math.hypot(c, s)
    return ((c / r, -s / r), (s / r, c / r))


def energy(fr, faces, u, rots=None):
    """E(u, R); with rots None, each R_t is the closest rotation, which gives min over R of E(u, R)."""
    total = 0.0
    for t, (q, area, _) in enumerate(fr):
        j = jacobian(q, area, [u[v] for v in faces[t]])
        r = closest_rotation(j) if rots is None else rots[t]
        total += area * sum((j[a][b] - r[a][b]) ** 2 for a in range(2) for b in range(2))
    return total


def global_matrix(fr, faces, n, pin):
    """The cotangent Laplacian with the row and column of the pinned vertex removed, and the index map."""
    idx = {v: k for k, v in enumerate(v for v in range(n) if v != pin)}
    a = [[0.0] * (n - 1) for _ in range(n - 1)]
    for (q, area, cots), tri in zip(fr, faces):
        for k in range(3):
            # cots[k] is the angle at corner k, which is opposite the edge (k+1, k+2).
            w = 0.5 * cots[k]
            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 != pin and y != pin:
                    a[idx[x]][idx[y]] += val
    return a, idx


def global_step(fr, faces, n, pin, pin_pos, rots, factor, idx):
    """The u that minimizes E(u, R) for the fixed rotations, with u[pin] = pin_pos."""
    b = [[0.0] * (n - 1), [0.0] * (n - 1)]
    for (q, area, cots), tri, r in zip(fr, faces, rots):  # @line L7
        for k in range(3):
            w = 0.5 * cots[k]
            ki, kj = (k + 1) % 3, (k + 2) % 3
            i, j = tri[ki], tri[kj]
            e = (q[ki][0] - q[kj][0], q[ki][1] - q[kj][1])
            d = (r[0][0] * e[0] + r[0][1] * e[1], r[1][0] * e[0] + r[1][1] * e[1])
            for c in range(2):
                # Terms of w * |(u_i - u_j) - d|^2 that are linear in u, and the pinned vertex.
                if i != pin:
                    b[c][idx[i]] += w * d[c] + (w * pin_pos[c] if j == pin else 0.0)
                if j != pin:
                    b[c][idx[j]] += -w * d[c] + (w * pin_pos[c] if i == pin else 0.0)
    xs = [cholesky_solve(factor, b[c]) for c in range(2)]  # @line L8
    u = [None] * n
    for v in range(n):
        u[v] = pin_pos if v == pin else (xs[0][idx[v]], xs[1][idx[v]])
    return u


def arap_parameterization(vertices, faces, iterations=20, start=None, pin=None):
    """Run the local and global steps from a start map (default: Tutte). Returns (u, energies).

    energies[k] is min over R of E(u_k, R) for the map after k global steps.
    """
    n = len(vertices)
    fr = frames(vertices, faces)  # @line L1
    u = list(start) if start is not None else tutte_start(vertices, faces)
    if pin is None:
        pin = faces[0][0]
    a, idx = global_matrix(fr, faces, n, pin)  # @line L2
    factor = cholesky(a)  # @line L3
    energies = [energy(fr, faces, u)]
    for _ in range(iterations):  # @line L4
        rots = []
        for (q, area, _), tri in zip(fr, faces):  # @line L5
            rots.append(closest_rotation(jacobian(q, area, [u[v] for v in tri])))  # @line L6
        u = global_step(fr, faces, n, pin, u[pin], rots, factor, idx)
        energies.append(energy(fr, faces, u))
    return u, energies  # @line L9
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_arap_parameterization.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/arap-parameterization/. The authors are listed in prov/7SBDXS.jsonl.

import math
import random

from arap_parameterization import (
    arap_parameterization,
    closest_rotation,
    energy,
    frames,
    global_matrix,
    global_step,
    jacobian,
)
from mx2geom import cholesky, 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


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)]


def test_closest_rotation_against_angle_search():
    rng = random.Random(1)
    for _ in range(200):
        j = [[rng.uniform(-2, 2), rng.uniform(-2, 2)], [rng.uniform(-2, 2), rng.uniform(-2, 2)]]
        r = closest_rotation(j)
        assert abs(r[0][0] * r[1][1] - r[0][1] * r[1][0] - 1) < 1e-12
        best = sum(j[a][b] * r[a][b] for a in range(2) for b in range(2))
        for k in range(720):
            t = 2 * math.pi * k / 720
            rk = ((math.cos(t), -math.sin(t)), (math.sin(t), math.cos(t)))
            assert sum(j[a][b] * rk[a][b] for a in range(2) for b in range(2)) <= best + 1e-12


def test_energy_equals_cotangent_edge_form():
    rng = random.Random(2)
    v, f = hex_disk(2, rng, 0.5)
    fr = frames(v, f)
    u = [(rng.uniform(-3, 3), rng.uniform(-3, 3)) for _ in v]
    rots = []
    for _ in f:
        t = rng.uniform(0, 2 * math.pi)
        rots.append(((math.cos(t), -math.sin(t)), (math.sin(t), math.cos(t))))
    edge_form = 0.0
    for (q, area, cots), tri, r in zip(fr, f, rots):
        for k in range(3):
            ki, kj = (k + 1) % 3, (k + 2) % 3
            e = (q[ki][0] - q[kj][0], q[ki][1] - q[kj][1])
            d = (r[0][0] * e[0] + r[0][1] * e[1], r[1][0] * e[0] + r[1][1] * e[1])
            du = (u[tri[ki]][0] - u[tri[kj]][0], u[tri[ki]][1] - u[tri[kj]][1])
            edge_form += 0.5 * cots[k] * ((du[0] - d[0]) ** 2 + (du[1] - d[1]) ** 2)
    assert abs(edge_form - energy(fr, f, u, rots)) < 1e-9 * edge_form


def test_global_step_beats_random_perturbations():
    rng = random.Random(3)
    v, f = hex_disk(2, rng, 0.5)
    fr = frames(v, f)
    u0, _ = arap_parameterization(v, f, iterations=2)
    rots = [closest_rotation(jacobian(q, area, [u0[x] for x in tri])) for (q, area, _), tri in zip(fr, f)]
    pin = f[0][0]
    a, idx = global_matrix(fr, f, len(v), pin)
    u = global_step(fr, f, len(v), pin, u0[pin], rots, cholesky(a), idx)
    best = energy(fr, f, u, rots)
    for _ in range(300):
        w = [p if k == pin else (p[0] + rng.gauss(0, 0.01), p[1] + rng.gauss(0, 0.01)) for k, p in enumerate(u)]
        assert energy(fr, f, w, rots) >= best - 1e-12


def test_energy_does_not_increase_and_no_flips_on_small_disks():
    for seed in range(8):
        rng = random.Random(seed)
        v, f = hex_disk(3, rng, 0.4)
        u, es = arap_parameterization(v, f, iterations=25)
        for k in range(len(es) - 1):
            assert es[k + 1] <= es[k] * (1 + 1e-12) + 1e-15
        assert es[-1] < es[0]
        for a, b, c in f:
            assert exact_orient2d(u[a], u[b], u[c]) > 0


def test_planar_disk_comes_back_isometric():
    for seed in range(3):
        rng = random.Random(seed)
        v, f = hex_disk(3, rng, 0.0)
        u, es = arap_parameterization(v, f, iterations=100)
        assert es[-1] < 1e-20
        for a, b, c in f:
            for x, y in ((a, b), (b, c), (c, a)):
                assert abs(math.dist(u[x], u[y]) - math.dist(v[x], v[y])) < 1e-9


def test_pyramid_example():
    u, es = arap_parameterization(PYRAMID_V, PYRAMID_F, iterations=5, pin=0)
    assert abs(es[0] - 1.899495) < 1e-6
    assert abs(es[1] - 0.323521) < 1e-6
    assert abs(es[-1] - es[1]) < 1e-12
    assert abs(math.dist(u[0], u[1]) - 2.276142) < 1e-6
    assert abs(math.dist(u[0], u[4]) - 1.609476) < 1e-6

History

Olga Sorkine and Marc Alexa presented the alternation of rotation fits and one fixed sparse solve for surface deformation at the Symposium on Geometry Processing 2007. Ligang Liu, Lei Zhang, Yin Xu, Craig Gotsman and Steven J. Gortler applied the same idea to parameterization at the 2008 symposium, with 2×22 \times 2 rotations, similarities, and a mixed model, and showed that the result is close to isometric on surfaces that are close to developable. The local and global scheme became a standard tool, and many later methods for low distortion and locally injective maps use it with other energies.

References

  1. Ligang Liu, Lei Zhang, Yin Xu, Craig Gotsman and Steven J. Gortler, A local/global approach to mesh parameterization, Computer Graphics Forum 27(5), 2008, 1495 to 1504, the energy with one linear map per triangle, the local step by a 2 x 2 SVD, the global step with the cotangent Laplacian, and the ARAP, ASAP and hybrid models
  2. Olga Sorkine and Marc Alexa, As-rigid-as-possible surface modeling, Symposium on Geometry Processing 2007, 109 to 116, the alternation of a rotation fit by SVD and a Poisson solve with a fixed matrix, and the proof that the energy does not increase
  3. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 5, Parametrization (distortion of a map and the most isometric parametrizations)

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