Algorithm Search⌘K

Algorithmcore

Taubin smoothing

Also called lambda-mu smoothing.

Alternates a shrinking Laplacian step with factor lambda and an expanding one with factor mu < -lambda, a low-pass filter that smooths without shrinking.

Time
Θ(K n) worst
Space
Θ(n) extra
Where
K = the number of passes; n = the number of vertices
Properties
deterministicexactiterative
Origin
Gabriel Taubin, 1995

Taubin smoothing repeats a pass of two Laplacian smoothing steps, x←x+f U(x)x \leftarrow x + f\,U(x), first with a positive factor f=λf = \lambda, which shrinks, and then with a negative factor f=μ<−λf = \mu < -\lambda, which inflates. U(x)iU(x)_i is the umbrella vector, the centroid of the neighbours of vertex ii minus xix_i. On the eigenvectors of the uniform Laplacian, a pass multiplies the part of frequency kk by (1−λk)(1−μk)(1 - \lambda k)(1 - \mu k). This factor is about 1 for low frequencies, the overall shape, and well below 1 for high frequencies, the noise. So the method is a low-pass filter, and a closed mesh keeps its size, where plain Laplacian smoothing shrinks it to a point. A pass costs Θ(n)\Theta(n) time.

In plain words

Plain smoothing moves each corner a bit toward the middle of its neighbours. That removes bumps, but it also pulls a round shape inward, a little at every step.

Taubin's idea is to follow each such step by a step the other way, slightly larger, which pushes each corner away from the middle of its neighbours. A large bump, such as the round shape itself, is pulled in by the first step and pushed back out by the second, and stays about the same. A small sharp bump is cut down a lot by the first step. The second step then pushes back only a little of it, so the bump stays small. After a few pairs of steps the noise is gone and the shape has kept its size.

The problem

The input is a triangle mesh with vertex positions x1,…,xn∈R3x_1, \ldots, x_n \in \mathbb{R}^3, two factors λ>0\lambda > 0 and μ<−λ\mu < -\lambda, a number of passes KK, and a set FF of fixed vertices, by default the border vertices. The output is new positions with the same connectivity, with the high frequencies damped and the low frequencies kept. As for Laplacian smoothing, there is no single target shape. The user picks λ\lambda, μ\mu and KK.

The algorithm

Let N(i)N(i) be the neighbours of vertex ii, di=∣N(i)∣d_i = |N(i)|, and ci=1di∑j∈N(i)xjc_i = \frac{1}{d_i}\sum_{j \in N(i)} x_j.

  1. TAUBIN-SMOOTH(x[1 .. n], faces, λ, μ, K, F)
  2. 1require λ > 0 and μ < −λ; N ← the neighbour lists; F ← the border vertices if not given
  3. 2for k ← 1 to K do
  4. 3for each factor f in (λ, μ) do
  5. 4for each vertex i ∉ F do y_i ← x_i + f (c_i − x_i) ▷ c_i from the old x
  6. 5y_i ← x_i for each i ∈ F
  7. 6x ← y
  8. return x

Write G=I−D−1AG = I - D^{-1}A for the uniform Laplacian of the edge graph, with AA the adjacency matrix and D=diag⁡(di)D = \operatorname{diag}(d_i), so that U(x)=−GxU(x) = -Gx. On a closed mesh, one pass is

x←(I−μG)(I−λG) x.x \leftarrow (I - \mu G)(I - \lambda G)\, x.

GG has real eigenvalues 0=k1≤k2≤⋯≤kn≤20 = k_1 \le k_2 \le \cdots \le k_n \le 2, the frequencies, and a basis of eigenvectors. A pass multiplies the part of xx along an eigenvector of frequency kk by the transfer function

f(k)=(1−λk)(1−μk).f(k) = (1 - \lambda k)(1 - \mu k).

It has f(0)=1f(0) = 1, and f(k)=1f(k) = 1 again at the pass-band frequency

kPB=1λ+1μ,k_{PB} = \frac{1}{\lambda} + \frac{1}{\mu},

which is positive because μ<−λ\mu < -\lambda. Values of kPBk_{PB} from about 0.010.01 to 0.10.1 are the usual choice. With λ=0.33\lambda = 0.33 and μ=−0.34\mu = -0.34, as in the code, kPB=50561≈0.089k_{PB} = \frac{50}{561} \approx 0.089.

Example

The six modes of a hexagon. Take a closed polygon with 6 vertices, the graph of a cycle, where each vertex has the two neighbours i±1i \pm 1. The eigenvectors of GG are xi=cos⁡(πmi/3)x_i = \cos(\pi m i / 3) with frequencies k=1−cos⁡(πm/3)k = 1 - \cos(\pi m / 3), that is k=0,12,32,2k = 0, \frac{1}{2}, \frac{3}{2}, 2 for m=0,1,2,3m = 0, 1, 2, 3. Use one coordinate and λ=33100\lambda = \frac{33}{100}, μ=−34100\mu = -\frac{34}{100}.

For m=1m = 1, x=(1,12,−12,−1,−12,12)x = (1, \frac{1}{2}, -\frac{1}{2}, -1, -\frac{1}{2}, \frac{1}{2}). At vertex 0 the neighbours average to 12\frac{1}{2}, so the λ\lambda step gives 1+33100(12−1)=1672001 + \frac{33}{100}(\frac{1}{2} - 1) = \frac{167}{200}. All other vertices scale by the same factor 1−λ21 - \frac{\lambda}{2}. The μ\mu step then scales by 1+342001 + \frac{34}{200}, and x0x_0 ends at 167200⋅234200=1953920000=0.97695\frac{167}{200} \cdot \frac{234}{200} = \frac{19539}{20000} = 0.97695. For m=3m = 3, x=(1,−1,1,−1,1,−1)x = (1, -1, 1, -1, 1, -1), the noisiest shape. The λ\lambda step gives x0=1−2λ=1750x_0 = 1 - 2\lambda = \frac{17}{50} and the μ\mu step multiplies by 1−2μ=1681001 - 2\mu = \frac{168}{100}, so x0=357625=0.5712x_0 = \frac{357}{625} = 0.5712.

kk f(k)f(k), one Taubin pass (1−λk)2(1 - \lambda k)^2, two Laplacian steps
0 1 1
1/21/2 0.976950.97695 0.6972250.697225
3/23/2 0.762550.76255 0.2550250.255025
2 0.57120.5712 0.11560.1156

Both damp the noise, but the two Laplacian steps also cut the low mode k=12k = \frac{1}{2} by 30 percent, and the Taubin pass cuts it by 2 percent. On a longer cycle the lowest modes have kk near 0 and are kept almost exactly.

A sphere. On the icosphere with 162 vertices on the unit sphere, 10 Taubin passes with λ=0.33\lambda = 0.33, μ=−0.34\mu = -0.34 change the volume by the measured factor 1.00641.0064. Twenty Laplacian steps with λ=0.33\lambda = 0.33, the same work, give 0.4090.409. After 50 passes the factors are 1.0321.032 and 0.01160.0116.

Correctness

These are proved in the correctness file:

  • A pass is the matrix product. Lines L3 to L6 compute (I−μG)(I−λG)x(I - \mu G)(I - \lambda G)x on the free rows and keep the fixed rows. The tests compare the code with the product of the two step matrices exactly.
  • The transfer function. On a closed mesh, an eigenvector of GG with frequency kk is multiplied by f(k)f(k) in each pass. The tests check this exactly on the hexagon.
  • The shape of ff. For λ>0>μ\lambda > 0 > \mu and λ+μ<0\lambda + \mu < 0, f(0)=f(kPB)=1f(0) = f(k_{PB}) = 1, f(k)>1f(k) > 1 for 0<k<kPB0 < k < k_{PB}, and ff decreases on [kPB,2][k_{PB}, 2]. So every frequency above kPBk_{PB} is damped and the method is stable, exactly when f(2)=(1−2λ)(1−2μ)>−1f(2) = (1 - 2\lambda)(1 - 2\mu) > -1. The largest gain is 1+(λ+μ)2−4λμ1 + \frac{(\lambda + \mu)^2}{-4\lambda\mu}, which is 1.000221.00022 for the factors above.
  • Affine invariance and the weighted centroid. Each step is an affine combination with weights summing to 1, and on a closed mesh each step keeps ∑idixi\sum_i d_i x_i, as for Laplacian smoothing.

The gain above 1 means that Taubin smoothing does not converge as KK grows. The frequencies in (0,kPB)(0, k_{PB}) grow slowly, which is why the measured volume of the sphere grows by 3 percent in 50 passes. The method is a filter used for a fixed small KK, not an iteration to a limit. The volume figures above are measured, not proved.

Proof: A Taubin pass is the product of two Laplacian step matrices, it scales each eigenvector of the uniform Laplacian by (1 - lambda k)(1 - mu k), and this transfer function keeps the low frequencies and damps the othersfull

Setup. The mesh graph has vertices 1,…,n1, \ldots, n, neighbour sets N(i)N(i), valences di≥1d_i \ge 1, adjacency matrix AA, D=diag⁡(di)D = \operatorname{diag}(d_i) and P=D−1AP = D^{-1}A. Let G=I−PG = I - P. FF is the set of fixed vertices. The positions are treated one coordinate at a time. The factors satisfy λ>0\lambda > 0 and μ<−λ\mu < -\lambda, which line L1 checks. The loop runs KK passes of two steps each, so the algorithm stops; the claims are about what it computes.

Lemma 1 (matrix form). For a factor ff, lines L4 to L6 map xx to SfxS_f x, where row ii of SfS_f is row ii of I−fGI - fG for i∉Fi \notin F and row ii of II for i∈Fi \in F. One pass maps xx to SμSλxS_\mu S_\lambda x.

Proof. Line L4 uses the old array xx for every cic_i, since yy is separate until line L6. For i∉Fi \notin F, yi=xi+f(ci−xi)=xi−f(Gx)iy_i = x_i + f(c_i - x_i) = x_i - f(Gx)_i. Line L5 keeps the fixed rows. Line L3 applies the step with λ\lambda and then the step with μ\mu. □\square

Lemma 2 (the steps commute). SλSμ=SμSλS_\lambda S_\mu = S_\mu S_\lambda.

Proof. Let G′G' be GG with the rows of FF set to zero. Then Sf=I−fG′S_f = I - fG', and two polynomials in the same matrix G′G' commute. □\square

Lemma 3 (spectrum). GG is similar to the symmetric matrix I−D−1/2AD−1/2I - D^{-1/2}AD^{-1/2}, so it has real eigenvalues and a basis of eigenvectors. The eigenvalues lie in [0,2][0, 2], and 00 has the eigenvector 1\mathbf{1}.

Proof. G=D−1/2(I−D−1/2AD−1/2)D1/2G = D^{-1/2}(I - D^{-1/2}AD^{-1/2})D^{1/2}. The eigenvalues of PP lie in [−1,1][-1, 1]: for Pv=ρvPv = \rho v and ii with ∣vi∣|v_i| largest, ∣ρ∣∣vi∣≤1di∑j∈N(i)∣vj∣≤∣vi∣|\rho||v_i| \le \frac{1}{d_i}\sum_{j \in N(i)}|v_j| \le |v_i|. So the eigenvalues 1−ρ1 - \rho of GG lie in [0,2][0, 2], and G1=0G\mathbf{1} = 0 because each row of PP sums to 1. □\square

Theorem 1 (transfer function). Let F=∅F = \emptyset. If Gv=kvGv = kv, then one pass maps vv to f(k)vf(k)v with f(k)=(1−λk)(1−μk)f(k) = (1 - \lambda k)(1 - \mu k). For a general x=∑jajvjx = \sum_j a_j v_j in an eigenvector basis, KK passes give ∑jf(kj)Kajvj\sum_j f(k_j)^K a_j v_j.

Proof. With F=∅F = \emptyset, Sf=I−fGS_f = I - fG, so Sλv=(1−λk)vS_\lambda v = (1 - \lambda k)v and SμSλv=(1−μk)(1−λk)vS_\mu S_\lambda v = (1 - \mu k)(1 - \lambda k)v. The general case follows by linearity. □\square

Theorem 2 (shape of the transfer function). Let λ>0\lambda > 0, μ<−λ\mu < -\lambda and kPB=1λ+1μk_{PB} = \frac{1}{\lambda} + \frac{1}{\mu}. Then:

  1. kPB>0k_{PB} > 0, and f(0)=f(kPB)=1f(0) = f(k_{PB}) = 1.
  2. f(k)>1f(k) > 1 for 0<k<kPB0 < k < k_{PB}, with the largest value 1−(λ+μ)24λμ1 - \frac{(\lambda + \mu)^2}{4\lambda\mu} at k∗=kPB/2k^* = k_{PB}/2.
  3. ff is strictly decreasing on [k∗,∞)[k^*, \infty), so f(k)<1f(k) < 1 for k>kPBk > k_{PB}.
  4. ∣f(k)∣<1|f(k)| < 1 for all k∈(kPB,2]k \in (k_{PB}, 2] if and only if f(2)>−1f(2) > -1.

Proof. kPB=λ+μλμk_{PB} = \frac{\lambda + \mu}{\lambda\mu}. Both λ+μ<0\lambda + \mu < 0 and λμ<0\lambda\mu < 0, so kPB>0k_{PB} > 0. Expand f(k)=1−(λ+μ)k+λμk2=1+λμ k(k−kPB)f(k) = 1 - (\lambda + \mu)k + \lambda\mu k^2 = 1 + \lambda\mu\, k (k - k_{PB}), which gives (1). Since λμ<0\lambda\mu < 0, ff is a parabola that opens downward with roots of f−1f - 1 at 00 and kPBk_{PB}. So f>1f > 1 between them, its top is at the midpoint k∗k^*, and f(k∗)=1+λμ k∗(−k∗)=1−λμ (λ+μ)24λ2μ2=1−(λ+μ)24λμf(k^*) = 1 + \lambda\mu\, k^*(-k^*) = 1 - \lambda\mu\, \frac{(\lambda + \mu)^2}{4\lambda^2\mu^2} = 1 - \frac{(\lambda + \mu)^2}{4\lambda\mu}. That is (2) and (3). For (4), on (kPB,2](k_{PB}, 2] the function decreases from 1, so its values lie in [f(2),1)[f(2), 1), and they all have absolute value less than 1 exactly when f(2)>−1f(2) > -1. □\square

Corollary (low-pass filter). On a closed mesh with f(2)>−1f(2) > -1, the parts of xx with frequency in (kPB,2](k_{PB}, 2] tend to 0 as KK grows, the part with k=0k = 0, the weighted centroid, stays, and the parts with k∈(0,kPB)k \in (0, k_{PB}) grow by at most the factor f(k∗)Kf(k^*)^K. So Taubin smoothing is not a convergent iteration. It is used for a fixed small KK, and then the low band is kept up to a factor near 1.

Proof. Theorems 1 and 2 and Lemma 3. For k∈(kPB,2]k \in (k_{PB}, 2], ∣f(k)∣<1|f(k)| < 1, so f(k)K→0f(k)^K \to 0. □\square

Lemma 4 (the weighted centroid). If F=∅F = \emptyset, each step keeps ∑idixi\sum_i d_i x_i, for any factor ff.

Proof. ∑idiyi=(1−f)∑idixi+f∑i∑j∈N(i)xj\sum_i d_i y_i = (1 - f)\sum_i d_i x_i + f\sum_i \sum_{j \in N(i)} x_j, and the double sum counts xjx_j once for each of its djd_j neighbours. □\square

Lemma 5 (affine invariance). Each new position is ∑jsijxj\sum_j s_{ij}x_j with ∑jsij=1\sum_j s_{ij} = 1, so smoothing commutes with every affine map of R3\mathbb{R}^3.

Proof. Row ii of SfS_f sums to (1−f)+f=1(1 - f) + f = 1 or is a row of II, and products of such matrices have rows that sum to 1. □\square

What is measured. The volume changes of the icosphere in the example, 1.00641.0064 after 10 passes and 1.0321.032 after 50, are measured. They agree with the corollary: the sphere is mostly made of low frequencies, which are kept or grow slightly.

Complexity

The neighbour lists take O(n)O(n) time to build. Each pass does two Laplacian steps, each with ∑idi≤6n\sum_i d_i \le 6n additions and one division per free vertex, so KK passes take Θ(Kn)\Theta(Kn) time on the real RAM. The extra space is the array yy and the lists, Θ(n)\Theta(n). The cost is twice that of KK Laplacian steps.

Properties

  • A polynomial filter. KK passes apply the polynomial f(k)Kf(k)^K of degree 2K2K to the spectrum of GG, without computing any eigenvector. This is a finite impulse response filter on the mesh graph.
  • No shrinkage in the low band. Frequencies below kPBk_{PB} are kept or very slightly amplified. Plain Laplacian smoothing damps every nonzero frequency.
  • Linear. The result is a linear function of the input positions, so noise added to a shape is filtered on its own. A test checks this exactly on a cycle.
  • Exact. With rational input and rational factors, all values are exact.
  • Connectivity-dependent. With the uniform weights, the frequencies depend on the graph, not on the geometry, and flat irregular regions drift inside the plane.

Variants and improvements

  • Other weights. Use the cotangent weights, or Fujiwara's inverse edge-length weights, in place of the uniform average. The spectral analysis then holds for the generalized eigenproblem of the weighted Laplacian.
  • Other polynomials. Taubin, Zhang and Golub (1996) designed polynomial low-pass filters of higher degree with a sharper cut-off than (1−λk)(1−μk)(1 - \lambda k)(1 - \mu k), evaluated with the recurrence of the Chebyshev polynomials. The Butterworth filter is a 1-D analogue.
  • Implicit steps. Implicit fairing solves a linear system per step and is stable for any step size, at a higher cost per step.
  • Curves. The same two steps smooth a closed polygon, as in the hexagon example, and any graph with positions.

When to use it

Use it to remove noise from a scanned or reconstructed mesh without changing its size, when a fast explicit method is wanted and the noise is at the scale of a few edges. It is the default non-shrinking smoother in many mesh libraries. Use implicit fairing when the mesh is irregular and the geometry should decide the smoothing, and Laplacian smoothing when shrinking does not matter or the border is fixed and close.

Pitfalls

  • μ\mu too close to −λ-\lambda. Then kPBk_{PB} is near 0 and almost everything is damped, as in plain smoothing. If ∣μ∣|\mu| is much larger than λ\lambda, kPBk_{PB} is large and the low band grows.
  • Too many passes. The gain above 1 in (0,kPB)(0, k_{PB}) makes the low frequencies grow. Hundreds of passes inflate the mesh slowly.
  • λ\lambda too large. If λ≥1/2\lambda \ge 1/\sqrt{2}, then −μ>λ-\mu > \lambda gives f(2)=−(2λ−1)(1−2μ)<−(4λ2−1)≤−1f(2) = -(2\lambda - 1)(1 - 2\mu) < -(4\lambda^2 - 1) \le -1, and the highest frequencies grow with alternating sign.
  • Wrong order of steps. The two step matrices commute, so the order does not change the linear map. But doing all λ\lambda steps first and then all μ\mu steps can lose precision in floating point, because the intermediate shape is tiny.
  • A free border. On an open mesh without fixed vertices, the border moves inward in the λ\lambda step and outward in the μ\mu step, and does not stay where it was.

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.

mp2mesh.pyI0RawGitHub
# 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
taubin_smoothing.py 57 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/taubin-smoothing/. The authors are listed in prov/Y17GAM.jsonl.

"""Taubin's lambda-mu smoothing (SIGGRAPH 1995) with the uniform weights.

Each pass does two Laplacian steps, x <- x + f (c - x), first with the
shrinking factor f = lam > 0 and then with the inflating factor f = mu < -lam,
where c_i is the centroid of the neighbours of vertex i. A frequency k of
the graph Laplacian I - D^-1 A is multiplied by (1 - lam k)(1 - mu k) per pass.
The steps work on any graph, given by its neighbour lists, so that a test can
use a cycle, whose eigenvectors are known.
"""

from fractions import Fraction
from typing import Iterable, Optional, Sequence

from mp2mesh import boundary_vertices, neighbours

Point = tuple


def taubin_graph(points: Sequence[Sequence], nb: Sequence[Sequence[int]], lam, mu, passes: int,
                 fixed: Iterable[int] = ()) -> list[Point]:
    """Taubin smoothing on a graph with neighbour lists nb."""
    stay = set(fixed)
    x = [tuple(p) for p in points]
    for _ in range(passes):                                   # @line L2
        for f in (lam, mu):                                   # @line L3
            y = list(x)                                       # @line L5
            for i in range(len(x)):                           # @line L4
                if i in stay or not nb[i]:
                    continue
                d = len(nb[i])
                c = tuple(sum(x[j][k] for j in nb[i]) / d for k in range(len(x[i])))
                y[i] = tuple(x[i][k] + f * (c[k] - x[i][k]) for k in range(len(x[i])))
            x = y                                             # @line L6
    return x


def taubin_smoothing(points: Sequence[Sequence], faces: Sequence[Sequence[int]], lam=Fraction(33, 100),
                     mu=Fraction(-34, 100), passes: int = 1, fixed: Optional[Iterable[int]] = None) -> list[Point]:
    """Taubin smoothing of a triangle mesh. The border vertices are fixed unless `fixed` is given."""
    if not (lam > 0 and mu < -lam):
        raise ValueError("need lam > 0 and mu < -lam")
    nb = neighbours(len(points), faces)                       # @line L1
    stay = boundary_vertices(faces) if fixed is None else set(fixed)
    return taubin_graph(points, nb, lam, mu, passes, stay)


def transfer(k, lam, mu):
    """The factor (1 - lam k)(1 - mu k) of one pass on the frequency k."""
    return (1 - lam * k) * (1 - mu * k)


def pass_band(lam, mu):
    """The frequency k_PB = 1/lam + 1/mu > 0 where the transfer function is 1 again."""
    return 1 / lam + 1 / mu
test_taubin_smoothing.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/taubin-smoothing/. The authors are listed in prov/Y17GAM.jsonl.

import random
from fractions import Fraction as Fr

from mp2mesh import boundary_vertices, grid_mesh, icosphere, neighbours, signed_volume
from taubin_smoothing import pass_band, taubin_graph, taubin_smoothing, transfer

LAM, MU = Fr(33, 100), Fr(-34, 100)

# The hexagon modes cos(pi m i / 3), m = 0, 1, 2, 3, have the frequencies k = 1 - cos(pi m / 3).
HEX_MODES = {
    0: ([1, 1, 1, 1, 1, 1], Fr(0)),
    1: ([1, Fr(1, 2), Fr(-1, 2), -1, Fr(-1, 2), Fr(1, 2)], Fr(1, 2)),
    2: ([1, Fr(-1, 2), Fr(-1, 2), 1, Fr(-1, 2), Fr(-1, 2)], Fr(3, 2)),
    3: ([1, -1, 1, -1, 1, -1], Fr(2)),
}


def cycle(n):
    return [[(i - 1) % n, (i + 1) % n] for i in range(n)]


# ---- brute force: the product of the two step matrices, as dense matrices ----


def step_matrix(nb, f, fixed):
    n = len(nb)
    S = [[Fr(0)] * n for _ in range(n)]
    for i in range(n):
        if i in fixed or not nb[i]:
            S[i][i] = Fr(1)
            continue
        S[i][i] = 1 - f
        for j in nb[i]:
            S[i][j] += f / len(nb[i])
    return S


def matmul(A, B):
    n = len(A)
    return [[sum(A[i][k] * B[k][j] for k in range(n)) for j in range(n)] for i in range(n)]


def matrix_taubin(points, nb, lam, mu, passes, fixed):
    T = matmul(step_matrix(nb, mu, fixed), step_matrix(nb, lam, fixed))
    x = [list(p) for p in points]
    d = len(points[0])
    for _ in range(passes):
        x = [[sum(T[i][j] * x[j][k] for j in range(len(x))) for k in range(d)] for i in range(len(x))]
    return [tuple(r) for r in x]


def test_hexagon_modes_are_scaled_by_the_transfer_function() -> None:
    assert transfer(Fr(1, 2), LAM, MU) == Fr(19539, 20000)
    assert transfer(Fr(3, 2), LAM, MU) == Fr(15251, 20000)
    assert transfer(Fr(2), LAM, MU) == Fr(357, 625)
    for m, (v, k) in HEX_MODES.items():
        x = [(Fr(c),) for c in v]
        for passes in (1, 2, 3):
            y = taubin_graph(x, cycle(6), LAM, MU, passes)
            g = transfer(k, LAM, MU) ** passes
            assert y == [(g * c[0],) for c in x]


def test_example_trace() -> None:
    x = [(Fr(c),) for c in HEX_MODES[1][0]]
    assert taubin_graph(x, cycle(6), LAM, 0, 1)[0] == (Fr(167, 200),)
    assert taubin_graph(x, cycle(6), LAM, MU, 1)[0] == (Fr(19539, 20000),)
    x = [(Fr(c),) for c in HEX_MODES[3][0]]
    assert taubin_graph(x, cycle(6), LAM, 0, 1)[0] == (Fr(17, 50),)
    assert taubin_graph(x, cycle(6), LAM, MU, 1)[0] == (Fr(357, 625),)


def test_against_matrix_product() -> None:
    rng = random.Random(17)
    for _ in range(12):
        p, f = grid_mesh(rng.randrange(1, 4), rng.randrange(1, 4))
        p = [(Fr(a) + Fr(rng.randrange(-2, 3), 8), Fr(b) + Fr(rng.randrange(-2, 3), 8), Fr(rng.randrange(-4, 5), 8))
             for a, b, _ in p]
        lam = Fr(rng.randrange(1, 9), 10)
        mu = -lam - Fr(rng.randrange(1, 5), 100)
        k = rng.randrange(1, 3)
        nb = neighbours(len(p), f)
        fixed = boundary_vertices(f)
        assert taubin_smoothing(p, f, lam, mu, k) == matrix_taubin(p, nb, lam, mu, k, fixed)
        assert taubin_smoothing(p, f, lam, mu, k, fixed=()) == matrix_taubin(p, nb, lam, mu, k, set())


def test_border_fixed() -> None:
    rng = random.Random(4)
    p, f = grid_mesh(4, 3)
    p = [(Fr(a), Fr(b), Fr(rng.randrange(-4, 5), 8)) for a, b, _ in p]
    x = taubin_smoothing(p, f, passes=4)
    for v in boundary_vertices(f):
        assert x[v] == p[v]


def test_pass_band() -> None:
    kpb = pass_band(LAM, MU)
    assert kpb == Fr(50, 561)
    assert transfer(kpb, LAM, MU) == 1 and transfer(0, LAM, MU) == 1
    for i in range(1, 201):
        k = Fr(i, 100)
        g = transfer(k, LAM, MU)
        if k < kpb:
            assert 1 < g < Fr(10003, 10000)          # a slight gain on the lowest frequencies
        else:
            assert -1 < g < 1                         # damped, and stable up to k = 2


def test_shrinks_much_less_than_laplacian() -> None:
    p, f = icosphere(2)
    v0 = signed_volume(p, f)
    x = taubin_smoothing(p, f, 0.33, -0.34, 10)
    assert 0.99 < signed_volume(x, f) / v0 < 1.02    # measured: 1.0064
    nb = neighbours(len(p), f)
    y = taubin_graph(p, nb, 0.33, 0.0, 20)           # 20 plain Laplacian steps, the same work
    assert signed_volume(y, f) / v0 < 0.5            # measured: 0.409


def test_high_frequency_noise_is_removed() -> None:
    n = 12
    rng = random.Random(9)
    base = [(Fr(rng.randrange(-8, 9), 8),) for _ in range(n)]
    smooth = taubin_graph(base, cycle(n), LAM, MU, 0)
    alt = [(Fr((-1) ** i, 10),) for i in range(n)]
    x = [(a[0] + b[0],) for a, b in zip(base, alt)]
    y = taubin_graph(x, cycle(n), LAM, MU, 3)
    z = taubin_graph(smooth, cycle(n), LAM, MU, 3)
    # linearity: the result is the smoothed base plus the alternating mode times f(2)^3
    g = transfer(Fr(2), LAM, MU) ** 3
    assert y == [(a[0] + g * b[0],) for a, b in zip(z, alt)]


def test_bad_parameters() -> None:
    p, f = grid_mesh(1, 1)
    for lam, mu in ((Fr(1, 3), Fr(-1, 3)), (Fr(-1, 3), Fr(-1, 2)), (Fr(1, 3), Fr(1, 2))):
        try:
            taubin_smoothing(p, f, lam, mu)
        except ValueError:
            continue
        raise AssertionError("bad parameters were accepted")

History

Taubin published the method in 1995, in a SIGGRAPH paper on fair surface design and in an ICCV paper on curve and surface smoothing without shrinkage, while he was at IBM. He viewed the vertex positions as a signal on the mesh graph, the eigenvectors of the Laplacian as its frequencies, and plain Laplacian smoothing as a filter with transfer function 1−λk1 - \lambda k. The second step with a negative factor gave a low-pass filter. In 1996 Taubin, Zhang and Golub designed sharper polynomial filters, and in 1999 Desbrun, Meyer, Schröder and Barr replaced the explicit steps by implicit fairing with cotangent weights.

References

  1. Gabriel Taubin, A signal processing approach to fair surface design, Proceedings of SIGGRAPH 95, 1995, 351 to 358, the lambda-mu algorithm, its transfer function (1 - lambda k)(1 - mu k), and the pass-band frequency 1/lambda + 1/mu
  2. Gabriel Taubin, Curve and surface smoothing without shrinkage, Proceedings of the Fifth International Conference on Computer Vision (ICCV), 1995, 852 to 857, the same two-step filter for curves and surfaces, with the analysis of the shrinkage of plain Laplacian smoothing
  3. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 4, Smoothing (the spectral view of Laplacian smoothing and the lambda-mu filter)

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