Algorithmadvanced
Mitchell-Mount-Papadimitriou algorithm
Also called MMP algorithm, continuous Dijkstra.
Computes exact geodesic distances from a source on a polyhedral surface by propagating intervals of edges with one unfolding each, in O(n^2 log n) time.
- Time
- O(n² log n) worst
- Space
- O(n²) extra
- Where
- n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Joseph S. B. Mitchell, David M. Mount, Christos H. Papadimitriou, 1987
The Mitchell-Mount-Papadimitriou algorithm, or MMP, computes exact shortest path distances on the surface of a triangle mesh. Paths may cross faces anywhere, not only along edges, so the answer is the true geodesic distance of the polyhedral surface and not a graph distance. The method keeps, on each edge, a set of windows. A window is an interval of the edge where the shortest paths all come straight from one point, a pseudo-source, in one flat unfolding of the faces they cross. Windows are taken in order of distance from a priority queue, as in Dijkstra's algorithm, and each one is pushed across the next face and cut at the two other edges. Vertices where shortest paths can bend start new windows. MMP runs in time, and it is the reference against which approximate methods such as the heat method and the fast marching method are measured.
In plain words
Think of an ant walking on the surface of a box. It can walk straight across a side, and when it reaches an edge it keeps going straight on the next side, as if the two sides were unfolded flat. The shortest walk to a far corner may cross several sides, and it is a straight line on the right unfolding.
The method spreads out from the start like a ripple. On each edge it keeps pieces where the ripple arrives straight from one known point. It always grows the nearest piece first. When a piece crosses a triangle, it splits where the triangle's far corner is, and when two pieces from different directions land on the same part of an edge, only the nearer one is kept. At corners where a walk can bend, such as the inner corner of an L-shaped room, the ripple restarts from the corner.
The problem
The input is a triangle mesh that is a connected manifold, possibly with border, and one or more source vertices. The surface is the union of the flat triangles. The length of a path on the surface is its Euclidean length, and the geodesic distance is the length of a shortest path from the nearest source to . The output is for every vertex . This is the discrete geodesic problem.
Two facts about shortest paths drive the method. Inside a face a shortest path is a straight segment, and across an edge it continues straight in the unfolding of the two faces. A shortest path passes through a vertex only if is on the border, or the angles of the faces at sum to at least (MMP call the case above a saddle vertex, and its curvature is negative, see discrete Gaussian curvature). At a vertex with angle sum below a shortest path never bends.
The algorithm
A window lives on an edge and looks into one face of that edge. In the frame where , and the third vertex of has , it holds an interval of the edge, a pseudo-source with , and the distance from the source to . On the interval the window claims the distance . Its key is the smallest such value. A vertex is a pseudo-source vertex if it is a source, a border vertex, or has angle sum at least .
MMP(mesh, sources)- 1
d(v) ← ∞ for all v; d(s) ← 0 and push the vertex event s for each source s - 2
while the queue is not empty do pop the event with the smallest key - 3
if it is a vertex event at a pseudo-source vertex v with key d(v) then for each face (v, a, b) put the window [0, |ab|] with pseudo-source v and σ = d(v) on the edge ab, looking into the face beyond it - 4
if it is a window w on edge pq into face h with third vertex r then unfold r into the frame; if r lies in the cone from s through w then d(r) ← min(d(r), σ + |r − s|); cut the cone at the edges pr and rq - 5
for each new window on an edge e: lower d at the end points it covers, trim it and the windows already on e so that each point keeps only the windows with the smallest value, and push the pieces that remain; push a vertex event whenever some d(v) drops - 6
return d
Cutting the cone (line L4). The rays from through and bound a cone. The ray from through the third vertex meets the edge at . Rays through leave the face through , and rays through leave through . Each part becomes a window on its edge, with written in the frame of that edge and the next face, and the same .
Trimming (line L5). Two windows on one edge give two distance functions and . They are equal where a hyperbola meets the edge, at most two points, which a quadratic equation gives. Between these points one window is better, and the worse one loses that part. Windows on the two sides of an edge are compared too, because the distance on the edge is the same from both sides.
Example
The unit cube. Take the cube as 12 triangles, with the source at the corner . The source is a pseudo-source vertex, so line L3 puts a window on the far edge of each of its 6 faces. One of them lies on the edge from to of the bottom face and looks into the side . Unfolding that side into the plane of the bottom puts the far corner at , inside the cone from the source, so line L4 gives . A path along edges needs at least . The whole run makes 14 windows.
A box. On the box , the three ways to unfold two sides between opposite corners give , and . MMP returns , and the edge graph gives .
An L-shaped floor. On the flat region without the square , with the source at , the vertices , and cannot be seen in a straight line. The reflex corner is a border vertex, so it becomes a pseudo-source with , and the distance to is . The tests check every vertex against the exact visibility test.
Correctness
The correctness file proves three things in exact arithmetic. Soundness: every value that the method assigns is the length of a real path on the surface, because a window only holds rays that stay inside the unfolded faces they cross. Completeness: for every vertex, the window chain of one shortest path survives all trimming, because a window is only cut where another one is strictly better, and a shortest path cannot be beaten at any point it crosses. Order: as in Dijkstra's algorithm, keys never decrease along a chain, so when a vertex event is taken, its distance is final, and the windows it starts use the right . Together these give equal to the geodesic distance for every vertex. The algorithm stops because each window is pushed across a face once and, by the analysis of Mitchell, Mount and Papadimitriou, only finitely many windows are made.
The code uses floating point, with a relative tolerance of in the cone and trimming tests. The tests compare it with an exhaustive search over unfoldings on convex polyhedra, with exact visibility on the L-shape, with the Euclidean distance on flat grids, and with Steiner-point graph distances on rough terrains, which are upper bounds.
Proof: In exact arithmetic the window method returns the geodesic distance at every vertex, because every value is the length of a real path, a window chain along each shortest path survives the trimming, and pseudo-source vertices start with their final distancefull
Setup. The mesh is a connected manifold triangle mesh, possibly with border, and every face has positive area. is the geodesic distance from the nearest source to a point of the surface. is the value that the algorithm holds for a vertex , which only goes down. The arithmetic is exact and the tolerances are 0. A window on edge has the value at the points of its interval. A pseudo-source vertex is a source, a border vertex, or a vertex with angle sum at least .
Two facts about shortest paths are used, both from the structure lemmas of Mitchell, Mount and Papadimitriou.
- (F1) A shortest path exists. It is straight in each face, and where it crosses the inside of an edge, it is straight in the unfolding of the two faces. So it does not bend at a point that is not a vertex.
- (F2) If a shortest path passes through a vertex that is not one of its ends, then is a border vertex or its angle sum is at least . Reason: the path cuts the faces around an inner vertex into two sides. If one side had an angle below , a short cut on that side would make the path shorter. So both sides are at least .
Lemma 1 (soundness). Every window value and every value given to is the length of a path on the surface from a source to that point. So , and .
Proof. By induction in the order of creation. At a source, . A window made by line L3 at the vertex in the face has at the image of and . For on , the segment from to lies in , and its length is , because the frame is an isometric copy of . Add a path of length to , which exists by induction. A child window of in line L4 holds a point of the edge or only if the ray from to meets the edge at a point with . The segment from to lies in the face , which is convex. So the path of to followed by this segment has length , as the three points are on one line. This is the value of the child at , written in the frame of the new edge. The values given to the third vertex and to the end points of a new window are values of windows at those points. Trimming only makes intervals smaller.
Lemma 2 (keys never go down). Every event that is pushed while an event of key is processed has a key at least . So the keys are taken in an order that never goes down.
Proof. A child of has, at each of its points , the value . A window made at a vertex has all its values at least . A trimmed piece has a key at least that of the whole window. A vertex event is pushed with a value of one of these windows, or of itself at the third vertex, so it is at least too.
So once a vertex event with key is taken, does not change again, and the windows that starts in line L3 use its final value.
Lemma 3 (trimming). In line L5 a part of a window is removed only where another window that stays alive at that moment has a value at most as large. On each piece between two roots of the quadratic, the sign of the difference of the two distance functions does not change, so the test at the middle of the piece is right for the whole piece.
Proof. The new window loses a piece where an existing window is at most as good. An existing window loses a piece where the new window is strictly better, and that piece of the new window is kept at this step. For the second claim, with the squared distances to the two pseudo-sources implies, after squaring twice, the quadratic of the code, so every point where the two values are equal is a root, or the quadratic is identically 0. In the first case the difference is continuous with no zero inside a piece. In the second case the two windows have equal values on the whole overlap and the existing one is kept.
Theorem 1 (completeness). At the end, for every vertex .
Proof. Fix and a shortest path from the nearest source to . Cut at each vertex it passes through. By (F2) these vertices are pseudo-source vertices, and each piece goes from to the next vertex without touching any other vertex. We show by induction on that at the end and that starts its windows with .
Start of a pseudo-source. If at the end, then the vertex event pushed when took this value is taken later. At that time , because it cannot go lower by Lemma 1, and has not started yet, because a start at an earlier, larger value would be followed by a drop, which Lemma 2 forbids. So starts with .
One piece. Let the piece from to cross the edges at inner points , passing from face into face at , with and . Call a window good for if it lies on , looks into , holds , has the value there, and its pseudo-source lies on the line of behind in the unfolding. Such a window carries through .
If , then is a vertex of a face , and the window that puts on in line L3, or the direct update for a border edge, sets . Otherwise the window that puts on , the far edge of , is good for 1, since is inside and .
A good window stays good where it holds , and if trimming removes from it, another good window holds . By Lemma 3, a good window loses only to a window with , so by Lemma 1. The path of to followed by the rest of is then a shortest path to . By (F1) it does not bend at , so arrives along the line of from the side of , and is good for . A good window cannot lose to a strictly better window, since nothing is below . So from the time the first good window for is made, some alive window is good for . When the queue is empty, every alive window has been taken, so some good window for is taken in line L4.
When is taken, the ray through crosses straight. It does not pass through the third vertex of , because touches no vertex there. If , it leaves at , inside . The part of on the same side of as has positive length, because and has positive length, so the child on is made and holds , with the value . It is good for . It is not skipped as grazing, because crosses and does not run along it. If , the ray reaches , which is then the third vertex of (it cannot be an end of , as the segment would run along ), and line L4 sets .
So , and with Lemma 1, . Applying this to the pieces in turn gives the claim for every and finally for .
Theorem 2 (termination). The loop stops.
Proof. Let be the largest distance of a point on an edge, which is finite. The proof of Theorem 1 also works when is any point of an edge, so every edge point is held by a good window from the time its parent, of key at most , is taken. Once the key of the taken events is above , every new window has all its values above , so at each of its points an alive window is strictly better, and line L5 removes all of it. So no window with a key above is ever pushed after that, and vertex events above are stale. Each window with a key at most belongs to a pseudo-source vertex and the sequence of faces that its rays cross within length . A straight segment of bounded length that avoids the vertices crosses a bounded number of faces, so there are finitely many such sequences, and each trimming step splits a window into at most three pieces per comparison. So finitely many windows are pushed, and each is taken once.
What is not proved here. The bounds of windows per edge and time are those of Mitchell, Mount and Papadimitriou for their data structures, and they are cited, not proved for this code. The code uses floating point with a relative tolerance of , so its exactness is checked by the tests, not proved: against an exhaustive search over unfoldings on convex polyhedra, exact visibility on an L-shape, Euclidean distance on flat grids, symmetry, and Steiner-point upper bounds on terrains.
Complexity
Mitchell, Mount and Papadimitriou show that each edge carries intervals of optimality, so there are windows in all. Each is pushed and taken once, at for the queue, which gives time and space. These bounds are cited, not proved here, and the implementation does not keep their data structures. Surazhsky and coauthors measured running times close to on typical models. On random terrains of 81, 169 and 289 vertices, this implementation makes 451, 1019 and 1839 windows, which is about .
Properties
- Exact. The answer is the true distance of the polyhedral surface, not of a graph, and it does not depend on how the faces are cut.
- Single source per run. Several sources are handled by starting from all of them, which gives the distance to the nearest one.
- Full field. The windows describe the distance at every point of every edge, and so inside every face, not only at the vertices.
- Paths too. Following the pseudo-sources back gives the shortest paths.
- Order matters only for the pseudo-sources. Trimming is safe in any order, but a pseudo-source vertex must start its windows with its final distance.
Variants and improvements
- Chen and Han (1990). A tree of unfoldings pruned by the rule that each vertex angle keeps at most one child that splits, in time and space, with no priority queue.
- Surazhsky, Surazhsky, Kirsanov, Gortler and Hoppe (2005). The window form used here, a fast practical implementation of MMP, and an approximate version that merges nearby windows with a bounded error.
- Convex polytopes. Sharir and Schorr gave the first method for convex surfaces, and Schreiber and Sharir reached the optimal time on them.
- Approximations. Steiner points on the edges with graph search, the fast marching method, and the heat method are faster, with errors that shrink as the mesh is refined.
- Planar obstacles. The Euclidean shortest path among polygons is the flat case, where the visibility graph also works.
When to use it
Use MMP when exact distances matter, for example to measure the error of an approximate method, for geodesic Voronoi diagrams, or for paths that must be truly shortest on a coarse mesh. On meshes with millions of vertices, or when many sources and repeated queries are needed, the heat method or fast marching is often faster, at the cost of a small error.
Pitfalls
- Lost crossing points. When two windows have the same , the quadratic for their crossing has a double root, which rounding can turn into no root. Then a whole piece is given to the wrong window and a distance is too large. The code solves the linear equation in that case, and the symmetry test catches the error.
- Missing pseudo-sources. Forgetting border vertices or saddle vertices loses every path that bends there, as at the corner of the L-shape.
- Starting a pseudo-source too early. If a vertex starts its windows before its distance is final, the wrong spreads. The priority queue prevents this.
- Grazing rays. When the pseudo-source lies on the line of an edge, the rays only touch that edge, and the new window has no width. Skip it, the neighbouring windows cover the same points.
- Memory. The windows can be too many on large meshes.
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/mmp-geodesic-algorithm/. The authors are listed in prov/14F19Q.jsonl.
"""Exact geodesic distances on a triangle mesh by the Mitchell-Mount-Papadimitriou method.
This is the window form of the method described by Surazhsky, Surazhsky,
Kirsanov, Gortler and Hoppe (2005). A window lives on an edge (p, q), p < q,
and looks into one face h of that edge. In the frame of (edge, h) the vertex p
is at (0, 0), q is at (|pq|, 0) and the third vertex of h has y > 0. The window
holds an interval [b0, b1] of the edge, a pseudo-source s = (sx, sy) with
sy < 0 (an unfolded image of the source or of a saddle vertex) and the
distance sigma from the source to that pseudo-source. On the interval, the
distance is sigma + |(x, 0) - s|.
Events are taken from a priority queue in order of distance. A window event
pushes the window across its face onto the two other edges. A vertex event at
a source, a saddle vertex (angle sum above 2 pi), a flat vertex (angle sum
exactly 2 pi) or a border vertex makes that vertex a pseudo-source. New windows are trimmed against the windows already on
the same edge, so that each point of an edge keeps only the windows that give
it the smallest distance.
"""
import heapq
from math import acos, hypot, pi, sqrt
from typing import Optional, Sequence
QUEUED, DONE, DEAD = 0, 1, 2
def _sub(a, b):
return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
def _dot(a, b):
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def _norm(a):
return sqrt(_dot(a, a))
class Window:
__slots__ = ("edge", "face", "b0", "b1", "sx", "sy", "sigma", "state", "ver")
def __init__(self, edge, face, b0, b1, sx, sy, sigma):
self.edge, self.face, self.b0, self.b1 = edge, face, b0, b1
self.sx, self.sy, self.sigma = sx, sy, sigma
self.state, self.ver = QUEUED, 0
def at(self, x: float) -> float:
return self.sigma + hypot(x - self.sx, self.sy)
def key(self) -> float:
if self.b0 <= self.sx <= self.b1:
return self.sigma - self.sy
return min(self.at(self.b0), self.at(self.b1))
def _crossing_roots(w: Window, x: Window, lo: float, hi: float) -> list[float]:
"""The x in (lo, hi) where the distance functions of w and x may be equal."""
d = x.sigma - w.sigma # sqrt(A) - sqrt(B) = d with A, B the squared distances
hw, hx = w.sy * w.sy, x.sy * x.sy
p = -2 * (w.sx - x.sx) # A - B - d^2 = p t + q
q = w.sx * w.sx - x.sx * x.sx + hw - hx - d * d
a2 = p * p - 4 * d * d # (p t + q)^2 = 4 d^2 B
a1 = 2 * p * q + 8 * d * d * x.sx
a0 = q * q - 4 * d * d * (x.sx * x.sx + hx)
scale = max(abs(a2), abs(a1), abs(a0), 1e-300)
roots = []
if abs(d) <= 1e-13 * (abs(w.sigma) + abs(x.sigma) + 1):
if p != 0: # equal sigma: the equation is linear, p t + q = 0
roots.append(-(q + d * d) / p)
elif abs(a2) <= 1e-12 * scale:
if abs(a1) > 1e-12 * scale:
roots.append(-a0 / a1)
else:
disc = a1 * a1 - 4 * a2 * a0
if disc >= -1e-12 * a1 * a1: # a double root can come out slightly negative
r = sqrt(max(disc, 0.0))
roots += [(-a1 - r) / (2 * a2), (-a1 + r) / (2 * a2)]
return sorted(t for t in roots if lo < t < hi)
def _minus(lo: float, hi: float, cuts: list[tuple[float, float]], tol: float) -> list[tuple[float, float]]:
"""[lo, hi] with the intervals in cuts removed, dropping pieces shorter than tol."""
pieces = [(lo, hi)]
for c0, c1 in cuts:
nxt = []
for a, b in pieces:
if c1 <= a or c0 >= b:
nxt.append((a, b))
continue
if c0 > a:
nxt.append((a, c0))
if c1 < b:
nxt.append((c1, b))
pieces = nxt
return [(a, b) for a, b in pieces if b - a > tol]
def mmp_geodesic(points: Sequence[Sequence[float]], faces: Sequence[Sequence[int]], sources: Sequence[int],
stats: Optional[dict] = None) -> list[float]:
"""Exact geodesic distance from the nearest source to every vertex of a manifold triangle mesh."""
P = [tuple(map(float, p)) for p in points]
n = len(P)
F = [tuple(f) for f in faces]
edge_faces: dict[tuple[int, int], list[int]] = {}
for fid, f in enumerate(F):
for k in range(3):
a, b = f[k], f[(k + 1) % 3]
edge_faces.setdefault((min(a, b), max(a, b)), []).append(fid)
vfaces = [[] for _ in range(n)]
angle = [0.0] * n
for fid, f in enumerate(F):
for k in range(3):
v, a, b = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
vfaces[v].append(fid)
x, y = _sub(P[a], P[v]), _sub(P[b], P[v])
angle[v] += acos(max(-1.0, min(1.0, _dot(x, y) / (_norm(x) * _norm(y)))))
border = [False] * n
for (a, b), fs in edge_faces.items():
if len(fs) == 1:
border[a] = border[b] = True
# A shortest path can only pass through a border vertex or a vertex with angle sum at least 2 pi. Flat
# vertices (exactly 2 pi) are included, so that a path straight through one is also carried.
pseudo = [border[v] or angle[v] > 2 * pi - 1e-9 for v in range(n)]
is_source = [False] * n
for s in sources:
is_source[s] = True
frames: dict[tuple[int, int, int], tuple[float, float, float]] = {}
def third(fid, e):
return next(w for w in F[fid] if w != e[0] and w != e[1])
def frame(e, fid):
"""(|pq|, x, y) of the third vertex of face fid in the frame of edge e = (p, q)."""
key = (e[0], e[1], fid)
if key not in frames:
p, q, r = P[e[0]], P[e[1]], P[third(fid, e)]
L = _norm(_sub(q, p))
u = tuple(c / L for c in _sub(q, p))
w = _sub(r, p)
x = _dot(w, u)
frames[key] = (L, x, sqrt(max(_dot(w, w) - x * x, 0.0)))
return frames[key]
def other_face(e, fid):
return next((g for g in edge_faces[e] if g != fid), None)
dist = [float("inf")] * n
spawned = [False] * n
windows: dict[tuple[int, int], list[Window]] = {e: [] for e in edge_faces}
heap: list = []
counter = [0, 0] # heap tie breaker, windows made
def push(key, item, ver):
counter[0] += 1
heapq.heappush(heap, (key, counter[0], item, ver))
def update(v, d):
if d < dist[v]:
dist[v] = d
push(d, v, -1)
def insert(e, fid, b0, b1, sx, sy, sigma):
L = frame(e, fid)[0]
tol = 1e-10 * L
b0, b1 = max(b0, 0.0), min(b1, L)
if b0 <= tol:
update(e[0], sigma + hypot(sx, sy))
if b1 >= L - tol:
update(e[1], sigma + hypot(L - sx, sy))
if b1 - b0 <= tol:
return
w = Window(e, fid, b0, b1, sx, sy, sigma)
mine = [(b0, b1)]
for x in list(windows[e]):
if x.state == DEAD or x.b1 <= b0 or x.b0 >= b1:
continue
better = [] # where w is strictly better than x
worse = [] # where x is at least as good as w
for m0, m1 in mine:
lo, hi = max(m0, x.b0), min(m1, x.b1)
if hi - lo <= tol:
continue
cuts = [lo] + _crossing_roots(w, x, lo, hi) + [hi]
for c0, c1 in zip(cuts, cuts[1:]):
mid = (c0 + c1) / 2
(better if w.at(mid) < x.at(mid) - tol else worse).append((c0, c1))
if worse:
mine = [piece for m0, m1 in mine for piece in _minus(m0, m1, worse, tol)]
if better:
rest = _minus(x.b0, x.b1, better, tol)
if not rest:
x.state = DEAD
windows[e].remove(x)
else:
x.b0, x.b1 = rest[0]
x.ver += 1
if x.state == QUEUED:
push(x.key(), x, x.ver)
for a, b in rest[1:]:
y = Window(e, x.face, a, b, x.sx, x.sy, x.sigma)
y.state = x.state
windows[e].append(y)
if y.state == QUEUED:
push(y.key(), y, y.ver)
if not mine:
return
for a, b in mine:
y = Window(e, fid, a, b, sx, sy, sigma)
counter[1] += 1
windows[e].append(y)
push(y.key(), y, y.ver)
def spawn(v):
"""Make v a pseudo-source: one window on the far edge of each face around v."""
for g in vfaces[v]:
f = F[g]
a, b = (w for w in f if w != v)
e = (min(a, b), max(a, b))
L, x, y = frame(e, g) # v is the third vertex of g
h = other_face(e, g)
if h is None:
update(e[0], dist[v] + hypot(x, y))
update(e[1], dist[v] + hypot(L - x, y))
else:
insert(e, h, 0.0, L, x, -y, dist[v])
def propagate(w):
e, h = w.edge, w.face
L, rx, ry = frame(e, h)
r = third(h, e)
sx, sy = w.sx, w.sy
def g(px, py): # where the ray from s to (px, py) meets y = 0
return sx + (px - sx) * (-sy) / (py - sy)
gr = g(rx, ry)
tol = 1e-10 * L
if w.b0 - tol <= gr <= w.b1 + tol:
update(r, w.sigma + hypot(rx - sx, ry - sy)) # the third vertex is lit by the window
for (i, (ax, ay), ga), (j, (bx, by), gb), (ox, oy) in (
((e[0], (0.0, 0.0), 0.0), (r, (rx, ry), gr), (L, 0.0)),
((r, (rx, ry), gr), (e[1], (L, 0.0), L), (0.0, 0.0))):
ne = (min(i, j), max(i, j))
h2 = other_face(ne, h)
if h2 is None:
continue
lo, hi = max(w.b0, min(ga, gb)), min(w.b1, max(ga, gb))
if hi - lo <= tol:
continue
ex, ey = bx - ax, by - ay
def at(xv): # the point of segment a-b on the ray through (xv, 0)
if xv == ga:
return 0.0
if xv == gb:
return 1.0
dx, dy = xv - sx, -sy
wx, wy = ax - sx, ay - sy
return (wx * dy - wy * dx) / (dx * ey - dy * ex)
t0, t1 = at(lo), at(hi)
if i > j:
(ax, ay), (bx, by), t0, t1 = (bx, by), (ax, ay), 1 - t0, 1 - t1
ln = hypot(bx - ax, by - ay)
ux, uy = (bx - ax) / ln, (by - ay) / ln
vx, vy = -uy, ux
if (ox - ax) * vx + (oy - ay) * vy > 0: # y must point away from face h
vx, vy = -vx, -vy
nsx = (sx - ax) * ux + (sy - ay) * uy
nsy = (sx - ax) * vx + (sy - ay) * vy
if nsy > -1e-12 * ln:
continue # the rays only graze this edge
insert(ne, h2, min(t0, t1) * ln, max(t0, t1) * ln, nsx, nsy, w.sigma)
for s in sources: # @line L1
update(s, 0.0)
while heap: # @line L2
key, _, item, ver = heapq.heappop(heap)
if ver == -1:
v = item
if key > dist[v] or spawned[v]:
continue
if is_source[v] or pseudo[v]: # @line L3
spawned[v] = True
spawn(v)
else:
if item.state != QUEUED or item.ver != ver:
continue
item.state = DONE
propagate(item) # @line L4 @line L5
if stats is not None:
stats["windows"] = counter[1]
stats["alive"] = sum(len(ws) for ws in windows.values())
return dist # @line L6
test_mmp_geodesic_algorithm.py 295 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mmp-geodesic-algorithm/. The authors are listed in prov/14F19Q.jsonl.
import heapq
import random
from fractions import Fraction
from math import acos, hypot, pi, sqrt
from mmp_geodesic_algorithm import mmp_geodesic
def sub(a, b):
return tuple(x - y for x, y in zip(a, b))
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def norm(a):
return sqrt(dot(a, a))
# ---- meshes ----
def grid(m, rng=None, height=None):
"""The unit square cut into m x m cells, each cut by a diagonal (random if rng is given)."""
pts = [(i / m, j / m, height(i, j) if height else 0.0) for j in range(m + 1) for i in range(m + 1)]
faces = []
for j in range(m):
for i in range(m):
a, b, c, d = j * (m + 1) + i, j * (m + 1) + i + 1, (j + 1) * (m + 1) + i + 1, (j + 1) * (m + 1) + i
if rng is not None and rng.random() < 0.5:
faces += [(a, b, d), (b, c, d)]
else:
faces += [(a, b, c), (a, c, d)]
return pts, faces
def l_shape():
"""[0, 2]^2 without the open square (1, 2]^2, in cells of size 1/2, with exact coordinates."""
idx, pts = {}, []
for j in range(5):
for i in range(5):
if not (i > 2 and j > 2):
idx[(i, j)] = len(pts)
pts.append((Fraction(i, 2), Fraction(j, 2)))
faces = []
for j in range(4):
for i in range(4):
if i >= 2 and j >= 2:
continue
a, b, c, d = idx[(i, j)], idx[(i + 1, j)], idx[(i + 1, j + 1)], idx[(i, j + 1)]
faces += [(a, b, c), (a, c, d)] if (i + j) % 2 else [(a, b, d), (b, c, d)]
return pts, faces
def box(a, b, c):
"""The surface of [0, a] x [0, b] x [0, c] as 12 triangles."""
pts = [(x, y, z) for z in (0, c) for y in (0, b) for x in (0, a)]
quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)]
faces = [t for q, r, s, u in quads for t in ((q, r, s), (q, s, u))]
return pts, faces
def octahedron(sx, sy, sz):
pts = [(sx, 0, 0), (-sx, 0, 0), (0, sy, 0), (0, -sy, 0), (0, 0, sz), (0, 0, -sz)]
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 icosahedron(sx, sy, sz):
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)]
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)]
return [(sx * x, sy * y, sz * z) for x, y, z in raw], faces
# ---- reference methods ----
def unfolding_distances(P, F, s):
"""Brute force for convex polyhedra: try every face sequence from s whose unfolding still lets a line through."""
n = len(P)
ef = {}
for fid, f in enumerate(F):
for k in range(3):
ef.setdefault(frozenset((f[k], f[(k + 1) % 3])), []).append(fid)
best = [float("inf")] * n
best[s] = 0.0
def cr(a, b):
return a[0] * b[1] - a[1] * b[0]
def place(pa, pb, a, b, c):
"""The 2D image of vertex c across the segment pa-pb, on the side away from the origin."""
u3 = sub(P[b], P[a])
L = norm(u3)
w = sub(P[c], P[a])
x = dot(w, u3) / L
y = sqrt(max(dot(w, w) - x * x, 0.0))
ux, uy = (pb[0] - pa[0]) / L, (pb[1] - pa[1]) / L
vx, vy = -uy, ux
if vx * pa[0] + vy * pa[1] < 0:
vx, vy = -vx, -vy
return (pa[0] + x * ux + y * vx, pa[1] + x * uy + y * vy)
def visit(fid, a, b, pa, pb, lo, hi, seen):
h = next((g for g in ef[frozenset((a, b))] if g != fid), None)
if h is None or h in seen:
return
c = next(w for w in F[h] if w != a and w != b)
pc = place(pa, pb, a, b, c)
tol = 1e-12 * norm(pc) ** 2
if cr(lo, pc) >= -tol and cr(pc, hi) >= -tol:
best[c] = min(best[c], hypot(*pc))
for x, px, y, py in ((a, pa, c, pc), (c, pc, b, pb)):
l2, h2 = (px, py) if cr(px, py) > 0 else (py, px)
nl = l2 if cr(lo, l2) > 0 else lo
nh = h2 if cr(hi, h2) < 0 else hi
if cr(nl, nh) > 1e-12 * hypot(*nl) * hypot(*nh):
visit(h, x, y, px, py, nl, nh, seen | {h})
for fid, f in enumerate(F):
if s not in f:
continue
k = f.index(s)
a, b = f[(k + 1) % 3], f[(k + 2) % 3]
la = norm(sub(P[a], P[s]))
pa = (la, 0.0)
w = sub(P[b], P[s])
x = dot(w, sub(P[a], P[s])) / la
pb = (x, sqrt(max(dot(w, w) - x * x, 0.0)))
best[a] = min(best[a], la)
best[b] = min(best[b], hypot(*pb))
visit(fid, a, b, pa, pb, pa, pb, {fid})
return best
def steiner_dijkstra(P, F, s, k):
"""Dijkstra on k extra points per edge, with straight segments across each face (an upper bound)."""
nodes = [tuple(p) for p in P]
on_edge = {}
for f in F:
for i in range(3):
a, b = f[i], f[(i + 1) % 3]
e = (min(a, b), max(a, b))
if e not in on_edge:
ids = []
for t in range(1, k + 1):
nodes.append(tuple(P[e[0]][c] + (P[e[1]][c] - P[e[0]][c]) * t / (k + 1) for c in range(3)))
ids.append(len(nodes) - 1)
on_edge[e] = ids
adj = [[] for _ in nodes]
for f in F:
ring = list(f)
for i in range(3):
a, b = f[i], f[(i + 1) % 3]
ring += on_edge[(min(a, b), max(a, b))]
for i in range(len(ring)):
for j in range(i + 1, len(ring)):
d = norm(sub(nodes[ring[i]], nodes[ring[j]]))
adj[ring[i]].append((ring[j], d))
adj[ring[j]].append((ring[i], d))
dist = [float("inf")] * len(nodes)
dist[s] = 0.0
heap = [(0.0, s)]
while heap:
d, v = heapq.heappop(heap)
if d > dist[v]:
continue
for w, c in adj[v]:
if d + c < dist[w]:
dist[w] = d + c
heapq.heappush(heap, (d + c, w))
return dist[:len(P)]
def angle_sums(P, F):
tot = [0.0] * len(P)
for f in F:
for k in range(3):
v, a, b = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
x, y = sub(P[a], P[v]), sub(P[b], P[v])
tot[v] += acos(max(-1.0, min(1.0, dot(x, y) / (norm(x) * norm(y)))))
return tot
# ---- tests ----
def test_flat_grid_is_euclidean() -> None:
rng = random.Random(1)
P, F = grid(6, rng)
for s in (0, 24):
d = mmp_geodesic(P, F, [s])
for v, q in enumerate(P):
assert abs(d[v] - norm(sub(q, P[s]))) < 1e-9
e = steiner_dijkstra(P, F, 0, 0)
assert e[len(P) - 1] > sqrt(2) + 1e-3 or e[13] > hypot(1 / 6, 2 / 6) + 1e-3 # the edge graph is worse
def test_l_shape_matches_the_visibility_graph() -> None:
P2, F = l_shape()
P = [(float(x), float(y), 0.0) for x, y in P2]
s = P2.index((Fraction(2), Fraction(0)))
r = (Fraction(1), Fraction(1)) # the reflex corner, a border vertex with angle 3 pi / 2
def visible(p, q): # exact: does segment p-q miss the open square x > 1, y > 1?
lo, hi = Fraction(0), Fraction(1)
for c in range(2):
f0, f1 = p[c], q[c]
if f0 == f1:
if f0 <= 1:
return True
continue
tau = (1 - f0) / (f1 - f0)
if f1 > f0:
lo = max(lo, tau)
else:
hi = min(hi, tau)
return lo >= hi
d = mmp_geodesic(P, F, [s])
bent = 0
for v, q in enumerate(P2):
if visible(P2[s], q):
ref = hypot(*(float(a - b) for a, b in zip(q, P2[s])))
else:
bent += 1
ref = hypot(*(float(a - b) for a, b in zip(r, P2[s]))) + hypot(*(float(a - b) for a, b in zip(q, r)))
assert abs(d[v] - ref) < 1e-9
assert bent == 3 # (1, 3/2), (1, 2) and (1/2, 2) must go around the corner
def test_cube_and_box_corners() -> None:
P, F = box(1, 1, 1)
d = mmp_geodesic(P, F, [0])
assert abs(d[7] - sqrt(5)) < 1e-12 # unfold two faces: a 1 x 2 rectangle
assert abs(d[3] - sqrt(2)) < 1e-12 and abs(d[1] - 1) < 1e-12
assert steiner_dijkstra(P, F, 0, 0)[7] > sqrt(5) + 0.1
P, F = box(1, 2, 3)
d = mmp_geodesic(P, F, [0])
assert abs(d[7] - sqrt(18)) < 1e-12 # min of sqrt((1+2)^2+3^2), sqrt((1+3)^2+2^2), sqrt((2+3)^2+1^2)
def test_convex_polyhedra_match_brute_force_unfolding() -> None:
rng = random.Random(7)
meshes = [box(1, 1, 1), box(1, 2, 3)]
for _ in range(3):
meshes.append(octahedron(*(rng.uniform(0.5, 2) for _ in range(3))))
meshes.append(icosahedron(*(rng.uniform(0.5, 2) for _ in range(3))))
for P, F in meshes:
for s in range(len(P)):
d = mmp_geodesic(P, F, [s])
ref = unfolding_distances(P, F, s)
for v in range(len(P)):
assert abs(d[v] - ref[v]) < 1e-9 * (1 + ref[v])
def test_terrain_with_saddles_lies_between_the_bounds() -> None:
rng = random.Random(4)
h = {(i, j): 0.25 * rng.random() for i in range(6) for j in range(6)}
P, F = grid(5, rng, lambda i, j: h[(i, j)])
tot = angle_sums(P, F)
inner = [v for v in range(len(P)) if 0 < v % 6 < 5 and 0 < v // 6 < 5]
assert sum(1 for v in inner if tot[v] > 2 * pi + 1e-6) >= 3 # there are saddle vertices
for s in (0, 14):
d = mmp_geodesic(P, F, [s])
coarse, fine = steiner_dijkstra(P, F, s, 1), steiner_dijkstra(P, F, s, 7) # 7 points include the midpoint
gap = 0.0
for v in range(len(P)):
assert norm(sub(P[v], P[s])) <= d[v] + 1e-12 # the chord is a lower bound
assert d[v] <= fine[v] + 1e-9 <= coarse[v] + 2e-9 # Steiner paths are real paths
gap = max(gap, fine[v] - d[v])
assert gap < 0.01 # measured: 0.0049 and 0.0034
def test_symmetry_and_several_sources() -> None:
rng = random.Random(9)
h = {(i, j): 0.3 * rng.random() for i in range(5) for j in range(5)}
P, F = grid(4, rng, lambda i, j: h[(i, j)])
table = [mmp_geodesic(P, F, [s]) for s in range(len(P))]
for a in range(len(P)):
for b in range(len(P)):
assert abs(table[a][b] - table[b][a]) < 1e-9 # a root lost in the trimming shows up here
for c in range(len(P)):
assert table[a][c] <= table[a][b] + table[b][c] + 1e-9 # the triangle inequality
both = mmp_geodesic(P, F, [3, 17])
for v in range(len(P)):
assert abs(both[v] - min(table[3][v], table[17][v])) < 1e-12
History
Sharir and Schorr solved the problem on convex polytopes in 1986. In 1987 Mitchell, Mount and Papadimitriou gave the first polynomial method for general polyhedral surfaces, sweeping intervals of optimality over the edges in Dijkstra order, in time. Chen and Han lowered the time to and the space to in 1990. For many years both methods were thought too complex to implement, until Surazhsky and coauthors showed in 2005 that the window form of MMP is simple and fast in practice. Schreiber and Sharir later reached for convex polytopes.
References
- Joseph S. B. Mitchell, David M. Mount and Christos H. Papadimitriou, The discrete geodesic problem, SIAM Journal on Computing 16(4), 1987, 647 to 668, the structure of shortest paths (straight in each face, through vertices only at saddle or border vertices), intervals of optimality on edges, and the O(n^2 log n) time and O(n^2) space bounds
- Vitaly Surazhsky, Tatiana Surazhsky, Danil Kirsanov, Steven J. Gortler and Hugues Hoppe, Fast exact and approximate geodesics on meshes, ACM Transactions on Graphics 24(3) (SIGGRAPH 2005), 553 to 560, the window data (interval, pseudo-source position, distance to the pseudo-source), the propagation across a face, the trimming of overlapping windows, and the measured running times
- Jindong Chen and Yijie Han, Shortest paths on a polyhedron, the O(n^2) time and O(n) space method that keeps one tree of unfoldings and prunes it with the "one angle one split" rule
- Micha Sharir and Amir Schorr, On shortest paths in polyhedral spaces, SIAM Journal on Computing 15(1), 1986, 193 to 215, the first algorithm for shortest paths on the surface of a convex polytope
- Yevgeny Schreiber and Micha Sharir, An optimal-time algorithm for shortest paths on a convex polytope in three dimensions, Discrete and Computational Geometry 39, 2008, the O(n log n) time algorithm for convex polytopes (general locator, the pages were not checked)
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 14F19Q Edit this page History Report an error Markdown