Algorithm Search⌘K

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
Properties
deterministicexactiterative
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 O(n2log⁡n)O(n^2 \log n) 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 d(v)d(v) is the length of a shortest path from the nearest source to vv. The output is d(v)d(v) for every vertex vv. 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 vv only if vv is on the border, or the angles of the faces at vv sum to at least 2π2\pi (MMP call the case above 2π2\pi a saddle vertex, and its curvature 2π−∑2\pi - \sum is negative, see discrete Gaussian curvature). At a vertex with angle sum below 2π2\pi a shortest path never bends.

The algorithm

A window ww lives on an edge pqpq and looks into one face hh of that edge. In the frame where p=(0,0)p = (0, 0), q=(∣pq∣,0)q = (|pq|, 0) and the third vertex of hh has y>0y > 0, it holds an interval [b0,b1][b_0, b_1] of the edge, a pseudo-source s=(sx,sy)s = (s_x, s_y) with sy<0s_y < 0, and the distance σ\sigma from the source to ss. On the interval the window claims the distance σ+∣(x,0)−s∣\sigma + |(x, 0) - s|. 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 2π2\pi.

  1. MMP(mesh, sources)
  2. 1d(v) ← ∞ for all v; d(s) ← 0 and push the vertex event s for each source s
  3. 2while the queue is not empty do pop the event with the smallest key
  4. 3if 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
  5. 4if 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
  6. 5for 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
  7. 6return d

Cutting the cone (line L4). The rays from ss through (b0,0)(b_0, 0) and (b1,0)(b_1, 0) bound a cone. The ray from ss through the third vertex rr meets the edge at x=grx = g_r. Rays through [b0,min⁡(b1,gr)][b_0, \min(b_1, g_r)] leave the face through prpr, and rays through [max⁡(b0,gr),b1][\max(b_0, g_r), b_1] leave through rqrq. Each part becomes a window on its edge, with ss written in the frame of that edge and the next face, and the same σ\sigma.

Trimming (line L5). Two windows on one edge give two distance functions σ1+∣x−s1∣\sigma_1 + |x - s_1| and σ2+∣x−s2∣\sigma_2 + |x - s_2|. 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 [0,1]3[0, 1]^3 as 12 triangles, with the source at the corner (0,0,0)(0, 0, 0). 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 (1,0,0)(1, 0, 0) to (1,1,0)(1, 1, 0) of the bottom face and looks into the side x=1x = 1. Unfolding that side into the plane of the bottom puts the far corner (1,1,1)(1, 1, 1) at (2,1,0)(2, 1, 0), inside the cone from the source, so line L4 gives d=22+12=5≈2.236d = \sqrt{2^2 + 1^2} = \sqrt{5} \approx 2.236. A path along edges needs at least 1+2≈2.4141 + \sqrt{2} \approx 2.414. The whole run makes 14 windows.

A box. On the box 1×2×31 \times 2 \times 3, the three ways to unfold two sides between opposite corners give (1+2)2+32=18\sqrt{(1 + 2)^2 + 3^2} = \sqrt{18}, (1+3)2+22=20\sqrt{(1 + 3)^2 + 2^2} = \sqrt{20} and (2+3)2+12=26\sqrt{(2 + 3)^2 + 1^2} = \sqrt{26}. MMP returns 18≈4.243\sqrt{18} \approx 4.243, and the edge graph gives 4.6064.606.

An L-shaped floor. On the flat region [0,2]2[0, 2]^2 without the square (1,2]×(1,2](1, 2] \times (1, 2], with the source at (2,0)(2, 0), the vertices (1,32)(1, \frac{3}{2}), (1,2)(1, 2) and (12,2)(\frac{1}{2}, 2) cannot be seen in a straight line. The reflex corner (1,1)(1, 1) is a border vertex, so it becomes a pseudo-source with σ=2\sigma = \sqrt{2}, and the distance to (12,2)(\frac{1}{2}, 2) is 2+54\sqrt{2} + \sqrt{\frac{5}{4}}. 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 σ\sigma. Together these give d(v)d(v) 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 10−1010^{-10} 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. d(x)d(x) is the geodesic distance from the nearest source to a point xx of the surface. d^(v)\hat d(v) is the value that the algorithm holds for a vertex vv, which only goes down. The arithmetic is exact and the tolerances are 0. A window ww on edge ee has the value w(x)=σ+∣(x,0)−s∣w(x) = \sigma + |(x, 0) - s| at the points xx of its interval. A pseudo-source vertex is a source, a border vertex, or a vertex with angle sum at least 2π2\pi.

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 vv that is not one of its ends, then vv is a border vertex or its angle sum is at least 2π2\pi. Reason: the path cuts the faces around an inner vertex vv into two sides. If one side had an angle below π\pi, a short cut on that side would make the path shorter. So both sides are at least π\pi.

Lemma 1 (soundness). Every window value w(x)w(x) and every value given to d^\hat d is the length of a path on the surface from a source to that point. So d^(v)≥d(v)\hat d(v) \ge d(v), and w(x)≥d(x)w(x) \ge d(x).

Proof. By induction in the order of creation. At a source, d^=0\hat d = 0. A window made by line L3 at the vertex vv in the face g=(v,a,b)g = (v, a, b) has ss at the image of vv and σ=d^(v)\sigma = \hat d(v). For xx on abab, the segment from vv to xx lies in gg, and its length is ∣(x,0)−s∣|(x, 0) - s|, because the frame is an isometric copy of gg. Add a path of length d^(v)\hat d(v) to vv, which exists by induction. A child window of ww in line L4 holds a point XX of the edge prpr or rqrq only if the ray from ss to XX meets the edge pqpq at a point (g,0)(g, 0) with b0≤g≤b1b_0 \le g \le b_1. The segment from (g,0)(g, 0) to XX lies in the face hh, which is convex. So the path of ww to (g,0)(g, 0) followed by this segment has length σ+∣s−(g,0)∣+∣(g,0)−X∣=σ+∣s−X∣\sigma + |s - (g, 0)| + |(g, 0) - X| = \sigma + |s - X|, as the three points are on one line. This is the value of the child at XX, written in the frame of the new edge. The values given to the third vertex rr and to the end points of a new window are values of windows at those points. Trimming only makes intervals smaller. □\square

Lemma 2 (keys never go down). Every event that is pushed while an event of key kk is processed has a key at least kk. So the keys are taken in an order that never goes down.

Proof. A child of ww has, at each of its points XX, the value σ+∣s−X∣≥σ+∣s−(g,0)∣=w(g)≥key⁡(w)\sigma + |s - X| \ge \sigma + |s - (g, 0)| = w(g) \ge \operatorname{key}(w). A window made at a vertex vv has all its values at least σ=d^(v)=k\sigma = \hat d(v) = k. 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 ww itself at the third vertex, so it is at least kk too. □\square

So once a vertex event with key d^(v)\hat d(v) is taken, d^(v)\hat d(v) does not change again, and the windows that vv 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, σ1+A(x)=σ2+B(x)\sigma_1 + \sqrt{A(x)} = \sigma_2 + \sqrt{B(x)} with A,BA, B 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. □\square

Theorem 1 (completeness). At the end, d^(t)=d(t)\hat d(t) = d(t) for every vertex tt.

Proof. Fix tt and a shortest path γ\gamma from the nearest source v0v_0 to tt. Cut γ\gamma at each vertex it passes through. By (F2) these vertices v1,…,vkv_1, \dots, v_k are pseudo-source vertices, and each piece goes from viv_i to the next vertex zz without touching any other vertex. We show by induction on ii that d^(vi)=d(vi)\hat d(v_i) = d(v_i) at the end and that viv_i starts its windows with σ=d(vi)\sigma = d(v_i).

Start of a pseudo-source. If d^(vi)=d(vi)\hat d(v_i) = d(v_i) at the end, then the vertex event pushed when d^(vi)\hat d(v_i) took this value is taken later. At that time d^(vi)=d(vi)\hat d(v_i) = d(v_i), because it cannot go lower by Lemma 1, and viv_i has not started yet, because a start at an earlier, larger value would be followed by a drop, which Lemma 2 forbids. So viv_i starts with σ=d(vi)\sigma = d(v_i).

One piece. Let the piece from u=viu = v_i to zz cross the edges e1,…,eme_1, \dots, e_m at inner points x1,…,xmx_1, \dots, x_m, passing from face hj−1h_{j-1} into face hjh_j at xjx_j, with h0∋uh_0 \ni u and hm∋zh_m \ni z. Call a window good for jj if it lies on eje_j, looks into hjh_j, holds xjx_j, has the value d(xj)d(x_j) there, and its pseudo-source lies on the line of γ\gamma behind xjx_j in the unfolding. Such a window carries γ\gamma through xjx_j.

If m=0m = 0, then zz is a vertex of a face (u,a,b)(u, a, b), and the window that uu puts on abab in line L3, or the direct update for a border edge, sets d^(z)≤d(u)+∣uz∣=d(z)\hat d(z) \le d(u) + |uz| = d(z). Otherwise the window that uu puts on e1e_1, the far edge of h0h_0, is good for 1, since x1x_1 is inside e1e_1 and σ=d(u)\sigma = d(u).

A good window stays good where it holds xjx_j, and if trimming removes xjx_j from it, another good window holds xjx_j. By Lemma 3, a good window loses xjx_j only to a window yy with y(xj)≤d(xj)y(x_j) \le d(x_j), so y(xj)=d(xj)y(x_j) = d(x_j) by Lemma 1. The path of yy to xjx_j followed by the rest of γ\gamma is then a shortest path to zz. By (F1) it does not bend at xjx_j, so yy arrives along the line of γ\gamma from the side of hj−1h_{j-1}, and yy is good for jj. A good window cannot lose xjx_j to a strictly better window, since nothing is below d(xj)d(x_j). So from the time the first good window for jj is made, some alive window is good for jj. When the queue is empty, every alive window has been taken, so some good window ww for jj is taken in line L4.

When ww is taken, the ray through xjx_j crosses hjh_j straight. It does not pass through the third vertex rr of hjh_j, because γ\gamma touches no vertex there. If j<mj < m, it leaves hjh_j at xj+1x_{j+1}, inside ej+1e_{j+1}. The part of [b0,b1][b_0, b_1] on the same side of grg_r as xjx_j has positive length, because xj≠grx_j \ne g_r and ww has positive length, so the child on ej+1e_{j+1} is made and holds xj+1x_{j+1}, with the value d(xj)+∣xjxj+1∣=d(xj+1)d(x_j) + |x_j x_{j+1}| = d(x_{j+1}). It is good for j+1j + 1. It is not skipped as grazing, because γ\gamma crosses ej+1e_{j+1} and does not run along it. If j=mj = m, the ray reaches zz, which is then the third vertex of hmh_m (it cannot be an end of eme_m, as the segment would run along eme_m), and line L4 sets d^(z)≤d(xm)+∣xmz∣=d(z)\hat d(z) \le d(x_m) + |x_m z| = d(z).

So d^(z)≤d(z)\hat d(z) \le d(z), and with Lemma 1, d^(z)=d(z)\hat d(z) = d(z). Applying this to the pieces in turn gives the claim for every viv_i and finally for tt. □\square

Theorem 2 (termination). The loop stops.

Proof. Let DD be the largest distance dd of a point on an edge, which is finite. The proof of Theorem 1 also works when zz is any point of an edge, so every edge point xx is held by a good window from the time its parent, of key at most d(x)d(x), is taken. Once the key of the taken events is above DD, every new window has all its values above DD, 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 DD is ever pushed after that, and vertex events above DD are stale. Each window with a key at most DD belongs to a pseudo-source vertex and the sequence of faces that its rays cross within length DD. 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. □\square

What is not proved here. The bounds of O(n)O(n) windows per edge and O(n2log⁡n)O(n^2 \log n) 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 10−1010^{-10}, 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 O(n)O(n) intervals of optimality, so there are O(n2)O(n^2) windows in all. Each is pushed and taken once, at O(log⁡n)O(\log n) for the queue, which gives O(n2log⁡n)O(n^2 \log n) time and O(n2)O(n^2) 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 O(n1.5log⁡n)O(n^{1.5} \log n) on typical models. On random terrains of 81, 169 and 289 vertices, this implementation makes 451, 1019 and 1839 windows, which is about 6n6n.

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 O(n2)O(n^2) time and O(n)O(n) 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 O(nlog⁡n)O(n \log n) 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 σ\sigma, 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 d(a,b)=d(b,a)d(a, b) = d(b, a) 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 σ\sigma 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 O(n2)O(n^2) 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.

mmp_geodesic_algorithm.pyI0RawGitHub
# 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 O(n2log⁡n)O(n^2 \log n) time. Chen and Han lowered the time to O(n2)O(n^2) and the space to O(n)O(n) 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 O(nlog⁡n)O(n \log n) for convex polytopes.

References

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

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