Algorithm Search⌘K

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.

Time
Θ(n²) worstΘ(n) best
Space
Θ(n) extra
Where
h = the number of hull vertices; n = the number of points
Properties
deterministicexactofflineiterative
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 PP of points in R3\mathbb{R}^3. A zone is a slab {x:ℓ≤u⋅x≤ℓ+t}\{x : \ell \le u \cdot x \le \ell + t\} with a unit normal uu, and its width is tt. The zone shape for flatness is the region between two parallel planes, and the objective is the least width of a zone that holds PP:

F(P)=min⁡∣u∣=1(max⁡x∈Pu⋅x−min⁡x∈Pu⋅x).F(P) = \min_{\lvert u \rvert = 1} \Bigl( \max_{x \in P} u \cdot x - \min_{x \in P} u \cdot x \Bigr).

This is the minimum zone, or Chebyshev, flatness. The output is F(P)F(P) 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 F(P)F(P), and it is often larger. Standards such as ISO 1101 define flatness by the minimum zone.

The algorithm

  1. MIN-ZONE-FLATNESS(P)
  2. 1if P lies in one plane then return that plane, width 0
  3. 2T ← triangles of the convex hull of P, with outward normals
  4. 3best ← ∞
  5. 4for each triangle t with normal N and a vertex a of t
  6. 5best ← min(best, (N·a − min over vertices v of N·v) / |N|)
  7. 6for each pair of hull edges e, f with directions d_e, d_f not parallel
  8. 7n ← d_e × d_f
  9. 8for s in {+1, −1}
  10. 9if s·n is in the normal cone of e and −s·n is in the normal cone of f
  11. 10best ← min(best, s·n·(a_e − a_f) / |n|) ▷ a_e on e, a_f on f
  12. 11return 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 N1N_1, N2N_2 of its two triangles; these are the directions in which the edge is highest. A direction normal to both edges is parallel to n=de×dfn = d_e \times d_f. If it is in the cone of ee and its opposite is in the cone of ff, the planes through ee and ff normal to nn hold all points between them. With t=det⁡(N1,N2,d)t = \det(N_1, N_2, d), a vector uu normal to dd is in the cone when det⁡(N1,u,d)\det(N_1, u, d) and det⁡(u,N2,d)\det(u, N_2, d) are each zero or have the sign of tt; when t=0t = 0 the cone is the ray of N1N_1.

Every candidate is a true zone, so the minimum is never below F(P)F(P), and the optimum is among the candidates.

Example

Edge and edge. The regular tetrahedron (0,0,0),(1,1,0),(1,0,1),(0,1,1)(0,0,0), (1,1,0), (1,0,1), (0,1,1) has edge length 2\sqrt 2. Each face is at the height 2/3≈1.15472/\sqrt 3 \approx 1.1547 from the opposite vertex, but the opposite edges (0,0,0)(1,1,0)(0,0,0)(1,1,0) and (1,0,1)(0,1,1)(1,0,1)(0,1,1) lie in the planes z=0z = 0 and z=1z = 1. The flatness is 11, attained by two edges. A method that tests faces only gives 1.15471.1547.

Tilted surface. The points (0,0,0),(2,0,2),(0,2,0),(2,2,2),(1,1,2)(0,0,0), (2,0,2), (0,2,0), (2,2,2), (1,1,2) lie on and above the plane z=xz = x, tilted 4545 degrees. The minimum zone is the face z=xz = x and the parallel plane through (1,1,2)(1,1,2), so F=1/2≈0.7071F = 1/\sqrt 2 \approx 0.7071. The vertical deviation from that plane is 11, which overstates the flatness by 1/cos⁡45°1/\cos 45°.

The vertical Chebyshev fit is a different plane. Minimizing tt subject to ∣zi−axi−byi−c∣≤t\lvert z_i - a x_i - b y_i - c \rvert \le t is a linear program, and it is often used for flatness. It measures the zone along zz, not along the normal. For the points (1,2,2),(0,0,1),(4,3,10),(3,3,7),(1,3,4)(1,2,2), (0,0,1), (4,3,10), (3,3,7), (1,3,4) it has the unique optimum a=2a = 2, b=1/3b = 1/3, with vertical thickness 5/35/3. The orthogonal width of that zone is (5/3)/1+4+1/9≈0.7372(5/3)/\sqrt{1 + 4 + 1/9} \approx 0.7372. The minimum zone has the normal (−12,−1,5)(-12, -1, 5), is attained by two edges, and has F2=81/170F^2 = 81/170, so F≈0.6903F \approx 0.6903. 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 u⋅cu \cdot c for a fixed cc. 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 (a∗,b∗)(a^*, b^*) solves the vertical fit with value V∗V^* and the minimum zone plane has slope gg, then F≤V∗/1+∣(a∗,b∗)∣2≤V∗≤F1+∣g∣2F \le V^*/\sqrt{1 + \lvert (a^*, b^*) \rvert^2} \le V^* \le F \sqrt{1 + \lvert g \rvert^2}. 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. PP is a finite set of points in R3\mathbb{R}^3 and KK is its convex hull. For a unit vector uu let h(u)=max⁡x∈Pu⋅xh(u) = \max_{x \in P} u \cdot x, the support function, and w(u)=h(u)+h(−u)w(u) = h(u) + h(-u), the extent of PP in the direction uu. A zone with unit normal uu is a slab {x:ℓ≤u⋅x≤ℓ+t}\{x : \ell \le u \cdot x \le \ell + t\}, and it holds PP only if t≥w(u)t \ge w(u). So the minimum zone flatness is

F(P)=min⁡∣u∣=1w(u),F(P) = \min_{\lvert u \rvert = 1} w(u),

the width of PP. The minimum exists because ww is continuous on the unit sphere S2S^2. If PP lies in a plane, F(P)=0F(P) = 0; from now on KK has full dimension, so w(u)>0w(u) > 0 for every uu.

Lemma 1 (the faces met by a direction). For each uu, let F+(u)F^+(u) be the face of KK on which u⋅xu \cdot x is largest and F−(u)=F+(−u)F^-(u) = F^+(-u). The normal cones of the vertices, edges and facets of KK cut S2S^2 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 KK. Overlay it with its image under u↦−uu \mapsto -u. On each cell of the overlay, F+F^+ and F−F^- are fixed, and w(u)=u⋅cw(u) = u \cdot c with c=a−bc = a - b for any a∈F+a \in F^+ and b∈F−b \in F^-.

Proof. u⋅xu \cdot x is constant on F+(u)F^+(u) and equal to h(u)h(u) there, and h(−u)=−u⋅bh(-u) = -u \cdot b for b∈F−(u)b \in F^-(u). In a cell of the overlay, both faces are fixed by the definition of the cell. □\square

Lemma 2 (where the minimum is). Let u∗u^* minimize ww. Then one of these holds: (a) u∗u^* or −u∗-u^* is the outward normal of a facet of KK (a face and a vertex, the vertex in the face of the other side); (b) u∗u^* is normal to an edge ee and an edge ff of KK that are not parallel, u∗u^* is in the normal cone of ee and −u∗-u^* in the normal cone of ff (two edges).

Proof. Suppose first that u∗u^* is in an open two-dimensional cell of the overlay. By Lemma 1, w(u)=u⋅cw(u) = u \cdot c near u∗u^*, and u∗u^* is a local minimum of u⋅cu \cdot c on S2S^2. The gradient of u⋅cu \cdot c on the sphere is c−(u⋅c)uc - (u \cdot c) u, which is zero only at u=±c/∣c∣u = \pm c / \lvert c \rvert (or everywhere if c=0c = 0). The point c/∣c∣c / \lvert c \rvert is the maximum, and at −c/∣c∣-c / \lvert c \rvert and for c=0c = 0 the value is ≤0\le 0. Each case contradicts w(u∗)>0w(u^*) > 0.

Suppose next that u∗u^* is in an open arc of the overlay. The arc lies on a great circle CC, and on the arc w(u)=u⋅cw(u) = u \cdot c by Lemma 1. Write u=cos⁡s g1+sin⁡s g2u = \cos s \, g_1 + \sin s \, g_2 for an orthonormal basis g1,g2g_1, g_2 of the plane of CC. Then u⋅c=Acos⁡s+Bsin⁡s=Rcos⁡(s−s0)u \cdot c = A \cos s + B \sin s = R \cos(s - s_0) with R≥0R \ge 0, whose local minima on CC have the value −R≤0-R \le 0. Again w(u∗)>0w(u^*) > 0 gives a contradiction.

So u∗u^* is a vertex of the overlay: a vertex of the Gaussian map (a facet normal, case (a)), a vertex of its antipodal image (−u∗-u^* a facet normal, case (a)), or a point where an arc of an edge ee crosses the antipodal image of an arc of an edge ff. Two arcs on distinct great circles meet in isolated points, which is case (b); u∗u^* is then normal to both ee and ff. If the two great circles are the same (ee parallel to ff), 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). □\square

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 KK, each with all points of PP 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 Kj=conv⁡K_j = \operatorname{conv} of the points so far. A new point pp is in KjK_j exactly when no triangle has pp strictly on its outer side, and then Kj+1=KjK_{j+1} = K_j. Otherwise the visible triangles (strictly outer side) are the triangles of the facets of KjK_j whose planes separate pp strictly, and their union is a disk whose boundary is the horizon. The boundary of Kj+1K_{j+1} is the rest of the old boundary and the cone from pp 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 pp as not visible only adds coplanar neighbor triangles. A new triangle (u,v,p)(u, v, p) is never degenerate: u,vu, v lie on a visible triangle, and if pp were on the line uvuv 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. □\square

The tests check on random integer sets with many coplanar points that the result is a closed oriented surface, that V−E+F=2V - E + F = 2, 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 dd and the outward normals N1N_1, N2N_2 of its two triangles, both normal to dd. A vector uu normal to dd is a combination αN1+βN2\alpha N_1 + \beta N_2 with α,β≥0\alpha, \beta \ge 0 if and only if: when t=det⁡(N1,N2,d)=0t = \det(N_1, N_2, d) = 0, uu is a positive multiple of N1N_1 (or u=0u = 0); when t≠0t \ne 0, det⁡(N1,u,d)\det(N_1, u, d) and det⁡(u,N2,d)\det(u, N_2, d) are each 00 or of the sign of tt.

Proof. If t≠0t \ne 0, then N1,N2N_1, N_2 are independent and span the plane normal to dd, so u=αN1+βN2u = \alpha N_1 + \beta N_2 for unique α,β\alpha, \beta. By linearity of the determinant, det⁡(N1,u,d)=βt\det(N_1, u, d) = \beta t and det⁡(u,N2,d)=αt\det(u, N_2, d) = \alpha t. If t=0t = 0, then N1N_1 and N2N_2 are parallel; they are not opposite, because two triangles of a closed convex surface with opposite outward normals on a common edge would make KK flat. So N2N_2 is a positive multiple of N1N_1 and the cone is the ray of N1N_1. □\square

Lemma 5 (every candidate is a zone). If u=αN1+βN2u = \alpha N_1 + \beta N_2 with α,β≥0\alpha, \beta \ge 0 for an edge with endpoint aa, then u⋅x≤u⋅au \cdot x \le u \cdot a for all x∈Px \in P. So for each candidate of the code (a triangle with its lowest vertex, or two edges with uu in the cone of the first and −u-u in the cone of the second), the slab between the two planes holds PP, and its width is at least F(P)F(P).

Proof. By Lemma 3, Nk⋅x≤Nk⋅aN_k \cdot x \le N_k \cdot a for k=1,2k = 1, 2, because aa lies on both triangles. Add the inequalities with weights α,β\alpha, \beta. 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 N⋅xN \cdot x. □\square

Theorem (correctness). minimum_zone_flatness returns a zone of width F(P)F(P) that holds PP.

Proof. By Lemma 5 the result holds PP and its width is at least F(P)F(P). Let u∗u^* be as in Lemma 2. In case (a), the facet with normal ±u∗\pm u^* is a union of triangles of the code with outward normals that are positive multiples of ±u∗\pm u^*, and the code measures each triangle against the lowest vertex, which gives the width w(u∗)w(u^*). In case (b), the edge ee of KK is a union of collinear triangle edges, and each one has its two triangles in the two facets of KK at ee, so its cone is the normal cone of ee; the same holds for ff. For such a pair the code forms n=de×dfn = d_e \times d_f, which is parallel to u∗u^*, tries nn and −n-n, and by Lemma 4 accepts the sign that points along u∗u^*. The width of that candidate is u∗⋅(a−b)=w(u∗)u^* \cdot (a - b) = w(u^*) for points a∈ea \in e, b∈fb \in f. So the minimum over the candidates is at most F(P)F(P). All values are compared as exact squared widths. □\square

Termination. Every loop runs over finite lists: nn 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 w(u)=u⋅cw(u) = u \cdot c has no local minimum with a positive value, so u∗u^* is the normal of an edge of the hull or the opposite of one. □\square

The vertical Chebyshev fit. The linear program minimize tt subject to ∣zi−axi−byi−c∣≤t\lvert z_i - a x_i - b y_i - c \rvert \le t has the optimal value V∗=min⁡a,bV(a,b)V^* = \min_{a,b} V(a, b) with V(a,b)=max⁡iri−min⁡iriV(a, b) = \max_i r_i - \min_i r_i, ri=zi−axi−byir_i = z_i - a x_i - b y_i, and the optimum zone has the thickness 2t=V∗2t = V^*. The zone { c≤z−ax−by≤c+V }\{\, c \le z - a x - b y \le c + V \,\} has the normal (−a,−b,1)(-a, -b, 1) and the orthogonal width V/1+a2+b2V / \sqrt{1 + a^2 + b^2}.

Theorem (the vertical fit only bounds flatness). Let (a∗,b∗)(a^*, b^*) solve the vertical fit, and let the minimum zone have a normal (−g1,−g2,1)(-g_1, -g_2, 1) that is not horizontal. Then

F(P)≤V∗1+a∗2+b∗2≤V∗≤F(P)1+g12+g22.F(P) \le \frac{V^*}{\sqrt{1 + a^{*2} + b^{*2}}} \le V^* \le F(P) \sqrt{1 + g_1^2 + g_2^2}.

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 V(g1,g2)=F(P)1+g12+g22V(g_1, g_2) = F(P) \sqrt{1 + g_1^2 + g_2^2}, and V∗V^* is the least vertical thickness. □\square

The first inequality can be strict: the point set (1,2,2),(0,0,1),(4,3,10),(3,3,7),(1,3,4)(1,2,2), (0,0,1), (4,3,10), (3,3,7), (1,3,4) has F2=81/170F^2 = 81/170, attained by two edges with the normal (−12,−1,5)(-12, -1, 5), while the vertical fit has the unique optimum V∗=5/3V^* = 5/3 at (a,b)=(2,1/3)(a, b) = (2, 1/3) and the orthogonal width 0.7372>0.6903=F0.7372 > 0.6903 = F. 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 F(P)F(P) by the definition of FF. 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 O(nh)O(n h) and Θ(n2)\Theta(n^2) in the worst case. Testing each triangle against all vertices is O(hn)O(h n), and the pairs of edges are O(h2)O(h^2) with O(1)O(1) work each. So the time is Θ(n2)\Theta(n^2) in the worst case on the real RAM, and Θ(n)\Theta(n) when the hull has a bounded size. A faster hull, the randomized incremental hull in expected O(nlog⁡n)O(n \log n) time or quickhull, which is fast in practice, reduces the first term, but the edge pairs stay O(h2)O(h^2). The space is Θ(n)\Theta(n). In exact arithmetic the numbers grow: for integer input of bb bits, the normals and dot products have O(b)O(b) bits.

Houle and Toussaint list the antipodal pairs in O(nlog⁡n+I)O(n \log n + I) time, with II the number of antipodal edge pairs, which is Θ(n2)\Theta(n^2) in the worst case. Chazelle, Edelsbrunner, Guibas and Sharir computed the width in O(n8/5+ε)O(n^{8/5 + \varepsilon}) time, and Agarwal and Sharir in O(n3/2+ε)O(n^{3/2 + \varepsilon}) expected time. Those methods are not practical for inspection data, where nn 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 zz against xx and yy measures thickness along zz, which overstates flatness by 1/cos⁡1/\cos 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.

minimum_zone_flatness.pyI0RawGitHub
# 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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • 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