Algorithm Search⌘K

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
Properties
deterministicnot exactiterative
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

(M+Δt C) xnew=M xold(M + \Delta t\, C)\, x^{\text{new}} = M\, x^{\text{old}}

for each coordinate, where C=−LC = -L is the stiffness matrix of the cotangent Laplacian and MM 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 Δt>0\Delta t > 0, so one step can do the work of many. With the cotangent weights, the motion follows the mean curvature normal −2Hn-2Hn. 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 x1,…,xnx_1, \ldots, x_n, a time step Δt>0\Delta t > 0, a number of steps KK, and a set FF of fixed vertices, by default the border. The output is new positions with the same connectivity, after KK steps of the discrete flow Mx˙=−CxM\dot x = -Cx on the free vertices, with the fixed vertices as boundary data. Larger ΔtK\Delta t K means more smoothing. There is no single target: the user picks the amount.

The algorithm

Let wij=12(cot⁡αij+cot⁡βij)w_{ij} = \frac{1}{2}(\cot\alpha_{ij} + \cot\beta_{ij}) be the cotangent weights, Cij=−wijC_{ij} = -w_{ij} for an edge ijij, Cii=∑jwijC_{ii} = \sum_j w_{ij}, and MiiM_{ii} one third of the area of the faces at ii. RR is the set of free vertices.

  1. IMPLICIT-FAIR(x[1 .. n], faces, Δt, K, F)
  2. 1F ← the border vertices if not given; R ← the other vertices
  3. 2for k ← 1 to K do
  4. 3C, M ← the stiffness and mass matrices at the current x
  5. 4A ← (M + Δt C) restricted to the rows and columns of R
  6. 5for each coordinate: b ← M_R x_R − Δt C_RF x_F; solve A y = b
  7. 6x_R ← y
  8. 7optionally scale x about its centroid so that the volume is the starting volume
  9. return x

AA is symmetric. It is positive definite because CC is positive semidefinite, being the matrix of the Dirichlet energy 12x⊤Cx\frac{1}{2}x^\top C x, and MM is positive. So conjugate gradients applies, and the code uses it, started from the old positions.

With uniform weights, C=D−AadjC = D - A_{\text{adj}} is the graph Laplacian and M=DM = D the valences. The step is then (I+Δt G)xnew=xold(I + \Delta t\, G)x^{\text{new}} = x^{\text{old}} with G=I−D−1AadjG = I - D^{-1}A_{\text{adj}}, 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 (±1,0,0)(\pm 1, 0, 0), (0,±1,0)(0, \pm 1, 0), (0,0,±1)(0, 0, \pm 1) has four neighbours per vertex, summing to 0, so Gx=xGx = x for each coordinate. The step is (1+Δt)xnew=x(1 + \Delta t)x^{\text{new}} = x, so xnew=x/(1+Δt)x^{\text{new}} = x / (1 + \Delta t), exactly. With Δt=3\Delta t = 3, the octahedron shrinks to 14\frac{1}{4} of its size. The explicit step with the same Δt\Delta t gives x+3(0−x)=−2xx + 3(0 - x) = -2x: it turns the octahedron inside out and doubles it, and repeating it blows up.

The octahedron, cotangent weights. Every angle is 60°60°, so wij=cot⁡60°=13w_{ij} = \cot 60° = \frac{1}{\sqrt{3}}, and (Cx)i=13(4xi−0)=43xi(Cx)_i = \frac{1}{\sqrt{3}}(4x_i - 0) = \frac{4}{\sqrt{3}}x_i. Each face has area 32\frac{\sqrt{3}}{2}, so Mii=43⋅32=23M_{ii} = \frac{4}{3} \cdot \frac{\sqrt{3}}{2} = \frac{2}{\sqrt{3}}. The step is (23+4Δt3)xnew=23x(\frac{2}{\sqrt{3}} + \frac{4\Delta t}{\sqrt{3}})x^{\text{new}} = \frac{2}{\sqrt{3}}x, so xnew=x/(1+2Δt)x^{\text{new}} = x / (1 + 2\Delta t). After a first step to size ss, the areas are s2s^2 times larger and the weights the same, so the second step multiplies by s2/(s2+2Δt)s^2 / (s^2 + 2\Delta t). This matches the smooth flow of a sphere of radius rr, which moves inward with speed 2/r2/r, so that r2r^2 falls by 44 per unit time.

A sphere. On the icosphere with 162 vertices, one step with Δt=0.01\Delta t = 0.01, 11 and 1010 gives measured radii within 1 percent of 1/(1+2Δt)1/(1 + 2\Delta t), that is 0.9800.980, 0.3330.333 and 0.04760.0476. 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 Δt=0.001\Delta t = 0.001, 0.0030.003 and 0.010.01 lowers the measured relative spread of the radii from 0.02850.0285 to 0.02750.0275, 0.02570.0257 and 0.02150.0215.

Correctness

These are proved in the correctness file:

  • The step solves the system. Lines L4 to L6 give the unique xRx_R with (M+ΔtC)x=Mxold(M + \Delta t C)x = Mx^{\text{old}} on the free rows, with xFx_F 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 Mxnew−xoldΔt=−CxnewM\frac{x^{\text{new}} - x^{\text{old}}}{\Delta t} = -Cx^{\text{new}}, the backward Euler step of Mx˙=−CxM\dot x = -Cx with the matrices frozen at the start of the step.
  • Unconditional stability. For fixed CC and MM, the step does not increase the energy norm x⊤Mxx^\top M x, and each eigenmode of M−1CM^{-1}C with eigenvalue kk is multiplied by 11+Δtk∈(0,1]\frac{1}{1 + \Delta t k} \in (0, 1], for every Δt>0\Delta t > 0. The explicit step multiplies it by 1−Δtk1 - \Delta t k, which is less than −1-1 when Δt>2/k\Delta t > 2/k.
  • 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, ∑idixi\sum_i d_i x_i is also kept. The tests check both exactly.
  • Flat regions stay. With cotangent weights, (Cx)i=0(Cx)_i = 0 at each inner vertex of a planar mesh, so a planar mesh with a fixed border is a fixed point for every Δt\Delta t. 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 1,…,n1, \ldots, n, every vertex lies on a face of positive area, and FF is the set of fixed vertices, RR the free ones. For one coordinate, u∈Rnu \in \mathbb{R}^n. Let ϕi\phi_i be the hat function of vertex ii: linear on each triangle, 1 at ii and 0 at the other vertices. The interpolant of uu is ∑iuiϕi\sum_i u_i \phi_i, and its Dirichlet energy is E(u)=12∑Tarea⁡(T) ∣∇u∣T∣2E(u) = \frac{1}{2}\sum_T \operatorname{area}(T)\,|\nabla u|_T|^2. The loop of line L2 runs KK times, and each step does three solves, so the algorithm stops if each solve stops, which Lemma 2 shows.

Lemma 1 (the stiffness matrix). E(u)=12u⊤CuE(u) = \frac{1}{2}u^\top C u, where CC is the cotangent matrix of line L3. So CC is symmetric positive semidefinite, and Cu=0Cu = 0 exactly when uu is constant on each connected part of the mesh.

Proof. On a triangle TT with vertices a,b,ca, b, c and angles αa,αb,αc\alpha_a, \alpha_b, \alpha_c, area⁡(T) ∣∇u∣2=12(cot⁡αc(ua−ub)2+cot⁡αa(ub−uc)2+cot⁡αb(uc−ua)2)\operatorname{area}(T)\,|\nabla u|^2 = \frac{1}{2}\big(\cot\alpha_c (u_a - u_b)^2 + \cot\alpha_a (u_b - u_c)^2 + \cot\alpha_b (u_c - u_a)^2\big). This is the cotangent formula of Pinkall and Polthier, proved on the cotangent Laplacian page. Summing over the triangles gives E(u)=12∑ijwij(ui−uj)2=12u⊤CuE(u) = \frac{1}{2}\sum_{ij} w_{ij}(u_i - u_j)^2 = \frac{1}{2}u^\top C u with wij=12(cot⁡αij+cot⁡βij)w_{ij} = \frac{1}{2}(\cot\alpha_{ij} + \cot\beta_{ij}). Since E≥0E \ge 0, CC is positive semidefinite. E(u)=0E(u) = 0 means ∇u=0\nabla u = 0 on every triangle of positive area, so uu is constant along every edge and on each connected part. □\square

The tests check Cii=2E(ei)C_{ii} = 2E(e_i) and Cij=E(ei+ej)−E(ei)−E(ej)C_{ij} = E(e_i + e_j) - E(e_i) - E(e_j) with the energy computed from the Gram matrix of each triangle.

Lemma 2 (the system is solvable). A=MRR+Δt CRRA = M_{RR} + \Delta t\, C_{RR} is symmetric positive definite for every Δt>0\Delta t > 0. So line L5 has a unique solution, and conjugate gradients reach it in at most ∣R∣|R| iterations in exact arithmetic.

Proof. CRRC_{RR} is a principal submatrix of a positive semidefinite matrix, so it is positive semidefinite. MRRM_{RR} is diagonal with positive entries. So y⊤Ay≥y⊤MRRy>0y^\top A y \ge y^\top M_{RR} y > 0 for y≠0y \ne 0. Conjugate gradients on a symmetric positive definite matrix of size mm find the solution in at most mm steps (see conjugate gradient method). □\square

Lemma 3 (backward Euler). The new positions satisfy MRRxRnew−xRΔt=−(Cxnew)RM_{RR}\frac{x^{\text{new}}_R - x_R}{\Delta t} = -(C x^{\text{new}})_R with xFnew=xFx^{\text{new}}_F = x_F, where CC and MM are taken at the old positions.

Proof. Line L5 solves (MRR+ΔtCRR)y=MRRxR−ΔtCRFxF(M_{RR} + \Delta t C_{RR})y = M_{RR}x_R - \Delta t C_{RF}x_F, and line L6 sets xRnew=yx^{\text{new}}_R = y. Move the terms: MRR(y−xR)=−Δt(CRRy+CRFxF)=−Δt(Cxnew)RM_{RR}(y - x_R) = -\Delta t(C_{RR}y + C_{RF}x_F) = -\Delta t (Cx^{\text{new}})_R. □\square

Theorem 1 (unconditional stability). Fix CC and MM. Let k1≤⋯≤kmk_1 \le \cdots \le k_m be the eigenvalues of the generalized problem CRRv=kMRRvC_{RR}v = k M_{RR}v, all real and nonnegative. With xF=0x_F = 0, one step multiplies the coordinate of xRx_R along vjv_j by 11+Δtkj∈(0,1]\frac{1}{1 + \Delta t k_j} \in (0, 1], so xR⊤MRRxRx_R^\top M_{RR} x_R does not increase, for every Δt>0\Delta t > 0. The explicit step xR←xR−ΔtMRR−1CRRxRx_R \leftarrow x_R - \Delta t M_{RR}^{-1}C_{RR}x_R multiplies the same coordinate by 1−Δtkj1 - \Delta t k_j, which is less than −1-1 when Δt>2/kj\Delta t > 2/k_j.

Proof. MRR−1/2CRRMRR−1/2M_{RR}^{-1/2}C_{RR}M_{RR}^{-1/2} is symmetric positive semidefinite, so the generalized eigenvectors vjv_j can be chosen MRRM_{RR}-orthonormal, with kj≥0k_j \ge 0. With xF=0x_F = 0, the step is (MRR+ΔtCRR)y=MRRxR(M_{RR} + \Delta t C_{RR})y = M_{RR}x_R. For xR=vjx_R = v_j, y=vj/(1+Δtkj)y = v_j/(1 + \Delta t k_j) solves it, because (MRR+ΔtCRR)vj=(1+Δtkj)MRRvj(M_{RR} + \Delta t C_{RR})v_j = (1 + \Delta t k_j)M_{RR}v_j. By linearity, xR=∑ajvjx_R = \sum a_j v_j goes to ∑aj1+Δtkjvj\sum \frac{a_j}{1 + \Delta t k_j} v_j, and xR⊤MRRxR=∑aj2x_R^\top M_{RR}x_R = \sum a_j^2 does not increase. The explicit claim is the same computation for the forward step. □\square

Theorem 2 (maximum principle). If wij≥0w_{ij} \ge 0 for all edges, then each new free position is a convex combination of the old free positions and the fixed positions. If moreover F=∅F = \emptyset, then ∑iMiixinew=∑iMiixi\sum_i M_{ii}x^{\text{new}}_i = \sum_i M_{ii}x_i, and with the uniform weights, M=DM = D, this is ∑idixi\sum_i d_i x_i.

Proof. Let B=MRR+ΔtCRRB = M_{RR} + \Delta t C_{RR} and WRF=−CRF≥0W_{RF} = -C_{RF} \ge 0. Then BB has positive diagonal and nonpositive off-diagonal entries, and row ii has Bii−∑j∈R,j≠i∣Bij∣=Mii+Δt∑j∈Fwij>0B_{ii} - \sum_{j \in R, j \ne i}|B_{ij}| = M_{ii} + \Delta t\sum_{j \in F}w_{ij} > 0. So BB is strictly diagonally dominant with this sign pattern, a nonsingular M-matrix, and B−1≥0B^{-1} \ge 0 entrywise. The new positions are xRnew=B−1MRRxR+B−1ΔtWRFxFx^{\text{new}}_R = B^{-1}M_{RR}x_R + B^{-1}\Delta t W_{RF}x_F, with nonnegative coefficients. The rows of CC sum to 0, so CRR1=WRF1C_{RR}\mathbf{1} = W_{RF}\mathbf{1} and B1=MRR1+ΔtWRF1B\mathbf{1} = M_{RR}\mathbf{1} + \Delta t W_{RF}\mathbf{1}. So for all-ones input the output is 1\mathbf{1}, and the coefficients in each row sum to 1. For the second claim, 1⊤C=0\mathbf{1}^\top C = 0 because CC is symmetric with zero row sums, so 1⊤(M+ΔtC)xnew=1⊤Mxnew\mathbf{1}^\top(M + \Delta t C)x^{\text{new}} = \mathbf{1}^\top M x^{\text{new}} equals 1⊤Mx\mathbf{1}^\top M x. □\square

Theorem 3 (planar meshes are fixed). Let the mesh lie in a plane, with every vertex of RR an inner vertex whose star is embedded in the plane, and let the weights be the cotangent weights. Then xnew=xx^{\text{new}} = x for every Δt\Delta t.

Proof. Each coordinate uu of the positions is a linear function u(p)=a⋅p+bu(p) = a \cdot p + b of the point, and its interpolant is that linear function. By Lemma 1, (Cu)i=∂E/∂ui=∑Tarea⁡(T) ∇u⋅∇ϕi=a⋅∫star⁡(i)∇ϕi dA(Cu)_i = \partial E/\partial u_i = \sum_T \operatorname{area}(T)\,\nabla u \cdot \nabla\phi_i = a \cdot \int_{\operatorname{star}(i)} \nabla\phi_i\,dA. By the divergence theorem, this integral is ∮ϕi ν ds\oint \phi_i\, \nu\, ds over the border of the star, where ϕi=0\phi_i = 0. So (Cu)i=0(Cu)_i = 0 for every free ii. Then uRu_R itself solves (MRR+ΔtCRR)y=MRRuR−ΔtCRFuF(M_{RR} + \Delta t C_{RR})y = M_{RR}u_R - \Delta t C_{RF}u_F, since the difference is Δt(Cu)R=0\Delta t(Cu)_R = 0. By Lemma 2 the solution is unique. □\square

With the uniform weights the claim fails: (Gu)i=ui−ci(Gu)_i = u_i - c_i 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, Gx=xGx = x for each coordinate, so the step is x/(1+Δt)x/(1 + \Delta t), which the tests check exactly. With the cotangent weights, every wij=1/3w_{ij} = 1/\sqrt{3} and Mii=2/3M_{ii} = 2/\sqrt{3}, so (Cx)i=43xi(Cx)_i = \frac{4}{\sqrt{3}}x_i and the step is x/(1+2Δt)x/(1 + 2\Delta t). After scaling by ss, MM scales by s2s^2 and CC does not change, so the next step is s2/(s2+2Δt)s^2/(s^2 + 2\Delta t).

Lemma 4 (volume correction). Line L7 makes the enclosed volume of a closed mesh equal to the starting volume V0V_0.

Proof. The signed volume 16∑abcxa⋅(xb×xc)\frac{1}{6}\sum_{abc} x_a \cdot (x_b \times x_c) of a closed mesh does not change under translation and is homogeneous of degree 3. Scaling about the centroid by s=(V0/V)1/3s = (V_0/V)^{1/3} multiplies VV by s3=V0/Vs^3 = V_0/V. □\square

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 CC and MM takes O(n)O(n) time, because a manifold mesh has O(n)O(n) faces. The matrix has at most 7n7n nonzero entries, and one product with it costs O(n)O(n). Conjugate gradients need ss iterations per coordinate, so one step costs Θ(sn)\Theta(sn), and KK steps Θ(Ksn)\Theta(Ksn) on the real RAM. The number ss depends on the condition number of M+ΔtCM + \Delta t C, about 1+Δt kmax⁡1 + \Delta t\, k_{\max}, and grows like Δt/h\sqrt{\Delta t}/h for edge length hh. A sparse Cholesky factorization costs more once, about O(n1.5)O(n^{1.5}) time for a planar-like mesh with nested dissection, and then O(nlog⁡n)O(n \log n) per solve, but it must be redone when CC and MM change. The extra space is Θ(n)\Theta(n) for conjugate gradients.

Properties

  • Stable for any step. Large Δt\Delta t 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 M+ΔtCM + \Delta t C used here is the later standard.
  • Fixed matrices. Compute CC and MM once and factor M+ΔtCM + \Delta t C 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 CC by CM−1CCM^{-1}C, 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 MM and CC, in one heat step, give the first solve of the heat method for geodesic distance.

Pitfalls

  • Degenerate triangles. A triangle with an angle near 00 or 180°180° has a huge cotangent and makes the system badly conditioned. Remesh first, or clamp the weights.
  • Negative weights. With obtuse triangles, some wij<0w_{ij} < 0. 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 Δt\Delta t it shrinks almost to a point in one step, as for the sphere above.
  • Forgetting the mass matrix. Solving (I+ΔtC)xnew=x(I + \Delta t C)x^{\text{new}} = x 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.

implicit_fairing.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example