Algorithmresearch
Boundary first flattening
Also called BFF.
Sawhney and Crane's conformal flattening that first fixes boundary scale factors or angles, then extends them inside by harmonic functions, with a few linear solves.
- Solves
- Mesh parameterization
- Time
- O(n^3) worstO(n^(3/2)) nested_dissectionO(n^2 + m) new_target
- Space
- O(n^2) extraO(n log n) nested_dissection
- Where
- m = the number of boundary vertices; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Rohan Sawhney, Keenan Crane, 2017
Boundary first flattening, BFF, computes a conformal flattening of a triangle mesh with the topology of a disk, and lets the user choose the shape of the boundary. A conformal map keeps angles and changes only the local scale, by a factor . On a smooth surface, the Cherrier formula says how changes the curvature of the boundary, so the user can give either the scale factors on the boundary or the turning angles of the boundary, and the other one follows from a linear solve. BFF builds the boundary curve first and then fills in the interior with a harmonic map. All the steps are linear, and they use one Laplace matrix, so a new boundary target costs only solves with a factored matrix. It solves the mesh parameterization problem.
In plain words
To flatten a curved patch without bending its small angles, each small piece may only grow or shrink. How much each piece grows is one number per point, and these numbers are tied to the curvature of the surface.
BFF uses this tie at the edge of the patch. You say either how much the edge should stretch, or how sharply the flat outline should turn at each edge point, for example to get a rectangle. The method computes the other one, draws the flat outline from the turns and the lengths, and closes it with the smallest change.
The inside is then filled the smoothest way that fits the outline, the way a soap film fills a wire loop.
The problem
The input is a triangle mesh with vertices, with the topology of a disk, whose triangles all have positive area and whose faces are oriented so that the outward normal follows the right-hand rule. The boundary is one loop , in the order of the face orientation. The input also has one of two targets:
- Scale factors. A number for each boundary vertex. The image of a boundary edge should have the length . With the boundary keeps its lengths.
- Turning angles. An angle for each boundary vertex, with . The image of the boundary should turn left by at . A polygon with corners has at its corners, or any other angles that add up to , and 0 at the other boundary vertices.
The output is a point in the plane for each vertex. The map should be close to conformal and meet the target on the boundary.
The algorithm
The smooth relation. If a metric is changed to , the Gaussian curvature and the geodesic curvature of the boundary change as
where is the Laplace-Beltrami operator and is the derivative along the outward normal. The second equation is the Cherrier formula. A flat image needs , that is inside. Given on the boundary, this Poisson problem fixes , and then gives the new boundary curvature. Given the new boundary curvature, the same problem with Neumann data fixes up to a constant.
The discrete relation. Let be the angle defect at an inner vertex , the discrete Gaussian curvature, and the turning angle at a boundary vertex , where is the sum of the corner angles at the vertex. Let be the cotangent Laplacian with for an edge and rows that add up to 0. BFF uses
and asks for . The subscripts and are the inner and boundary vertices.
BFF(M, target)- 1
compute the corner angles, Ω_I, k_B and the cotangent Laplacian A - 2
if the target is the scale factors u_B then - 3
solve A_II u_I = −Ω_I − A_IB u_B ▷ Dirichlet problem - 4
k̃_B ← k_B + (A u)_B - 5
else ▷ the target is k̃_B, with Σ k̃_B = 2π - 6
solve A u = (−Ω_I, k̃_B − k_B), with u = 0 at one vertex ▷ Neumann problem - 7
l̃_t ← e^{(u_i + u_j)/2} ℓ_ij for each boundary edge t = (b_t, b_{t+1}) - 8
φ_t ← k̃_1 + ⋯ + k̃_t; T_t ← (cos φ_t, sin φ_t) - 9
l*_t ← l̃_t − l̃_t (λ · T_t), with λ such that Σ_t l*_t T_t = 0 - 10
γ(b_1) ← 0; γ(b_{t+1}) ← γ(b_t) + l*_t T_t - 11
solve A_II x_I = −A_IB γ for each of the two coordinates ▷ harmonic extension - 12
return (γ on the boundary, x inside)
Lines L2 to L6 turn one kind of boundary data into the other. Line L3 is a Poisson problem with the curvature as its source, and line L4 reads off the new turning angles. Line L6 is the inverse: the system is singular because kills the constants, and it is solvable because the right side adds up to 0 (see the correctness section), so one vertex is fixed.
Lines L7 to L10 draw the boundary. The edge leaves in the direction , after the curve has turned by at . The asked lengths and the angles do not in general give a closed polygon, because the discrete relation is only an approximation of the smooth one. Line L9 changes the lengths by the least amount, in the weighted norm , that closes the polygon. The minimizer has the form of line L9 by a Lagrange multiplier , and solves the system . The angles are not changed.
Line L11 extends the boundary curve inside. The two coordinates of a conformal map are harmonic functions, so in the smooth setting the harmonic extension of the boundary values is the conformal map itself. Sawhney and Crane also give a variant that extends one coordinate and takes the other as its harmonic conjugate, which is closer to conformal on coarse meshes.
Degenerate cases. Turning angles that do not add up to have no solution, and the code raises an error. If all the directions are parallel, the system of line L9 is singular. If the asked polygon is far from closed, line L9 can give a length that is 0 or negative, and the output boundary then crosses itself.
Example
Take the pyramid of the LSCM and ARAP pages: base corners , , , , apex , side triangles , , , . The boundary loop is .
Target , keep the boundary lengths.
| step | value |
|---|---|
| L1 | apex angles each, so ; base corners have two angles of , so ; , |
| L3 | |
| L4 | , so at each corner |
| L7 | for all four edges |
| L9 | the square closes, so , no change |
| L10 | |
| L11 | apex at , the centre |
The image is a square of side 2 with the apex at its centre, so the four side edges have length instead of . The apex has the scale factor , so the region near it shrinks, as a conformal map must do near a point of positive curvature. ARAP gives a square of side on the same pyramid instead, because it trades angles for lengths.
Target turning angles , a triangle. Line L6 gives for the vertices to . Line L7 asks for the lengths , which do not close. Line L9 changes them to . The output is an equilateral triangle of side with vertex 3 at the midpoint of the side from vertex 2 to vertex 0, and its turning angles are to . The large change of the lengths comes from the coarse mesh: four triangles are a poor model of a conformal map.
Measured on finer meshes. On 5 random disks of 37 vertices and 18 boundary vertices (a hexagonal grid with jitter, lifted to a random quadratic surface, seeds 0 to 4):
| target | largest relative change of a length at L9 | turning angles met to | flipped triangles |
|---|---|---|---|
| to | (not asked) | 0 | |
| rectangle, at 4 vertices | to | 0 |
The flips were checked with ORIENT2D, the orientation test, evaluated exactly on the float coordinates converted to rationals. A float evaluation of that sign is not reliable for tiny triangles, because of catastrophic cancellation; exact predicates avoid it. This is the robustness problem of geometry. The numbers are measurements on these meshes, not bounds.
Correctness
The proof in proofs/correctness.md shows the following.
- For every choice of , the angles of line L4 add up to . This uses the discrete Gauss-Bonnet theorem, for a disk, and the fact that the columns of add up to 0.
- is positive definite, so lines L3 and L11 have unique solutions. The system of line L6 has a solution exactly when , and the solution is unique up to a constant. Lines L3 to L4 and line L6 are inverse maps: from the of line L4, line L6 gives back up to a constant.
- Key invariant. The polygon of line L10 is closed, its turning angle at each is (when all ), and is the unique closest closed choice of lengths to in the weighted norm. If the asked polygon closes, .
- If is planar and , the output is congruent to the input.
So the turning angles that were asked for are met exactly, up to rounding, and the lengths that were asked for are met up to the smallest change that closes the boundary. The proof does not show that the interior map has no flipped triangle, or that the output is exactly conformal in any discrete sense.
Proof: BFF turns boundary scale factors into turning angles and back, meets the asked angles exactly, and changes the asked lengths by the least amount that closes the boundaryfull
Setting. is a connected triangle mesh with the topology of a disk, with inner vertices, boundary vertices in one loop , edges and triangles, all of positive area. at an inner vertex and at a boundary vertex, where is the sum of the corner angles at the vertex. is the cotangent Laplacian, for an edge with opposite angles and (one of them absent on the boundary), for non-adjacent , and . The algorithm and its lines L1 to L12 are as on the page.
Claim.
- For every , the angles of line L4 satisfy .
- is positive definite. The system of line L6 has a solution if and only if ; the solution is unique up to adding a constant, and fixing at one vertex makes it unique. Lines L3 to L4 and line L6 are inverse to each other, up to the constant.
- The polygon of line L10 is closed, its turning angle at is when all and , and is the unique minimizer of over all with , provided the directions are not all parallel. If then .
- If lies in the plane, its triangles are counterclockwise and it is embedded, then with the output is the image of the input under a rotation and a translation.
- (Termination.) The algorithm does a fixed, finite number of operations: one pass over the triangles, at most three linear solves, one solve and two passes over the boundary.
Step 1 (discrete Gauss-Bonnet for a disk). Every triangle has angle sum , so the sum of all corner angles is . Each triangle has three edges, inner edges lie in two triangles and the boundary edges in one, so . Then
since a disk has Euler characteristic .
Step 2 (part 1). is symmetric and its rows add up to 0, so its columns add up to 0, and for every . Line L3 says . So
Step 3 (the Dirichlet energy). For a function on the vertices, extend it linearly over each triangle , of area . The same computation as in Steps 1 and 2 of the proof of the ARAP parameterization page, done for a scalar function, gives over the three edges of , with the angle opposite. Adding over the triangles, . If , then on each triangle, so is constant on each triangle, and since is connected, is one constant. So is positive semidefinite with kernel the constants. Differentiating in also gives , where is the hat function of vertex .
Step 4 (part 2). For on the inner vertices, extend it by 0 on the boundary to . Then , because is not constant (it is 0 on the boundary and not 0 somewhere). So is positive definite and line L3 has one solution. For line L6, is symmetric with kernel the constants, so its range is the set of vectors orthogonal to the constants: has a solution if and only if . Here by Step 1. Two solutions differ by an element of the kernel, a constant. With fixed at one vertex , the matrix without row and column is positive definite by the argument above with in place of the boundary, so the reduced system has one solution. That solution also satisfies row : all rows of add up to , and all rows but row are 0.
For the inverse property, let and come from lines L3 and L4. Then and , so solves the system of line L6 with these , and line L6 returns . Conversely, if comes from line L6, then solves line L3 with its own , by the inner rows of the system, and line L3 has only one solution; line L4 then gives back by the boundary rows.
Step 5 (part 3). By line L9, , by the choice of . The matrix is positive semidefinite, and only if is orthogonal to every , which for means that all are parallel. So is invertible when they are not. The problem subject to has a strictly convex objective, since every , and linear constraints. Its Lagrange condition is for all , that is, with . For a convex objective with linear constraints this condition is sufficient for a minimum, and strict convexity makes the minimizer unique. meets the condition and the constraint, so it is the minimizer. If then and .
By line L10, the edge goes from in the direction , at the angle , when . The turning angle at is the angle from to , which is for , and for it is by part 1, the same direction change. Since , this is the signed turning angle. After the last edge the polygon is back at because .
Step 6 (part 4). An embedded planar mesh with counterclockwise triangles has angle sum at each inner vertex, so , and at each boundary vertex is the turning angle of the input boundary polygon. With , line L3 is , so , line L4 gives , and line L7 gives , the input lengths. The input boundary is a closed polygon with these lengths and turning angles, so for its own edge directions , which are the turned by one fixed angle. Hence too, and by part 3, . A polygon is fixed up to a rotation and a translation by its edge lengths and its turning angles, so on the boundary for a rotation and translation .
For line L11, let be an affine function of the plane, such as a coordinate of . At an inner vertex , by Step 3, , where is the star of , because is constant. By the divergence theorem, , because on the boundary of the star. So the coordinates of solve line L11, and by part 2 they are its only solution. So the output is applied to the input.
Step 7 (part 5). The steps are the ones listed in part 5. Each solve is with a positive definite matrix by part 2, or with of Step 5, so the elimination finishes without a zero pivot in exact arithmetic. There is no loop whose length depends on the data except the passes over the vertices, triangles and boundary.
What is not claimed. The proof does not show that the interior map of line L11 has every triangle counterclockwise, that the output boundary is a simple curve when some , or that the result is close to conformal by any stated bound.
Complexity
For vertices and boundary vertices, line L1 takes time. Lines L3, L6 and L11 are solves with or with without one row and column, which do not depend on the target. With dense elimination, as in the code of this page, each takes time and space. With sparse Cholesky factorization and nested dissection on the planar mesh graph, the factorization takes time and space, and each solve time. Lines L7 to L10 take time. The matrices are factored once, so a new target costs only back substitutions, dense or sparse, and for the boundary.
Properties
- Proved. Exact boundary angles: the output boundary turns by the asked angles, up to rounding.
- Proved. The asked lengths are changed only by the smallest weighted change that closes the polygon, and not at all when the asked polygon closes.
- Proved. A planar mesh with comes back congruent to itself.
- Linear. Every step is a linear solve with a fixed matrix, or a 2 by 2 solve. There is no iteration and no start map.
- Not guaranteed. The interior can have flipped triangles, because the cotangent weights can be negative, and the boundary can cross itself when the asked target is far from what the surface allows.
- Approximately conformal. The discrete relation is a discretization of the smooth one, and the page proves no bound on the angle distortion of the result.
Variants and improvements
- Cone singularities. The paper puts curvature at a few inner vertices, the cones, and cuts the mesh through them. Then the area distortion of a conformal map can be made much smaller. Choosing the cones is a separate problem.
- Target shapes. The paper uses the same two boundary maps to flatten onto a disk and onto a given boundary curve.
- Harmonic conjugate. Line L11 can extend only one coordinate and compute the other as its conjugate, which is closer to conformal.
- Nonlinear discrete conformal maps. Discrete conformal equivalence changes the lengths exactly by and solves a convex nonlinear problem for exact target angles inside and on the boundary. It is slower but its result is exactly a discrete conformal map in its sense.
- Other conformal maps. LSCM also needs one linear solve, but it does not let the user choose the boundary. ARAP trades angles for lengths.
When to use it
Use it when a conformal map must have a given outline, for example a rectangle for a texture atlas or a polygon that fits a cutting sheet, or when a user changes the boundary target many times and each change must be fast. With it is a good default free-boundary conformal map. It needs a disk; cut a closed or higher-genus surface first along a cut graph. Check the result with an exact orientation test. If injectivity is required, use a method that guarantees it.
Pitfalls
- Angles that do not add up to . A user who asks for a rectangle by setting four angles to and forgets to set all other boundary angles to 0 gives line L6 a right side that does not add up to 0. A solver that ignores the singular row then returns a that meets none of the angles.
- Wrong sign of the Laplacian. Some texts use the negative semidefinite Laplacian. Putting that matrix into lines L3 and L6 without changing the signs of the right sides gives instead of . With a turning-angle target, line L7 then asks for times the lengths, the regions that should shrink grow, and line L9 must make large changes to close the curve.
- Exterior angle against interior angle. is minus the angle sum, the turning of the boundary. Using the angle sum itself at line L4 gives angles whose sum is not , so the directions of line L8 do not wind around once, and no change of the lengths at line L9 gives a simple closed curve.
- Expecting exact lengths. The asked lengths are met only if the asked polygon closes. Line L9 changes them, by up to in the rectangle test above and on the coarse pyramid. A target that needs exact lengths must allow the angles to change instead.
- Clamping cotangents. Setting negative cotangent weights to 0 at line L1 keeps the rows of adding up to 0, so the angles still add up to , but line L11 then no longer reproduces linear functions, and a planar mesh does not come back congruent to itself.
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/boundary-first-flattening/. The authors are listed in prov/HE01QC.jsonl.
"""Boundary first flattening (Sawhney and Crane 2017), with a dense solver.
A conformal change of metric with log scale factor u changes the discrete
curvature by the cotangent Laplacian A (positive semidefinite, with
A_ij = -(cot a + cot b)/2 for an edge ij):
new curvature = old curvature + A u,
at interior vertices (angle defect Omega) and at boundary vertices (turning
angle k). A flat image needs the new Omega to be 0 at the interior vertices.
Given the scale factors on the boundary (Dirichlet data), the code finds the
new turning angles, and given the turning angles (Neumann data), it finds
the scale factors. It then builds the boundary polygon, closes it by the
smallest weighted change of its lengths, and extends it to the interior by
a harmonic map.
"""
import math
from mx2geom import boundary_loop, corner_angle, length, solve
def curvatures_and_laplacian(vertices, faces):
"""The cotangent Laplacian (dense), the angle sum at each vertex and the boundary loop."""
n = len(vertices)
a = [[0.0] * n for _ in range(n)]
angle_sum = [0.0] * n
for tri in faces:
ls = [length(vertices[tri[(k + 1) % 3]], vertices[tri[(k + 2) % 3]]) for k in range(3)]
for k in range(3):
# ls[k] is the edge opposite corner k.
theta = corner_angle(ls[k], ls[(k + 1) % 3], ls[(k + 2) % 3])
angle_sum[tri[k]] += theta
w = 0.5 / math.tan(theta)
i, j = tri[(k + 1) % 3], tri[(k + 2) % 3]
a[i][j] -= w
a[j][i] -= w
a[i][i] += w
a[j][j] += w
return a, angle_sum, boundary_loop(faces)
def dirichlet_to_neumann(a, angle_sum, loop, u_boundary):
"""Scale factors u_B on the boundary -> (u at all vertices, new turning angles k~ on the boundary)."""
n = len(a)
on_b = set(loop)
inner = [v for v in range(n) if v not in on_b]
u = [0.0] * n
for v, x in zip(loop, u_boundary):
u[v] = x
if inner:
rows = [[a[i][j] for j in inner] for i in inner]
rhs = [[-(2 * math.pi - angle_sum[i]) - sum(a[i][b] * u[b] for b in loop)] for i in inner]
for i, x in zip(inner, solve(rows, rhs)): # @line L3
u[i] = x[0]
k_new = [(math.pi - angle_sum[b]) + sum(a[b][j] * u[j] for j in range(n)) for b in loop] # @line L4
return u, k_new
def neumann_to_dirichlet(a, angle_sum, loop, k_target):
"""Turning angles k~ on the boundary (adding up to 2 pi) -> u at all vertices, with u = 0 at loop[0]."""
n = len(a)
if abs(sum(k_target) - 2 * math.pi) > 1e-9:
raise ValueError("the target turning angles must add up to 2 pi")
target = [-(2 * math.pi - angle_sum[v]) for v in range(n)]
for b, k in zip(loop, k_target):
target[b] = k - (math.pi - angle_sum[b])
# A u = target has a one-dimensional kernel (the constants); fix u at loop[0].
fix = loop[0]
free = [v for v in range(n) if v != fix]
rows = [[a[i][j] for j in free] for i in free]
x = solve(rows, [[target[i]] for i in free]) # @line L6
u = [0.0] * n
for v, xv in zip(free, x):
u[v] = xv[0]
return u
def boundary_polygon(vertices, loop, u, k_new):
"""The closed boundary polygon with turning angles k_new and lengths near e^((u_i+u_j)/2) l_ij.
Returns the points, the asked lengths and the lengths after closing.
"""
m = len(loop)
lt = []
for t in range(m):
i, j = loop[t], loop[(t + 1) % m]
lt.append(math.exp((u[i] + u[j]) / 2) * length(vertices[i], vertices[j])) # @line L7
phi, tang = 0.0, []
for t in range(m):
# The edge from loop[t] to loop[t+1] leaves vertex loop[t], where the curve turns by k_new[t].
phi += k_new[t]
tang.append((math.cos(phi), math.sin(phi))) # @line L8
# Close the curve: minimize sum (l* - l~)^2 / l~ subject to sum l* T = 0, a 2 x 2 system.
g = [[sum(lt[t] * tang[t][r] * tang[t][c] for t in range(m)) for c in range(2)] for r in range(2)]
gap = [sum(lt[t] * tang[t][r] for t in range(m)) for r in range(2)]
lam = solve(g, [[gap[0]], [gap[1]]])
ls = [lt[t] - lt[t] * (tang[t][0] * lam[0][0] + tang[t][1] * lam[1][0]) for t in range(m)] # @line L9
pts, p = {}, (0.0, 0.0)
for t in range(m):
pts[loop[t]] = p # @line L10
p = (p[0] + ls[t] * tang[t][0], p[1] + ls[t] * tang[t][1])
return pts, lt, ls
def harmonic_extension(a, loop, pts, n):
"""Extend the boundary positions to the interior: (A x)_i = 0 at every interior vertex."""
on_b = set(loop)
inner = [v for v in range(n) if v not in on_b]
out = [pts.get(v) for v in range(n)]
if inner:
rows = [[a[i][j] for j in inner] for i in inner]
rhs = [[-sum(a[i][b] * pts[b][c] for b in loop) for c in range(2)] for i in inner]
for i, x in zip(inner, solve(rows, rhs)): # @line L11
out[i] = (x[0], x[1])
return out
def bff(vertices, faces, u_boundary=None, k_target=None):
"""Flatten a disk mesh. Give the boundary scale factors u_boundary or the turning angles k_target.
With neither, u_boundary = 0 (keep the boundary lengths). Returns (points, info), where info has
the boundary loop, the scale factors u, the turning angles k, the asked boundary lengths and the
boundary lengths after closing, in the order of the loop.
"""
a, angle_sum, loop = curvatures_and_laplacian(vertices, faces) # @line L1
if k_target is None: # @line L2
if u_boundary is None:
u_boundary = [0.0] * len(loop)
u, k_new = dirichlet_to_neumann(a, angle_sum, loop, u_boundary)
else: # @line L5
k_new = list(k_target)
u = neumann_to_dirichlet(a, angle_sum, loop, k_new)
pts, asked, closed = boundary_polygon(vertices, loop, u, k_new)
out = harmonic_extension(a, loop, pts, len(vertices))
return out, {"loop": loop, "u": u, "k": k_new, "asked": asked, "lengths": closed} # @line L12
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_boundary_first_flattening.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-first-flattening/. The authors are listed in prov/HE01QC.jsonl.
import math
import random
from boundary_first_flattening import bff, curvatures_and_laplacian, dirichlet_to_neumann, neumann_to_dirichlet
from mx2geom import exact_orient2d
def hex_disk(r, rng, bend, jitter=0.15):
"""A hexagonal patch of the triangular lattice, jittered and lifted to z = a x^2 + b y^2 + c x y."""
pts, index = [], {}
for i in range(-r, r + 1):
for j in range(-r, r + 1):
if abs(i + j) <= r:
index[(i, j)] = len(pts)
pts.append((i + 0.5 * j + rng.uniform(-jitter, jitter), j * math.sqrt(3) / 2 + rng.uniform(-jitter, jitter)))
a, b, c = [rng.uniform(-bend, bend) for _ in range(3)]
verts = [(x, y, a * x * x + b * y * y + c * x * y) for x, y in pts]
faces = []
for (i, j), v in index.items():
if (i + 1, j) in index and (i, j + 1) in index:
faces.append((v, index[(i + 1, j)], index[(i, j + 1)]))
if (i + 1, j) in index and (i + 1, j - 1) in index:
faces.append((v, index[(i + 1, j - 1)], index[(i + 1, j)]))
return verts, faces
def turning_angles(pts, loop):
"""The signed exterior angle of the output polygon at each boundary vertex."""
m, out = len(loop), []
for t in range(m):
p0, p1, p2 = pts[loop[t - 1]], pts[loop[t]], pts[loop[(t + 1) % m]]
d0 = (p1[0] - p0[0], p1[1] - p0[1])
d1 = (p2[0] - p1[0], p2[1] - p1[1])
out.append(math.atan2(d0[0] * d1[1] - d0[1] * d1[0], d0[0] * d1[0] + d0[1] * d1[1]))
return out
def boundary_lengths(pts, loop):
return [math.dist(pts[loop[t]], pts[loop[(t + 1) % len(loop)]]) for t in range(len(loop))]
def rectangle_angles(m):
k = [0.0] * m
for c in range(4):
k[(c * m) // 4] = math.pi / 2
return k
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_new_turning_angles_add_up_to_two_pi():
for seed in range(5):
rng = random.Random(seed)
v, f = hex_disk(3, rng, 0.4)
a, s, loop = curvatures_and_laplacian(v, f)
_, k = dirichlet_to_neumann(a, s, loop, [rng.uniform(-0.5, 0.5) for _ in loop])
assert abs(sum(k) - 2 * math.pi) < 1e-12
def test_dirichlet_and_neumann_maps_are_inverse():
for seed in range(5):
rng = random.Random(10 + seed)
v, f = hex_disk(3, rng, 0.4)
a, s, loop = curvatures_and_laplacian(v, f)
u, k = dirichlet_to_neumann(a, s, loop, [rng.uniform(-0.5, 0.5) for _ in loop])
u2 = neumann_to_dirichlet(a, s, loop, k)
c = u[loop[0]] - u2[loop[0]]
assert max(abs(u[x] - u2[x] - c) for x in range(len(v))) < 1e-12
def test_asked_turning_angles_are_met():
for seed in range(5):
rng = random.Random(seed)
v, f = hex_disk(3, rng, 0.4)
_, info = bff(v, f)
m = len(info["loop"])
raw = [rng.uniform(0.0, 1.0) for _ in range(m)]
targets = [rectangle_angles(m), [2 * math.pi * x / sum(raw) for x in raw]]
for kt in targets:
pts, info = bff(v, f, k_target=kt)
got = turning_angles(pts, info["loop"])
assert max(abs(x - y) for x, y in zip(got, kt)) < 1e-9
got_len = boundary_lengths(pts, info["loop"])
assert max(abs(x - y) for x, y in zip(got_len, info["lengths"])) < 1e-9
def test_rectangle_and_length_modes_have_no_flips_on_small_disks():
for seed in range(5):
rng = random.Random(seed)
v, f = hex_disk(3, rng, 0.4)
for kt in (None, rectangle_angles(18)):
pts, _ = bff(v, f, k_target=kt)
for x, y, z in f:
assert exact_orient2d(pts[x], pts[y], pts[z]) > 0
def test_planar_disk_keeps_all_lengths():
for seed in range(3):
rng = random.Random(seed)
v, f = hex_disk(3, rng, 0.0)
pts, info = bff(v, f)
assert max(abs(x - y) for x, y in zip(info["asked"], info["lengths"])) < 1e-12
for x, y, z in f:
for p, q in ((x, y), (y, z), (z, x)):
assert abs(math.dist(pts[p], pts[q]) - math.dist(v[p], v[q])) < 1e-9
def test_asked_lengths_are_met_up_to_the_smallest_closing_change():
for seed in range(5):
rng = random.Random(seed)
v, f = hex_disk(3, rng, 0.4)
a, s, loop = curvatures_and_laplacian(v, f)
ub = [rng.uniform(-0.3, 0.3) for _ in loop]
pts, info = bff(v, f, u_boundary=ub)
assert max(abs(x - y) for x, y in zip(boundary_lengths(pts, loop), info["lengths"])) < 1e-9
asked, got, m = info["asked"], info["lengths"], len(loop)
tang, phi = [], 0.0
for t in range(m):
phi += info["k"][t]
tang.append((math.cos(phi), math.sin(phi)))
cost = sum((x - y) ** 2 / y for x, y in zip(got, asked))
# Every other closed polygon with the same directions changes the asked lengths at least as much.
for _ in range(200):
d = [rng.gauss(0, 0.05) for _ in range(m)]
# Project d onto the closing directions: sum d_t T_t = 0.
g = [[sum(tang[t][r] * tang[t][c] for t in range(m)) for c in range(2)] for r in range(2)]
h = [sum(d[t] * tang[t][r] for t in range(m)) for r in range(2)]
det = g[0][0] * g[1][1] - g[0][1] * g[1][0]
lam = ((g[1][1] * h[0] - g[0][1] * h[1]) / det, (g[0][0] * h[1] - g[1][0] * h[0]) / det)
d = [d[t] - tang[t][0] * lam[0] - tang[t][1] * lam[1] for t in range(m)]
other = [x + y for x, y in zip(got, d)]
assert sum((x - y) ** 2 / y for x, y in zip(other, asked)) >= cost - 1e-15
def test_pyramid_example():
pts, info = bff(PYRAMID_V, PYRAMID_F)
assert all(abs(k - math.pi / 2) < 1e-12 for k in info["k"])
assert abs(info["u"][4] + 0.480602) < 1e-6
assert max(abs(x - 2) for x in info["lengths"]) < 1e-12
centre = ((pts[0][0] + pts[2][0]) / 2, (pts[0][1] + pts[2][1]) / 2)
assert math.dist(centre, pts[4]) < 1e-12
k_t = [math.radians(x) for x in (120, 120, 120, 0)]
pts, info = bff(PYRAMID_V, PYRAMID_F, k_target=k_t)
got = turning_angles(pts, info["loop"])
assert max(abs(x - y) for x, y in zip(got, k_t)) < 1e-12
assert abs(info["lengths"][0] - 2.031153) < 1e-6
History
Rohan Sawhney and Keenan Crane published boundary first flattening in ACM Transactions on Graphics in 2017. Earlier conformal flattenings either fixed the boundary completely, as in harmonic maps, or left it free, as in LSCM, and the nonlinear methods of discrete conformal geometry could prescribe the boundary angles but needed an iterative solver. BFF uses the Cherrier formula, known from conformal geometry, to turn boundary data of one kind into the other by one linear solve, and so gives boundary control at the cost of a few back substitutions with one factored matrix.
References
- Rohan Sawhney and Keenan Crane, Boundary first flattening, ACM Transactions on Graphics 37(1), Article 5, 2017, the Cherrier formula and its discrete form, the Dirichlet-to-Neumann and Neumann-to-Dirichlet maps, the closing of the boundary curve, and the extension to the interior
- Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 5, Parametrization (conformal maps and the discrete Laplacian)
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 HE01QC Edit this page History Report an error Markdown