Algorithmadvanced
Minimum zone flatness
Also called minimum zone straightness and flatness.
Finds the two closest parallel planes that hold all measured points, which is the width of the set, by testing face-vertex and edge-edge pairs of the convex hull exactly.
- Solves
- Form error evaluation
- Time
- Θ(n²) worstΘ(n) best
- Space
- Θ(n) extra
- Where
- h = the number of hull vertices; n = the number of points
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Michael E. Houle, Godfried T. Toussaint, 1988
Minimum zone flatness computes the flatness of a measured surface as the distance between the two closest parallel planes that hold all the measured points. That distance is the width of the point set. The width is attained by a pair of parallel supporting planes of the convex hull that touch a face and a vertex, or two edges, so the algorithm builds the hull and tests these pairs. With exact arithmetic the answer is exact. In two dimensions the same method gives straightness: the thinnest strip between two parallel lines, attained by an edge of the hull and the farthest vertex, which is the polygon width. This page is a method; the problem, with all the forms (straightness, flatness, roundness, cylindricity) and the choice of the reference, is form error evaluation, and the method for cylindricity is minimum zone cylindricity.
In plain words
A machine touches many points on a surface that should be flat. To grade the surface, we hold it between two parallel sheets of glass and push the sheets together until they touch the points. The gap left between the sheets is the flatness. We may tilt the sheets any way we like, and we want the tilt that makes the gap smallest.
Only a few tilts can be the best one. Wrap the points in the tightest convex shell. At the best tilt, one sheet lies flat on a face of the shell and the other touches a corner, or each sheet touches an edge of the shell, and the two edges cross. So we test each face against the farthest corner, and each pair of edges that can face each other, and keep the smallest gap.
The problem
The input is a finite set of points in . A zone is a slab with a unit normal , and its width is . The zone shape for flatness is the region between two parallel planes, and the objective is the least width of a zone that holds :
This is the minimum zone, or Chebyshev, flatness. The output is and the two planes. For straightness of points in a plane, replace the planes by lines.
A least-squares plane is not the minimum zone plane. The two planes parallel to it through the extreme points form a zone, so its width is never smaller than , and it is often larger. Standards such as ISO 1101 define flatness by the minimum zone.
The algorithm
MIN-ZONE-FLATNESS(P)- 1
if P lies in one plane then return that plane, width 0 - 2
T ← triangles of the convex hull of P, with outward normals - 3
best ← ∞ - 4
for each triangle t with normal N and a vertex a of t - 5
best ← min(best, (N·a − min over vertices v of N·v) / |N|) - 6
for each pair of hull edges e, f with directions d_e, d_f not parallel - 7
n ← d_e × d_f - 8
for s in {+1, −1} - 9
if s·n is in the normal cone of e and −s·n is in the normal cone of f - 10
best ← min(best, s·n·(a_e − a_f) / |n|) ▷ a_e on e, a_f on f - 11
return best and the planes that attain it
Line L2. The hull is built incrementally from a tetrahedron. A triangle is visible from a new point if the point is strictly on its outer side; the visible triangles are removed and the horizon edges are joined to the new point. A point in the plane of a triangle does not see it, so adjacent triangles may be coplanar. All signs are computed with integers or fractions.
Line L5, face and vertex. The plane of the triangle supports the hull, and the parallel plane through the lowest vertex closes the zone.
Lines L6 to L10, edge and edge. The normal cone of an edge is the set of directions spanned by the outward normals , of its two triangles; these are the directions in which the edge is highest. A direction normal to both edges is parallel to . If it is in the cone of and its opposite is in the cone of , the planes through and normal to hold all points between them. With , a vector normal to is in the cone when and are each zero or have the sign of ; when the cone is the ray of .
Every candidate is a true zone, so the minimum is never below , and the optimum is among the candidates.
Example
Edge and edge. The regular tetrahedron has edge length . Each face is at the height from the opposite vertex, but the opposite edges and lie in the planes and . The flatness is , attained by two edges. A method that tests faces only gives .
Tilted surface. The points lie on and above the plane , tilted degrees. The minimum zone is the face and the parallel plane through , so . The vertical deviation from that plane is , which overstates the flatness by .
The vertical Chebyshev fit is a different plane. Minimizing subject to is a linear program, and it is often used for flatness. It measures the zone along , not along the normal. For the points it has the unique optimum , , with vertical thickness . The orthogonal width of that zone is . The minimum zone has the normal , is attained by two edges, and has , so . The tests check these values with exact arithmetic.
Correctness
The correctness file proves:
- The face-vertex and edge-edge characterization. On a cell of the overlay of the Gaussian map of the hull with its antipodal image, the extent is for a fixed . This function has no local minimum with a positive value on an open region or an open great circle arc of the sphere, so the minimum is at a facet normal or at a crossing of two edge arcs. This is the result of Houle and Toussaint.
- The hull. The incremental hull with exact orientation tests bounds the hull and has no degenerate triangle.
- The cone test above, and that every candidate is a zone that holds all points.
- The vertical fit only bounds flatness. If solves the vertical fit with value and the minimum zone plane has slope , then . So the vertical fit is close only when the part is nearly level, and the example shows that the first inequality can be strict.
The tests compare the result with a brute force over every plane through three points and every direction normal to two segments, in exact arithmetic, on random sets with many coplanar points. They also compare it with a search over a one-degree grid of normals, using the fact that the extent changes by at most the diameter of the set times the change of the unit normal.
Proof: The minimum zone of flatness is attained by a face and a vertex or by two edges of the convex hull, the exact candidate tests find it, and the vertical Chebyshev fit only bounds itfull
Setup. is a finite set of points in and is its convex hull. For a unit vector let , the support function, and , the extent of in the direction . A zone with unit normal is a slab , and it holds only if . So the minimum zone flatness is
the width of . The minimum exists because is continuous on the unit sphere . If lies in a plane, ; from now on has full dimension, so for every .
Lemma 1 (the faces met by a direction). For each , let be the face of on which is largest and . The normal cones of the vertices, edges and facets of cut into open regions (one per vertex), open great circle arcs (one per edge, normal to the edge) and points (the facet normals); this is the Gaussian map of . Overlay it with its image under . On each cell of the overlay, and are fixed, and with for any and .
Proof. is constant on and equal to there, and for . In a cell of the overlay, both faces are fixed by the definition of the cell.
Lemma 2 (where the minimum is). Let minimize . Then one of these holds: (a) or is the outward normal of a facet of (a face and a vertex, the vertex in the face of the other side); (b) is normal to an edge and an edge of that are not parallel, is in the normal cone of and in the normal cone of (two edges).
Proof. Suppose first that is in an open two-dimensional cell of the overlay. By Lemma 1, near , and is a local minimum of on . The gradient of on the sphere is , which is zero only at (or everywhere if ). The point is the maximum, and at and for the value is . Each case contradicts .
Suppose next that is in an open arc of the overlay. The arc lies on a great circle , and on the arc by Lemma 1. Write for an orthonormal basis of the plane of . Then with , whose local minima on have the value . Again gives a contradiction.
So is a vertex of the overlay: a vertex of the Gaussian map (a facet normal, case (a)), a vertex of its antipodal image ( a facet normal, case (a)), or a point where an arc of an edge crosses the antipodal image of an arc of an edge . Two arcs on distinct great circles meet in isolated points, which is case (b); is then normal to both and . If the two great circles are the same ( parallel to ), the arcs overlap in an arc, and a vertex of the overlay on it is an end of one of the arcs, which is a facet normal of case (a).
This is the characterization of Houle and Toussaint (1988); the proof above follows the Gaussian map.
Lemma 3 (the incremental hull). The procedure convex_hull_3d returns oriented triangles whose union is the boundary of , each with all points of on its inner side or on it, and no triangle has zero area.
Proof sketch. The start is a tetrahedron of four points that are not coplanar, oriented so that the fourth vertex is on the inner side of each face. Assume the triangles bound of the points so far. A new point is in exactly when no triangle has strictly on its outer side, and then . Otherwise the visible triangles (strictly outer side) are the triangles of the facets of whose planes separate strictly, and their union is a disk whose boundary is the horizon. The boundary of is the rest of the old boundary and the cone from over the horizon; this is the standard incremental argument in de Berg, Cheong, van Kreveld and Overmars, Chapter 11. Treating a triangle whose plane holds as not visible only adds coplanar neighbor triangles. A new triangle is never degenerate: lie on a visible triangle, and if were on the line it would be in the plane of that triangle, which then would not be strictly visible. Each signed volume is computed with exact integers or fractions, so all tests are exact.
The tests check on random integer sets with many coplanar points that the result is a closed oriented surface, that , and that every point is on the inner side of every triangle.
Lemma 4 (the cone test). Let an edge of the triangulated hull have direction and the outward normals , of its two triangles, both normal to . A vector normal to is a combination with if and only if: when , is a positive multiple of (or ); when , and are each or of the sign of .
Proof. If , then are independent and span the plane normal to , so for unique . By linearity of the determinant, and . If , then and are parallel; they are not opposite, because two triangles of a closed convex surface with opposite outward normals on a common edge would make flat. So is a positive multiple of and the cone is the ray of .
Lemma 5 (every candidate is a zone). If with for an edge with endpoint , then for all . So for each candidate of the code (a triangle with its lowest vertex, or two edges with in the cone of the first and in the cone of the second), the slab between the two planes holds , and its width is at least .
Proof. By Lemma 3, for , because lies on both triangles. Add the inequalities with weights . For a triangle, the upper plane holds the triangle, all points are on its inner side, and the lower plane is through the point of least .
Theorem (correctness). minimum_zone_flatness returns a zone of width that holds .
Proof. By Lemma 5 the result holds and its width is at least . Let be as in Lemma 2. In case (a), the facet with normal is a union of triangles of the code with outward normals that are positive multiples of , and the code measures each triangle against the lowest vertex, which gives the width . In case (b), the edge of is a union of collinear triangle edges, and each one has its two triangles in the two facets of at , so its cone is the normal cone of ; the same holds for . For such a pair the code forms , which is parallel to , tries and , and by Lemma 4 accepts the sign that points along . The width of that candidate is for points , . So the minimum over the candidates is at most . All values are compared as exact squared widths.
Termination. Every loop runs over finite lists: insertions, each over the current triangles, then the triangles and the pairs of edges.
Lemma 6 (straightness). For points in the plane, the thinnest strip is attained by an edge of the convex hull and the farthest hull vertex. Proof. The same argument in one dimension lower: on the unit circle, the cells of the overlay are open arcs and points, on an open arc has no local minimum with a positive value, so is the normal of an edge of the hull or the opposite of one.
The vertical Chebyshev fit. The linear program minimize subject to has the optimal value with , , and the optimum zone has the thickness . The zone has the normal and the orthogonal width .
Theorem (the vertical fit only bounds flatness). Let solve the vertical fit, and let the minimum zone have a normal that is not horizontal. Then
Proof. The first inequality holds because the vertical zone is a zone. The second is clear. For the third, the minimum zone has the vertical thickness , and is the least vertical thickness.
The first inequality can be strict: the point set has , attained by two edges with the normal , while the vertical fit has the unique optimum at and the orthogonal width . The tests check these values with exact arithmetic.
The least-squares plane. Any plane through the centroid along the smallest eigenvector of the covariance matrix gives a zone, so its width is at least by the definition of . It is never narrower than the minimum zone, and it is often wider.
Complexity
The incremental hull tests each new point against every current triangle, which is and in the worst case. Testing each triangle against all vertices is , and the pairs of edges are with work each. So the time is in the worst case on the real RAM, and when the hull has a bounded size. A faster hull, the randomized incremental hull in expected time or quickhull, which is fast in practice, reduces the first term, but the edge pairs stay . The space is . In exact arithmetic the numbers grow: for integer input of bits, the normals and dot products have bits.
Houle and Toussaint list the antipodal pairs in time, with the number of antipodal edge pairs, which is in the worst case. Chazelle, Edelsbrunner, Guibas and Sharir computed the width in time, and Agarwal and Sharir in expected time. Those methods are not practical for inspection data, where is at most a few thousand.
Properties
- Exact. With integer or rational input, every comparison is exact, and the result is the true minimum zone of the measured points.
- Invariant. The width does not change under rigid motions of the data, unlike the vertical fit.
- Depends on the extreme points only. Only hull vertices matter, so one outlier changes the result. That is the definition of the tolerance, not a defect, but it makes the method sensitive to spikes in the data.
- Global. No starting plane is needed and there is no local minimum.
Variants and improvements
- Straightness. In two dimensions the width is attained by a hull edge and a vertex, and rotating calipers list the antipodal pairs in linear time after the hull. The code checks each hull edge against all hull vertices.
- Linear programming. With a reference direction fixed near the normal, the vertical fit is a small LP in three variables, and it is an LP-type problem, solvable in expected linear time. It is exact for the vertical measure only, and the theorem above bounds its error.
- Repeated linear programs. Solving the vertical fit, rotating the data so that the found normal is vertical, and solving again gives a sequence of zones that does not get wider. Each zone is a true zone, so this gives an upper bound at each step.
- Approximation. A grid or an iterative search over normals gives upper bounds, and the Lipschitz bound of the extent gives an error estimate.
When to use it
Use it to report flatness or straightness under a standard that defines them by the minimum zone, and to check software that reports flatness. Use a least-squares plane when a stable reference with a smooth dependence on the data is needed, and say that its zone width is an upper bound. Use the vertical linear program only when the surface is nearly level, and convert its value to an orthogonal width.
Pitfalls
- Testing faces only. The width of a tetrahedron is attained by two edges. Methods that only rest a plane on a face of the hull overstate flatness.
- Vertical distances. A Chebyshev fit of against and measures thickness along , which overstates flatness by of the tilt and can pick a different plane.
- Floating point orientation tests. Rounded signs on nearly coplanar points give hulls with holes or folded triangles. Use exact predicates, or adaptive ones.
- Too few points. The minimum zone of the sample is a lower bound of the flatness of the surface, since the true extreme points may not be measured. A larger or better spread sample, for example Hammersley sampling, reduces the gap.
- Probe radius. The points must be corrected for the probe radius before the evaluation.
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/minimum-zone-flatness/. The authors are listed in prov/5ZWKK1.jsonl.
"""Minimum zone flatness and straightness, exact.
The flatness of a set of points in 3D is the distance between the two closest
parallel planes that hold all the points between them, which is the width of
the set. The width is attained by a pair of parallel supporting planes of the
convex hull that touch a face and a vertex, or two edges (Houle and Toussaint
1988). The code builds the hull with an exact incremental method, then checks
every face against the farthest vertex and every pair of edges that admit
antipodal supporting planes.
All arithmetic is done with int and Fraction, so the result is exact. Floats
in the input are converted to the Fraction of their binary value.
"""
from fractions import Fraction
from math import sqrt
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 _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 _det(a, b, c):
return _dot(_cross(a, b), c)
def _sign(x):
return (x > 0) - (x < 0)
class Zone:
"""Two parallel planes lo <= normal . p <= hi that hold all points.
The normal is exact and not normalized. width2 is the exact squared
width (hi - lo)^2 / |normal|^2, and width is its float square root.
kind is "face-vertex", "edge-edge" or "degenerate".
"""
def __init__(self, normal, lo, hi, kind):
self.normal = normal
self.lo = lo
self.hi = hi
self.kind = kind
nn = _dot(normal, normal)
self.width2 = Fraction(0) if lo == hi else Fraction((hi - lo) ** 2) / nn
self.width = sqrt(self.width2)
def __repr__(self):
return "Zone(width=%r, kind=%r)" % (self.width, self.kind)
def _exact(points, dim):
out = []
seen = set()
for p in points:
if len(p) != dim:
raise ValueError("each point needs %d coordinates" % dim)
q = tuple(Fraction(x) for x in p)
if q not in seen:
seen.add(q)
out.append(q)
return out
def convex_hull_3d(points):
"""Return the triangles (i, j, k) of the hull of the distinct points pts.
The faces are oriented so that cross(pts[j] - pts[i], pts[k] - pts[i])
points out of the hull. Coplanar adjacent triangles are allowed.
Return None if the points are coplanar. Time O(n^2).
"""
pts = points
n = len(pts)
if n < 4:
return None
i0 = 0
i1 = next((i for i in range(n) if pts[i] != pts[i0]), None)
if i1 is None:
return None
d01 = _sub(pts[i1], pts[i0])
i2 = next((i for i in range(n) if _cross(d01, _sub(pts[i], pts[i0])) != (0, 0, 0)), None)
if i2 is None:
return None
nrm = _cross(d01, _sub(pts[i2], pts[i0]))
i3 = next((i for i in range(n) if _dot(nrm, _sub(pts[i], pts[i0])) != 0), None)
if i3 is None:
return None
tet = (i0, i1, i2, i3)
faces = []
for skip in range(4):
f = [tet[k] for k in range(4) if k != skip]
if _orient(pts, f, pts[tet[skip]]) > 0:
f[1], f[2] = f[2], f[1]
faces.append(tuple(f))
used = set(tet)
for i in range(n):
if i in used:
continue
p = pts[i]
visible = [f for f in faces if _orient(pts, f, p) > 0]
if not visible:
continue
vis_edges = set()
for a, b, c in visible:
vis_edges.update(((a, b), (b, c), (c, a)))
horizon = [(a, b) for (a, b) in vis_edges if (b, a) not in vis_edges]
vis_set = set(visible)
faces = [f for f in faces if f not in vis_set]
faces.extend((a, b, i) for (a, b) in horizon)
return faces
def _orient(pts, f, p):
a, b, c = pts[f[0]], pts[f[1]], pts[f[2]]
return _det(_sub(b, a), _sub(c, a), _sub(p, a))
def _face_normal(pts, f):
a, b, c = pts[f[0]], pts[f[1]], pts[f[2]]
return _cross(_sub(b, a), _sub(c, a))
def _in_edge_cone(n1, n2, d, u):
"""True if u is a nonnegative combination of n1 and n2 (u is normal to d)."""
t = _det(n1, n2, d)
if t == 0:
return _cross(n1, u) == (0, 0, 0) and _dot(n1, u) > 0
s = _sign(t)
return _sign(_det(n1, u, d)) in (0, s) and _sign(_det(u, n2, d)) in (0, s)
def _degenerate_zone(pts):
"""Zone of width 0 for coplanar or collinear points."""
if len(pts) <= 1:
return Zone((0, 0, 1), Fraction(0), Fraction(0), "degenerate")
p0 = pts[0]
d = _sub(pts[1], p0)
for q in pts[2:]:
nrm = _cross(d, _sub(q, p0))
if nrm != (0, 0, 0):
v = _dot(nrm, p0)
return Zone(nrm, v, v, "degenerate")
for axis in ((1, 0, 0), (0, 1, 0), (0, 0, 1)):
nrm = _cross(d, axis)
if nrm != (0, 0, 0):
v = _dot(nrm, p0)
return Zone(nrm, v, v, "degenerate")
raise AssertionError("unreachable")
def minimum_zone_flatness(points):
"""Return the Zone of least width that holds the 3D points.
The zone width is the flatness of the points in the minimum zone sense.
"""
pts = _exact(points, 3)
faces = convex_hull_3d(pts) # @line L2
if faces is None:
return _degenerate_zone(pts) # @line L1
verts = sorted({i for f in faces for i in f})
best = None # @line L3
normals = [_face_normal(pts, f) for f in faces]
# Face against the farthest vertex.
for f, nf in zip(faces, normals): # @line L4
hi = _dot(nf, pts[f[0]])
lo = min(_dot(nf, pts[v]) for v in verts)
z = Zone(nf, lo, hi, "face-vertex")
if best is None or z.width2 < best.width2: # @line L5
best = z
# Edge against edge, when the two edges admit antipodal supporting planes.
side = {}
for k, (a, b, c) in enumerate(faces):
side[(a, b)] = k
side[(b, c)] = k
side[(c, a)] = k
edges = []
for (a, b), k in side.items():
if a < b:
d = _sub(pts[b], pts[a])
edges.append((pts[a], d, normals[k], normals[side[(b, a)]]))
for i in range(len(edges)): # @line L6
pa, da, na1, na2 = edges[i]
for j in range(i + 1, len(edges)):
pb, db, nb1, nb2 = edges[j]
n = _cross(da, db) # @line L7
if n == (0, 0, 0):
continue
for u in (n, (-n[0], -n[1], -n[2])): # @line L8
neg = (-u[0], -u[1], -u[2])
if _in_edge_cone(na1, na2, da, u) and _in_edge_cone(nb1, nb2, db, neg): # @line L9
z = Zone(u, _dot(u, pb), _dot(u, pa), "edge-edge")
if z.width2 < best.width2: # @line L10
best = z
break
return best # @line L11
def convex_hull_2d(points):
"""Andrew's monotone chain on distinct exact points, counterclockwise."""
pts = sorted(set(points))
if len(pts) <= 2:
return pts
def turn(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
lower, upper = [], []
for p in pts:
while len(lower) >= 2 and turn(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
for p in reversed(pts):
while len(upper) >= 2 and turn(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
return lower[:-1] + upper[:-1]
def minimum_zone_straightness(points):
"""Return (width2, normal, lo, hi) of the thinnest strip that holds 2D points.
The width of a planar set is attained by a hull edge and the farthest
hull vertex, so each hull edge is checked against all hull vertices.
Time O(n log n + h^2) for h hull vertices.
"""
pts = _exact(points, 2)
hull = convex_hull_2d(pts)
if len(hull) <= 1:
return Fraction(0), (0, 1), Fraction(0), Fraction(0)
if len(hull) == 2:
(x0, y0), (x1, y1) = hull
nrm = (y0 - y1, x1 - x0)
v = nrm[0] * x0 + nrm[1] * y0
return Fraction(0), nrm, v, v
best = None
h = len(hull)
for i in range(h):
(x0, y0), (x1, y1) = hull[i], hull[(i + 1) % h]
nrm = (y1 - y0, x0 - x1)
hi = nrm[0] * x0 + nrm[1] * y0
lo = min(nrm[0] * x + nrm[1] * y for x, y in hull)
w2 = Fraction((hi - lo) ** 2) / (nrm[0] ** 2 + nrm[1] ** 2)
if best is None or w2 < best[0]:
best = (w2, nrm, lo, hi)
return best
if __name__ == "__main__":
tet = [(0, 0, 0), (1, 1, 0), (1, 0, 1), (0, 1, 1)]
print(minimum_zone_flatness(tet))
lp = [(1, 2, 2), (0, 0, 1), (4, 3, 10), (3, 3, 7), (1, 3, 4)]
z = minimum_zone_flatness(lp)
print(z, z.width2, z.normal)
test_minimum_zone_flatness.py 224 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-zone-flatness/. The authors are listed in prov/5ZWKK1.jsonl.
import math
import random
import unittest
from fractions import Fraction
from itertools import combinations
from minimum_zone_flatness import (
convex_hull_3d,
minimum_zone_flatness,
minimum_zone_straightness,
)
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 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 extent(points, n):
v = [dot(n, p) for p in points]
return max(v) - min(v)
def brute_width2(points):
"""Minimum over every plane through three points and every direction
normal to two segments of the extent of the set, with exact arithmetic.
This candidate set holds every face-vertex and edge-edge normal, and every
candidate gives a zone that holds all points, so the minimum is the width.
"""
best = None
cands = []
for a, b, c in combinations(points, 3):
cands.append(cross(sub(b, a), sub(c, a)))
segs = list(combinations(points, 2))
for (a, b), (c, d) in combinations(segs, 2):
cands.append(cross(sub(b, a), sub(d, c)))
for n in cands:
if n == (0, 0, 0):
continue
w2 = Fraction(extent(points, n) ** 2, dot(n, n))
if best is None or w2 < best:
best = w2
return best
def random_set(rng, n, lo=-5, hi=5):
return [tuple(rng.randint(lo, hi) for _ in range(3)) for _ in range(n)]
class TestHull(unittest.TestCase):
def test_hull_is_closed_and_convex(self):
rng = random.Random(1)
for _ in range(30):
pts = list(dict.fromkeys(random_set(rng, 25)))
fp = [tuple(Fraction(x) for x in p) for p in pts]
faces = convex_hull_3d(fp)
self.assertIsNotNone(faces)
edges = set()
for a, b, c in faces:
for e in ((a, b), (b, c), (c, a)):
self.assertNotIn(e, edges)
edges.add(e)
for a, b in edges:
self.assertIn((b, a), edges)
verts = {i for f in faces for i in f}
self.assertEqual(len(verts) - len(edges) // 2 + len(faces), 2)
for a, b, c in faces:
nrm = cross(sub(fp[b], fp[a]), sub(fp[c], fp[a]))
self.assertNotEqual(nrm, (0, 0, 0))
for p in fp:
self.assertLessEqual(dot(nrm, sub(p, fp[a])), 0)
class TestFlatness(unittest.TestCase):
def test_against_brute_force(self):
rng = random.Random(7)
for trial in range(40):
n = rng.randint(4, 10)
pts = random_set(rng, n)
z = minimum_zone_flatness(pts)
self.assertEqual(z.width2, brute_width2(pts), pts)
for p in pts:
v = dot(z.normal, p)
self.assertTrue(z.lo <= v <= z.hi)
def test_near_planar_sets(self):
rng = random.Random(11)
for trial in range(30):
pts = []
for _ in range(rng.randint(5, 10)):
x, y = rng.randint(-6, 6), rng.randint(-6, 6)
pts.append((x, y, 2 * x - y + rng.randint(0, 2)))
self.assertEqual(minimum_zone_flatness(pts).width2, brute_width2(pts), pts)
def test_against_grid_of_normals(self):
rng = random.Random(5)
step = math.radians(1.0)
grid = []
for i in range(91):
th = i * step
for j in range(360):
ph = j * step
grid.append((math.sin(th) * math.cos(ph), math.sin(th) * math.sin(ph), math.cos(th)))
for trial in range(4):
pts = random_set(rng, 9)
z = minimum_zone_flatness(pts)
nn = math.sqrt(float(dot(z.normal, z.normal)))
ustar = tuple(float(c) / nn for c in z.normal)
if ustar[2] < 0:
ustar = tuple(-c for c in ustar)
diam = max(math.dist(p, q) for p, q in combinations(pts, 2))
gap = min(math.dist(g, ustar) for g in grid)
best = min(extent(pts, g) for g in grid)
# Every direction gives a zone at least as wide as the optimum.
self.assertGreaterEqual(best, z.width - 1e-9)
# The extent is Lipschitz in the normal with constant diam.
self.assertLessEqual(best, z.width + diam * gap + 1e-9)
def test_regular_tetrahedron_needs_edge_edge(self):
z = minimum_zone_flatness([(0, 0, 0), (1, 1, 0), (1, 0, 1), (0, 1, 1)])
self.assertEqual(z.width2, 1)
self.assertEqual(z.kind, "edge-edge")
def test_cube(self):
cube = [(x, y, z) for x in (0, 2) for y in (0, 2) for z in (0, 2)]
self.assertEqual(minimum_zone_flatness(cube + [(1, 1, 1)]).width2, 4)
def test_degenerate(self):
self.assertEqual(minimum_zone_flatness([(1, 2, 3)]).width2, 0)
self.assertEqual(minimum_zone_flatness([(0, 0, 0), (1, 1, 1), (2, 2, 2)]).width2, 0)
z = minimum_zone_flatness([(0, 0, 1), (1, 0, 3), (0, 1, 2), (5, 7, 18)])
self.assertEqual(z.width2, 0)
for p in [(0, 0, 1), (5, 7, 18)]:
self.assertEqual(dot(z.normal, p), z.lo)
def test_float_input(self):
z = minimum_zone_flatness([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 0.5)])
# The origin is at distance 1/sqrt(6) from the face x + y + 2z = 1.
self.assertEqual(z.width2, Fraction(1, 6))
self.assertEqual(z.kind, "face-vertex")
class TestPageExamples(unittest.TestCase):
def test_tilted_face(self):
pts = [(0, 0, 0), (2, 0, 2), (0, 2, 0), (2, 2, 2), (1, 1, 2)]
z = minimum_zone_flatness(pts)
self.assertEqual(z.width2, Fraction(1, 2))
def test_vertical_chebyshev_differs(self):
pts = [(1, 2, 2), (0, 0, 1), (4, 3, 10), (3, 3, 7), (1, 3, 4)]
z = minimum_zone_flatness(pts)
self.assertEqual(z.width2, Fraction(81, 170))
def vertical(a, b):
r = [p[2] - a * p[0] - b * p[1] for p in pts]
return max(r) - min(r)
# The vertical thickness V(a, b) is convex and piecewise linear, so its
# minimum is at a vertex, where the zone touches the points in a
# triple or in two pairs. Those planes are among the candidates below.
vals = {}
for a3, b3, c3 in combinations(pts, 3):
n = cross(sub(b3, a3), sub(c3, a3))
if n[2] != 0:
vals[(Fraction(-n[0], n[2]), Fraction(-n[1], n[2]))] = None
for (a2, b2), (c2, d2) in combinations(list(combinations(pts, 2)), 2):
n = cross(sub(b2, a2), sub(d2, c2))
if n[2] != 0:
vals[(Fraction(-n[0], n[2]), Fraction(-n[1], n[2]))] = None
for ab in vals:
vals[ab] = vertical(*ab)
vstar = min(vals.values())
argmin = [ab for ab, v in vals.items() if v == vstar]
self.assertEqual(vstar, Fraction(5, 3))
self.assertEqual(argmin, [(2, Fraction(1, 3))])
a, b = argmin[0]
orth = float(vstar) / math.sqrt(1 + a * a + b * b)
self.assertAlmostEqual(orth, 0.7372, places=4)
self.assertAlmostEqual(z.width, 0.6903, places=4)
self.assertGreater(orth, z.width)
class TestStraightness(unittest.TestCase):
def test_against_brute_force(self):
rng = random.Random(3)
for trial in range(60):
pts = [(rng.randint(-8, 8), rng.randint(-8, 8)) for _ in range(rng.randint(3, 12))]
w2, nrm, lo, hi = minimum_zone_straightness(pts)
best = None
for (ax, ay), (bx, by) in combinations(set(pts), 2):
n = (ay - by, bx - ax)
v = [n[0] * x + n[1] * y for x, y in pts]
c = Fraction((max(v) - min(v)) ** 2, n[0] ** 2 + n[1] ** 2)
best = c if best is None or c < best else best
self.assertEqual(w2, best if best is not None else 0, pts)
for x, y in pts:
self.assertTrue(lo <= nrm[0] * x + nrm[1] * y <= hi)
def test_collinear(self):
self.assertEqual(minimum_zone_straightness([(0, 0), (1, 2), (3, 6)])[0], 0)
class TestScale(unittest.TestCase):
def test_many_points_on_a_plate(self):
rng = random.Random(9)
pts = [(rng.randint(0, 1000), rng.randint(0, 1000), rng.randint(0, 3)) for _ in range(300)]
z = minimum_zone_flatness(pts)
self.assertLessEqual(z.width2, 9)
for p in pts:
self.assertTrue(z.lo <= dot(z.normal, p) <= z.hi)
if __name__ == "__main__":
unittest.main()
History
Houle and Toussaint gave the characterization of the width of a set by antipodal pairs of the convex hull in 1985 at the Symposium on Computational Geometry, and in the journal in 1988. Traband, Joshi, Wysk and Cavalier gave minimum zone methods for straightness and flatness for inspection in 1989, when coordinate measuring machine software still used least-squares fits. Later work in computational geometry reduced the time to subquadratic bounds by parametric search and randomization. The ISO and ASME standards define flatness by the zone between two parallel planes.
References
- Michael E. Houle and Godfried T. Toussaint, Computing the width of a set, IEEE Transactions on Pattern Analysis and Machine Intelligence 10(5), 1988, 761 to 765, the characterization of the width in three dimensions by antipodal vertex-face and edge-edge pairs of the convex hull, the algorithm in O(n log n + I) time for I antipodal edge pairs, and the minimax plane fit
- Mark T. Traband, Sanjay Joshi, Richard A. Wysk and Tom M. Cavalier, Evaluation of straightness and flatness tolerances using the minimum zone, Manufacturing Review 2(3), 1989, 189 to 195, the minimum zone evaluation of straightness and flatness from measured points
- Bernard Chazelle, Herbert Edelsbrunner, Leonidas J. Guibas and Micha Sharir, Diameter, width, closest line pair, and parametric searching, Discrete and Computational Geometry 10(2), 1993, 183 to 196, the width of a point set in three dimensions in O(n^(8/5+ε)) time
- Pankaj K. Agarwal and Micha Sharir, Efficient randomized algorithms for some geometric optimization problems, Discrete and Computational Geometry 16(4), 1996, 317 to 337, the width of a point set in three dimensions in O(n^(3/2+ε)) expected time
- Mark de Berg, Otfried Cheong, Marc van Kreveld and Mark Overmars, Computational Geometry, Algorithms and Applications, 3rd edition, Springer, 2008, Chapter 11, Convex Hulls (the incremental construction of a three-dimensional hull and the horizon of a new point)
- ISO 1101:2017, Geometrical product specifications (GPS), Geometrical tolerancing, Tolerances of form, orientation, location and run-out, fourth edition, the standard as a whole (the flatness and straightness tolerance zones); no clause is quoted
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 5ZWKK1 Edit this page History Report an error Markdown