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.
- Solves
- Mesh parameterization
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with 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 for each vertex. The output is a new map of lower distortion. Each triangle has a frame: a counterclockwise triangle in the plane congruent to , with area . The map sends the frame of to the image triangle by a linear map plus a translation, and is the Jacobian of that linear map. The ARAP energy is
where each is a rotation of the plane and is the Frobenius norm. 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 . 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 for the edge from corner to corner of the frame, and for the angle of the frame opposite that edge. Then
see the proof. So for fixed rotations, is a quadratic function of , and its normal equations have the cotangent Laplacian of the mesh as their matrix: , one system for the coordinates and one for the coordinates. does not change when moves by a translation, so one vertex is pinned.
ARAP-PARAMETERIZATION(M, u, iterations)- 1
for each triangle t do compute its frame, A_t and the cotangents of its angles - 2
L ← the cotangent Laplacian without the row and column of the pinned vertex p - 3
factor L once (Cholesky) - 4
repeat iterations times - 5
for each triangle t do ▷ local step - 6
J ← J_t(u); R_t ← the rotation by the angle atan2(J₂₁ − J₁₂, J₁₁ + J₂₂) - 7
b ← Σ over the edges (i, j) of each t of ½ cot θ_ij · R_t e_ij, added to row i and subtracted from row j - 8
solve L u = b for x and for y, with u_p fixed ▷ global step - 9
return u
Line L6 is the closest rotation to in the Frobenius norm. For the rotation by , , and , so the best is the angle of the vector . This is the same rotation as the usual from the singular value decomposition , with the sign of the last column of changed when , 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 is the turned frame edge . 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 is singular.
Example
Take the pyramid of the LSCM page: base corners , , , , apex , and the four side triangles , , , . The base edges have length 2 and the side edges have length . The angles at the apex add up to , so no flat map keeps all lengths. Vertex 0 is pinned.
| step | value |
|---|---|
| L1 | each frame is with ; the cotangents are at the base corners and at the apex |
| start | Tutte: , , , , ; |
| L6, triangle | , the vector , so turns by |
| L6, the other three | , and |
| L8 | , , , ; |
| second round | no change: the map is a fixed point |
The result is a square of side with the apex at its centre. Each base edge is too long and each side edge is 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 of the surface area.
The pyramid is symmetric, so one round reaches the fixed point. Move the apex to and the energies after 0, 1, 2, 3 and 4 rounds are , , , and . After 11 rounds the energy is 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.
- The local step is exact: line L6 gives a rotation that minimizes over all rotations .
- The global step is exact: with the rotations fixed, is a convex quadratic function of 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.
- Key invariant. The energies never increase: , where are the rotations of round .
- 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 " stops after at most rounds.
The proof does not show that the maps 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. is a triangle mesh with a connected dual graph, and every triangle has a frame: corner points of a counterclockwise triangle congruent to , with area . A map assigns to each vertex. On the frame of , let be the affine function with that is 0 on the opposite edge, and , a column vector. The Jacobian of the affine map of the frame to the image is
a linear function of . The energy is for rotations , and . A vertex is pinned. Round of the algorithm computes from by the local step and then from by the global step, with .
Claim.
- (Edge form.) , summed over the three edges of , with the angle of the frame at the third corner .
- (Local step.) For , the rotation by the angle of the vector minimizes over all rotations .
- (Global step.) For fixed rotations and a fixed , has exactly one minimizer, and it is the solution of a linear system whose matrix is the cotangent Laplacian of with the row and column of removed. That matrix is positive definite.
- (Monotone energy.) for all .
- (Termination.) The values converge. For every , the rule "stop after the first round that lowers by less than " stops after at most rounds.
Step 1 (facts about the corner gradients). The functions add up to 1, and for every point of the plane, because both sides are affine and agree at the three corners. Taking gradients, and . The vector is perpendicular to the edge opposite , points into the triangle, and has length , where is the height on that edge of length . For and the third corner , the edges opposite and meet at with the angle between them, so their inward normals make the angle . Hence
and so .
Step 2 (part 1). First take . With ,
Since , . Put this in, and group the terms of each pair : , so
Multiply by and use Step 1: . Now take any rotation and put . By Step 1, , and . This is part 1.
Step 3 (part 2). For a rotation , , so . Minimizing it is the same as maximizing . For the rotation by , with entries , ,
with and . By the Cauchy-Schwarz inequality this is at most , with equality when is the unit vector in the direction of . If , the value is 0 for every , and every rotation is a minimizer.
Step 4 (part 3). Fix the rotations. By part 1, is a sum of terms with constant vectors , so it is a quadratic polynomial in the free values , , of the form , where . The and coordinates do not mix in , and for each coordinate the matrix of is the cotangent Laplacian , with the off-diagonal entry for an edge with the opposite angles and ( absent on the boundary). Fix in , which removes the row and column of . always. If then on every triangle, so 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, is one constant, which is . So 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 , with the reduced Laplacian. This is part 3. Since for a translation (it does not change any ), pinning at any value does not change the minimum value over all maps.
Step 5 (part 4). The local step of round takes as in part 2 for , so it minimizes each term separately and . The global step takes the minimizer of with fixed, and is one of the candidates, so . Finally is a minimum over all rotations, so it is at most the value at . Together,
Step 6 (part 5). The sequence does not increase (Step 5) and is at least 0, so it converges. Suppose the first rounds each lower by at least . Then , so . So some round among the first lowers by less than , 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 , 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 , so the result is not proved to be free of flips.
Complexity
For vertices and rounds, the local step takes time per round, with a constant amount of work per triangle. The matrix 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 time and space, and each round time. The sparsity graph of is the mesh graph, which is planar for a disk, so a sparse Cholesky factorization with nested dissection takes time and space, and each round 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 , 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 within 100 rounds, and all edge lengths agree with the input to . 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 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 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 with the true signed cotangents. With clamped weights the global step no longer minimizes , and the proof that the energy does not increase fails.
- A reflection instead of a rotation. Taking from the SVD at line L6 without the sign fix gives a reflection when . The energy then rewards a flipped triangle, and flips stay in the map.
- No pinned vertex. Without the pin at line L2, is singular, because a translation of does not change the energy. A dense or Cholesky solver then fails, and an iterative solver can drift.
- Rebuilding the matrix each round. 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.
# 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 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
- 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
- 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
- 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.
| 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 7SBDXS Edit this page History Report an error Markdown