Algorithmadvanced
Variational shape approximation
Also called VSA, Cohen-Steiner-Alliez-Desbrun approximation.
Cohen-Steiner, Alliez and Desbrun's Lloyd-like partition of a mesh into connected regions, each fit by a plane under a normal error, then a coarse polygon mesh from them.
- Time
- O(k s n log n) worst
- Space
- Θ(n) extra
- Where
- k = the number of proxies; n = the number of faces; s = the largest number of rounds for each number of proxies
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David Cohen Steiner, Pierre Alliez, Mathieu Desbrun, 2004
Variational shape approximation (VSA) cuts a triangle mesh into connected regions and fits a plane, the proxy, to each region, so that the faces of each region are nearly parallel to their plane. From the regions it then builds a coarse polygon mesh, with one polygon for each region. Cohen-Steiner, Alliez and Desbrun (2004) cast this as a clustering of the faces and solved it in the style of Lloyd's algorithm: fit the best proxy to each region, then grow the regions again from the proxies, and repeat. The error of a face against a proxy with unit normal is , with the area and the unit normal of , and the total over all faces is called the energy. It depends on the normals and not on the positions, so it follows the shape of the surface and ignores where the plane is. The fit step is optimal, and with one guard on the growth step the energy never increases.
In plain words
Think of a model made of many tiny triangles, and the job is to describe it with a few large flat pieces. Each flat piece covers a group of triangles that face almost the same way.
Start with one group and one direction. Find the triangle that disagrees most with its group, and start a new group there. Then improve the groups. For each group, find the direction that fits its triangles best. Then let the groups grow again, like ink spreading from one triangle of each group, where each triangle goes to the group whose ink reaches it first. Keep the new groups only if they fit at least as well. Repeat until there are as many groups as you want.
At the end, the corners where three or more groups meet become the corners of the flat pieces.
The problem
The input is a connected triangle mesh in which each face has area and unit normal , and an integer , at most the number of faces. The output is a partition of the faces into at most connected regions with unit proxy normals of small energy
and a coarse polygon mesh with one polygon for each region. The exact minimum of over connected partitions is not the target. Like k-means, the method returns a local optimum.
The algorithm
VSA(faces with areas a_T and unit normals n_T, k, s)- 1
R ← one region that holds all faces; N_1 ← the normal of the first face - 2
repeat - 3
for up to s rounds do - 4
for each region i do m ← Σ over T in R_i of a_T n_T; if m ≠ 0 then N_i ← m / |m| - 5
seed_i ← the face T of R_i with the least error a_T |n_T − N_i|² - 6
R′ ← grow the regions from the seeds, always giving the free face of least error to the region that reached it - 7
if R′ ≠ R and E(R′, N) ≤ E(R, N) then R ← R′ else stop the rounds - 8
fit N again as in L4; if there are k proxies or E(R, N) = 0 then return R, N - 9
i ← the region with the largest total error; T ← the face of R_i with the largest error - 10
move T to a new region, with the proxy normal n_T
Line L4 is the fit step. The best unit normal of a set of faces is the unit vector along , because for unit . On a closed surface the sum over all faces is 0, so line L4 keeps the old normal when . Lines L5 and L6 are the flood. A priority queue holds entries (error, face, region). Each seed pushes its neighbours with their error to the proxy of its region. The flood pops the entry of least error, and if its face is still free, gives the face that region and pushes the free neighbours of the face. So each region grows through shared edges and stays connected. Line L7 is the guard: the flood is not proved to decrease the energy, and it sometimes increases it, so the new partition is kept only when its energy is not larger. Lines L9 and L10 add proxies one at a time where the error is worst.
The coarse mesh. An anchor is a vertex where three or more regions meet. It moves to the mean of its projections to the proxy planes of those regions, where the plane of region has the normal and passes through the area-weighted centroid of . The polygon of a region is the list of the anchors on its border, in order. The code does only this step. The paper also adds anchors on a border between two regions that has too few of them, and splits long polygon edges where the border is far from the straight edge.
Example
A box. Take the surface of the box , each side cut into a grid of squares and each square into two triangles, 48 faces in total. The area is . With one proxy the energy is , because the area-weighted normals of a closed surface sum to 0 and so every normal fits equally badly. As proxies are added, the energy goes down:
| 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|
| energy |
At the regions are the six sides and the proxy normals are the six axis directions. The anchors are the 8 corners, at their exact positions, and the coarse mesh is the box itself, as 6 rectangles. With a grid on the sides the result is the same.
A sphere. On the icosphere of radius 1 with 1280 faces, the energy at , and is , and . It halves each time doubles. At the coarse mesh has 8 anchors and 6 quadrilaterals, connected like the faces of a cube. At there are 19 anchors and at there are 44.
Correctness
The proof file shows these facts.
- The fit is optimal. For a set of faces with total area and , the error of a unit normal is , with equality exactly at , by the Cauchy-Schwarz inequality. So line L4 does not increase the energy.
- The classic assignment is optimal, the flood is not. With the proxies fixed, giving each face to its proxy of least error minimizes the energy over all partitions. That is the second step of Lloyd's algorithm, and it can make regions that are not connected. The flood of line L6 keeps the regions connected but is not proved to decrease the energy. In 30 runs from random seeds on perturbed icospheres with 320 faces, 119 of 337 flood steps increased it, by up to 16%.
- The energy never increases. The fit does not increase it, the guard of line L7 rejects a flood that would, and an insertion sets the error of the moved face to 0 and changes nothing else.
- It stops with connected regions. On a connected mesh every face gets a region, each region is connected and holds its seed, and an insertion never empties a region. The rounds are bounded by and there are at most insertions. If the energy reaches 0 first, the algorithm stops with fewer regions.
- The box. A partition of a box into 6 regions has energy 0 exactly when the regions are the 6 sides. From the 6 side normals with one seed on each side, the flood returns the 6 sides, and the anchors are the 8 corners.
The method returns a local optimum, not the partition of least energy. That the full algorithm reaches the six sides on every subdivision of every box is not proved. The tests check it on two subdivisions.
Proof: The fit step of variational shape approximation is optimal, the guarded loop never increases the L^(2,1) energy and stops, and a box gives its six sidesfull
Setup. The mesh is connected and each face has an area and a unit normal . A partition puts each face in one region, and each region has a unit proxy normal . The energy is
For a set of faces write and . The fit step sets when and keeps otherwise. The flood step takes, in each region, the face of least error as the seed of that region, and then grows the regions from the seeds with a priority queue: it pops the entry of least error, and if the face of the entry is still free, it gives the face the region of the entry and pushes each free neighbour with its error to the proxy of that region.
Lemma 1 (the best normal). For a set of faces and a unit vector ,
If , equality holds exactly for . If , every unit gives .
Proof. For unit vectors, . Multiply by and add. By the Cauchy-Schwarz inequality , with equality for unit exactly when .
Lemma 2 (the fit step does not increase the energy). If is the result of the fit step on , then .
Proof. is a sum of one term for each region, and the term of depends only on . By Lemma 1, the new minimizes its term, or the term does not depend on and is kept.
Lemma 3 (the best assignment, without connectivity). For fixed proxies , the partition that gives each face to a proxy of least error minimizes over all partitions.
Proof. With fixed, is a sum of one term for each face, and each term depends only on the region of that face.
So the two steps of Lloyd's algorithm, the fit of Lemma 2 and the assignment of Lemma 3, never increase . Variational shape approximation does not use the assignment of Lemma 3, because it can give regions that are not connected. The flood step gives each face to the first region that reaches it in the order of the queue, which need not be a region of least error for that face. It is not proved to decrease the energy, and it can increase it: in 30 runs from random seeds on perturbed icospheres with 320 faces, 119 of the 337 flood steps increased the energy, by up to 16%. For this reason the algorithm keeps the new partition only if its energy is not larger (line L7).
Lemma 4 (the flood). On a connected mesh, the flood gives a region to every face. Each region of the result holds the seed of that region and is connected through shared edges. Distinct regions have distinct seeds, so no region is empty.
Proof. A face gets the region only when an entry for it, pushed by a neighbour that has region , is popped. By induction on the order of the pops, each face of region is joined to the seed of by a path of faces of region . Suppose a face is free at the end. The mesh is connected and the seeds are not free, so there are adjacent faces and with not free and free at the end. When got its region, was free, so an entry for was pushed. That entry was popped before the queue was empty, and was free then, so got a region, a contradiction. Each face is in one region, so the seeds of distinct regions are distinct faces.
Theorem 1 (the energy never increases). Let be the energies after each step of the algorithm: each fit, each accepted flood, and each insertion of a proxy. Then .
Proof. A fit step does not increase the energy by Lemma 2. A flood is accepted only if its energy with the same proxies is not larger (line L7), and a rejected flood changes nothing. An insertion moves one face to a new region with the proxy normal . The error of becomes , and the region and the proxy of every other face do not change. So no step increases .
Theorem 2 (termination and the number of regions). Let the number of faces. The algorithm stops, and it returns a partition with nonempty regions, or fewer regions and energy 0.
Proof. The rounds of line L3 stop after at most rounds. Each pass of the outer loop either stops at line L8 or adds one proxy, so there are at most passes. It remains to show that every region stays nonempty. A flood keeps all regions nonempty by Lemma 4. An insertion happens only when , right after a fit. It takes a face of largest error from a region of largest total error, so the total error of is positive. If were the single face , the fit would have set , and its error would be 0. So has at least two faces and is not empty after leaves.
The algorithm finds a local optimum in this sense: no single step of it decreases further. It is not proved to find the partition of least energy for the given , and the energy it reaches depends on the order of the insertions.
Theorem 3 (a box). Let the mesh be the surface of a box, each of the six sides cut into triangles, and let .
- A partition into 6 regions has energy 0, for some proxies, if and only if its regions are the six sides.
- If the 6 proxy normals are the 6 outward side normals and each region has its seed on its own side, the flood returns the six sides.
- For the six sides with their fitted proxies, the coarse mesh has the 8 corners of the box as its anchors and the 6 rectangles of the sides as its polygons.
Proof. (1) By Lemma 1 the least energy of a region is . Since , with equality only if all in the region are equal, the energy is 0 only if each region lies in one side. Six nonempty regions cover the six sides, and each side needs a region of its own, so there is one region for each side. Conversely, each side has and energy 0.
(2) For a face of a side with normal , the error to the proxy of its own side is 0, to the proxy of an adjacent side , and to the proxy of the opposite side . An entry with error 0 is pushed only by the region of the same side. We show by induction on the pops that, while some side still has a free face, there is an entry of error 0 for a free face in the queue, and that every face labelled so far has the region of its own side. Take a side with a free face. The faces of that are labelled carry region , by the induction, and they include the seed. The triangles of a side are connected through shared edges, so a free face of is adjacent to a labelled face of . When got region , was free, so an entry was pushed, and it is still in the queue or it has been popped. If it was popped while was free, would have region . So it is in the queue. Every entry with positive error is popped only after all entries with error 0, so the next face that gets a region gets it with error 0, which means from its own side. So every face gets the region of its own side.
(3) A vertex inside a side touches 1 region, a vertex inside an edge of the box touches 2, and a corner touches 3. So the anchors are the 8 corners. The proxy point of a side is the area-weighted mean of the centroids of its faces, which lies on the plane of the side, and a corner lies on the planes of its 3 sides, so each projection, and so the mean, is the corner itself. The border of a side is the rectangle around it, which passes through its 4 corners in order, so each polygon is the rectangle of a side.
That the full algorithm, which starts from one proxy and adds the others one at a time, reaches the six sides on every subdivision of every box is not proved here. The tests check it on the box of size with two subdivisions.
Complexity
One fit costs for faces. One flood pushes each face at most once from each neighbour, so at most entries, and costs with a binary heap. Each insertion costs . With at most rounds for each of the numbers of proxies, the time is on the real RAM. The extra space is for the labels, the queue and the face data. On the sphere of the example with , the run made 330 floods, about 14 for each number of proxies.
Properties
- Monotone with the guard. The energy never increases, and the run stops.
- Connected regions. Each region is connected through shared edges, unlike plain clustering of the normals.
- Local optimum. The result depends on the first face and on the order of the insertions, like any Lloyd-style method.
- Normal-based. The energy does not change when a region moves along its plane or the whole mesh is translated, and it does not change under scaling except by the factor of the areas. It captures how the surface bends, not how far it is from the planes.
- Deterministic. With the same mesh, and tie-breaking, the output is the same.
Variants and improvements
- The error. The squared distance of the surface to the proxy plane, integrated over each face. The best plane of a region passes through its centroid with the normal of least variance, the eigenvector of the smallest eigenvalue of the covariance matrix of the region. It controls the distance but follows the normals less well.
- Other proxies. Spheres, cylinders and general quadrics as proxies give coarse models of mechanical parts with curved faces.
- Proxy deletion and teleportation. Cohen-Steiner, Alliez and Desbrun also merge two adjacent regions whose union costs little and move a proxy from a region of low error to one of high error, to escape poor local optima.
- A target error instead of . Insert proxies until the energy falls below a threshold.
- Interactive control. The user can add, remove or move proxies between rounds and see the regions change, because each round is fast.
When to use it
Use VSA to turn a dense scan or a tessellated model of a mostly flat object, such as a building or a mechanical part, into a few large polygons, for simplification, for reverse engineering, or as a segmentation into nearly flat patches. For a coarse triangle mesh that stays close in distance, edge collapse with quadric error metrics is simpler and faster. For curved organic shapes, where no small number of planes fits well, a segmentation into meaningful parts, for example by the shape diameter function, is the better tool.
Pitfalls
- No guard. Without line L7 the energy can go up between rounds, and the loop can cycle between partitions.
- The zero sum. On a closed surface, or on any region whose area-weighted normals cancel, and is undefined. Keep the old normal.
- A poor start. Random seeds can leave two proxies on one flat side and none on another. Insert proxies at the worst face, or teleport them.
- Too few anchors. A border between two regions that meets no third region, such as the circle between two halves of a cylinder, has no anchor, and its region gives no polygon. Add anchors on such borders.
- Disconnected meshes. The flood does not cross between components. Run the method on each component.
- Units. The energy is an area, so a threshold on it must scale with the model.
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 mx1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small tools for triangle meshes and dense linear algebra, used by the mx1 pages.
Points are tuples of three numbers. Faces are tuples of three vertex indices,
counterclockwise when seen from outside, so that the face normals point out.
Only the standard library is used. The geometric signs (an obtuse angle, the
side of a plane) are decided exactly, with Fraction, from the float input.
The linear solvers work on float input and on Fraction input.
"""
import math
from fractions import Fraction
# ---------------------------------------------------------------- vectors
def add(a, b):
return tuple(x + y for x, y in zip(a, b))
def sub(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 norm(a):
return math.sqrt(dot(a, a))
def unit(a):
n = norm(a)
return tuple(x / n for x in a)
def exact(p):
"""The exact rational value of a point with float or Fraction coordinates."""
return tuple(Fraction(x) for x in p)
def sign(x):
return (x > 0) - (x < 0)
def dot_sign(a, b, c):
"""The exact sign of (b - a) . (c - a): positive for an acute angle at a, negative for an obtuse one."""
a, b, c = exact(a), exact(b), exact(c)
return sign(dot(sub(b, a), sub(c, a)))
def orient3d(a, b, c, d):
"""The exact sign of det(b - a, c - a, d - a): positive when d lies on the side of the plane abc that its normal points to."""
a, b, c, d = exact(a), exact(b), exact(c), exact(d)
return sign(dot(cross(sub(b, a), sub(c, a)), sub(d, a)))
# ---------------------------------------------------------------- topology
def edges(faces):
"""The undirected edges as sorted pairs, in sorted order."""
s = set()
for f in faces:
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
s.add((min(i, j), max(i, j)))
return sorted(s)
def neighbours(n, faces):
nb = [set() for _ in range(n)]
for f in faces:
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
nb[i].add(j)
nb[j].add(i)
return [sorted(s) for s in nb]
def edge_faces(faces):
"""Map each undirected edge to the list of the faces that hold it."""
m = {}
for t, f in enumerate(faces):
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
m.setdefault((min(i, j), max(i, j)), []).append(t)
return m
def face_adjacency(faces):
"""For each face, the sorted list of the faces that share an edge with it."""
adj = [set() for _ in faces]
for fs in edge_faces(faces).values():
for a in fs:
for b in fs:
if a != b:
adj[a].add(b)
return [sorted(s) for s in adj]
def boundary_vertices(faces):
b = set()
for (i, j), fs in edge_faces(faces).items():
if len(fs) == 1:
b.update((i, j))
return b
def vertex_faces(n, faces):
vf = [[] for _ in range(n)]
for t, f in enumerate(faces):
for i in f:
vf[i].append(t)
return vf
# ---------------------------------------------------------------- face geometry
def face_cross(points, f):
"""cross(b - a, c - a): twice the area times the unit normal."""
a, b, c = (points[i] for i in f)
return cross(sub(b, a), sub(c, a))
def face_area(points, f):
return norm(face_cross(points, f)) / 2
def face_normal(points, f):
return unit(face_cross(points, f))
def centroid(points, f):
a, b, c = (points[i] for i in f)
return tuple((x + y + z) / 3 for x, y, z in zip(a, b, c))
def cot_at(a, b, c):
"""The cotangent of the angle at a in the triangle a, b, c."""
u, v = sub(b, a), sub(c, a)
return dot(u, v) / norm(cross(u, v))
def cotan_weights(points, faces):
"""w_ij = (cot alpha_ij + cot beta_ij) / 2, with alpha and beta the angles opposite the edge ij."""
w = {}
for f in faces:
for k in range(3):
i, j, o = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
e = (min(i, j), max(i, j))
w[e] = w.get(e, 0.0) + cot_at(points[o], points[i], points[j]) / 2
return w
def stiffness_rows(n, weights):
"""The cotangent stiffness matrix C = -L as a list of dict rows: C_ij = -w_ij, C_ii = sum of w_ij."""
C = [dict() for _ in range(n)]
for (i, j), w in weights.items():
C[i][j] = C[i].get(j, 0) - w
C[j][i] = C[j].get(i, 0) - w
C[i][i] = C[i].get(i, 0) + w
C[j][j] = C[j].get(j, 0) + w
return C
def barycentric_area(points, faces):
A = [0.0] * len(points)
for f in faces:
a = face_area(points, f) / 3
for i in f:
A[i] += a
return A
def mixed_area(points, faces):
"""The mixed Voronoi area of Meyer, Desbrun, Schroeder and Barr (2003).
A triangle with no obtuse angle gives each corner its Voronoi part,
(|ij|^2 cot k + |ik|^2 cot j) / 8. An obtuse triangle gives half its area
to the obtuse corner and a quarter to each other corner.
"""
A = [0.0] * len(points)
for f in faces:
P = [points[i] for i in f]
obtuse = [dot_sign(P[k], P[(k + 1) % 3], P[(k + 2) % 3]) < 0 for k in range(3)]
area = face_area(points, f)
for k in range(3):
i, pj, pk, pi = f[k], P[(k + 1) % 3], P[(k + 2) % 3], P[k]
if not any(obtuse):
eij, eik = sub(pj, pi), sub(pk, pi)
A[i] += (dot(eij, eij) * cot_at(pk, pi, pj) + dot(eik, eik) * cot_at(pj, pi, pk)) / 8
else:
A[i] += area / 2 if obtuse[k] else area / 4
return A
def mean_curvature_normal(points, faces, area="mixed"):
"""K_i = (1 / (2 A_i)) sum_j (cot alpha_ij + cot beta_ij)(x_i - x_j), which is 2 H n_i with outward n_i."""
A = mixed_area(points, faces) if area == "mixed" else barycentric_area(points, faces)
w = cotan_weights(points, faces)
K = [[0.0, 0.0, 0.0] for _ in points]
for (i, j), wij in w.items():
d = sub(points[i], points[j])
for c in range(3):
K[i][c] += wij * d[c]
K[j][c] -= wij * d[c]
return [tuple(x / A[i] for x in K[i]) for i in range(len(points))]
def area_gradient(points, faces):
"""The gradient of the total area with respect to each vertex, summed face by face.
For a face with corner i and other corners j, k, the gradient at i is
(cot k (x_i - x_j) + cot j (x_i - x_k)) / 2, where cot j is the cotangent of the angle at j.
"""
g = [[0.0, 0.0, 0.0] for _ in points]
for f in faces:
for k in range(3):
i, j, l = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
pi, pj, pl = points[i], points[j], points[l]
cl, cj = cot_at(pl, pi, pj), cot_at(pj, pi, pl)
for c in range(3):
g[i][c] += (cl * (pi[c] - pj[c]) + cj * (pi[c] - pl[c])) / 2
return [tuple(v) for v in g]
def total_area(points, faces):
return sum(face_area(points, f) for f in faces)
# ---------------------------------------------------------------- dense linear algebra
def identity(n, one=1):
return [[one if i == j else 0 * one for j in range(n)] for i in range(n)]
def transpose(A):
return [list(r) for r in zip(*A)]
def mat_mul(A, B):
Bt = transpose(B)
return [[sum(a * b for a, b in zip(r, c)) for c in Bt] for r in A]
def mat_vec(A, x):
return [sum(a * b for a, b in zip(r, x)) for r in A]
def det3(A):
return dot(A[0], cross(A[1], A[2]))
def solve_dense(A, b):
"""Solve A x = b by Gaussian elimination with partial pivoting. Exact on Fraction input."""
n = len(A)
M = [list(A[i]) + [b[i]] for i in range(n)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(M[r][c]))
if M[p][c] == 0:
raise ValueError("singular matrix")
M[c], M[p] = M[p], M[c]
for r in range(c + 1, n):
f = M[r][c] / M[c][c]
if f:
for k in range(c, n + 1):
M[r][k] -= f * M[c][k]
x = [0] * n
for r in range(n - 1, -1, -1):
x[r] = (M[r][n] - sum(M[r][k] * x[k] for k in range(r + 1, n))) / M[r][r]
return x
def cholesky(A):
"""The lower triangular L with A = L L^T, for a symmetric positive definite A."""
n = len(A)
L = [[0.0] * n for _ in range(n)]
for j in range(n):
d = A[j][j] - sum(L[j][k] ** 2 for k in range(j))
if d <= 0:
raise ValueError("matrix is not positive definite")
L[j][j] = math.sqrt(d)
for i in range(j + 1, n):
L[i][j] = (A[i][j] - sum(L[i][k] * L[j][k] for k in range(j))) / L[j][j]
return L
def cholesky_solve(L, b):
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 _rotation(theta):
"""c, s of the Jacobi rotation for the cotangent theta of twice its angle."""
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1))
c = 1 / math.sqrt(1 + t * t)
return c, t * c
def jacobi_eigen(A, tol=1e-15, sweeps=100):
"""Eigenvalues (ascending) and unit eigenvectors of a symmetric matrix, by cyclic Jacobi rotations."""
n = len(A)
a = [[float(x) for x in r] for r in A]
v = identity(n, 1.0)
for _ in range(sweeps):
off = sum(a[i][j] ** 2 for i in range(n) for j in range(i + 1, n))
if off <= tol * tol * sum(a[i][i] ** 2 for i in range(n)) or off == 0:
break
for p in range(n):
for q in range(p + 1, n):
if a[p][q] == 0:
continue
c, s = _rotation((a[q][q] - a[p][p]) / (2 * a[p][q]))
for k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p], a[k][q] = c * akp - s * akq, s * akp + c * akq
for k in range(n):
apk, aqk = a[p][k], a[q][k]
a[p][k], a[q][k] = c * apk - s * aqk, s * apk + c * aqk
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p], v[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
order = sorted(range(n), key=lambda k: a[k][k])
return [a[k][k] for k in order], [[v[i][k] for i in range(n)] for k in order]
def svd3(A, sweeps=60):
"""A = U diag(s) V^T for a 3 x 3 matrix, with s descending and U, V orthogonal (one-sided Jacobi)."""
U = [[float(x) for x in r] for r in A]
V = identity(3, 1.0)
for _ in range(sweeps):
done = True
for p, q in ((0, 1), (0, 2), (1, 2)):
al = sum(U[i][p] ** 2 for i in range(3))
be = sum(U[i][q] ** 2 for i in range(3))
ga = sum(U[i][p] * U[i][q] for i in range(3))
if ga == 0 or abs(ga) <= 1e-15 * math.sqrt(al * be):
continue
done = False
c, s = _rotation((be - al) / (2 * ga))
for M in (U, V):
for i in range(3):
mp, mq = M[i][p], M[i][q]
M[i][p], M[i][q] = c * mp - s * mq, s * mp + c * mq
if done:
break
sig = [math.sqrt(sum(U[i][k] ** 2 for i in range(3))) for k in range(3)]
order = sorted(range(3), key=lambda k: -sig[k])
s = [sig[k] for k in order]
cols = [[U[i][k] for i in range(3)] for k in order]
vcols = [[V[i][k] for i in range(3)] for k in order]
tiny = 1e-13 * max(s[0], 1e-300)
u = [tuple(x / s[k] for x in cols[k]) for k in range(3) if s[k] > tiny]
while len(u) < 3: # complete U where A has a null direction
if not u:
u.append((1.0, 0.0, 0.0))
elif len(u) == 1:
e = min(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), key=lambda t: abs(dot(t, u[0])))
u.append(unit(cross(u[0], e)))
else:
u.append(cross(u[0], u[1]))
Um = [[u[k][i] for k in range(3)] for i in range(3)]
Vm = [[vcols[k][i] for k in range(3)] for i in range(3)]
return Um, s, Vm
def best_rotation(S):
"""The rotation R (det 1) that maximizes trace(R S): with S = U diag(s) V^T, R = V diag(1, 1, d) U^T, d = det(V U^T)."""
U, _, V = svd3(S)
d = 1.0 if det3(mat_mul(V, transpose(U))) > 0 else -1.0
return mat_mul(mat_mul(V, [[1.0, 0, 0], [0, 1.0, 0], [0, 0, d]]), transpose(U))
def rotation_matrix(axis, angle):
"""The rotation by angle about the unit vector axis (Rodrigues)."""
x, y, z = unit(axis)
c, s = math.cos(angle), math.sin(angle)
C = 1 - c
return [[c + x * x * C, x * y * C - z * s, x * z * C + y * s],
[y * x * C + z * s, c + y * y * C, y * z * C - x * s],
[z * x * C - y * s, z * y * C + x * s, c + z * z * C]]
# ---------------------------------------------------------------- test meshes
def orient_outward(points, faces):
"""Flip each face of a mesh around the origin so that its normal points away from the origin (exact test)."""
out = []
o = (0, 0, 0)
for f in faces:
a, b, c = (points[i] for i in f)
out.append(tuple(f) if orient3d(a, b, c, o) < 0 else (f[0], f[2], f[1]))
return out
def octahedron():
p = [(1.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, -1.0)]
f = [(0, 2, 4), (2, 1, 4), (1, 3, 4), (3, 0, 4), (2, 0, 5), (1, 2, 5), (3, 1, 5), (0, 3, 5)]
return p, orient_outward(p, f)
def icosahedron():
t = (1 + math.sqrt(5)) / 2
raw = [(-1, t, 0), (1, t, 0), (-1, -t, 0), (1, -t, 0), (0, -1, t), (0, 1, t), (0, -1, -t), (0, 1, -t),
(t, 0, -1), (t, 0, 1), (-t, 0, -1), (-t, 0, 1)]
p = [unit(tuple(float(x) for x in q)) for q in raw]
f = [(0, 11, 5), (0, 5, 1), (0, 1, 7), (0, 7, 10), (0, 10, 11), (1, 5, 9), (5, 11, 4), (11, 10, 2), (10, 7, 6),
(7, 1, 8), (3, 9, 4), (3, 4, 2), (3, 2, 6), (3, 6, 8), (3, 8, 9), (4, 9, 5), (2, 4, 11), (6, 2, 10),
(8, 6, 7), (9, 8, 1)]
return p, orient_outward(p, f)
def icosphere(level, radius=1.0):
"""The icosahedron with each triangle cut into four `level` times, projected to the sphere."""
p, f = icosahedron()
p = list(p)
for _ in range(level):
mid = {}
def m(i, j):
e = (min(i, j), max(i, j))
if e not in mid:
mid[e] = len(p)
p.append(unit(scale(0.5, add(p[i], p[j]))))
return mid[e]
nf = []
for a, b, c in f:
ab, bc, ca = m(a, b), m(b, c), m(c, a)
nf += [(a, ab, ca), (b, bc, ab), (c, ca, bc), (ab, bc, ca)]
f = nf
return [scale(radius, q) for q in p], f
def cylinder(radius, height, m, k, twisted=False):
"""An open tube of m vertices around and k + 1 rings, axis z, centred at the origin, normals outward.
Plain: each rectangle is cut by the same diagonal. Twisted: ring l is turned by l half steps,
so that each vertex has six neighbours, as in a grid of near-equilateral triangles.
"""
p = []
for l in range(k + 1):
z = height * l / k - height / 2
for s in range(m):
th = 2 * math.pi * (s + (l / 2 if twisted else 0)) / m
p.append((radius * math.cos(th), radius * math.sin(th), z))
f = []
for l in range(k):
for s in range(m):
a, b = l * m + s, l * m + (s + 1) % m
c, d = b + m, a + m
if twisted: # the ring above is turned half a step forward
f += [(a, b, d), (b, c, d)]
else:
f += [(a, b, c), (a, c, d)]
return p, f
def box_mesh(size, div):
"""The closed surface of the box [-a/2, a/2] x [-b/2, b/2] x [-c/2, c/2], each side a grid of div cells.
size = (a, b, c) may hold Fractions, div = (na, nb, nc) are the numbers of cells along each axis.
Each grid cell is cut into two triangles. The normals point out.
"""
index, p, f = {}, [], []
def vid(key):
if key not in index:
index[key] = len(p)
p.append(tuple(size[a] * Fraction(key[a], div[a]) - Fraction(size[a]) / 2 for a in range(3)))
return index[key]
for ax in range(3):
u, w = [a for a in range(3) if a != ax]
for side in (0, div[ax]):
out = 1 if side else -1
eu = [0, 0, 0]
ew = [0, 0, 0]
eu[u], ew[w] = 1, 1
flip = cross(eu, ew)[ax] != out
for s in range(div[u]):
for t in range(div[w]):
q = []
for ds, dt in ((0, 0), (1, 0), (1, 1), (0, 1)):
key = [0, 0, 0]
key[ax], key[u], key[w] = side, s + ds, t + dt
q.append(vid(tuple(key)))
tris = [(q[0], q[1], q[2]), (q[0], q[2], q[3])]
f += [(a, c, b) if flip else (a, b, c) for a, b, c in tris]
return p, f
def to_float(points):
return [tuple(float(x) for x in q) for q in points]
variational_shape_approximation.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variational-shape-approximation/. The authors are listed in prov/J5DY1Y.jsonl.
"""Variational shape approximation with planar proxies and the L^(2,1) error.
Cohen-Steiner, Alliez and Desbrun (SIGGRAPH 2004). Each region R_i of faces
has a proxy, a unit normal N_i and a point X_i. The error of a face T in R_i
is area(T) |n_T - N_i|^2, and the energy is the sum over all faces.
The loop alternates two steps, as in Lloyd's algorithm. The fit step sets
N_i to the unit vector along the sum of area(T) n_T over R_i, which is the
best normal for R_i. The partition step grows the regions again from one
seed face each, in order of error, so that each region stays connected. The
grown partition is kept only if its energy is not larger than the energy of
the old partition with the same proxies. With this guard the energy never
increases. Proxies are added one at a time, at the face with the largest
error in the region with the largest total error, until there are k.
coarse_mesh then puts an anchor at each vertex where three or more regions
meet, moved to the mean of its projections to the planes of those regions,
and gives each region the polygon of the anchors on its border, in order.
"""
import heapq
from mx1mesh import add, dot, face_adjacency, face_area, face_cross, scale, sub, unit
def face_data(points, faces):
areas = [face_area(points, f) for f in faces]
normals = [unit(face_cross(points, f)) for f in faces]
return areas, normals
def error(area, n, N):
d = sub(n, N)
return area * dot(d, d)
def energy(areas, normals, label, N):
return sum(error(areas[t], normals[t], N[label[t]]) for t in range(len(label)))
def fit(areas, normals, label, N):
"""The best unit normal of each region: unit(sum of area n_T), or the old normal if the sum is 0."""
m = [(0.0, 0.0, 0.0) for _ in N]
for t, i in enumerate(label):
m[i] = add(m[i], scale(areas[t], normals[t]))
return [unit(m[i]) if dot(m[i], m[i]) > 0 else N[i] for i in range(len(N))] # @line L4
def flood(areas, normals, adj, label, N):
"""Grow each region from its best face, always taking the free face with the least error to the proxy that reached it."""
best = {}
for t, i in enumerate(label):
e = error(areas[t], normals[t], N[i])
if i not in best or e < best[i][0]:
best[i] = (e, t)
new = [-1] * len(label)
heap, count = [], 0
for i in sorted(best): # @line L5
t = best[i][1]
new[t] = i
for u in adj[t]:
heapq.heappush(heap, (error(areas[u], normals[u], N[i]), count, u, i))
count += 1
while heap: # @line L6
_, _, t, i = heapq.heappop(heap)
if new[t] != -1:
continue
new[t] = i
for u in adj[t]:
if new[u] == -1:
heapq.heappush(heap, (error(areas[u], normals[u], N[i]), count, u, i))
count += 1
return new
def vsa(points, faces, k, iters=30):
"""Partition the faces of a connected mesh into at most k regions with planar proxies.
Returns (label, N, X, history): the region of each face, the proxy normals,
the proxy points (area-weighted centroids), and the energy after each step.
"""
areas, normals = face_data(points, faces)
adj = face_adjacency(faces)
label = [0] * len(faces) # @line L1
N = [normals[0]]
history = [energy(areas, normals, label, N)]
while True: # @line L2
for _ in range(iters): # @line L3
N = fit(areas, normals, label, N)
history.append(energy(areas, normals, label, N))
new = flood(areas, normals, adj, label, N)
if new != label and energy(areas, normals, new, N) <= history[-1]: # @line L7
label = new
history.append(energy(areas, normals, label, N))
else:
break
N = fit(areas, normals, label, N)
history.append(energy(areas, normals, label, N))
if len(N) >= k or history[-1] == 0: # @line L8
break
total = [0.0] * len(N)
for t, i in enumerate(label):
total[i] += error(areas[t], normals[t], N[i])
worst = max(range(len(N)), key=lambda i: total[i]) # @line L9
t = max((t for t in range(len(faces)) if label[t] == worst), key=lambda t: error(areas[t], normals[t], N[worst]))
label[t] = len(N) # @line L10
N = N + [normals[t]]
history.append(energy(areas, normals, label, N))
X = []
for i in range(len(N)):
a = sum(areas[t] for t in range(len(faces)) if label[t] == i)
c = (0.0, 0.0, 0.0)
for t in range(len(faces)):
if label[t] == i:
g = scale(1 / 3, add(add(points[faces[t][0]], points[faces[t][1]]), points[faces[t][2]]))
c = add(c, scale(areas[t] / a, g))
X.append(c)
return label, N, X, history
def coarse_mesh(points, faces, label, N, X):
"""Anchors where three or more regions meet, and for each region the loops of anchors on its border.
Returns (anchor_points, polygons), where each polygon is (region, list of anchor indices).
A border loop with fewer than three anchors gives no polygon.
"""
regions = [set() for _ in points]
for t, f in enumerate(faces):
for v in f:
regions[v].add(label[t])
anchor, anchor_points = {}, []
for v, rs in enumerate(regions):
if len(rs) >= 3:
p = (0.0, 0.0, 0.0)
for i in rs: # project to the plane of each proxy and average
q = sub(points[v], scale(dot(sub(points[v], X[i]), N[i]), N[i]))
p = add(p, scale(1 / len(rs), q))
anchor[v] = len(anchor_points)
anchor_points.append(p)
owner = {}
for t, f in enumerate(faces):
for c in range(3):
owner[(f[c], f[(c + 1) % 3])] = label[t]
polygons = []
for i in sorted(set(label)):
nxt = {}
for t, f in enumerate(faces):
if label[t] != i:
continue
for c in range(3):
a, b = f[c], f[(c + 1) % 3]
if owner.get((b, a)) != i: # a border half-edge of the region
nxt.setdefault(a, []).append(b)
while nxt:
start = min(nxt)
loop, v = [], start
while True:
loop.append(v)
w = nxt[v].pop()
if not nxt[v]:
del nxt[v]
v = w
if v == start:
break
poly = [anchor[v] for v in loop if v in anchor]
if len(poly) >= 3:
polygons.append((i, poly))
return anchor_points, polygons
test_variational_shape_approximation.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variational-shape-approximation/. The authors are listed in prov/J5DY1Y.jsonl.
import math
import random
from fractions import Fraction
from mx1mesh import box_mesh, dot, exact, face_adjacency, icosphere, norm, scale, to_float, unit
from variational_shape_approximation import coarse_mesh, energy, face_data, fit, flood, vsa
def noisy_sphere(seed, level=2):
rng = random.Random(seed)
p, f = icosphere(level)
return [scale(1 + 0.3 * rng.random(), q) for q in p], f
def test_the_fit_step_gives_the_best_normal() -> None:
rng = random.Random(7)
p, f = noisy_sphere(1)
areas, normals = face_data(p, f)
label = [0 if normals[t][2] > 0.3 else 1 for t in range(len(f))]
N = fit(areas, normals, label, [(1.0, 0.0, 0.0), (1.0, 0.0, 0.0)])
best = energy(areas, normals, label, N)
for i in (0, 1): # the closed form 2A - 2|m| of each region
A = sum(areas[t] for t in range(len(f)) if label[t] == i)
m = [sum(areas[t] * normals[t][c] for t in range(len(f)) if label[t] == i) for c in range(3)]
e = sum(areas[t] * norm(tuple(a - b for a, b in zip(normals[t], N[i]))) ** 2 for t in range(len(f)) if label[t] == i)
assert abs(e - (2 * A - 2 * norm(m))) < 1e-9
for _ in range(200):
Q = [unit((rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1))) for _ in range(2)]
assert energy(areas, normals, label, Q) >= best - 1e-12
def test_the_energy_never_increases() -> None:
for seed in range(4):
p, f = noisy_sphere(seed)
_, _, _, h = vsa(p, f, 10)
assert all(b <= a + 1e-12 for a, b in zip(h, h[1:]))
assert h[-1] < h[0]
def test_the_guard_is_needed() -> None:
# without the guard, growing the regions from random seeds can raise the energy
raised = 0
for seed in range(3):
rng = random.Random(seed)
p, f = noisy_sphere(seed)
areas, normals = face_data(p, f)
adj = face_adjacency(f)
k = 8
seeds = rng.sample(range(len(f)), k)
N = [normals[t] for t in seeds]
label = [max(range(k), key=lambda i: dot(normals[t], N[i])) for t in range(len(f))]
for i, t in enumerate(seeds):
label[t] = i
for _ in range(15):
N = fit(areas, normals, label, N)
new = flood(areas, normals, adj, label, N)
if energy(areas, normals, new, N) > energy(areas, normals, label, N) + 1e-12:
raised += 1
label = new
assert raised > 0
def test_regions_are_connected() -> None:
p, f = noisy_sphere(5)
label, N, _, _ = vsa(p, f, 12)
adj = face_adjacency(f)
for i in set(label):
faces = [t for t in range(len(f)) if label[t] == i]
seen, stack = {faces[0]}, [faces[0]]
while stack:
t = stack.pop()
for u in adj[t]:
if label[u] == i and u not in seen:
seen.add(u)
stack.append(u)
assert len(seen) == len(faces)
def test_a_box_gives_its_six_sides() -> None:
size = (2, 3, 5)
for div in ((2, 2, 2), (3, 4, 5)):
p, f = box_mesh(size, div)
p = to_float(p)
label, N, X, h = vsa(p, f, 6)
assert h[-1] == 0 and len(N) == 6
axes = sorted(tuple(round(c) for c in n) for n in N)
assert axes == sorted([(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)])
_, normals = face_data(p, f)
for t in range(len(f)):
assert normals[t] == N[label[t]]
anchors, polygons = coarse_mesh(p, f, label, N, X)
corners = sorted((sx * size[0] / 2, sy * size[1] / 2, sz * size[2] / 2)
for sx in (-1, 1) for sy in (-1, 1) for sz in (-1, 1))
assert len(anchors) == 8
assert all(max(abs(a - b) for a, b in zip(x, y)) < 1e-12 for x, y in zip(sorted(anchors), corners))
assert len(polygons) == 6
for i, poly in polygons:
assert len(poly) == 4
q = [anchors[a] for a in poly]
assert all(abs(dot(x, N[i]) - dot(q[0], N[i])) < 1e-12 for x in q) # one side of the box
# Newell's normal of the quad points out, along the proxy (exact on the float values)
nw = [Fraction(0)] * 3
qe = [exact(x) for x in q]
for a, b in zip(qe, qe[1:] + qe[:1]):
nw[0] += (a[1] - b[1]) * (a[2] + b[2])
nw[1] += (a[2] - b[2]) * (a[0] + b[0])
nw[2] += (a[0] - b[0]) * (a[1] + b[1])
assert dot(nw, exact(N[i])) > 0
def test_fewer_than_six_proxies_leave_error_on_a_box() -> None:
p, f = box_mesh((2, 3, 5), (2, 2, 2))
p = to_float(p)
for k in range(1, 6):
label, N, _, h = vsa(p, f, k)
assert len(set(label)) == k and h[-1] > 0
assert math.isclose(vsa(p, f, 1)[3][-1], 2 * 62) # one proxy on a closed surface: m = 0, energy 2A
History
Lloyd described in 1957, and published in 1982, the alternation between the best representative of each cell and the best cell of each point, for quantization. It became the standard heuristic for k-means and for centroidal Voronoi tessellations. In 2004 Cohen-Steiner, Alliez and Desbrun applied it to shape approximation. They clustered the faces of a mesh with planar proxies, introduced the error on the normals, replaced the assignment step by a flood that keeps each region connected, and built a coarse polygon mesh from the regions. Later work used other proxies, such as spheres, cylinders and quadrics.
References
- David Cohen-Steiner, Pierre Alliez and Mathieu Desbrun, Variational shape approximation, ACM Transactions on Graphics 23(3), 2004, 905 to 914, the L^2 and L^(2,1) error metrics, the fit of the proxies, the partition by flooding with a priority queue, the insertion of proxies, and the extraction of the coarse mesh from the anchor vertices
- S. P. Lloyd, Least squares quantization in PCM, IEEE Transactions on Information Theory 28(2), 1982, 129 to 137, the alternation between the best representative of each cell and the best cell of each point, and the fact that neither step increases the error
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 J5DY1Y Edit this page History Report an error Markdown