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.
- Solves
- Mesh parameterization
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 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 and with target points in the plane. The output is a point for each vertex, and each triangle is mapped linearly. The goal is the map that minimizes the conformal energy below, with and fixed. The map should have every triangle counterclockwise, but LSCM does not guarantee this.
The algorithm
Each triangle gets a frame: corner points of a triangle in the plane that is congruent to and has the same orientation, with area . For a triangle in 3D, put , on the real axis, and in the upper half-plane. Write , with indices mod 3. The linear map of the frame to the images has with
and the Cauchy-Riemann equations hold on exactly when . The energy is
Each 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, is a weighted least squares problem in the free real unknowns, and the normal equations give its minimum.
LSCM(M, pins)- 1
for each triangle T of M do (q_0, q_1, q_2), A_T ← FRAME(T) - 2
w_T ← 1 / (4 A_T) - 3
for each of the two real rows ρ of s_T = Σ_j ε_j U_{v_j} do - 4
split ρ into ρ_free, on the free unknowns, and the value c of the pinned terms - 5
N ← N + w_T ρ_freeᵀ ρ_free; r ← r − w_T c ρ_freeᵀ - 6
solve N x = r - 7
return U, with the pinned values and x
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 has the sparsity of the mesh graph with 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 is singular. A mesh whose dual graph is not connected needs two pins on each part. Two pins also give a singular 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 , , , , apex , and the four side triangles , , , . Pin and . The angle at the apex in each triangle is , so the angles at the apex add up to , not . No flat map keeps all angles, and the minimum energy is not zero.
| step | value |
|---|---|
| L1, triangle | frame , , and the same for the other three |
| L2 | |
| L3 | , so |
| L6 | , , |
| energy | , , image area , and |
The image is a rhombus with the diagonals , of length , and , of length , and the four triangles are counterclockwise. The total surface area is , so the pins also fix the scale: the image area is 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 . 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 on a grid and on an 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, , so the term of is . It is zero exactly when the linear map is , a similarity that keeps the orientation. Expanding the squares gives , the Dirichlet energy minus the signed area of the image, twice. is a sum of squares, so the normal equations give a minimum, which is unique when the only map with and both pins at 0 is zero. A map with 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. is a triangle mesh whose dual graph (triangles, adjacent when they share an edge) is connected, and every triangle has positive area. Each triangle has a frame: corner positions that form a counterclockwise triangle congruent to , with area . Write (indices mod 3). A map assigns to each vertex, and is the affine map of the frame of with . The energy is
Two distinct vertices and are pinned to given values. LSCM returns the solution of the normal equations of in the free values.
Claim.
- , where , and is the signed area of the image.
- if and only if for complex , that is, is a similarity that keeps the orientation, or a constant.
- The minimizer with the two pins is unique if and only if there is no development of that maps and to the same point. A development is a map that is, on every triangle, a rotation and translation of its frame.
- If is planar, with its own coordinates as frames, and and have different positions, the minimizer is the similarity of the plane that takes and to their pins, and there.
Step 1 (the gradient of a corner function). Let be the affine function on the frame with and on the opposite edge, from to . Its gradient is perpendicular to that edge, points to , and has length , where is the height. Multiplying by turns a complex number by . For a counterclockwise triangle, points from the edge into the triangle. So, as a complex number , the gradient is .
Step 2 (part 1). On , , so with ,
So . With and , , which gives the first form. Expanding the squares, . The last bracket is the determinant of the Jacobian of , and times it is the signed area of the image of . Summing over gives .
Step 3 (part 2). An affine map of the plane is , and . So if and only if . In particular , and if and only if every has the form .
Step 4 (the normal equations). is a sum of squares of real linear forms in the real and imaginary parts of the , each with the weight . With the pinned values fixed, is a quadratic function of the free values , with symmetric and positive semidefinite. Its minimizers are exactly the solutions of , which always exist for a least squares problem. The minimizer is unique if and only if is nonsingular, that is, if and only if the only map with and is , because the kernel of is the set of free values with , which is of the map with the pins set to 0.
Step 5 (part 3). Let with and . By Step 3, on each triangle. Let and share the edge , of length . Both frames are congruent to the 3D triangles, so , and
So , and since the dual graph is connected, for all . If , every is constant, two triangles at an edge have the same constant, so is one constant, and gives , which is false. So , and is a rotation and a translation of the frame on each triangle: a development that maps and to .
Conversely, let be a development with . Then has with , so by Step 3, and . So the kernel is not trivial. This proves part 3.
Three cases where uniqueness follows at once. (a) If and are two vertices of one triangle, a development is one to one on that triangle, so . (b) If a development exists, the angles of the triangles around each inner vertex add up to a multiple of : 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 , 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 and to different points because their positions differ. So the minimizer is unique. The similarity with $S(x_p) = $ pin of and $S(x_q) = $ pin of exists, as , and has for every , because and (the six products cancel in pairs). So , which is the minimum, and the unique minimizer is . With int or Fraction coordinates and pins, the normal equations have rational entries and Gaussian elimination solves them exactly, so the computed map equals exactly.
Termination. LSCM builds and in one pass over the triangles and solves one linear system of size by elimination, which stops after operations. If is singular, by part 3 the input has a development that maps the pins to one point, and the code reports this.
Remark (Desbrun, Meyer and Alliez). Their discrete conformal parameterization minimizes , which by part 1 is . So with the same pins both methods give the same map.
Complexity
For vertices the system has unknowns, and has about nonzero blocks, one for each vertex and each edge. Building it takes time, one pass over the triangles. Dense Gaussian elimination, as in the code of this page, takes time and space. The sparsity graph is the mesh graph, which is planar for a disk, so a sparse Cholesky factorization with nested dissection takes time and 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 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 , which is , and writes 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 , 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 and in turn. The angles at the centre add up to , and LSCM with the pins at vertices 0 and 3 gives two triangles with ORIENT2D . 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.
# 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
- 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
- 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
- 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)
- 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.
| 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 67C616 Edit this page History Report an error Markdown