Algorithm Search⌘K

Algorithmcore

Metro mesh comparison

Also called Metro tool, mesh Hausdorff error.

Cignoni, Rocchini and Scopigno's estimate of the one-sided and symmetric Hausdorff and mean distances between two meshes by sampling one surface.

Time
O(S F) brute_force · grid_worst
Space
O(F + C) grid
Where
C = the number of grid cells; F = the number of triangles of the other mesh; S = the number of samples
Properties
randomizednot exactiterative
Origin
Paolo Cignoni, Claudio Rocchini, Roberto Scopigno, 1998

Metro is the standard way to say how far apart two triangle meshes are, for example a mesh and its simplified copy. It samples the surface of one mesh, finds for each sample the nearest point of the other mesh, and reports the largest of these distances, an estimate of the one-sided Hausdorff distance, with their mean and root mean square. It does the same in the other direction, and the larger of the two maxima estimates the symmetric Hausdorff distance. Paolo Cignoni, Claudio Rocchini and Roberto Scopigno released it in 1998 as a tool to compare mesh simplification methods. The estimate is never too large, and it is too small by at most the spacing of the samples.

In plain words

Two meshes describe nearly the same shape, and you want to know how much they differ. Put many points on the first surface. For each point, measure how far it is to the second surface. The largest of these distances tells you the worst place, and the average tells you the typical error.

The worst place can be missed if no point lands on it. More points make the miss smaller. A point that is far from the second surface can only be found from the first surface, so the measurement is done in both directions.

The problem

The input is two triangle meshes AA and BB. The distance of a point pp to BB is d(p,B)=min⁡q∈B∣p−q∣d(p, B) = \min_{q \in B} |p - q|. The one-sided Hausdorff distance is h(A,B)=max⁡p∈Ad(p,B)h(A, B) = \max_{p \in A} d(p, B), and the symmetric one is H(A,B)=max⁡(h(A,B),h(B,A))H(A, B) = \max(h(A, B), h(B, A)). The mean distance is 1∣A∣∫Ad(p,B) dp\frac{1}{|A|}\int_A d(p, B)\, dp, where ∣A∣|A| is the area of AA. Metro estimates these numbers. The distance does not depend on the orientation of the faces; the code of the page keeps the usual convention that faces are oriented so that the outward normal follows the right-hand rule, but it does not use it.

The algorithm

The core step is the exact distance from a point to a triangle. The plane around a triangle splits into seven regions, the three corner regions, the three edge regions and the inside, and the nearest point is the corner, the foot of the perpendicular on the edge, or the projection onto the plane. Six dot products of edge vectors with pp minus a corner decide the region, as in the orientation test, and only ring operations and one division follow, so the result is exact for rational input.

For speed, the triangles of BB are put into a uniform grid of cubic cells: each triangle goes into every cell that meets its bounding box. A query visits rings of cells around the cell of pp, of growing radius rr, and stops as soon as the nearest triangle found is at most rhr h away, where hh is the cell size, because every triangle not yet seen is at least that far.

  1. METRO(A, B, k, n)
  2. 1S ← the vertices of a k × k similar subdivision of each triangle of A, and n random points of A
  3. 2for each p ∈ S do δ(p)² ← min over triangles T of B near p of |p − CLOSEST-POINT(p, T)|²
  4. 3h_AB ← max over p ∈ S of δ(p)
  5. 4mean_AB ← average of δ(p); rms_AB ← square root of the average of δ(p)²
  6. 5compute h_BA, mean_BA and rms_BA by L1 to L4 with A and B exchanged
  7. 6return h_AB, h_BA and max(h_AB, h_BA)

The random points of L1 are uniform by area: a triangle is chosen with probability proportional to its area, and two uniform numbers u,vu, v in [0,1][0, 1] give the point a+u(b−a)+v(c−a)a + u(b - a) + v(c - a), with (u,v)(u, v) replaced by (1−u,1−v)(1 - u, 1 - v) when u+v>1u + v > 1. This reflection maps the unit square onto the triangle twice, evenly.

Degenerate cases. A triangle of zero area has no inside region and the formula divides by zero; the code requires positive area. A sample that lies on BB has distance 0. If AA and BB are the same mesh, all distances are 0. A mesh with no triangles has no defined distance. The grid needs a cell size h>0h > 0; a very small hh makes many cells and a very large hh puts all triangles in one cell, which is the brute-force loop.

Example

Let AA be the unit square in the plane z=0z = 0, as two triangles, and BB the triangle (0,0,0)(0,0,0), (1,0,0)(1,0,0), (0,1,0)(0,1,0), the lower left half of the square. With k=2k = 2, L1 gives the 9 points with coordinates in {0,12,1}\{0, \frac12, 1\}.

step value
L2 the 6 points with x+y≤1x + y \le 1 lie on BB: δ=0\delta = 0
L2 (1,12)(1, \frac12) and (12,1)(\frac12, 1) are 1/22≈0.354\frac{1/2}{\sqrt2} \approx 0.354 from the edge x+y=1x + y = 1
L2 (1,1)(1, 1) is 12≈0.707\frac{1}{\sqrt2} \approx 0.707 from that edge
L3 hAB=1/2≈0.7071h_{AB} = 1/\sqrt2 \approx 0.7071, the true value, because the farthest corner is a sample
L4 mean =(2⋅0.354+0.707)/9≈0.1571= (2 \cdot 0.354 + 0.707)/9 \approx 0.1571, rms ≈0.2887\approx 0.2887
L5 BB lies on AA, so hBA=0h_{BA} = 0
L6 the symmetric estimate is 0.70710.7071

The true mean is ∫01s2(1−s) ds=162≈0.1179\int_0^1 \frac{s}{\sqrt2}(1 - s)\, ds = \frac{1}{6\sqrt2} \approx 0.1179 and the true rms is 1/24≈0.2041\sqrt{1/24} \approx 0.2041. The grid points overweight the corner of the square, so their mean is too large. The table compares the two kinds of samples in the code of the page.

samples max mean rms
subdivision, k=2k = 2 (9 points) 0.7071 0.1571 0.2887
subdivision, k=8k = 8 (81 points) 0.7071 0.1309 0.2282
subdivision, k=32k = 32 (1089 points) 0.7071 0.1214 0.2104
Monte Carlo, 100 points 0.6555 0.1180 0.2053
Monte Carlo, 10000 points 0.7015 0.1173 0.2033
true value 0.7071 0.1179 0.2041

The subdivision vertices find the maximum when it is at a vertex, and Monte Carlo points estimate the mean without bias but miss the maximum. Metro uses both kinds for this reason.

When the arithmetic is floating point. The code of the page computes every squared distance exactly in rational arithmetic and takes square roots only for the reported numbers. In doubles, the region tests are signs of dot products and the last step divides by a sum that is proportional to the squared area of the triangle. For a sliver of length 2 and width 10−1510^{-15}, the float distance from a point at distance 0.41 was off by 0.025, a case of catastrophic cancellation; for widths down to 10−1210^{-12} the float error stayed below 10−1510^{-15} in 3000 random queries. Simplified meshes often contain slivers, so a tool that compares them should guard the division, use exact predicates for the region tests, or fall back to the three edge distances when the area is tiny. This is the robustness problem of geometry in a mild form: the answer is a measured number, and a wrong region gives a point of the triangle whose distance is close to the true one unless the triangle is nearly degenerate.

Correctness

Every sample lies on AA, so its distance to BB is at most h(A,B)h(A, B), and the sampled maximum is a lower bound. The distance to BB is 1-Lipschitz: moving the point by δ\delta changes it by at most δ\delta. The worst point of AA is within δ\delta of a sample, where δ\delta is the largest distance from a point of AA to its nearest sample, so the sampled maximum is at least h(A,B)−δh(A, B) - \delta. For the subdivision of each triangle into k2k^2 similar copies, δ\delta is at most the longest edge of AA divided by kk. The closest-point routine finds the nearest point of a triangle by its Voronoi regions, and the grid search stops only when no unseen triangle can be closer. The full proof is below.

Proof: Metro's sampled distance is a lower bound of the one-sided Hausdorff distance, and it is within the sample spacing of the true valuefull

Setting. AA and BB are finite sets of triangles in R3\mathbb{R}^3, each of positive area, and they also denote the union of their triangles, which are closed sets. The distance from a point pp to BB is d(p,B)=min⁡q∈B∣p−q∣d(p, B) = \min_{q \in B} |p - q|, and the one-sided Hausdorff distance is h(A,B)=max⁡p∈Ad(p,B)h(A, B) = \max_{p \in A} d(p, B). The symmetric distance is H(A,B)=max⁡(h(A,B),h(B,A))H(A, B) = \max(h(A, B), h(B, A)). A sample set S⊂AS \subset A is a finite set of points. The code reports h^S=max⁡p∈Sd(p,B)\hat h_S = \max_{p \in S} d(p, B), and the mean and root mean square of d(p,B)d(p, B) over SS. The subdivision sample SkS_k of a triangle (a,b,c)(a, b, c) is the set of points a+ik(b−a)+jk(c−a)a + \frac{i}{k}(b - a) + \frac{j}{k}(c - a) with i,j≥0i, j \ge 0 and i+j≤ki + j \le k, and Sk(A)S_k(A) is the union over the triangles of AA.

Claim.

  1. For a point pp and a triangle T=(a,b,c)T = (a, b, c), the function CLOSEST-POINT of the code returns the point of TT nearest to pp, so d(p,T)2d(p, T)^2 is computed exactly for rational input.
  2. The uniform grid query returns min⁡T∈Bd(p,T)2\min_{T \in B} d(p, T)^2, the same value as the loop over all triangles.
  3. For every sample set S⊂AS \subset A, h^S≤h(A,B)\hat h_S \le h(A, B).
  4. If every point of AA is within δ\delta of a point of SS, then h(A,B)≤h^S+δh(A, B) \le \hat h_S + \delta. For Sk(A)S_k(A), δ≤L/k\delta \le L / k, where LL is the longest edge of AA. Also h^Sk≤h^S2k\hat h_{S_k} \le \hat h_{S_{2k}}.
  5. The symmetric value returned is max⁡(h^S(A,B),h^S′(B,A))\max(\hat h_{S}(A, B), \hat h_{S'}(B, A)), and it lies between H(A,B)−δH(A, B) - \delta and H(A,B)H(A, B) when both sample sets are δ\delta-dense.

Step 1 (part 1). The squared distance f(u,v)=∣a+u(b−a)+v(c−a)−p∣2f(u, v) = |a + u(b - a) + v(c - a) - p|^2 is a convex quadratic on the convex set {u,v≥0,u+v≤1}\{u, v \ge 0, u + v \le 1\}. Its minimizer is the unique point qq of TT with (p−q)⋅(x−q)≤0(p - q) \cdot (x - q) \le 0 for all x∈Tx \in T. The plane around TT is split into seven regions: three corner regions, three edge regions and the inside. The corner region of aa is {(b−a)⋅(p−a)≤0, (c−a)⋅(p−a)≤0}\{(b - a) \cdot (p - a) \le 0,\ (c - a) \cdot (p - a) \le 0\}; there (p−a)⋅(x−a)≤0(p - a) \cdot (x - a) \le 0 for all x=a+u(b−a)+v(c−a)x = a + u(b - a) + v(c - a) in TT, so q=aq = a. The same holds at bb and cc with the tests d3≥0,d4≤d3d_3 \ge 0, d_4 \le d_3 and d6≥0,d5≤d6d_6 \ge 0, d_5 \le d_6 of the code. If pp is in none of them, the code tests the edge regions: for edge abab, vc≤0v_c \le 0 says that the projection of pp onto the plane is on the outer side of the line abab (the quantity vcv_c is the area coordinate of cc times twice the area times ∣n∣2|n|^2), and d1≥0≥d3d_1 \ge 0 \ge d_3 says that the foot on the line falls between aa and bb; then q=a+d1d1−d3(b−a)q = a + \frac{d_1}{d_1 - d_3}(b - a), the foot of the perpendicular on the segment, and p−qp - q is orthogonal to abab and points away from TT, which gives the variational inequality. The other two edges are the same. If pp is in no corner or edge region, all three area coordinates va,vb,vcv_a, v_b, v_c are positive and the projection of pp onto the plane lies in TT, so qq is that projection, with barycentric weights vb/(va+vb+vc)v_b / (v_a + v_b + v_c) and vc/(va+vb+vc)v_c / (v_a + v_b + v_c). Every operation is a ring operation or a division by a nonzero rational, so the result is exact. The tests of the page also check it against another exact route on 3000 random cases.

Step 2 (part 2). Let the cell of a point xx be ⌊x/h⌋\lfloor x / h \rfloor in each coordinate. Each triangle is stored in every cell that meets its bounding box, so a triangle is stored in the cell of each of its points. Let pp be in cell cc. After the query has visited all cells c′c' with ∥c′−c∥∞≤r\|c' - c\|_\infty \le r, any point xx in a cell with ∥c′−c∥∞≥r+1\|c' - c\|_\infty \ge r + 1 differs from pp by at least rhr h in some coordinate, so ∣x−p∣≥rh|x - p| \ge r h. If TT is a triangle not yet seen, its point nearest to pp is in such a cell (else TT would be stored in a visited cell and seen), so d(p,T)≥rhd(p, T) \ge r h. The query stops when (rh)2≥(r h)^2 \ge the best value found, so no unseen triangle is closer. It also stops when the ring has passed all occupied cells, and then every triangle has been seen. In both cases it returns the minimum over all triangles.

Step 3 (part 3). Every sample is a point of AA, so d(p,B)≤h(A,B)d(p, B) \le h(A, B) for each sample and the maximum over SS is at most h(A,B)h(A, B).

Step 4 (part 4). The function p↦d(p,B)p \mapsto d(p, B) is 1-Lipschitz: for q∈Bq \in B nearest to yy, d(x,B)≤∣x−q∣≤∣x−y∣+d(y,B)d(x, B) \le |x - q| \le |x - y| + d(y, B). The maximum h(A,B)h(A, B) is attained at some x∈Ax \in A, because AA is compact and dd is continuous. Take s∈Ss \in S with ∣x−s∣≤δ|x - s| \le \delta; then h(A,B)=d(x,B)≤d(s,B)+δ≤h^S+δh(A, B) = d(x, B) \le d(s, B) + \delta \le \hat h_S + \delta. For SkS_k, the subdivision of a triangle with corners a,b,ca, b, c into the k2k^2 small triangles with corners in SkS_k covers the triangle, each small triangle is similar to it with ratio 1/k1/k, and a point of a triangle is within the diameter of that triangle, its longest edge, of each of its corners. So δ≤L/k\delta \le L / k. Finally Sk⊂S2kS_k \subset S_{2k}, since i/k=2i/2ki/k = 2i/2k, so the maximum can only grow.

Step 5 (part 5). The code returns the larger of the two one-sided estimates. By parts 3 and 4 each is between h−δh - \delta and hh for its direction, and the maximum of two numbers each in such an interval is in [max⁡−δ,max⁡][\max - \delta, \max].

What is measured, not proved. The mean and the root mean square are estimates of the area-weighted mean 1∣A∣∫Ad(p,B) dp\frac{1}{|A|}\int_A d(p, B)\, dp and of the square root of 1∣A∣∫Ad(p,B)2 dp\frac{1}{|A|}\int_A d(p, B)^2\, dp. The Monte Carlo samples choose a triangle with probability proportional to its area and a point in it with the reflection trick, which maps the uniform distribution on the unit square to the uniform distribution on the triangle; with nn samples the error of the mean shrinks like 1/n1/\sqrt n. The code draws the two coordinates from a grid of step 10−610^{-6}, so the points are uniform up to that grid. The vertices of SkS_k are not area-weighted (the edges of the mesh get more of them), so a mean over SkS_k alone is biased, as the example of the page shows.

Termination. Sampling makes O(k2)O(k^2) points per triangle plus nn random points. Each grid query visits rings of growing radius and stops at the latest when the ring has passed all occupied cells, a finite number. ■\blacksquare

Complexity

With SS samples and FF triangles in BB, the brute-force query costs O(F)O(F) per sample and O(SF)O(S F) in total. The grid takes O(F+C)O(F + C) space for CC cells, counting a triangle once per cell it meets. A query on a mesh with evenly sized triangles and a cell size near the triangle size touches O(1)O(1) cells and triangles, but in the worst case, for example one long triangle in every cell, it touches all FF. The subdivision gives about k2/2k^2/2 samples per triangle, so the sampling error δ\delta falls like 1/k1/k while the cost grows like k2k^2. The Monte Carlo mean has an error that falls like 1/n1/\sqrt n.

Properties

  • One-sided lower bound. The sampled maximum never exceeds the true Hausdorff distance, and it grows when samples are added.
  • Two-sided error bound. The true value is at most the sampled maximum plus the sample spacing.
  • Not symmetric. h(A,B)h(A, B) and h(B,A)h(B, A) can be very different, as in the example, where they are 0.707 and 0.
  • Randomized. The Monte Carlo samples depend on the seed; the subdivision samples do not.
  • Unsigned. The distance does not say on which side of BB the sample lies.

Variants and improvements

  • Sampling schemes. The original tool offers similar-triangle subdivision, Monte Carlo sampling and a sampling by scan conversion of each triangle, a form of stratified sampling, with a sampling density per unit area.
  • Vertex-only error. Measuring only at the vertices of AA is cheap but misses the error in the middle of large triangles, which is where a simplified mesh is far from the original.
  • MESH. Aspert, Santa-Cruz and Ebrahimi (2002) gave a similar tool with a different sampling and a grid query.
  • Chamfer distance. Averaging the nearest distances both ways, instead of taking the maximum, gives the chamfer distance, which is common in learning on point sets.
  • Error during simplification. Quadric error metrics bound a different quantity, the sum of squared distances to planes, during the simplification itself; Metro checks the result afterwards.

When to use it

Use Metro to report the approximation error of a simplified, remeshed or compressed mesh against the original, and to compare methods such as mesh simplification or isotropic remeshing fairly. Report both one-sided maxima, the mean and the sampling density. When a guarantee is needed rather than an estimate, add the spacing bound to the maximum, or use an exact algorithm for the Hausdorff distance between triangle meshes.

Pitfalls

  • Only one direction. The distance from the simplified mesh to the original is often small while the other direction is large, for example when a thin part has been removed. Always measure both.
  • Too few samples. The maximum can be missed by up to the sample spacing. State the density.
  • Mean over vertices. A mean over subdivision vertices is not area-weighted, as the example shows: 0.157 against 0.118.
  • Units. The values are absolute lengths. Divide by the diagonal of the bounding box to compare meshes of different size, and say so.
  • Slivers in floating point. Nearly degenerate triangles give wrong distances with doubles, as shown above.

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.

metro_mesh_comparison.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/metro-mesh-comparison/. The authors are listed in prov/YBB4K3.jsonl.

"""Metro mesh comparison (Cignoni, Rocchini and Scopigno 1998).

Sample the surface A, find for each sample the distance to the surface B,
and report the largest (an estimate of the one-sided Hausdorff distance from
A to B), the mean and the root mean square. The symmetric Hausdorff distance
is the larger of the two one-sided values.

Squared point-to-triangle distances are exact for int or Fraction input. A
uniform grid over the triangles of B answers the nearest-triangle query; it
returns the same exact value as a loop over all triangles. Square roots are
taken only at the end, for the reported numbers.
"""

import math
import random
from fractions import Fraction

from mp3geom import add, dot, scale, sub


def closest_point_on_triangle(p, a, b, c):
    """The point of triangle abc closest to p, by the Voronoi regions of the corners and edges. Exact."""
    ab, ac, ap = sub(b, a), sub(c, a), sub(p, a)
    d1, d2 = dot(ab, ap), dot(ac, ap)
    if d1 <= 0 and d2 <= 0:
        return a
    bp = sub(p, b)
    d3, d4 = dot(ab, bp), dot(ac, bp)
    if d3 >= 0 and d4 <= d3:
        return b
    vc = d1 * d4 - d3 * d2
    if vc <= 0 and d1 >= 0 and d3 <= 0:
        return add(a, scale(Fraction(d1) / (d1 - d3), ab))
    cp = sub(p, c)
    d5, d6 = dot(ab, cp), dot(ac, cp)
    if d6 >= 0 and d5 <= d6:
        return c
    vb = d5 * d2 - d1 * d6
    if vb <= 0 and d2 >= 0 and d6 <= 0:
        return add(a, scale(Fraction(d2) / (d2 - d6), ac))
    va = d3 * d6 - d5 * d4
    if va <= 0 and (d4 - d3) >= 0 and (d5 - d6) >= 0:
        return add(b, scale(Fraction(d4 - d3) / ((d4 - d3) + (d5 - d6)), sub(c, b)))
    denom = Fraction(1) / (va + vb + vc)
    return add(a, add(scale(vb * denom, ab), scale(vc * denom, ac)))


def dist2_point_triangle(p, a, b, c):
    q = closest_point_on_triangle(p, a, b, c)
    d = sub(p, q)
    return dot(d, d)


def brute_force_dist2(p, points, faces):
    """Squared distance from p to the mesh, by a loop over all triangles."""
    return min(dist2_point_triangle(p, *(points[v] for v in f)) for f in faces)


class UniformGrid:
    """Triangles of a mesh bucketed by their bounding boxes in cubic cells of side h."""

    def __init__(self, points, faces, h):
        self.points, self.faces, self.h = points, faces, Fraction(h)
        self.cells = {}
        for i, f in enumerate(faces):
            lo = [min(points[v][k] for v in f) for k in range(3)]
            hi = [max(points[v][k] for v in f) for k in range(3)]
            rng = [range(self.cell(lo[k]), self.cell(hi[k]) + 1) for k in range(3)]
            for x in rng[0]:
                for y in rng[1]:
                    for z in rng[2]:
                        self.cells.setdefault((x, y, z), []).append(i)
        keys = list(self.cells)
        self.lo = tuple(min(k[j] for k in keys) for j in range(3))
        self.hi = tuple(max(k[j] for k in keys) for j in range(3))

    def cell(self, x):
        return math.floor(Fraction(x) / self.h)

    def dist2(self, p):
        """Exact squared distance from p to the mesh. Visits rings of cells around p until no closer triangle can exist."""
        c = tuple(self.cell(x) for x in p)
        best, seen, ring = None, set(), 0
        reach = max(max(abs(c[j] - self.lo[j]), abs(c[j] - self.hi[j])) for j in range(3))
        while True:
            for key in self.ring(c, ring):
                for i in self.cells.get(key, ()):
                    if i not in seen:
                        seen.add(i)
                        d = dist2_point_triangle(p, *(self.points[v] for v in self.faces[i]))
                        if best is None or d < best:
                            best = d
            # every cell not yet visited is at least ring * h away from p
            if best is not None and (ring * self.h) ** 2 >= best:
                return best
            if ring > reach:
                return best
            ring += 1

    @staticmethod
    def ring(c, r):
        for dx in range(-r, r + 1):
            for dy in range(-r, r + 1):
                for dz in range(-r, r + 1):
                    if max(abs(dx), abs(dy), abs(dz)) == r:
                        yield (c[0] + dx, c[1] + dy, c[2] + dz)


def subdivision_samples(points, faces, k):
    """The vertices of the subdivision of every triangle into k * k similar triangles. Exact."""
    out = set()
    for f in faces:
        a, b, c = (points[v] for v in f)
        for i in range(k + 1):
            for j in range(k + 1 - i):
                u, v = Fraction(i, k), Fraction(j, k)
                out.add(tuple(x + u * (y - x) + v * (z - x) for x, y, z in zip(a, b, c)))
    return sorted(out)


def area(a, b, c):
    e1, e2 = sub(b, a), sub(c, a)
    n = (e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0])
    return math.sqrt(float(dot(n, n))) / 2


def monte_carlo_samples(points, faces, n, rng, denominator=10**6):
    """n points uniform by area: a triangle by its area, then a point by the reflection trick. Exact coordinates."""
    weights = [area(*(points[v] for v in f)) for f in faces]
    out = []
    for f in rng.choices(faces, weights=weights, k=n):
        a, b, c = (points[v] for v in f)
        u, v = Fraction(rng.randint(0, denominator), denominator), Fraction(rng.randint(0, denominator), denominator)
        if u + v > 1:
            u, v = 1 - u, 1 - v
        out.append(tuple(x + u * (y - x) + v * (z - x) for x, y, z in zip(a, b, c)))
    return out


def one_sided(samples, points_b, faces_b, h=None):
    """(max, mean, rms) of the distances from the samples to mesh B."""
    query = UniformGrid(points_b, faces_b, h).dist2 if h else (lambda p: brute_force_dist2(p, points_b, faces_b))
    d2 = [query(p) for p in samples]  # @line L2
    worst = max(d2)  # @line L3
    mean = sum(math.sqrt(float(x)) for x in d2) / len(d2)  # @line L4
    rms = math.sqrt(float(sum(d2)) / len(d2))
    return math.sqrt(float(worst)), mean, rms


def metro(points_a, faces_a, points_b, faces_b, k=8, n=2000, seed=1998, h=None):
    """One-sided values both ways and the symmetric Hausdorff estimate."""
    rng = random.Random(seed)
    sa = subdivision_samples(points_a, faces_a, k) + monte_carlo_samples(points_a, faces_a, n, rng)  # @line L1
    sb = subdivision_samples(points_b, faces_b, k) + monte_carlo_samples(points_b, faces_b, n, rng)
    ab = one_sided(sa, points_b, faces_b, h)  # @line L5
    ba = one_sided(sb, points_a, faces_a, h)
    return ab, ba, max(ab[0], ba[0])  # @line L6
mp3geom.py 136 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mp3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small tools for triangle meshes, used by the mp3 pages.

Points are tuples of int, fractions.Fraction or float. The predicates are
exact when the coordinates are int or Fraction. A mesh is a list of faces,
each a tuple of three vertex indices, oriented so that the outward normal
follows the right-hand rule (counterclockwise seen from outside).
"""

from fractions import Fraction


def sub(a, b):
    return tuple(x - y for x, y in zip(a, b))


def add(a, b):
    return tuple(x + y for x, y in zip(a, b))


def scale(s, a):
    return tuple(s * x for x in a)


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    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 orient2d(a, b, c):
    """Twice the signed area of triangle abc: > 0 if counterclockwise."""
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def orient3d(a, b, c, d):
    """((b - a) x (c - a)) . (d - a): > 0 if d is on the side of the normal of abc."""
    return dot(cross(sub(b, a), sub(c, a)), sub(d, a))


def sign(x):
    return (x > 0) - (x < 0)


def solve(a, b, tol=0.0):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a list of n rows of length n, b is a list of n rows of length m
    (m right-hand sides). Entries are Fraction (exact) or float. Returns the
    n rows of x. Raises ValueError if a pivot has absolute value <= tol, so
    an exact singular matrix always raises when tol is 0.
    """
    n = len(a)
    m = len(b[0]) if n else 0
    rows = [list(a[i]) + list(b[i]) for i in range(n)]
    for col in range(n):
        piv = max(range(col, n), key=lambda r: abs(rows[r][col]))
        if abs(rows[piv][col]) <= tol:
            raise ValueError("singular matrix")
        rows[col], rows[piv] = rows[piv], rows[col]
        pr = rows[col]
        inv = 1 / pr[col] if isinstance(pr[col], float) else Fraction(1) / pr[col]
        for r in range(col + 1, n):
            f = rows[r][col]
            if f:
                f = f * inv
                row = rows[r]
                for k in range(col, n + m):
                    if pr[k]:
                        row[k] -= f * pr[k]
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        row = rows[i]
        for k in range(m):
            s = row[n + k]
            for j in range(i + 1, n):
                if row[j]:
                    s -= row[j] * x[j][k]
            x[i][k] = s / row[i] if isinstance(s, float) or isinstance(row[i], float) else Fraction(s) / row[i]
    return x


def directed_edges(faces):
    """Map each directed edge (i, j) to (face index, corner of i). Raises on a repeated directed edge."""
    out = {}
    for f, tri in enumerate(faces):
        for k in range(3):
            e = (tri[k], tri[(k + 1) % 3])
            if e in out:
                raise ValueError("directed edge %r used twice: not an oriented manifold" % (e,))
            out[e] = (f, k)
    return out


def neighbours(faces):
    """Map each vertex to the set of its neighbours."""
    nb = {}
    for tri in faces:
        for k in range(3):
            i, j = tri[k], tri[(k + 1) % 3]
            nb.setdefault(i, set()).add(j)
            nb.setdefault(j, set()).add(i)
    return nb


def boundary_loop(faces):
    """The boundary of an oriented disk as one vertex loop, in the order of the face orientation."""
    de = directed_edges(faces)
    nxt = {}
    for i, j in de:
        if (j, i) not in de:
            if i in nxt:
                raise ValueError("boundary vertex %r is not manifold" % (i,))
            nxt[i] = j
    if not nxt:
        raise ValueError("the mesh has no boundary")
    start = min(nxt)
    loop = [start]
    while True:
        v = nxt[loop[-1]]
        if v == start:
            break
        loop.append(v)
    if len(loop) != len(nxt):
        raise ValueError("the boundary has more than one loop")
    return loop


def euler_characteristic(faces):
    verts = {v for tri in faces for v in tri}
    edges = {frozenset((tri[k], tri[(k + 1) % 3])) for tri in faces for k in range(3)}
    return len(verts) - len(edges) + len(faces)
test_metro_mesh_comparison.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/metro-mesh-comparison/. The authors are listed in prov/YBB4K3.jsonl.

import math
import random
from fractions import Fraction

from metro_mesh_comparison import (
    UniformGrid,
    brute_force_dist2,
    dist2_point_triangle,
    metro,
    monte_carlo_samples,
    one_sided,
    subdivision_samples,
)
from mp3geom import cross, dot, sub

SQUARE = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
SQUARE_FACES = [(0, 1, 2), (0, 2, 3)]


def segment_dist2(p, a, b):
    ab, ap = sub(b, a), sub(p, a)
    t = min(max(Fraction(dot(ap, ab), dot(ab, ab)), 0), 1)
    d = tuple(x - (y + t * z) for x, y, z in zip(p, a, ab))
    return dot(d, d)


def reference_dist2(p, a, b, c):
    """Exact distance by another route: the plane if the foot is inside, else the three edges."""
    n = cross(sub(b, a), sub(c, a))
    nn = dot(n, n)
    s = Fraction(dot(n, sub(p, a)), nn)
    q = tuple(x - s * y for x, y in zip(p, n))
    inside = all(dot(cross(sub(v, u), sub(q, u)), n) >= 0 for u, v in ((a, b), (b, c), (c, a)))
    if inside:
        return s * s * nn
    return min(segment_dist2(p, a, b), segment_dist2(p, b, c), segment_dist2(p, c, a))


def random_mesh(rng, n_faces, size=6):
    points = [tuple(rng.randint(-size, size) for _ in range(3)) for _ in range(n_faces + 2)]
    faces = []
    while len(faces) < n_faces:
        f = tuple(rng.sample(range(len(points)), 3))
        a, b, c = (points[v] for v in f)
        if cross(sub(b, a), sub(c, a)) != (0, 0, 0):
            faces.append(f)
    return points, faces


def test_point_triangle_distance_is_exact() -> None:
    rng = random.Random(1998)
    for _ in range(3000):
        while True:
            a, b, c = (tuple(rng.randint(-5, 5) for _ in range(3)) for _ in range(3))
            if cross(sub(b, a), sub(c, a)) != (0, 0, 0):
                break
        p = tuple(Fraction(rng.randint(-40, 40), 4) for _ in range(3))
        assert dist2_point_triangle(p, a, b, c) == reference_dist2(p, a, b, c)
    # the corners, edge points and inner points of the triangle are at distance 0
    a, b, c = (0, 0, 0), (4, 0, 0), (0, 4, 0)
    for p in (a, b, c, (2, 0, 0), (2, 2, 0), (1, 1, 0)):
        assert dist2_point_triangle(p, a, b, c) == 0


def test_grid_equals_brute_force() -> None:
    rng = random.Random(7)
    for h in (1, 2, Fraction(5, 2)):
        points, faces = random_mesh(rng, 25)
        grid = UniformGrid(points, faces, h)
        for _ in range(120):
            p = tuple(Fraction(rng.randint(-60, 60), 5) for _ in range(3))
            assert grid.dist2(p) == brute_force_dist2(p, points, faces)


def test_parallel_squares() -> None:
    up = [(x, y, Fraction(1, 2)) for x, y, _ in SQUARE]
    ab, ba, sym = metro(SQUARE, SQUARE_FACES, up, SQUARE_FACES, k=4, n=200)
    for maximum, mean, rms in (ab, ba):
        assert maximum == mean == rms == 0.5
    assert sym == 0.5


def test_square_against_half_square() -> None:
    # The corner (1, 1, 0) of the square is sqrt(2)/2 from the triangle, and the triangle lies on the square.
    half = [(0, 0, 0), (1, 0, 0), (0, 1, 0)]
    ab, ba, sym = metro(SQUARE, SQUARE_FACES, half, [(0, 1, 2)], k=4, n=200)
    assert ab[0] == math.sqrt(2) / 2
    assert ba == (0.0, 0.0, 0.0)
    assert sym == math.sqrt(2) / 2


def test_tilted_plane_mean_and_rms() -> None:
    # B lies in the plane z = x / 2. A point (x, y, 0) of A is x / sqrt(5) from it, and its foot is inside B.
    tilted = [(0, 0, 0), (1, 0, Fraction(1, 2)), (1, 1, Fraction(1, 2)), (0, 1, 0)]
    samples = monte_carlo_samples(SQUARE, SQUARE_FACES, 3000, random.Random(17))
    maximum, mean, rms = one_sided(samples + subdivision_samples(SQUARE, SQUARE_FACES, 8), tilted, SQUARE_FACES)
    assert maximum == math.sqrt(Fraction(1, 5))       # exact sample at x = 1
    assert abs(mean - 1 / (2 * math.sqrt(5))) < 0.01  # the true mean; 0.01 is about 4 standard errors
    assert abs(rms - math.sqrt(1 / 15)) < 0.01


def test_refinement_sandwich() -> None:
    # sampled(k) <= sampled(2k) <= the true one-sided distance <= sampled(k) + the longest sub-triangle edge
    rng = random.Random(3)
    for _ in range(4):
        pa, fa = random_mesh(rng, 4)
        pb, fb = random_mesh(rng, 6)
        longest = max(math.sqrt(dot(sub(pa[f[i]], pa[f[(i + 1) % 3]]), sub(pa[f[i]], pa[f[(i + 1) % 3]]))) for f in fa for i in range(3))
        k = 3
        lo = one_sided(subdivision_samples(pa, fa, k), pb, fb)[0]
        hi = one_sided(subdivision_samples(pa, fa, 2 * k), pb, fb)[0]
        assert lo <= hi + 1e-12
        assert hi <= lo + longest / k + 1e-12


def test_float_fails_on_a_sliver() -> None:
    # A triangle of length 2 and width 1e-15: in doubles the region tests and the division lose all digits.
    a, b = (0.0, 0.0, 0.0), (1.0, 0.0, 0.0)
    c = (1.9875242733132161, 8.342347734145901e-16, 7.384876595764672e-16)
    p = (0.5196353826017766, 0.3307482815418452, -0.24314659152190998)
    exact = dist2_point_triangle(tuple(map(Fraction, p)), *(tuple(map(Fraction, v)) for v in (a, b, c)))
    assert exact == reference_dist2(tuple(map(Fraction, p)), *(tuple(map(Fraction, v)) for v in (a, b, c)))
    error = abs(math.sqrt(dist2_point_triangle(p, a, b, c)) - math.sqrt(exact))
    assert error > 0.02                       # measured 0.0251


def test_grid_and_brute_force_give_the_same_report() -> None:
    rng = random.Random(11)
    pa, fa = random_mesh(rng, 6)
    pb, fb = random_mesh(rng, 8)
    assert metro(pa, fa, pb, fb, k=3, n=100) == metro(pa, fa, pb, fb, k=3, n=100, h=2)

History

The Hausdorff distance goes back to Felix Hausdorff's 1914 book on set theory. Mesh simplification grew fast in the 1990s, and papers measured their error in different ways, often only at the vertices. Cignoni, Rocchini and Scopigno released Metro in 1998 at the CNR in Pisa as a free tool that made the comparison uniform, with sampling of the first surface, a uniform grid for the distance queries, and a coloured map of the error on the surface. It became the usual way to report the error of simplified meshes. Aspert, Santa-Cruz and Ebrahimi described the similar tool MESH in 2002, and the Metro code later became part of the VCG library and of MeshLab.

References

  1. Paolo Cignoni, Claudio Rocchini and Roberto Scopigno, Metro, measuring error on simplified surfaces, Computer Graphics Forum 17(2), 1998, 167 to 174, the one-sided and symmetric Hausdorff distance, the mean error, the sampling of the first surface (similar-triangle subdivision, Monte Carlo, scan conversion), and the uniform grid for distance queries
  2. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 7, Simplification and Approximation (the error metrics of simplification; general locator)

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.brute_force
  • a full proof of time.grid_worst
  • a full proof of space.grid
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
  • at least three sources
  • a scene preset for the example