Algorithmcore
Tutte embedding
Also called barycentric mapping, Tutte parameterization.
Fixes the boundary on a convex polygon and puts each inner vertex at a convex combination of its neighbours, by one sparse linear solve, which gives a planar embedding.
- 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 inner vertices
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- W. T. Tutte, Michael S. Floater, 1963
The Tutte embedding maps a triangle mesh with the topology of a disk into the plane. It pins the boundary vertices, in their order, to the corners of a convex polygon, and it puts each inner vertex at a convex combination of its neighbours, with . These conditions are one sparse linear system. If the polygon is strictly convex, the solution is a one-to-one map of the mesh onto the polygon in which no triangle is flipped. This is the theorem of Tutte (1963) for graphs, see Tutte's spring theorem, in the form that Floater (1997, 2003) proved for triangulated disks. This page is the algorithm: the system, how to solve it, and how to check the result. The weights decide the shape of the map. Equal weights ignore the 3D geometry, and mean value coordinates keep it better. It is the simplest method for the mesh parameterization problem, and the only common one with a proof of global injectivity.
In plain words
Think of the mesh as a net of rubber bands. Nail the edge of the net to the rim of a convex frame, in order, and let go. Each free knot moves until the pulls of its bands cancel. Then it sits at a weighted average of its neighbours.
The net that settles lies flat in the frame. No band crosses another, and no small triangle of the net is turned over. This is true for any net that is one piece without holes, if the frame is convex and every band pulls a little.
A stiffer band pulls its knot closer. If the strengths follow the shape of the surface, the flat net looks more like the surface. To find where the knots settle, a program solves one set of linear equations.
The problem
The input is a triangle mesh with the topology of a disk: its Euler characteristic is , it has one boundary loop with , and its faces are oriented so that the outward normal follows the right-hand rule, which makes the boundary loop run counterclockwise when the mesh lies flat. The input also gives a strictly convex polygon with corners in counterclockwise order, and weights for each inner vertex and neighbour with . The output is a point for each vertex. Each triangle is mapped linearly, and the result must be one to one, with ORIENT2D for every triangle .
The algorithm
ORIENT2D is the orientation test. It is twice the signed area of the triangle.
TUTTE-EMBED(M, p, λ)- 1
b_1, ..., b_k ← BOUNDARY-LOOP(M) ▷ in the orientation of the faces - 2
x_{b_t} ← p_t for t = 1, ..., k - 3
number the inner vertices 1, ..., n - 4
A ← I_n (n × n); r ← 0 (n × 2) - 5
for each inner vertex i and each neighbour j of i do - 6
if j is inner then A[i][j] ← A[i][j] − λ_ij - 7
else r[i] ← r[i] + λ_ij · x_j - 8
solve A X = r ▷ two right-hand sides, x and y - 9
x_i ← X[i] for each inner vertex i - 10
return x CHECK(M, x)- 11
for each triangle (a, b, c) of M do - 12
if ORIENT2D(x_a, x_b, x_c) ≤ 0 then return false - 13
return true
Row of the system is . With symmetric weights, and , row times is the inner block of a weighted Laplacian matrix. That block is symmetric and positive definite, so Cholesky decomposition or the conjugate gradient method solves it. Uniform weights, , are of this kind. Mean value weights are not symmetric, and need an LU solve or an iterative method for general matrices.
The common weights are these:
| weights | proportional to | positive | reproduces a planar mesh |
|---|---|---|---|
| uniform (Tutte) | yes | no | |
| shape-preserving (Floater 1997) | built from a local flattening of the 1-ring | yes | yes |
| mean value (Floater 2003) | yes | yes | |
| harmonic, the cotangent Laplacian | not always | yes |
Degenerate cases. A boundary vertex at a straight angle of the polygon (a convex but not strictly convex polygon) is allowed only if no inner edge joins two vertices of the same side, see the proof. A vertex of degree 2 or a non-manifold vertex is not allowed, because then the mesh is not a disk; BOUNDARY-LOOP rejects such input. Negative weights break the theorem.
Example
Take a mesh with boundary vertices 0, 1, 2, 3 and inner vertices 4 and 5, and the triangles , , , , , . In 3D it could be a square roof with the ridge . Pin the boundary to the square , , , and use uniform weights. Vertex 4 has the neighbours 0, 1, 3, 5, and vertex 5 has 1, 2, 3, 4.
| step | value |
|---|---|
| L5 to L7, row of 4 | |
| L5 to L7, row of 5 | |
| L8 | , |
| L11, ORIENT2D | , , , , , for the six triangles |
All signs are positive, and the six values add up to , twice the area of the square, so the triangles tile the square.
Now pin a wheel with centre 5 and boundary 0, 1, 2, 3, 4 to the polygon , , , , , which is not convex. The centre goes to the average , and the five triangles have ORIENT2D values , , , , . Two triangles are flipped. The convexity of the boundary is necessary.
When the arithmetic is floating point. The solve is well conditioned for small meshes, but the triangles of a Tutte map can be very small. Take 31 nested triangles , , each joined to the next by a band of 6 triangles, with the outer one pinned to , , . With uniform weights the area shrinks by a factor of about 50 per layer, and the innermost triangle has ORIENT2D . The same system solved in IEEE double gives 49 of the 181 triangles a sign that is zero or negative, because the positions near the centre differ by less than the spacing of doubles there. The exact map has no such triangle. A float result with flips does not mean that the theorem fails. To decide the signs, compute in exact rational arithmetic, as in the code of this page, or test ORIENT2D with exact predicates on the computed points. Exact predicates on rounded points can still report a flip, because rounding moves the points. This is the robustness problem of geometry, and catastrophic cancellation is its cause.
Correctness
The system has one solution by the maximum principle: with the boundary fixed at 0, the largest value of a solution is attained at a vertex all of whose neighbours have the same value, and a path to the boundary carries it to 0. If the mesh has no chord, an inner edge between two boundary vertices, its graph is 3-connected, and Tutte's spring theorem gives a drawing with no crossings in which the triangles are the faces. The boundary triangles are counterclockwise, and two triangles at an inner edge lie on opposite sides of it, so all triangles are counterclockwise. A chord cuts the disk into two smaller disks on two strictly convex polygons, and induction finishes the proof. The full proof is below.
Proof: The Tutte embedding of a triangulated disk with a strictly convex boundary is a bijection with no flipped trianglefull
Claim. Let be a triangulated disk: a finite simplicial complex of triangles that is homeomorphic to a closed disk, with vertex set , where , , is the boundary cycle and is the set of inner vertices. The triangles are oriented coherently, and is the order in which the oriented boundary edges run. Let be the corners of a strictly convex polygon in counterclockwise order. For each let for the neighbours of , with . Then:
- the system , () has exactly one solution;
- every triangle of has ORIENT2D;
- the map that is linear on each triangle with at the vertices is a homeomorphism onto .
With Fraction weights and corners, TUTTE-EMBED computes this solution exactly and stops.
Step 1 (the system has one solution). The system has unknown points and vector equations, so it is enough to show that the homogeneous system has only the zero solution. Let with on and on , and let . Suppose , so is attained at an inner vertex . Since is a convex combination with positive weights of values that are at most , all neighbours of have the value . The graph of a disk is connected, so there is a path from to a boundary vertex. Along the path, each inner vertex has the value and so passes it on to the next vertex. The first boundary vertex of the path then has , which is false. So , and in the same way . So . Each coordinate of is such a system, so the solution exists and is unique.
Step 2 (a lemma on cycles). For a set of triangles, let be the set of edges that lie in exactly one triangle of .
Lemma A. If is not empty, then is not empty, and every vertex has an even number of edges of .
Proof. If is the set of all triangles, the boundary edges of lie in exactly one triangle, so they are in . If not, the dual graph of (triangles, adjacent when they share an edge) is connected, because is connected and every edge of a triangle is in at most two triangles, so some edge is shared by a triangle in and a triangle not in . This edge is in . For a vertex , count the pairs (triangle at , edge of at ). Each triangle gives 2, so the count is even. An edge at in two triangles of is counted twice, and an edge in one is counted once. So the number of edges of at is even.
A nonempty set of edges in which every vertex has even degree contains a cycle, and in a simplicial complex a cycle has at least 3 vertices.
Lemma B. Let be a nonempty set of vertices and let be the set of triangles with a vertex in . Every edge of either is a boundary edge of with an end in , or has both ends in , the vertices outside that have a neighbour in .
Proof. Let lie in . If has an end and is an inner edge, the second triangle at contains , so it is in , and is in two triangles of , which is false. So an edge of with an end in is a boundary edge. If has no end in , the third vertex of is in , and both ends of are its neighbours.
Step 3 (chords and 3-connectivity). A chord is an inner edge whose two ends are boundary vertices.
Lemma C. If has no chord and at least 4 vertices, the graph of is 3-connected.
Proof. We show that no set of one or two vertices separates (for one vertex, let ). Suppose that has at least two components. If a component has no boundary vertex, then by Lemma B every edge of has both ends in . So , which by Lemma A is nonempty and contains a cycle, a contradiction. So every component contains a boundary vertex. The boundary cycle without is one arc if , if or is inner, or if and are consecutive on the cycle, and then all boundary vertices except are in one component, and another component has no boundary vertex. So and are boundary vertices that are not consecutive, the cycle without them is two arcs and , and they lie in different components. Let be the component of . Its boundary vertices are the vertices of . By Lemma B, consists of the boundary edges of the path (they lie in one triangle, which has an end in ) and possibly the edge . The path has degree 1 at , so by Lemma A the edge exists and is in . As and are not consecutive, is a chord, a contradiction.
Step 4 (the theorem without chords). Suppose has no chord. If has no inner vertex, every inner edge would be a chord, so has no inner edge, and it is one triangle , which is mapped onto with positive orientation. Otherwise has at least 4 vertices, so is 3-connected by Lemma C. The disk gives a planar embedding of whose faces are the triangles of and the outside of the boundary cycle . By Tutte's spring theorem, in the form with positive weights stated there, the solution of Step 1 draws with straight edges and no crossings, its faces are the faces of the embedding, every inner face is a convex polygon with nonzero area, and the outer face is the outside of . So every triangle of is drawn as a nondegenerate triangle, and the triangles tile with disjoint interiors.
Orientation. Let be a triangle with a boundary edge, written in its orientation as . The face lies inside , which is to the left of the counterclockwise edge from to , so ORIENT2D. Let be an inner edge with triangles and . They are two faces of a planar straight-line drawing on the two sides of the segment . If and were on the same side of the line , both triangles would contain the points on that side near the middle of , and their interiors would meet. So and are strictly on opposite sides, which means ORIENT2D and ORIENT2D have the same sign. The dual graph is connected, so every triangle has the sign of a boundary triangle, which is positive. The map is linear and one to one on each triangle, the images tile with disjoint interiors, and two triangles that share an edge or a vertex are glued in the same way in and in the drawing. So is a continuous bijection from the compact space onto , hence a homeomorphism.
Step 5 (chords, by induction on the number of triangles). Suppose has a chord , with and not consecutive. The chord is an arc in from boundary to boundary whose inside lies in the interior of . By the Jordan curve theorem for polygonal curves, it cuts into two triangulated disks and , each a union of triangles of with fewer triangles than . The boundary of is the boundary arc and the chord, and the boundary of is the other arc and the chord. An inner vertex of is not on the chord, so all its triangles and neighbours are in , and its equation involves only vertices of . The corners are corners of , so they are the corners of a strictly convex polygon , in counterclockwise order, and the same holds for with the other corners. So the restriction of the solution to is the solution of the same problem on and , and by induction every triangle of is positive and maps onto one to one. The same holds for and . The polygons and meet only in the segment , which is the image of the chord in both. So is one to one on and maps it onto . Steps 4 and 5 prove parts 2 and 3 for every triangulated disk.
Step 6 (the computation). TUTTE-EMBED builds the matrix of Step 1 and solves it by Gaussian elimination. With Fraction entries every operation is exact, and the matrix is nonsingular, so no pivot is zero after the row exchanges of partial pivoting, and the result is the exact solution. The elimination does a finite number of operations on an matrix, so it stops. The signs of ORIENT2D on the exact positions are exact, which is what the tests check.
What the hypotheses do. If is convex but not strictly convex, some boundary vertices lie on a side of , and a chord between two vertices of the same side cuts off a disk whose boundary vertices all lie on that side. By the argument of Step 1, the inner vertices of lie on the same segment, so the triangles of have zero area. Floater (2003) shows that the map is still one to one if no such chord exists. If is not convex, Step 4 fails, and the test file has a wheel with a non-convex boundary whose Tutte map has a triangle with negative orientation. If some is negative, as cotangent weights can be, Step 1 can fail, and so can the rest.
Complexity
The matrix has rows, one per inner vertex, and about nonzero entries, because the average degree of a triangle mesh is about 6. Dense Gaussian elimination takes time and space, which is what the code of this page does for small meshes. The graph is planar, so nested dissection with a planar separator orders the elimination with fill and operations. In practice a sparse Cholesky or LU factorization or a preconditioned iterative solver is used.
In exact arithmetic the size of the numbers also counts. By Cramer's rule each coordinate is a ratio of two determinants, so its numerator and denominator have more bits than the input, and fraction-free elimination as in the Bareiss algorithm keeps the cost polynomial. For the nested triangles above, with 90 inner vertices, the exact coordinates have denominators of at most 25 digits.
Properties
- Globally injective. With a strictly convex boundary and positive weights, the map is one to one, which most other parameterization methods do not guarantee.
- Fixed boundary. The boundary shape is chosen in advance. A circle or a square is common, and the distortion near the boundary can be large.
- Linear. One linear solve, with no iteration and no initial guess. The solution depends continuously on the weights.
- Reproduction. With weights that reproduce linear functions, a planar mesh whose boundary is already convex is mapped to itself.
- Exact. With rational weights and corners, the positions and all orientation signs are exact.
Variants and improvements
- Shape-preserving weights (Floater 1997). For each inner vertex, flatten its 1-ring by keeping the edge lengths and scaling the angles to add up to , then take the barycentric coordinates of the centre in this flat ring. The map reproduces planar meshes, and it looks much more like the surface than the uniform map.
- Mean value weights (Floater 2003). The mean value coordinates are positive and have a closed formula, so they are now the usual choice.
- Harmonic weights. The cotangent weights of the cotangent Laplacian give the discrete harmonic map of Eck and coauthors and of Pinkall and Polthier. It minimizes the Dirichlet energy, but some weights are negative on obtuse triangles, and then flips can occur.
- Convex but not strictly convex boundary. Floater (2003) proves that the map stays one to one if no inner edge joins two vertices on the same side. This allows a square with many boundary vertices on each side.
- Free boundary. Least squares conformal maps and angle-based flattening let the boundary move, which lowers distortion but loses the guarantee.
- Tutte maps as a start. Methods that minimize a nonlinear distortion energy with barriers against flips start from a Tutte map, because it is the one map that is known to be valid.
When to use it
Use it when a valid map with no flips is more important than low distortion: as a start for a nonlinear optimizer, for remeshing a patch, or for a robust texture layout of a patch that is close to a disk. Use mean value weights unless the mesh is planar, and pick a boundary polygon that follows the shape of the boundary, such as the boundary vertices placed on a circle in proportion to their arc length. Do not use it for long thin patches or patches with a very non-convex boundary, because the distortion is large; mesh segmentation into more compact charts or a free-boundary method is better there.
Pitfalls
- A non-convex boundary. The theorem needs a convex polygon. Mapping the boundary to its own projection is a common mistake.
- Negative weights. Cotangent weights on obtuse triangles can be negative, and then the map can fold.
- Orientation of the boundary. The polygon must run in the same direction as the boundary loop in the face orientation. If not, every triangle comes out with a negative sign.
- Thin triangles. The map is one to one in exact arithmetic, but the triangles near a long, narrow part of the mesh can be so small that float coordinates collapse them. See the example.
- Not a disk. A mesh with a handle or two boundary loops must be cut into a disk first; the seams are the cost.
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
# 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)
tutte_embedding.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tutte-embedding/. The authors are listed in prov/BD4HAH.jsonl.
"""Tutte embedding of a triangulated disk.
The boundary loop is pinned to the corners of a convex polygon, and each
inner vertex is put at a convex combination of its neighbours. The
positions solve one linear system. With Fraction weights and Fraction
corners the solve is exact, so the signs of the triangle orientations of
the result are exact too.
"""
import math
from fractions import Fraction
from mp3geom import boundary_loop, neighbours, orient2d, solve
def circle_polygon(k, denominator=10**6):
"""k rational points in strictly convex position on the unit circle, counterclockwise.
The point of parameter t is ((1 - t^2) / (1 + t^2), 2 t / (1 + t^2)). It is
on the circle exactly, and an increasing t goes counterclockwise.
"""
pts = []
for i in range(k):
theta = -math.pi + 2 * math.pi * (i + 0.5) / k
t = Fraction(math.tan(theta / 2)).limit_denominator(denominator)
d = 1 + t * t
pts.append(((1 - t * t) / d, 2 * t / d))
return pts
def uniform_weights(faces):
"""lambda_ij = 1 / deg(i): Tutte's barycentric weights."""
nb = neighbours(faces)
return {i: {j: Fraction(1, len(nb[i])) for j in nb[i]} for i in nb}
def mean_value_weights(points, faces):
"""Floater's mean value weights of each vertex with respect to its 1-ring, in floating point.
lambda_ij is proportional to (tan(a_(j-1)/2) + tan(a_j/2)) / |x_j - x_i|,
where a_(j-1) and a_j are the angles at x_i of the two triangles at the
edge ij. tan(a/2) = |d x e| / (|d| |e| + d . e), which has no cancellation
for small angles.
"""
w = {}
for tri in faces:
for k in range(3):
i, j, l = tri[k], tri[(k + 1) % 3], tri[(k + 2) % 3]
d = [float(points[j][c]) - float(points[i][c]) for c in range(len(points[i]))]
e = [float(points[l][c]) - float(points[i][c]) for c in range(len(points[i]))]
dd, ee = math.sqrt(sum(x * x for x in d)), math.sqrt(sum(x * x for x in e))
de = sum(x * y for x, y in zip(d, e))
if len(d) == 2:
cr = abs(d[0] * e[1] - d[1] * e[0])
else:
cr = math.sqrt(sum(x * x for x in (d[1] * e[2] - d[2] * e[1], d[2] * e[0] - d[0] * e[2], d[0] * e[1] - d[1] * e[0])))
half = cr / (dd * ee + de)
wi = w.setdefault(i, {})
wi[j] = wi.get(j, 0.0) + half / dd
wi[l] = wi.get(l, 0.0) + half / ee
for i in w:
s = sum(w[i].values())
for j in w[i]:
w[i][j] /= s
return w
def tutte_embedding(faces, corners, weights=None):
"""Positions of all vertices of the disk `faces`.
corners[t] is the position of the t-th vertex of boundary_loop(faces).
weights[i][j] > 0 with sum over j equal to 1, for each inner vertex i;
the default is uniform_weights. Returns a dict vertex -> (x, y).
"""
loop = boundary_loop(faces) # @line L1
if len(corners) != len(loop):
raise ValueError("need one corner per boundary vertex")
if weights is None:
weights = uniform_weights(faces)
pos = {v: tuple(c) for v, c in zip(loop, corners)} # @line L2
inner = sorted(v for v in neighbours(faces) if v not in pos)
index = {v: r for r, v in enumerate(inner)} # @line L3
n = len(inner)
zero = 0.0 if any(isinstance(x, float) for i in inner for x in weights[i].values()) else Fraction(0)
a = [[zero + (r == c) for c in range(n)] for r in range(n)] # @line L4
b = [[zero, zero] for _ in range(n)]
for i in inner: # @line L5: row i is x_i - sum_j lambda_ij x_j = 0
r = index[i]
for j, lam in weights[i].items():
if j in index:
a[r][index[j]] -= lam # @line L6
else:
b[r][0] += lam * pos[j][0] # @line L7
b[r][1] += lam * pos[j][1]
if n:
x = solve(a, b) # @line L8
for i in inner:
pos[i] = (x[index[i]][0], x[index[i]][1]) # @line L9
return pos # @line L10
def is_valid_embedding(faces, pos):
"""True if every triangle has positive orientation. Exact for int or Fraction positions."""
for a, b, c in faces: # @line L11
if orient2d(pos[a], pos[b], pos[c]) <= 0:
return False # @line L12
return True # @line L13
test_tutte_embedding.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tutte-embedding/. The authors are listed in prov/BD4HAH.jsonl.
import random
from fractions import Fraction
from mp3geom import boundary_loop, directed_edges, euler_characteristic, neighbours, orient2d
from tutte_embedding import circle_polygon, is_valid_embedding, mean_value_weights, tutte_embedding, uniform_weights
def random_disk(rng, steps):
"""A random triangulated disk (a simplicial complex), oriented counterclockwise.
It starts from one triangle and applies random 1-to-3 face splits, inner
edge splits, boundary ears and inner edge flips.
"""
faces = [(0, 1, 2)]
nv = 3
for _ in range(steps):
op = rng.randrange(4)
de = directed_edges(faces)
if op == 0:
f = rng.randrange(len(faces))
a, b, c = faces.pop(f)
faces += [(a, b, nv), (b, c, nv), (c, a, nv)]
nv += 1
elif op == 1:
inner = [e for e in de if (e[1], e[0]) in de and e[0] < e[1]]
if not inner:
continue
a, b = rng.choice(inner)
f1, k1 = de[(a, b)]
f2, k2 = de[(b, a)]
c = faces[f1][(k1 + 2) % 3]
d = faces[f2][(k2 + 2) % 3]
faces = [t for g, t in enumerate(faces) if g not in (f1, f2)]
faces += [(a, nv, c), (nv, b, c), (b, nv, d), (nv, a, d)]
nv += 1
elif op == 2:
bd = [e for e in de if (e[1], e[0]) not in de]
a, b = rng.choice(bd)
faces.append((b, a, nv))
nv += 1
else:
inner = [e for e in de if (e[1], e[0]) in de and e[0] < e[1]]
if not inner:
continue
a, b = rng.choice(inner)
f1, k1 = de[(a, b)]
f2, k2 = de[(b, a)]
c = faces[f1][(k1 + 2) % 3]
d = faces[f2][(k2 + 2) % 3]
nb = neighbours(faces)
if d in nb[c] or len(nb[a]) <= 3 or len(nb[b]) <= 3:
continue
faces = [t for g, t in enumerate(faces) if g not in (f1, f2)]
faces += [(c, d, b), (d, c, a)]
return faces
def random_weights(rng, faces):
nb = neighbours(faces)
w = {}
for i in nb:
raw = {j: Fraction(rng.randint(1, 9)) for j in nb[i]}
s = sum(raw.values())
w[i] = {j: x / s for j, x in raw.items()}
return w
def polygon_area2(pts):
return sum(pts[i][0] * pts[(i + 1) % len(pts)][1] - pts[(i + 1) % len(pts)][0] * pts[i][1] for i in range(len(pts)))
def check_embedding(faces, corners, weights, pos):
loop = boundary_loop(faces)
for v, c in zip(loop, corners):
assert pos[v] == tuple(c)
for i in weights:
if i in loop:
continue
avg = (sum(l * pos[j][0] for j, l in weights[i].items()), sum(l * pos[j][1] for j, l in weights[i].items()))
assert avg == pos[i]
assert is_valid_embedding(faces, pos)
assert sum(orient2d(pos[a], pos[b], pos[c]) for a, b, c in faces) == polygon_area2(corners)
def test_example_of_the_page() -> None:
faces = [(0, 1, 4), (1, 5, 4), (1, 2, 5), (2, 3, 5), (3, 4, 5), (3, 0, 4)]
corners = [(0, 0), (12, 0), (12, 12), (0, 12)]
pos = tutte_embedding(faces, corners)
assert pos[4] == (Fraction(24, 5), Fraction(24, 5))
assert pos[5] == (Fraction(36, 5), Fraction(36, 5))
check_embedding(faces, corners, uniform_weights(faces), pos)
def test_random_disks_have_no_flipped_triangle() -> None:
rng = random.Random(20260512)
for trial in range(40):
faces = random_disk(rng, rng.randint(3, 30))
assert euler_characteristic(faces) == 1
k = len(boundary_loop(faces))
corners = circle_polygon(k)
for weights in (uniform_weights(faces), random_weights(rng, faces)):
pos = tutte_embedding(faces, corners, weights)
check_embedding(faces, corners, weights, pos)
def test_integer_convex_polygon() -> None:
# The points (i, i^2) are in strictly convex position, counterclockwise.
rng = random.Random(7)
for _ in range(20):
faces = random_disk(rng, 25)
k = len(boundary_loop(faces))
parabola = [(i, i * i) for i in range(k)]
w = random_weights(rng, faces)
check_embedding(faces, parabola, w, tutte_embedding(faces, parabola, w))
def test_nonconvex_boundary_can_flip() -> None:
# A wheel: centre 5, boundary 0..4 on a non-convex arrow.
faces = [(0, 1, 5), (1, 2, 5), (2, 3, 5), (3, 4, 5), (4, 0, 5)]
corners = [(0, 0), (10, 0), (10, 10), (9, 1), (0, 1)]
pos = tutte_embedding(faces, corners)
assert pos[5] == (Fraction(29, 5), Fraction(12, 5))
assert min(orient2d(pos[a], pos[b], pos[c]) for a, b, c in faces) < 0
assert not is_valid_embedding(faces, pos)
def test_mean_value_weights_reproduce_a_planar_mesh() -> None:
rng = random.Random(11)
done = 0
while done < 10:
faces = random_disk(rng, 20)
k = len(boundary_loop(faces))
corners = circle_polygon(k)
planar = tutte_embedding(faces, corners, random_weights(rng, faces))
w = mean_value_weights(planar, faces)
assert all(x > 0 for i in w for x in w[i].values())
again = tutte_embedding(faces, [tuple(float(c) for c in p) for p in corners], w)
for v in planar:
assert abs(again[v][0] - float(planar[v][0])) < 1e-9
assert abs(again[v][1] - float(planar[v][1])) < 1e-9
done += 1
def nested_triangles(layers):
"""Triangles a_t b_t c_t, t = 0..layers, each joined to the next by a band of 6 triangles."""
faces = []
for t in range(layers):
a, b, c, a2, b2, c2 = 3 * t, 3 * t + 1, 3 * t + 2, 3 * t + 3, 3 * t + 4, 3 * t + 5
faces += [(a, b, a2), (b, b2, a2), (b, c, b2), (c, c2, b2), (c, a, c2), (a, a2, c2)]
faces.append((3 * layers, 3 * layers + 1, 3 * layers + 2))
return faces
def test_nested_triangles_exact_and_float() -> None:
faces = nested_triangles(30)
corners = [(0, 0), (1, 0), (0, 1)]
exact = tutte_embedding(faces, corners)
signs = [orient2d(exact[a], exact[b], exact[c]) for a, b, c in faces]
assert all(s > 0 for s in signs)
assert min(signs) < Fraction(1, 10**49)
w = {i: {j: float(x) for j, x in d.items()} for i, d in uniform_weights(faces).items()}
approx = tutte_embedding(faces, [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], w)
wrong = sum(1 for a, b, c in faces if not orient2d(approx[a], approx[b], approx[c]) > 0)
assert wrong > 0
def test_circle_polygon_is_strictly_convex() -> None:
for k in range(3, 40):
pts = circle_polygon(k)
assert all(x * x + y * y == 1 for x, y in pts)
for i in range(k):
for j in range(k):
if j not in (i, (i + 1) % k):
assert orient2d(pts[i], pts[(i + 1) % k], pts[j]) > 0
History
W. T. Tutte published "How to draw a graph" in 1963. He proved that the barycentric drawing of a 3-connected planar graph with a convex outer face has no crossings, which also gives a new proof of Fáry's theorem for these graphs. Michael Floater used the same system with general positive weights to parameterize surface triangulations for surface fitting in 1997, and introduced shape-preserving weights. In 2003 he gave mean value coordinates and a direct proof that the map of a triangulated disk is one to one. Gortler, Gotsman and Thurston gave a short proof with discrete one-forms in 2006. The method is the reference point for every later parameterization method.
References
- W. T. Tutte, How to draw a graph, Proceedings of the London Mathematical Society s3-13(1), 1963, 743 to 767, the barycentric construction and the theorem that it draws a 3-connected planar graph without crossings
- Michael S. Floater, Parametrization and smooth approximation of surface triangulations, Computer Aided Geometric Design 14(3), 1997, 231 to 250, the parameterization by convex combinations with the boundary on a convex polygon, and the shape-preserving weights
- Michael S. Floater, One-to-one piecewise linear mappings over triangulations, Mathematics of Computation 72(242), 2003, 685 to 696, the proof that the convex combination map of a triangulated disk is one to one, also for a boundary that is convex but not strictly convex
- Michael S. Floater and Kai Hormann, Surface parameterization, a tutorial and survey, in Advances in Multiresolution for Geometric Modelling, Springer, 2005, 157 to 186, the section on barycentric mappings and the choice of weights
- Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 5, Parametrization (barycentric mapping with fixed boundary)
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 BD4HAH Edit this page History Report an error Markdown