Algorithmadvanced
Implicit fairing
Also called mean curvature flow smoothing, Desbrun fairing.
Desbrun, Meyer, Schröder and Barr's smoothing by backward Euler steps of mean curvature flow with the cotangent Laplacian, stable for large time steps.
- Time
- Θ(K s n) worst
- Space
- Θ(n) extra
- Where
- K = the number of steps; n = the number of vertices; s = the number of solver iterations per step
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mathieu Desbrun, Mark Meyer, Peter Schröder, Alan H. Barr, 1999
Implicit fairing smooths a mesh by taking backward Euler steps of mean curvature flow. Each step solves the sparse linear system
for each coordinate, where is the stiffness matrix of the cotangent Laplacian and the diagonal matrix of vertex areas, both taken at the old positions. A Laplacian smoothing step is the explicit form of the same flow and is stable only for small steps. The implicit step is stable for every , so one step can do the work of many. With the cotangent weights, the motion follows the mean curvature normal . A flat region does not move, even on an irregular mesh. Each step costs one solve with a symmetric positive definite matrix, by conjugate gradients or a sparse Cholesky factorization.
In plain words
Plain smoothing moves each corner a small step toward its neighbours. If the step is too large, corners overshoot, swing back and forth, and the mesh blows up. So many small steps are needed, and a smooth result takes a long time.
Implicit fairing asks a different question: where should every corner be, so that one step back from there leads to where the corners are now? All corners are found at once, by solving one system of equations. The answer is never wild, even for a very large step, because a large step just means more smoothing.
The weights come from the angles of the triangles, not only from who is next to whom. On a flat part of the mesh the corners already balance, so they stay where they are, even if the triangles have very different shapes. On a curved part they move inward along the bend.
The problem
The input is a triangle mesh with positions , a time step , a number of steps , and a set of fixed vertices, by default the border. The output is new positions with the same connectivity, after steps of the discrete flow on the free vertices, with the fixed vertices as boundary data. Larger means more smoothing. There is no single target: the user picks the amount.
The algorithm
Let be the cotangent weights, for an edge , , and one third of the area of the faces at . is the set of free vertices.
IMPLICIT-FAIR(x[1 .. n], faces, Δt, K, F)- 1
F ← the border vertices if not given; R ← the other vertices - 2
for k ← 1 to K do - 3
C, M ← the stiffness and mass matrices at the current x - 4
A ← (M + Δt C) restricted to the rows and columns of R - 5
for each coordinate: b ← M_R x_R − Δt C_RF x_F; solve A y = b - 6
x_R ← y - 7
optionally scale x about its centroid so that the volume is the starting volume return x
is symmetric. It is positive definite because is positive semidefinite, being the matrix of the Dirichlet energy , and is positive. So conjugate gradients applies, and the code uses it, started from the old positions.
With uniform weights, is the graph Laplacian and the valences. The step is then with , the implicit form of Laplacian smoothing. The code offers both, and a dense exact solver for tests.
Example
The octahedron, uniform weights. The octahedron with vertices , , has four neighbours per vertex, summing to 0, so for each coordinate. The step is , so , exactly. With , the octahedron shrinks to of its size. The explicit step with the same gives : it turns the octahedron inside out and doubles it, and repeating it blows up.
The octahedron, cotangent weights. Every angle is , so , and . Each face has area , so . The step is , so . After a first step to size , the areas are times larger and the weights the same, so the second step multiplies by . This matches the smooth flow of a sphere of radius , which moves inward with speed , so that falls by per unit time.
A sphere. On the icosphere with 162 vertices, one step with , and gives measured radii within 1 percent of , that is , and . With the volume correction of line L7, the volume stays at its start value. On the same sphere with 10 percent radial noise, one corrected step with , and lowers the measured relative spread of the radii from to , and .
Correctness
These are proved in the correctness file:
- The step solves the system. Lines L4 to L6 give the unique with on the free rows, with fixed. The matrix is symmetric positive definite, so the solution exists, is unique, and conjugate gradients converge to it. The tests compare conjugate gradients with dense Gaussian elimination.
- It is the backward Euler step. The system is , the backward Euler step of with the matrices frozen at the start of the step.
- Unconditional stability. For fixed and , the step does not increase the energy norm , and each eigenmode of with eigenvalue is multiplied by , for every . The explicit step multiplies it by , which is less than when .
- A maximum principle. If all weights are nonnegative, as with uniform weights or on a Delaunay mesh, each new position is a convex combination of the old positions and the fixed positions. With uniform weights and no fixed vertex, is also kept. The tests check both exactly.
- Flat regions stay. With cotangent weights, at each inner vertex of a planar mesh, so a planar mesh with a fixed border is a fixed point for every . The uniform weights move it inside the plane.
The tests also check the cotangent matrix against the Hessian of the Dirichlet energy, computed triangle by triangle. How much noise a step removes, and how close the sphere is to the smooth flow, is measured, not proved.
Proof: Each implicit fairing step has a unique solution, it is the backward Euler step of M x' = -C x, it damps every mode for every time step, it obeys a maximum principle for nonnegative weights, and it keeps a planar mesh fixedfull
Setup. The mesh has vertices , every vertex lies on a face of positive area, and is the set of fixed vertices, the free ones. For one coordinate, . Let be the hat function of vertex : linear on each triangle, 1 at and 0 at the other vertices. The interpolant of is , and its Dirichlet energy is . The loop of line L2 runs times, and each step does three solves, so the algorithm stops if each solve stops, which Lemma 2 shows.
Lemma 1 (the stiffness matrix). , where is the cotangent matrix of line L3. So is symmetric positive semidefinite, and exactly when is constant on each connected part of the mesh.
Proof. On a triangle with vertices and angles , . This is the cotangent formula of Pinkall and Polthier, proved on the cotangent Laplacian page. Summing over the triangles gives with . Since , is positive semidefinite. means on every triangle of positive area, so is constant along every edge and on each connected part.
The tests check and with the energy computed from the Gram matrix of each triangle.
Lemma 2 (the system is solvable). is symmetric positive definite for every . So line L5 has a unique solution, and conjugate gradients reach it in at most iterations in exact arithmetic.
Proof. is a principal submatrix of a positive semidefinite matrix, so it is positive semidefinite. is diagonal with positive entries. So for . Conjugate gradients on a symmetric positive definite matrix of size find the solution in at most steps (see conjugate gradient method).
Lemma 3 (backward Euler). The new positions satisfy with , where and are taken at the old positions.
Proof. Line L5 solves , and line L6 sets . Move the terms: .
Theorem 1 (unconditional stability). Fix and . Let be the eigenvalues of the generalized problem , all real and nonnegative. With , one step multiplies the coordinate of along by , so does not increase, for every . The explicit step multiplies the same coordinate by , which is less than when .
Proof. is symmetric positive semidefinite, so the generalized eigenvectors can be chosen -orthonormal, with . With , the step is . For , solves it, because . By linearity, goes to , and does not increase. The explicit claim is the same computation for the forward step.
Theorem 2 (maximum principle). If for all edges, then each new free position is a convex combination of the old free positions and the fixed positions. If moreover , then , and with the uniform weights, , this is .
Proof. Let and . Then has positive diagonal and nonpositive off-diagonal entries, and row has . So is strictly diagonally dominant with this sign pattern, a nonsingular M-matrix, and entrywise. The new positions are , with nonnegative coefficients. The rows of sum to 0, so and . So for all-ones input the output is , and the coefficients in each row sum to 1. For the second claim, because is symmetric with zero row sums, so equals .
Theorem 3 (planar meshes are fixed). Let the mesh lie in a plane, with every vertex of an inner vertex whose star is embedded in the plane, and let the weights be the cotangent weights. Then for every .
Proof. Each coordinate of the positions is a linear function of the point, and its interpolant is that linear function. By Lemma 1, . By the divergence theorem, this integral is over the border of the star, where . So for every free . Then itself solves , since the difference is . By Lemma 2 the solution is unique.
With the uniform weights the claim fails: is not 0 for an irregular star, and the tests see the vertices move in the plane.
Example values. On the regular octahedron with the uniform weights, for each coordinate, so the step is , which the tests check exactly. With the cotangent weights, every and , so and the step is . After scaling by , scales by and does not change, so the next step is .
Lemma 4 (volume correction). Line L7 makes the enclosed volume of a closed mesh equal to the starting volume .
Proof. The signed volume of a closed mesh does not change under translation and is homogeneous of degree 3. Scaling about the centroid by multiplies by .
What is measured. How close the icosphere is to the smooth flow, and how much radial noise one step removes, are measured in the tests, not proved.
Complexity
Building and takes time, because a manifold mesh has faces. The matrix has at most nonzero entries, and one product with it costs . Conjugate gradients need iterations per coordinate, so one step costs , and steps on the real RAM. The number depends on the condition number of , about , and grows like for edge length . A sparse Cholesky factorization costs more once, about time for a planar-like mesh with nested dissection, and then per solve, but it must be redone when and change. The extra space is for conjugate gradients.
Properties
- Stable for any step. Large gives strong smoothing, never a blow-up.
- Geometric. With cotangent weights, the result depends on the shape, not on the mesh. Flat regions do not move, and on a curved region the motion is along the normal, with speed proportional to the mean curvature.
- Still shrinks. Mean curvature flow decreases the area of every closed surface, and a sphere shrinks to a point in finite time. So the volume correction of line L7 is part of the method in practice.
- Not exact. The cotangent weights need square roots, and the solver is iterative. With uniform weights and rational input, the dense solver gives exact results.
- Semi-implicit. The matrices are taken at the old positions, so the step is linear. The true implicit step of the nonlinear flow would need Newton iterations.
Variants and improvements
- Uniform weights. The implicit form of Laplacian smoothing, cheaper, but with tangential drift.
- Normalized operator. Desbrun et al. divided the cotangent sum by the area of the one-ring, which gives a nonsymmetric matrix. They solved it with a preconditioned biconjugate gradient method. The symmetric form used here is the later standard.
- Fixed matrices. Compute and once and factor once. All steps then reuse the factor. This is the heat equation on the first mesh, not mean curvature flow, but it is often good enough.
- Higher order. Replace by , the bi-Laplacian, for smoother results with tangent continuity at a fixed border, as used for hole filling and fairing patches.
- Conformalized flow. Keep the stiffness matrix of the first mesh and update only the mass matrix. Kazhdan, Solomon and Ben-Chen (2012) showed that this avoids the singularities that mean curvature flow forms on some shapes.
- Anisotropic diffusion. Lower the weights across sharp features, so that creases are kept.
When to use it
Use it to remove noise from a mesh with irregular triangles, where the uniform weights would drift, and when strong smoothing is wanted in few steps. It also fairs the patch of a filled hole inside a fixed border. For a quick, cheap cleanup with no solver, use Taubin smoothing. The same matrices and , in one heat step, give the first solve of the heat method for geodesic distance.
Pitfalls
- Degenerate triangles. A triangle with an angle near or has a huge cotangent and makes the system badly conditioned. Remesh first, or clamp the weights.
- Negative weights. With obtuse triangles, some . The system is still positive definite, but the maximum principle fails, and a new position can leave the convex hull of the old ones.
- Shrinking to a point. Without the volume correction, a closed mesh shrinks, and with a large enough it shrinks almost to a point in one step, as for the sphere above.
- Forgetting the mass matrix. Solving makes the smoothing depend on the size of the triangles, and a refined region moves faster.
- Singularities. Mean curvature flow pinches thin necks, as on a dumbbell, and the mesh degenerates there.
- A free border. Without fixed vertices, the border of an open mesh shrinks inward along the surface.
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/implicit-fairing/. The authors are listed in prov/6F02H1.jsonl.
"""Implicit fairing (Desbrun, Meyer, Schroeder and Barr, SIGGRAPH 1999).
Each step is one backward Euler step of the flow M x' = -C x, that is, it
solves (M + dt C) x_new = M x_old on the free vertices, with the fixed
vertices as Dirichlet data. With weights="cotan", C is the cotangent
stiffness matrix and M the lumped (barycentric) mass, both taken at the
current positions, so the flow is the discrete mean curvature flow. With
weights="uniform", C = D - A is the graph Laplacian and M = D the valence
matrix, so the step is (I + dt (I - D^-1 A)) x_new = x_old. The solver is
conjugate gradients, or dense Gaussian elimination, which is exact on
Fraction input with the uniform weights.
"""
from typing import Iterable, Optional, Sequence
from mp2mesh import (boundary_vertices, conjugate_gradient, lumped_mass, neighbours, signed_volume,
solve_dense, stiffness_matrix)
Point = tuple
def operators(points, faces, weights: str):
"""The stiffness matrix C (list of dict rows) and the diagonal mass M."""
n = len(points)
if weights == "cotan":
return stiffness_matrix(points, faces), lumped_mass(points, faces)
if weights == "uniform":
nb = neighbours(n, faces)
C = [{i: len(nb[i]), **{j: -1 for j in nb[i]}} if nb[i] else {} for i in range(n)]
return C, [len(nb[i]) for i in range(n)]
raise ValueError("weights must be 'cotan' or 'uniform'")
def implicit_fairing(points: Sequence[Sequence], faces: Sequence[Sequence[int]], dt, steps: int = 1,
weights: str = "cotan", fixed: Optional[Iterable[int]] = None, keep_volume: bool = False,
solver: str = "cg") -> list[Point]:
"""Smooth the mesh by `steps` backward Euler steps of size dt."""
n = len(points)
x = [tuple(p) for p in points]
F = boundary_vertices(faces) if fixed is None else set(fixed) # @line L1
used = {v for f in faces for v in f}
R = [i for i in range(n) if i not in F and i in used]
pos = {v: r for r, v in enumerate(R)}
v0 = signed_volume(x, faces) if keep_volume else None
for _ in range(steps): # @line L2
C, M = operators(x, faces, weights) # @line L3
A = [{pos[j]: dt * c for j, c in C[i].items() if j in pos} for i in R] # @line L4
for r, i in enumerate(R):
A[r][r] = A[r].get(r, 0) + M[i]
new = [list(p) for p in x]
for k in range(3):
b = [M[i] * x[i][k] - sum(dt * c * x[j][k] for j, c in C[i].items() if j not in pos)
for i in R] # @line L5
if solver == "dense":
y = solve_dense([[row.get(c, 0) for c in range(len(R))] for row in A], b)
else:
y = conjugate_gradient(A, b, x0=[x[i][k] for i in R])
for r, i in enumerate(R):
new[i][k] = y[r] # @line L6
x = [tuple(p) for p in new]
if keep_volume: # @line L7
x = rescale_volume(x, faces, v0)
return x
def rescale_volume(x, faces, v0):
"""Scale about the vertex centroid so that the enclosed volume is v0 again."""
v = signed_volume(x, faces)
s = (v0 / v) ** (1 / 3)
c = tuple(sum(p[k] for p in x) / len(x) for k in range(3))
return [tuple(c[k] + s * (p[k] - c[k]) for k in range(3)) for p in x]
def explicit_step(points, faces, dt, weights: str = "uniform"):
"""One forward Euler step x + dt M^-1 (-C x), for comparison. No fixed vertices."""
C, M = operators(points, faces, weights)
return [tuple(points[i][k] - dt * sum(c * points[j][k] for j, c in C[i].items()) / M[i] for k in range(3))
if M[i] else tuple(points[i]) for i in range(len(points))]
mp2mesh.py 252 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mp2 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small tools for triangle meshes, used by the mp2 pages.
A mesh is a list of points (tuples of 3 numbers) and a list of faces
(tuples of 3 vertex indices, oriented by the right-hand rule). The helper has
the adjacency, the cotangent weights and the lumped mass, a sparse conjugate
gradient solver, a dense solver, and the test meshes. It does not hold the
algorithm of any page.
"""
from math import sqrt
from typing import Sequence
Vec = tuple
# ---- vectors ----
def sub(a: Sequence, b: Sequence) -> Vec:
return tuple(x - y for x, y in zip(a, b))
def add(a: Sequence, b: Sequence) -> Vec:
return tuple(x + y for x, y in zip(a, b))
def scale(c, a: Sequence) -> Vec:
return tuple(c * x for x in a)
def dot(a: Sequence, b: Sequence):
return sum(x * y for x, y in zip(a, b))
def cross(a: Sequence, b: Sequence) -> Vec:
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: Sequence) -> float:
return sqrt(dot(a, a))
# ---- adjacency ----
def edges(faces: Sequence[Sequence[int]]) -> list[tuple[int, int]]:
"""The undirected edges (i, j) with i < j, sorted."""
out = set()
for f in faces:
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
out.add((min(i, j), max(i, j)))
return sorted(out)
def edge_faces(faces: Sequence[Sequence[int]]) -> dict[tuple[int, int], list[int]]:
"""For each undirected edge, the indices of the faces that contain it."""
out: dict[tuple[int, int], list[int]] = {}
for fi, f in enumerate(faces):
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
out.setdefault((min(i, j), max(i, j)), []).append(fi)
return out
def neighbours(n: int, faces: Sequence[Sequence[int]]) -> list[list[int]]:
"""The sorted neighbours of each of the n vertices."""
nb: list[set[int]] = [set() for _ in range(n)]
for i, j in edges(faces):
nb[i].add(j)
nb[j].add(i)
return [sorted(s) for s in nb]
def boundary_vertices(faces: Sequence[Sequence[int]]) -> set[int]:
"""The vertices on an edge that has one face."""
out: set[int] = set()
for (i, j), fs in edge_faces(faces).items():
if len(fs) == 1:
out.update((i, j))
return out
def euler_characteristic(n: int, faces: Sequence[Sequence[int]]) -> int:
used = {v for f in faces for v in f}
return len(used) - len(edges(faces)) + len(faces)
# ---- geometry ----
def face_area(points: Sequence[Sequence[float]], f: Sequence[int]) -> float:
a, b, c = (points[v] for v in f)
return norm(cross(sub(b, a), sub(c, a))) / 2
def cot_at(p: Sequence[float], q: Sequence[float], r: Sequence[float]) -> float:
"""The cotangent of the angle at p of the triangle p, q, r."""
u, v = sub(q, p), sub(r, p)
return dot(u, v) / norm(cross(u, v))
def cotan_weights(points: Sequence[Sequence[float]], faces: Sequence[Sequence[int]]) -> dict[tuple[int, int], float]:
"""w[(i, j)] = (cot a + cot b) / 2 over the angles opposite the edge (one term on the boundary)."""
w: dict[tuple[int, int], float] = {}
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_matrix(points, faces) -> list[dict[int, float]]:
"""C = -L for the cotangent Laplacian L: C[i][j] = -w_ij, C[i][i] = sum of w_ij."""
n = len(points)
C: list[dict[int, float]] = [dict() for _ in range(n)]
for (i, j), wij in cotan_weights(points, faces).items():
C[i][j] = C[i].get(j, 0.0) - wij
C[j][i] = C[j].get(i, 0.0) - wij
C[i][i] = C[i].get(i, 0.0) + wij
C[j][j] = C[j].get(j, 0.0) + wij
return C
def lumped_mass(points, faces) -> list[float]:
"""The barycentric vertex areas: one third of the area of each face at the vertex."""
m = [0.0] * len(points)
for f in faces:
a = face_area(points, f) / 3
for v in f:
m[v] += a
return m
def signed_volume(points, faces) -> float:
"""The volume enclosed by a closed oriented mesh (outward normals give a positive value)."""
return sum(dot(points[a], cross(points[b], points[c])) for a, b, c in faces) / 6
def mean_edge_length(points, faces) -> float:
es = edges(faces)
return sum(norm(sub(points[i], points[j])) for i, j in es) / len(es)
# ---- linear algebra ----
def mat_vec(A: Sequence[dict[int, float]], x: Sequence[float]) -> list[float]:
return [sum(a * x[j] for j, a in row.items()) for row in A]
def conjugate_gradient(A, b, x0=None, tol: float = 1e-12, max_iter: int | None = None) -> list[float]:
"""Solve A x = b for a sparse symmetric positive definite A (a list of dict rows)."""
n = len(b)
x = list(x0) if x0 is not None else [0.0] * n
Ax = mat_vec(A, x)
r = [bi - ai for bi, ai in zip(b, Ax)]
p = list(r)
rr = dot(r, r)
bb = max(dot(b, b), 1e-300)
for _ in range(max_iter or 10 * n + 10):
if rr <= tol * tol * bb:
break
Ap = mat_vec(A, p)
alpha = rr / dot(p, Ap)
x = [xi + alpha * pi for xi, pi in zip(x, p)]
r = [ri - alpha * qi for ri, qi in zip(r, Ap)]
rr_new = dot(r, r)
p = [ri + (rr_new / rr) * pi for ri, pi in zip(r, p)]
rr = rr_new
return x
def solve_dense(A: Sequence[Sequence], b: Sequence) -> list:
"""Gaussian elimination with partial pivoting. Works with float or Fraction entries."""
n = len(b)
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 c in range(n - 1, -1, -1):
x[c] = (M[c][n] - sum(M[c][k] * x[k] for k in range(c + 1, n))) / M[c][c]
return x
def dense(A: Sequence[dict[int, float]]) -> list[list[float]]:
n = len(A)
return [[A[i].get(j, 0.0) for j in range(n)] for i in range(n)]
# ---- test meshes ----
def grid_mesh(m: int, n: int, h=1.0):
"""The (m+1) x (n+1) grid in the plane z = 0, each square cut by the diagonal from (i, j) to (i+1, j+1)."""
pts = [(i * h, j * h, 0 * h) for j in range(n + 1) for i in range(m + 1)]
def v(i, j):
return j * (m + 1) + i
faces = []
for j in range(n):
for i in range(m):
faces.append((v(i, j), v(i + 1, j), v(i + 1, j + 1)))
faces.append((v(i, j), v(i + 1, j + 1), v(i, j + 1)))
return pts, faces
def octahedron():
pts = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
faces = [(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 pts, faces
def icosphere(level: int):
"""The icosahedron, with each triangle cut into 4 `level` times, on the unit sphere."""
t = (1 + 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)]
pts = [scale(1 / norm(p), p) for p in raw]
faces = [(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)]
for _ in range(level):
mid: dict[tuple[int, int], int] = {}
def m(i, j):
key = (min(i, j), max(i, j))
if key not in mid:
p = scale(0.5, add(pts[i], pts[j]))
pts.append(scale(1 / norm(p), p))
mid[key] = len(pts) - 1
return mid[key]
new = []
for a, b, c in faces:
ab, bc, ca = m(a, b), m(b, c), m(c, a)
new += [(a, ab, ca), (b, bc, ab), (c, ca, bc), (ab, bc, ca)]
faces = new
return pts, faces
test_implicit_fairing.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/implicit-fairing/. The authors are listed in prov/6F02H1.jsonl.
import random
from fractions import Fraction as Fr
from implicit_fairing import explicit_step, implicit_fairing
from mp2mesh import (boundary_vertices, dot, grid_mesh, icosphere, neighbours, norm, octahedron, signed_volume,
stiffness_matrix, sub)
def close(a, b, eps=1e-9):
return all(abs(u - v) <= eps for p, q in zip(a, b) for u, v in zip(p, q))
def noisy_sphere(level, seed, amp=0.1):
rng = random.Random(seed)
p, f = icosphere(level)
return [tuple((1 + amp * (rng.random() - 0.5)) * c for c in q) for q in p], f
# ---- brute force for the cotangent matrix: the Dirichlet energy of the linear interpolant ----
def dirichlet_energy(points, faces, u):
"""1/2 of the sum over triangles of area * |grad u|^2, from the Gram matrix of two edges."""
e = 0.0
for a, b, c in faces:
e1, e2 = sub(points[b], points[a]), sub(points[c], points[a])
g11, g12, g22 = dot(e1, e1), dot(e1, e2), dot(e2, e2)
det = g11 * g22 - g12 * g12
d1, d2 = u[b] - u[a], u[c] - u[a]
grad2 = (g22 * d1 * d1 - 2 * g12 * d1 * d2 + g11 * d2 * d2) / det
e += 0.5 * (det ** 0.5 / 2) * grad2
return e
def test_stiffness_matrix_is_the_hessian_of_the_dirichlet_energy() -> None:
p, f = noisy_sphere(0, 3, 0.4)
n = len(p)
C = stiffness_matrix(p, f)
def unit(*idx):
u = [0.0] * n
for i in idx:
u[i] = 1.0
return u
for i in range(n):
assert abs(C[i].get(i, 0.0) - 2 * dirichlet_energy(p, f, unit(i))) < 1e-12
for j in range(n):
if j != i:
cij = dirichlet_energy(p, f, unit(i, j)) - dirichlet_energy(p, f, unit(i)) - dirichlet_energy(p, f, unit(j))
assert abs(C[i].get(j, 0.0) - cij) < 1e-12
def test_octahedron_uniform_exact() -> None:
p, f = octahedron()
p = [tuple(Fr(c) for c in q) for q in p]
for dt in (Fr(1, 2), Fr(1), Fr(3)):
for steps in (1, 2):
x = implicit_fairing(p, f, dt, steps, "uniform", solver="dense")
assert x == [tuple(c / (1 + dt) ** steps for c in q) for q in p]
def test_octahedron_cotan() -> None:
p, f = octahedron()
for dt in (0.25, 1.0, 4.0):
s = 1 / (1 + 2 * dt) # the first step
x = implicit_fairing(p, f, dt, 1)
assert close(x, [tuple(s * c for c in q) for q in p], 1e-12)
s2 = s * s * s / (s * s + 2 * dt) # the mass is taken again at the smaller size
x = implicit_fairing(p, f, dt, 2)
assert close(x, [tuple(s2 * c for c in q) for q in p], 1e-12)
def test_explicit_blows_up_implicit_does_not() -> None:
p, f = octahedron()
p = [tuple(Fr(c) for c in q) for q in p]
assert explicit_step(p, f, Fr(3)) == [tuple(-2 * c for c in q) for q in p]
assert implicit_fairing(p, f, Fr(3), 1, "uniform", solver="dense") == [tuple(c / 4 for c in q) for q in p]
def test_cg_against_dense_solver() -> None:
p, f = noisy_sphere(1, 5)
for w in ("cotan", "uniform"):
a = implicit_fairing(p, f, 0.05, 2, w)
b = implicit_fairing(p, f, 0.05, 2, w, solver="dense")
assert close(a, b, 1e-9)
rng = random.Random(8)
g, gf = grid_mesh(4, 4)
g = [(a, b, rng.uniform(-0.3, 0.3)) for a, b, _ in g]
for w in ("cotan", "uniform"):
assert close(implicit_fairing(g, gf, 0.5, 1, w), implicit_fairing(g, gf, 0.5, 1, w, solver="dense"), 1e-9)
def test_maximum_principle_and_weighted_centroid_exact() -> None:
rng = random.Random(2)
p, f = icosphere(0)
p = [tuple(Fr(round(c * 32), 32) + Fr(rng.randrange(-4, 5), 64) for c in q) for q in p]
nb = neighbours(len(p), f)
for dt in (Fr(1, 10), Fr(10)):
x = implicit_fairing(p, f, dt, 1, "uniform", solver="dense")
for k in range(3):
lo, hi = min(q[k] for q in p), max(q[k] for q in p)
assert all(lo <= q[k] <= hi for q in x)
assert sum(len(nb[i]) * x[i][k] for i in range(len(p))) == sum(len(nb[i]) * p[i][k] for i in range(len(p)))
def test_planar_mesh_is_fixed_with_cotan_weights() -> None:
rng = random.Random(6)
g, gf = grid_mesh(5, 5)
g = [(a + rng.uniform(-0.15, 0.15), b + rng.uniform(-0.15, 0.15), 0.0) if 0 < a < 5 and 0 < b < 5 else (a, b, c)
for a, b, c in g]
x = implicit_fairing(g, gf, 10.0, 2, "cotan")
assert close(x, g, 1e-9)
y = implicit_fairing(g, gf, 10.0, 2, "uniform")
assert max(norm(sub(a, b)) for a, b in zip(y, g)) > 0.05 # the uniform weights slide in the plane
assert all(q[2] == 0.0 for q in y)
def test_border_fixed() -> None:
rng = random.Random(4)
g, gf = grid_mesh(4, 3)
g = [(a, b, rng.uniform(-1, 1)) for a, b, _ in g]
for w in ("cotan", "uniform"):
x = implicit_fairing(g, gf, 2.0, 3, w)
for v in boundary_vertices(gf):
assert x[v] == g[v]
def test_sphere_shrinks_like_mean_curvature_flow() -> None:
p, f = icosphere(2)
for dt in (0.01, 1.0, 10.0):
x = implicit_fairing(p, f, dt, 1)
r = 1 / (1 + 2 * dt) # the smooth sphere: x' = x / (1 + 2 dt / r^2)
assert all(abs(norm(q) - r) < 0.02 * r for q in x)
q, f = noisy_sphere(2, 1)
v0 = signed_volume(q, f)
x = implicit_fairing(q, f, 0.01, 1, keep_volume=True)
assert abs(signed_volume(x, f) - v0) < 1e-12
def test_noise_is_damped() -> None:
q, f = noisy_sphere(2, 1)
def spread(x):
r = [norm(v) for v in x]
m = sum(r) / len(r)
return (sum((a - m) ** 2 for a in r) / len(r)) ** 0.5 / m
prev = spread(q)
for dt in (0.001, 0.003, 0.01):
s = spread(implicit_fairing(q, f, dt, 1, keep_volume=True))
assert s < prev # measured: 0.0285, 0.0275, 0.0257, 0.0215
prev = s
History
Diffusion-based mesh smoothing goes back to Laplacian smoothing and to Taubin's 1995 signal processing view of it. In 1999 Desbrun, Meyer, Schröder and Barr made two changes. First, they took implicit steps of the diffusion, by solving a sparse linear system, and so allowed large time steps. Second, they replaced the uniform weights by the cotangent formula for the mean curvature normal, which goes back to Pinkall and Polthier (1993), so that the flow depends on the geometry and not on the sampling. They also rescaled the mesh after each step to keep its volume. The method became the standard reference for mesh fairing, and the symmetric form with mass and stiffness matrices became common through the later finite element view of the cotangent Laplacian.
References
- Mathieu Desbrun, Mark Meyer, Peter Schröder and Alan H. Barr, Implicit fairing of irregular meshes using diffusion and curvature flow, Proceedings of SIGGRAPH 99, 1999, 317 to 324, the implicit integration of the diffusion equation, the curvature normal from the cotangent formula, the volume correction, and the comparison with explicit steps
- Mark Meyer, Mathieu Desbrun, Peter Schröder and Alan H. Barr, Discrete differential-geometry operators for triangulated 2-manifolds, in Visualization and Mathematics III, Springer, 2003, 35 to 57, the mean curvature normal as the cotangent Laplacian of the positions, with the vertex areas
- Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 4, Smoothing (implicit smoothing with the symmetric system of mass and stiffness matrices)
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 6F02H1 Edit this page History Report an error Markdown