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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 . The heat itself is a poor guide to distance, but its gradient points away from the sources. So the method keeps only the direction, , a field of unit vectors along which distance grows at rate 1. Then it finds the function whose gradient is closest to , 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 , a nonempty set of source vertices, and a time , by default for the mean edge length . The output is a value at each vertex that approximates the geodesic distance from vertex to on the surface, with . Exact distances are the task of the MMP algorithm. The heat method trades exactness for two linear solves.
The algorithm
Let be the cotangent stiffness matrix, the lumped mass matrix (one third of the face areas at each vertex), and the vector with 1 at the sources and 0 elsewhere. On a face with area , unit normal , and the edge opposite vertex taken in the order of the face, the gradient of the linear interpolant of is . For a vector on each face, the integrated divergence at vertex is
where , are the two edges of out of and , the angles of opposite them.
HEAT-METHOD(x[1 .. n], faces, S, t)- 1
t ← h² for the mean edge length h, if not given - 2
C, M ← the cotangent stiffness and the lumped mass matrices - 3
solve (M + t C) u = δ_S ▷ one backward Euler step of heat flow - 4
for each face f do X_f ← −∇u / |∇u| ▷ the unit direction away from S - 5
b_i ← (∇ · X)_i for each vertex i - 6
solve C φ = −b with φ_s = 0 for one source s ▷ the Poisson equation - 7
φ ← φ − min over s ∈ S of φ_s return φ
Line L3 is one backward Euler step of the heat equation from the initial heat . The matrix is symmetric positive definite. Line L6 is the weak form of the Poisson equation . The matrix 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 grid of right triangles, with the diagonals from to , and the source at the corner . 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 |
|---|---|---|---|
Edge paths are exact along the grid lines and the diagonals, and too long in every other direction, instead of at , and no refinement removes this. The heat method errs in both directions but has the smaller mean error, against . Its largest errors are on the border, as at , where the free (Neumann) boundary condition of the heat flow bends the gradient. On the , and grids the measured mean error is , and .
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 , and . 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 against .
Correctness
The method is an approximation. These parts are proved in the correctness file:
- Both systems have unique solutions. is symmetric positive definite. restricted to the vertices other than one pinned vertex is positive definite on a connected mesh.
- The Poisson step inverts the gradient. If is the gradient of a piecewise linear function , then line L5 gives , and lines L6 and L7 return up to a constant. So the only errors come from 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 that minimizes .
- Why it works in the limit. For a smooth surface, Varadhan's formula says that the heat kernel satisfies as . So for small , is nearly parallel to , and is nearly , which has unit length. Crane, Weischedel and Wardetzky analyse the error when the mesh is refined with . 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. is the hat function of vertex , linear on each face, 1 at and 0 at the other vertices. A function on the vertices has the piecewise linear interpolant . is the cotangent stiffness matrix, as on the cotangent Laplacian page, and 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). is symmetric positive definite for . For any vertex , the matrix obtained from by deleting row and column 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. , so is positive semidefinite, and for . For , let and let be with inserted. Then . If this is 0, then on every face, so is constant on the connected mesh, and gives , a contradiction.
Lemma 2 (gradient of a hat function). On a face with area , unit normal , and the edge opposite in the order of the face, . So the formula of line L4 is the gradient of the interpolant.
Proof. lies in the plane of , is perpendicular to , has length , and points from toward because the face is oriented by . is 0 on the line of and 1 at , at the height above it. So its gradient is perpendicular to , points toward , and has length .
Lemma 3 (the divergence is the weak divergence). For any face vectors in the planes of the faces, the value of line L5 is .
Proof. Fix a face with vertices in order, and let , , , , . The angle at is opposite and the angle at is opposite , and , . Let and . Both lie in the plane of the face, which and span, so it is enough to compare their dot products with and . First, , and by symmetry . Second, with , , and in the same way . So , and the term of this face in line L5 is by Lemma 2.
Lemma 4 (the pinned system solves the full system). The solution of line L6 satisfies in every row, including row .
Proof. By Lemma 3, , because . The rows of also sum to the zero vector, since and is symmetric. So row of is minus the sum of the other rows, which are 0.
Theorem 1 (the Poisson step inverts the gradient). If for a piecewise linear , then lines L5 to L7 return .
Proof. By Lemma 3, , so . The vector is 0 at and satisfies , so by Lemma 1 it is the solution of line L6. Line L7 subtracts the smallest value at a source.
Theorem 2 (least squares). For any face vectors , the result of line L6 minimizes over all piecewise linear with , and so, up to a constant, over all piecewise linear .
Proof. by Lemma 3. This is a convex quadratic, and its gradient is , which is 0 exactly at the solution of .
So the computed is the exact distance whenever the unit field is the gradient of a piecewise linear function, and in general it is the best fit to . The error of the method is the error of as a gradient of the distance.
What is not proved here. That is close to the gradient of the true distance rests on Varadhan's formula 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 , , the gradients and the divergence takes time. The two solves dominate. With conjugate gradients each takes iterations of work, so in total on the real RAM, with of order for a well-shaped mesh. With a sparse Cholesky factorization, the two factorizations cost about time once, by nested dissection, and each new source set then costs two back-substitutions, about . This reuse is the main practical gain: the factors depend only on the mesh. The extra space is 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 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 smooths more.
- Any set of sources. A point, a curve of vertices, or a region, at the same cost.
- Not monotone. Nothing forces 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. with is the default. A larger gives a smoother result, and a smaller follows the true distance more closely until the mesh is too coarse to resolve the heat.
- Intrinsic Delaunay meshes. Computing 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 in the worst case.
- Fast marching. The fast marching method solves the eikonal equation directly, in 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 , the Poisson equation is , that is . 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 itself, not its direction, gives a smooth function that is not a distance.
- A too small for the mesh. If , the heat does not reach past the first ring of the source, 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 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.
# 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: tends to as . Using the formula directly on a mesh needs a very small and is sensitive to error, because is taken of tiny values. In 2013 Crane, Weischedel and Wardetzky observed that only the direction of is needed. That direction is already accurate for of the order of , 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag MWDDTN Edit this page History Report an error Markdown