Algorithm Search⌘K

Algorithmresearch

Heat method

Also called heat method for geodesics.

Crane, Weischedel and Wardetzky's geodesic distance by a short heat flow, normalizing its gradient and solving a Poisson equation, with two sparse linear solves.

Time
Θ(s n) worst
Space
Θ(n) extra
Where
n = the number of vertices; s = the number of solver iterations
Properties
deterministicnot exactiterative
Origin
Keenan Crane, Clarisse Weischedel, Max Wardetzky, 2013

The heat method computes an approximate geodesic distance from a set of source vertices to every vertex of a triangle mesh, with two sparse linear solves and one pass over the faces. It lets heat flow from the sources for a short time tt. The heat uu itself is a poor guide to distance, but its gradient points away from the sources. So the method keeps only the direction, X=−∇u/∣∇u∣X = -\nabla u/|\nabla u|, a field of unit vectors along which distance grows at rate 1. Then it finds the function φ\varphi whose gradient is closest to XX, by solving a Poisson equation. Both matrices are built from the cotangent Laplacian, do not depend on the source, and can be factored once. Then each new source costs two back-substitutions. This is a solution method for the discrete geodesic problem. It is not exact, and its error shrinks as the mesh is refined.

In plain words

Touch the surface at one point with something hot and wait a moment. The heat spreads out. Close to the point it is hot, farther away it is cooler. The heat does not tell you the distance well, because it fades in a complicated way. But the direction in which it gets cooler always points straight away from the hot point.

So the method warms the surface for a moment, notes on each triangle only the direction in which it gets cooler, and throws away how fast. That gives arrows of length one that point away from the start. A distance is a function that grows by exactly one per unit step along such arrows. The last step finds the function whose slope best matches the arrows, which is one more system of equations. Its values are the distances.

The problem

The input is a connected triangle mesh with positions x1,…,xnx_1, \ldots, x_n, a nonempty set SS of source vertices, and a time t>0t > 0, by default t=h2t = h^2 for the mean edge length hh. The output is a value φi\varphi_i at each vertex that approximates the geodesic distance from vertex ii to SS on the surface, with min⁡s∈Sφs=0\min_{s \in S}\varphi_s = 0. Exact distances are the task of the MMP algorithm. The heat method trades exactness for two linear solves.

The algorithm

Let C=−LC = -L be the cotangent stiffness matrix, MM the lumped mass matrix (one third of the face areas at each vertex), and δ\delta the vector with 1 at the sources and 0 elsewhere. On a face with area AfA_f, unit normal NN, and the edge eie_i opposite vertex ii taken in the order of the face, the gradient of the linear interpolant of uu is ∇u=12Af∑iui (N×ei)\nabla u = \frac{1}{2A_f}\sum_i u_i\, (N \times e_i). For a vector XfX_f on each face, the integrated divergence at vertex ii is

(∇⋅X)i=12∑f∋i(cot⁡θ1 (e1⋅Xf)+cot⁡θ2 (e2⋅Xf)),(\nabla \cdot X)_i = \frac{1}{2}\sum_{f \ni i}\big(\cot\theta_1\,(e_1 \cdot X_f) + \cot\theta_2\,(e_2 \cdot X_f)\big),

where e1e_1, e2e_2 are the two edges of ff out of ii and θ1\theta_1, θ2\theta_2 the angles of ff opposite them.

  1. HEAT-METHOD(x[1 .. n], faces, S, t)
  2. 1t ← h² for the mean edge length h, if not given
  3. 2C, M ← the cotangent stiffness and the lumped mass matrices
  4. 3solve (M + t C) u = δ_S ▷ one backward Euler step of heat flow
  5. 4for each face f do X_f ← −∇u / |∇u| ▷ the unit direction away from S
  6. 5b_i ← (∇ · X)_i for each vertex i
  7. 6solve C φ = −b with φ_s = 0 for one source s ▷ the Poisson equation
  8. 7φ ← φ − min over s ∈ S of φ_s
  9. return φ

Line L3 is one backward Euler step of the heat equation u˙=Δu\dot u = \Delta u from the initial heat δS\delta_S. The matrix M+tCM + tC is symmetric positive definite. Line L6 is the weak form of the Poisson equation Δφ=∇⋅X\Delta\varphi = \nabla \cdot X. The matrix CC has the constants in its kernel, so one value is fixed. The code solves both systems by conjugate gradients, or by a dense solver for tests.

Example

A flat square. Take the unit square as an 8×88 \times 8 grid of right triangles, with the diagonals from (i,j)(i, j) to (i+1,j+1)(i + 1, j + 1), and the source at the corner (0,0)(0, 0). On a flat convex region the geodesic distance is the straight-line distance. The table lists measured values of the heat method and of Dijkstra's algorithm on the edge graph.

point exact heat method edge Dijkstra
(1/2,1/2)(1/2, 1/2) 0.70710.7071 0.72460.7246 0.70710.7071
(1,1/4)(1, 1/4) 1.03081.0308 0.98360.9836 1.10361.1036
(1,1/2)(1, 1/2) 1.11801.1180 1.08561.0856 1.20711.2071
(1,1)(1, 1) 1.41421.4142 1.42761.4276 1.41421.4142
(1,0)(1, 0) 11 0.92860.9286 11

Edge paths are exact along the grid lines and the diagonals, and too long in every other direction, 1.2071=22+121.2071 = \frac{\sqrt{2}}{2} + \frac{1}{2} instead of 52\frac{\sqrt{5}}{2} at (1,12)(1, \frac{1}{2}), and no refinement removes this. The heat method errs in both directions but has the smaller mean error, 0.0210.021 against 0.0360.036. Its largest errors are on the border, as at (1,0)(1, 0), where the free (Neumann) boundary condition of the heat flow bends the gradient. On the 4×44 \times 4, 8×88 \times 8 and 16×1616 \times 16 grids the measured mean error is 0.0330.033, 0.0210.021 and 0.0140.014.

A sphere. On the icosphere with 42, 162 and 642 vertices on the unit sphere, the measured mean error against the great-circle distance is 0.0960.096, 0.0450.045 and 0.0230.023. It halves with each refinement, so it is about proportional to the edge length. At the antipode of the source of the 162-vertex sphere the method gives 3.0453.045 against π\pi.

Correctness

The method is an approximation. These parts are proved in the correctness file:

  • Both systems have unique solutions. M+tCM + tC is symmetric positive definite. CC restricted to the vertices other than one pinned vertex is positive definite on a connected mesh.
  • The Poisson step inverts the gradient. If XX is the gradient of a piecewise linear function φ0\varphi^0, then line L5 gives b=−Cφ0b = -C\varphi^0, and lines L6 and L7 return φ0\varphi^0 up to a constant. So the only errors come from XX not being a gradient field of unit length. The tests check this identity on random functions.
  • Least squares. In general, line L6 returns the piecewise linear φ\varphi that minimizes ∫∣∇φ−X∣2 dA\int |\nabla\varphi - X|^2\,dA.
  • Why it works in the limit. For a smooth surface, Varadhan's formula says that the heat kernel satisfies −4tlog⁡kt(x,y)→d(x,y)2-4t\log k_t(x, y) \to d(x, y)^2 as t→0t \to 0. So for small tt, ∇u\nabla u is nearly parallel to −∇d-\nabla d, and XX is nearly ∇d\nabla d, which has unit length. Crane, Weischedel and Wardetzky analyse the error when the mesh is refined with t=mh2t = mh^2. This page does not prove convergence on meshes and gives no proved rate.

The errors of the examples are measured, not proved.

Proof: The two systems of the heat method have unique solutions, the divergence of line L5 is the weak divergence, and the Poisson step returns the piecewise linear function whose gradient is closest to the unit fieldfull

Setup. The mesh is connected, every face has positive area, and the faces are oriented. φi\varphi_i is the hat function of vertex ii, linear on each face, 1 at ii and 0 at the other vertices. A function uu on the vertices has the piecewise linear interpolant ∑iuiφi\sum_i u_i\varphi_i. Cij=∫∇φi⋅∇φj dAC_{ij} = \int \nabla\varphi_i \cdot \nabla\varphi_j\,dA is the cotangent stiffness matrix, as on the cotangent Laplacian page, and MM is the diagonal lumped mass with positive entries. The algorithm does one pass over the faces and two linear solves, so it stops once the solves stop, which Lemma 1 shows. What it computes is an approximation; the claims below are about the exact parts.

Lemma 1 (unique solutions). M+tCM + tC is symmetric positive definite for t>0t > 0. For any vertex ss, the matrix C′C' obtained from CC by deleting row and column ss is symmetric positive definite. So lines L3 and L6 have unique solutions, and conjugate gradients reach them in finitely many steps in exact arithmetic.

Proof. u⊤Cu=∫∣∇u∣2 dA≥0u^\top C u = \int |\nabla u|^2\,dA \ge 0, so CC is positive semidefinite, and u⊤(M+tC)u≥u⊤Mu>0u^\top(M + tC)u \ge u^\top M u > 0 for u≠0u \ne 0. For C′C', let y≠0y \ne 0 and let zz be yy with zs=0z_s = 0 inserted. Then y⊤C′y=z⊤Cz=∫∣∇z∣2 dAy^\top C' y = z^\top C z = \int |\nabla z|^2\,dA. If this is 0, then ∇z=0\nabla z = 0 on every face, so zz is constant on the connected mesh, and zs=0z_s = 0 gives z=0z = 0, a contradiction. □\square

Lemma 2 (gradient of a hat function). On a face ff with area AfA_f, unit normal NN, and eie_i the edge opposite ii in the order of the face, ∇φi=12AfN×ei\nabla\varphi_i = \frac{1}{2A_f}N \times e_i. So the formula of line L4 is the gradient of the interpolant.

Proof. N×eiN \times e_i lies in the plane of ff, is perpendicular to eie_i, has length ∣ei∣|e_i|, and points from eie_i toward ii because the face is oriented by NN. φi\varphi_i is 0 on the line of eie_i and 1 at ii, at the height 2Af/∣ei∣2A_f/|e_i| above it. So its gradient is perpendicular to eie_i, points toward ii, and has length ∣ei∣/(2Af)|e_i|/(2A_f). □\square

Lemma 3 (the divergence is the weak divergence). For any face vectors XfX_f in the planes of the faces, the value of line L5 is bi=−∑f∋iAf ∇φi∣f⋅Xf=−∫X⋅∇φi dAb_i = -\sum_{f \ni i} A_f\,\nabla\varphi_i|_f \cdot X_f = -\int X \cdot \nabla\varphi_i\,dA.

Proof. Fix a face with vertices i,j,li, j, l in order, and let e1=pj−pie_1 = p_j - p_i, e2=pl−pie_2 = p_l - p_i, a=∣e1∣a = |e_1|, b=∣e2∣b = |e_2|, c=e1⋅e2c = e_1 \cdot e_2. The angle at ll is opposite e1e_1 and the angle at jj is opposite e2e_2, and cot⁡θl=(−e2)⋅(e1−e2)2Af=b2−c2Af\cot\theta_l = \frac{(-e_2)\cdot(e_1 - e_2)}{2A_f} = \frac{b^2 - c}{2A_f}, cot⁡θj=(−e1)⋅(e2−e1)2Af=a2−c2Af\cot\theta_j = \frac{(-e_1)\cdot(e_2 - e_1)}{2A_f} = \frac{a^2 - c}{2A_f}. Let V=cot⁡θl e1+cot⁡θj e2V = \cot\theta_l\, e_1 + \cot\theta_j\, e_2 and W=−N×(pl−pj)=−N×eiW = -N \times (p_l - p_j) = -N \times e_i. Both lie in the plane of the face, which e1e_1 and e2e_2 span, so it is enough to compare their dot products with e1e_1 and e2e_2. First, V⋅e1=(b2−c)a2+(a2−c)c2Af=a2b2−c22Af=(2Af)22Af=2AfV \cdot e_1 = \frac{(b^2 - c)a^2 + (a^2 - c)c}{2A_f} = \frac{a^2b^2 - c^2}{2A_f} = \frac{(2A_f)^2}{2A_f} = 2A_f, and by symmetry V⋅e2=2AfV \cdot e_2 = 2A_f. Second, with pl−pj=e2−e1p_l - p_j = e_2 - e_1, W⋅e1=(N×e1)⋅e1−(N×e2)⋅e1=N⋅(e1×e2)=2AfW \cdot e_1 = (N \times e_1)\cdot e_1 - (N \times e_2)\cdot e_1 = N \cdot (e_1 \times e_2) = 2A_f, and in the same way W⋅e2=(N×e1)⋅e2=N⋅(e1×e2)=2AfW \cdot e_2 = (N \times e_1) \cdot e_2 = N \cdot (e_1 \times e_2) = 2A_f. So V=WV = W, and the term of this face in line L5 is 12V⋅Xf=−12(N×ei)⋅Xf=−Af ∇φi⋅Xf\frac{1}{2}V \cdot X_f = -\frac{1}{2}(N \times e_i)\cdot X_f = -A_f\,\nabla\varphi_i \cdot X_f by Lemma 2. □\square

Lemma 4 (the pinned system solves the full system). The solution φ\varphi of line L6 satisfies Cφ=−bC\varphi = -b in every row, including row ss.

Proof. By Lemma 3, ∑ibi=−∫X⋅∇(∑iφi) dA=0\sum_i b_i = -\int X \cdot \nabla(\sum_i \varphi_i)\,dA = 0, because ∑iφi=1\sum_i \varphi_i = 1. The rows of CC also sum to the zero vector, since C1=0C\mathbf{1} = 0 and CC is symmetric. So row ss of Cφ+bC\varphi + b is minus the sum of the other rows, which are 0. □\square

Theorem 1 (the Poisson step inverts the gradient). If Xf=∇ψ∣fX_f = \nabla\psi|_f for a piecewise linear ψ\psi, then lines L5 to L7 return ψ−min⁡s∈Sψs\psi - \min_{s \in S}\psi_s.

Proof. By Lemma 3, bi=−∑fAf ∇φi⋅∇ψ=−∑jCijψjb_i = -\sum_f A_f\,\nabla\varphi_i \cdot \nabla\psi = -\sum_j C_{ij}\psi_j, so b=−Cψb = -C\psi. The vector ψ−ψs1\psi - \psi_s\mathbf{1} is 0 at ss and satisfies C(ψ−ψs1)=Cψ=−bC(\psi - \psi_s\mathbf{1}) = C\psi = -b, so by Lemma 1 it is the solution of line L6. Line L7 subtracts the smallest value at a source. □\square

Theorem 2 (least squares). For any face vectors XX, the result of line L6 minimizes Q(φ)=∫∣∇φ−X∣2 dAQ(\varphi) = \int |\nabla\varphi - X|^2\,dA over all piecewise linear φ\varphi with φs=0\varphi_s = 0, and so, up to a constant, over all piecewise linear φ\varphi.

Proof. Q(φ)=φ⊤Cφ−2∫X⋅∇φ dA+∫∣X∣2=φ⊤Cφ+2b⊤φ+constQ(\varphi) = \varphi^\top C\varphi - 2\int X \cdot \nabla\varphi\,dA + \int |X|^2 = \varphi^\top C\varphi + 2b^\top\varphi + \text{const} by Lemma 3. This is a convex quadratic, and its gradient is 2(Cφ+b)2(C\varphi + b), which is 0 exactly at the solution of Cφ=−bC\varphi = -b. □\square

So the computed φ\varphi is the exact distance whenever the unit field XX is the gradient of a piecewise linear function, and in general it is the best fit to XX. The error of the method is the error of XX as a gradient of the distance.

What is not proved here. That XX is close to the gradient of the true distance rests on Varadhan's formula −4tlog⁡kt(x,y)→d(x,y)2-4t\log k_t(x, y) \to d(x, y)^2 for smooth surfaces, and on the analysis of Crane, Weischedel and Wardetzky for meshes. The errors on the flat grid and on the icosphere are measured.

Complexity

Building CC, MM, the gradients and the divergence takes O(n)O(n) time. The two solves dominate. With conjugate gradients each takes ss iterations of O(n)O(n) work, so Θ(sn)\Theta(sn) in total on the real RAM, with ss of order n\sqrt{n} for a well-shaped mesh. With a sparse Cholesky factorization, the two factorizations cost about O(n1.5)O(n^{1.5}) time once, by nested dissection, and each new source set then costs two back-substitutions, about O(nlog⁡n)O(n \log n). This reuse is the main practical gain: the factors depend only on the mesh. The extra space is Θ(n)\Theta(n) for conjugate gradients, more for the factors.

Properties

  • Approximate. The error is not bounded by a constant times the true distance on a fixed mesh. It goes to 0 under refinement, at about first order in hh in the measured examples.
  • Smooth output. The result has no sharp crease at the cut locus, where two shortest paths meet, because the heat flow smooths it. A larger tt smooths more.
  • Any set of sources. A point, a curve of vertices, or a region, at the same cost.
  • Not monotone. Nothing forces φ≥0\varphi \ge 0 or the triangle inequality. Small negative values near a source can occur.
  • Works on other domains. The same three steps apply to point clouds, polygon meshes and grids, wherever a Laplacian, a gradient and a divergence exist.

Variants and improvements

  • Boundary conditions. On a mesh with a border, Crane et al. suggest the mean of the heat solutions with zero Neumann and zero Dirichlet conditions, which reduces the error near the border seen in the flat example.
  • The time step. t=mh2t = mh^2 with m=1m = 1 is the default. A larger mm gives a smoother result, and a smaller mm follows the true distance more closely until the mesh is too coarse to resolve the heat.
  • Intrinsic Delaunay meshes. Computing CC on an intrinsic Delaunay triangulation of the same surface keeps the weights nonnegative and improves accuracy on poor meshes.
  • Exact methods. The MMP algorithm and its successors compute exact distances, at a cost of O(n2log⁡n)O(n^2 \log n) in the worst case.
  • Fast marching. The fast marching method solves the eikonal equation ∣∇d∣=1|\nabla d| = 1 directly, in O(nlog⁡n)O(n \log n) time, with first-order error and an extra step on obtuse triangles.

When to use it

Use it when many distance queries are made on one fixed mesh, because the factorizations are reused, and when a smooth, approximate distance is enough, as for texture placement, sampling, mesh segmentation or the descriptors of shape analysis. Use the MMP algorithm when exact distances or exact shortest paths are needed, and Dijkstra on the edge graph only for a fast upper bound.

Pitfalls

  • The sign of the Laplacian. With L=−CL = -C, the Poisson equation is Lφ=∇⋅XL\varphi = \nabla \cdot X, that is Cφ=−∇⋅XC\varphi = -\nabla \cdot X. With the wrong sign, the result is minus the distance, and the shift of line L7 hides the error until the values are compared.
  • Forgetting to normalize. Solving the Poisson equation with −∇u-\nabla u itself, not its direction, gives a smooth function that is not a distance.
  • A tt too small for the mesh. If t≪h2t \ll h^2, the heat does not reach past the first ring of the source, ∇u\nabla u is near 0 elsewhere, and the directions are noise from rounding.
  • Degenerate and obtuse triangles. They give huge or negative cotangents and a poorly conditioned system. Remesh, or use an intrinsic Delaunay triangulation.
  • Disconnected meshes. The heat never reaches another part, and CC has one constant per part in its kernel. Run the method on each part.
  • The border. Near a border the error is larger, as in the example.

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.

heat_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/heat-method/. The authors are listed in prov/MWDDTN.jsonl.

"""The heat method for geodesic distance (Crane, Weischedel and Wardetzky, 2013).

1. Heat: solve (M + t C) u = delta, one backward Euler step of the heat
   equation from the sources, with t = h^2 for the mean edge length h.
2. Normalize: on each face, X = -grad u / |grad u|.
3. Poisson: solve C phi = -div X, with the integrated divergence of X at
   each vertex, and shift phi so that the smallest value at a source is 0.

C is the cotangent stiffness matrix (C = -L) and M the lumped mass.
"""

from typing import Iterable, Optional, Sequence

from mp2mesh import (conjugate_gradient, cot_at, cross, dense, dot, lumped_mass, mean_edge_length, norm, scale,
                     solve_dense, stiffness_matrix, sub)

Vec = tuple


def face_gradients(points, faces, u) -> list[Vec]:
    """The gradient of the linear interpolant of u on each face: (1 / 2A) sum of u_i (N x e_i)."""
    out = []
    for f in faces:
        p = [points[v] for v in f]
        n = cross(sub(p[1], p[0]), sub(p[2], p[0]))
        a2 = norm(n)                                       # twice the area
        nn = scale(1 / a2, n)
        g = (0.0, 0.0, 0.0)
        for k in range(3):
            e = sub(p[(k + 2) % 3], p[(k + 1) % 3])         # the edge opposite vertex k, in face order
            g = tuple(gi + u[f[k]] * ci / a2 for gi, ci in zip(g, cross(nn, e)))
        out.append(g)
    return out


def divergence(points, faces, X) -> list[float]:
    """The integrated divergence at each vertex: 1/2 sum over faces of cot(t1) (e1 . X) + cot(t2) (e2 . X)."""
    div = [0.0] * len(points)
    for f, x in zip(faces, X):
        for k in range(3):
            i, j, l = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
            pi, pj, pl = points[i], points[j], points[l]
            e1, e2 = sub(pj, pi), sub(pl, pi)
            div[i] += 0.5 * (cot_at(pl, pi, pj) * dot(e1, x) + cot_at(pj, pl, pi) * dot(e2, x))
    return div


def solve_pinned(C, b, pin: int, solver: str) -> list[float]:
    """Solve C phi = b with phi[pin] = 0. C is singular with the constants in its kernel."""
    n = len(b)
    keep = [i for i in range(n) if i != pin]
    pos = {v: r for r, v in enumerate(keep)}
    A = [{pos[j]: c for j, c in C[i].items() if j in pos} for i in keep]
    rhs = [b[i] for i in keep]
    y = solve_dense(dense(A), rhs) if solver == "dense" else conjugate_gradient(A, rhs)
    phi = [0.0] * n
    for r, i in enumerate(keep):
        phi[i] = y[r]
    return phi


def heat_method(points: Sequence[Sequence[float]], faces: Sequence[Sequence[int]], sources: Iterable[int],
                t: Optional[float] = None, solver: str = "cg") -> list[float]:
    """Approximate geodesic distance from the source vertices to every vertex of a connected mesh."""
    src = sorted(set(sources))
    n = len(points)
    if t is None:
        t = mean_edge_length(points, faces) ** 2                       # @line L1
    C = stiffness_matrix(points, faces)                                 # @line L2
    M = lumped_mass(points, faces)
    A = [{j: t * c for j, c in C[i].items()} for i in range(n)]
    for i in range(n):
        A[i][i] = A[i].get(i, 0.0) + M[i]
    delta = [1.0 if i in src else 0.0 for i in range(n)]
    u = solve_dense(dense(A), delta) if solver == "dense" else conjugate_gradient(A, delta)  # @line L3
    X = []
    for g in face_gradients(points, faces, u):                          # @line L4
        m = norm(g)
        X.append(scale(-1 / m, g) if m > 0 else (0.0, 0.0, 0.0))
    div = divergence(points, faces, X)                                  # @line L5
    phi = solve_pinned(C, [-d for d in div], src[0], solver)            # @line L6
    low = min(phi[s] for s in src)
    return [p - low for p in phi]                                       # @line L7
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_heat_method.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/heat-method/. The authors are listed in prov/MWDDTN.jsonl.

import heapq
import random
from math import acos

from heat_method import divergence, face_gradients, heat_method, solve_pinned
from mp2mesh import dot, edges, grid_mesh, icosphere, mat_vec, norm, stiffness_matrix, sub


def mean_error(d, exact):
    return sum(abs(a - b) for a, b in zip(d, exact)) / len(d)


def great_circle(points, s):
    return [acos(max(-1.0, min(1.0, dot(q, points[s])))) for q in points]


# ---- reference: Dijkstra on the edge graph, an upper bound on the true distance ----


def edge_dijkstra(points, faces, s):
    adj = {i: [] for i in range(len(points))}
    for i, j in edges(faces):
        w = norm(sub(points[i], points[j]))
        adj[i].append((j, w))
        adj[j].append((i, w))
    dist = [float("inf")] * len(points)
    dist[s] = 0.0
    pq = [(0.0, s)]
    while pq:
        d, v = heapq.heappop(pq)
        if d > dist[v]:
            continue
        for w, c in adj[v]:
            if d + c < dist[w]:
                dist[w] = d + c
                heapq.heappush(pq, (d + c, w))
    return dist


def test_poisson_step_recovers_a_piecewise_linear_function() -> None:
    rng = random.Random(1)
    for p, f in (icosphere(1), grid_mesh(4, 3, 0.5)):
        phi0 = [rng.uniform(-1, 1) for _ in p]
        X = face_gradients(p, f, phi0)
        div = divergence(p, f, X)
        Cphi = mat_vec(stiffness_matrix(p, f), phi0)
        assert max(abs(d + c) for d, c in zip(div, Cphi)) < 1e-12      # div of grad phi0 is -C phi0
        phi = solve_pinned(stiffness_matrix(p, f), [-d for d in div], 0, "cg")
        assert max(abs(a - (b - phi0[0])) for a, b in zip(phi, phi0)) < 1e-8


def test_flat_grid_against_euclidean_distance() -> None:
    prev = None
    for m in (4, 8, 16):
        g, gf = grid_mesh(m, m, 1.0 / m)
        d = heat_method(g, gf, [0])
        assert d[0] == 0.0
        err = mean_error(d, [norm(q) for q in g])
        assert prev is None or err < prev                              # measured: 0.033, 0.021, 0.014
        prev = err
    assert prev < 0.02


def test_symmetry_of_the_grid() -> None:
    m = 8
    g, gf = grid_mesh(m, m, 1.0 / m)
    d = heat_method(g, gf, [0])
    for i in range(m + 1):
        for j in range(m + 1):
            assert abs(d[j * (m + 1) + i] - d[i * (m + 1) + j]) < 1e-9


def test_better_than_edge_dijkstra_on_a_grid() -> None:
    m = 8
    g, gf = grid_mesh(m, m, 1.0 / m)
    exact = [norm(q) for q in g]
    heat = mean_error(heat_method(g, gf, [0]), exact)
    graph = edge_dijkstra(g, gf, 0)
    assert all(a >= b - 1e-12 for a, b in zip(graph, exact))         # graph paths are never shorter
    assert heat < mean_error(graph, exact)


def test_sphere_against_great_circle_distance() -> None:
    prev = None
    for level in (1, 2, 3):
        s, sf = icosphere(level)
        err = mean_error(heat_method(s, sf, [0]), great_circle(s, 0))
        assert prev is None or err < prev                              # measured: 0.096, 0.045, 0.023
        prev = err
    assert prev < 0.03


def test_two_sources() -> None:
    m = 8
    g, gf = grid_mesh(m, m, 1.0 / m)
    a, b = 0, (m + 1) * (m + 1) - 1
    d = heat_method(g, gf, [a, b])
    exact = [min(norm(sub(q, g[a])), norm(sub(q, g[b]))) for q in g]
    assert min(d[a], d[b]) == 0.0
    assert mean_error(d, exact) < 0.03


def test_cg_against_dense_solver() -> None:
    s, sf = icosphere(1)
    for src in ([0], [0, 5], [3, 17, 30]):
        a = heat_method(s, sf, src)
        b = heat_method(s, sf, src, solver="dense")
        assert max(abs(x - y) for x, y in zip(a, b)) < 1e-9

History

Varadhan proved in 1967 that the heat kernel on a Riemannian manifold determines the distance: −4tlog⁡kt(x,y)-4t \log k_t(x, y) tends to d(x,y)2d(x, y)^2 as t→0t \to 0. Using the formula directly on a mesh needs a very small tt and is sensitive to error, because log⁡u\log u is taken of tiny values. In 2013 Crane, Weischedel and Wardetzky observed that only the direction of ∇u\nabla u is needed. That direction is already accurate for tt of the order of h2h^2, and a Poisson solve recovers the distance from it. They called the method the heat method, showed its convergence under refinement, and applied it to triangle meshes, polygon meshes and point clouds.

References

  1. Keenan Crane, Clarisse Weischedel and Max Wardetzky, Geodesics in heat, a new approach to computing distance based on heat flow, ACM Transactions on Graphics 32(5), 2013, article 152, the three steps of the method, the choice t = h^2, the discrete gradient and divergence on triangle meshes, and the boundary conditions
  2. S. R. S. Varadhan, On the behavior of the fundamental solution of the heat equation with variable coefficients, Communications on Pure and Applied Mathematics 20(2), 1967, 431 to 455, the limit of -4t log k(t, x, y) as t goes to 0, which is the square of the Riemannian distance
  3. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 3, Differential geometry (the cotangent Laplacian, the lumped mass matrix and the gradient of a linear function on a triangle)

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