Algorithm Search⌘K

Algorithmadvanced

Minimum zone cylindricity

Also called minimum zone cylinder.

Finds two coaxial cylinders of least radial gap that hold measured points, a nonlinear Chebyshev fit, by linear programs on linearized radii. It finds a local optimum only.

Time
O(s k n²) worst
Space
Θ(n²) extra
Where
k = the number of simplex pivots in one linear program; n = the number of points; s = the number of iterations
Properties
deterministicnot exactofflineiterative
Origin
Kirsten Carr, Placid Ferreira, 1995

Minimum zone cylindricity computes the cylindricity of a measured cylindrical feature: the least radial gap Rout−RinR_{\mathrm{out}} - R_{\mathrm{in}} of two coaxial cylinders that hold all the measured points. For a fixed axis the gap is the range of the distances from the points to the axis, so the problem is to choose the axis, four numbers. The function of the axis is not convex, so this is a nonlinear Chebyshev fit. The method here, after Carr and Ferreira, linearizes the distances about the current axis, solves the linear program that minimizes the linearized gap inside a box of trust, and keeps the new axis only if the true gap goes down. It finds a local minimum and has no global guarantee. This page is a method; the problem, with the other forms and the choice of reference, is form error evaluation, and the method for flatness and straightness is minimum zone flatness.

In plain words

A shaft should be a perfect cylinder. A machine measures many points on it. We want two tubes with the same center line, one inside the other, so that all points lie between them, and with the walls as close as possible. The gap between the walls is the cylindricity.

If we knew the center line, the answer would be easy: take the nearest and the farthest point from the line. The hard part is the line. So we start with a good guess, then ask how each distance would change if we moved or tilted the line a little. With that simple rule, the best small move is a standard linear problem. We make the move only if the true gap gets smaller, and otherwise we try a smaller move. This ends at a line that no small move improves, but there may be a better line far away.

The problem

The input is a set of points q1,…,qnq_1, \dots, q_n in R3\mathbb{R}^3, measured on a nominally cylindrical surface and corrected for the probe radius. For a line LL, let ρi(L)\rho_i(L) be the distance from qiq_i to LL. The zone shape is the region between two coaxial cylinders, and the objective is the least width

C=min⁡L(max⁡iρi(L)−min⁡iρi(L)),C = \min_L \Bigl( \max_i \rho_i(L) - \min_i \rho_i(L) \Bigr),

the minimum zone cylindricity. The output is an axis and the two radii. The method below returns an axis LL with the width W(L)≥CW(L) \ge C of a true zone, which is a local minimum in practice.

The least-squares cylinder, fitted as in geometric primitive fitting, is not the minimum zone cylinder. The zone about its axis is a true zone, so its width is never smaller than CC. It is a good start for this method.

The algorithm

  1. MIN-ZONE-CYLINDER(q_1..q_n)
  2. 1(p, u) ← start axis; W ← width about (p, u); b ← W
  3. 2repeat
  4. 3δ ← solution of the LP: minimize R − r subject to
  5. r ≤ ρ_i + g_i·δ ≤ R for all i, and δ in the box of size b
  6. 4(p', u') ← axis moved by δ
  7. 5W' ← max_i ρ_i(p', u') − min_i ρ_i(p', u')
  8. 6if W' < W then (p, u, W) ← (p', u', W'); b ← 2b
  9. 7else b ← b/4
  10. 8until b is below a tolerance; return (p, u), min ρ_i, max ρ_i

Line L1, the start. The code tries each principal direction of the points as the axis, with the center of a linear circle fit of the points projected on the normal plane, and keeps the thinnest zone. A least-squares cylinder is a better start when it is available, and the caller can pass any start.

Line L3, the linear program. In a frame (e1,e2,u)(e_1, e_2, u) at pp, let qi−pq_i - p have coordinates (xi,yi,zi)(x_i, y_i, z_i) and ρi=xi2+yi2\rho_i = \sqrt{x_i^2 + y_i^2}. Moving the axis to pass through (δ1,δ2,0)(\delta_1, \delta_2, 0) with the direction (δ3,δ4,1)(\delta_3, \delta_4, 1) changes the distance to first order to

ρi−xiδ1+yiδ2+zi(xiδ3+yiδ4)ρi=ρi+gi⋅δ.\rho_i - \frac{x_i \delta_1 + y_i \delta_2 + z_i (x_i \delta_3 + y_i \delta_4)}{\rho_i} = \rho_i + g_i \cdot \delta .

The program has six variables, δ\delta, rr and RR, and 2n+42n + 4 constraints. The code shifts the variables so that the origin is feasible and solves it by a dense simplex method with Bland's rule. The tilt box is the shift box divided by the largest ∣zi∣\lvert z_i \rvert, so both move the points by similar amounts.

Lines L5 to L7, the safeguard. The linear model is only first-order. The new axis is accepted only if the exact width is smaller, and then the box grows; otherwise the box shrinks. This makes the accepted widths strictly decrease.

Example

Alternating contacts. Twenty-four points lie on three levels z=−3,0,3z = -3, 0, 3, at eight angles on each level, alternately at radius 44 and 4.054.05 about a known axis, and the set is moved by a random rigid motion. From a start tilted by about 0.020.02 radians and shifted by 0.030.03, the method returns the width 0.050.05 to 10−910^{-9}, the true axis.

A lobed shaft. Forty points on a shaft of radius 55 and length 1010 with a three-lobe error of amplitude 0.010.01 and uniform noise of ±0.002\pm 0.002, seed 1. From the default start, the method stops after six accepted steps at the width 0.019970.01997. Moving the axis does little against a three-lobe error, so the width stays close to twice the amplitude.

Noise-free cylinder. Points on an exact cylinder in a random position give a width below 10−810^{-8}.

These numbers are measured with the code on this page, not proved.

Correctness

The correctness file proves:

  • A true zone. For a fixed axis, the thinnest coaxial zone has the radii min⁡iρi\min_i \rho_i and max⁡iρi\max_i \rho_i, so every reported value is the width of a zone that holds all points and is at least CC.
  • The linearization of the distances in the axis parameters, with a second-order remainder when no point is on the axis.
  • Each linear program is feasible at the origin after the change of variables, is bounded, and is solved by the simplex method with Bland's rule, which does not cycle.
  • Monotone decrease. The accepted widths strictly decrease, and the method stops.
  • Progress away from stationary axes. If the zero step does not minimize the linearized width, a small enough box gives an accepted step.

It does not prove convergence to a stationary axis, and it does not prove that the result is the global minimum CC. The problem is not convex. The tests compare the result with a grid of directions and positions around the true axis and check that the result is at least as good, and that no axis of a fine grid around the result is better. These checks are measured, not proved.

Proof: The width for a fixed axis, the linearized radii, the feasible start of each linear program, the monotone decrease of the accepted widths, and why a step is found away from stationary axesfull

Setup. The data are points q1,…,qnq_1, \dots, q_n in R3\mathbb{R}^3. An axis is a line LL through a point pp with unit direction uu. Let ρi(L)\rho_i(L) be the distance from qiq_i to LL. The cylindricity in the minimum zone sense is

C=min⁡LW(L),W(L)=max⁡iρi(L)−min⁡iρi(L).C = \min_L W(L), \qquad W(L) = \max_i \rho_i(L) - \min_i \rho_i(L).

The method returns an axis LL and the value W(L)≥CW(L) \ge C. What is proved below is that this value is the width of a true zone, that it decreases at each accepted step, and that a step is found from any axis that is not first-order stationary. That the value equals CC is not proved, and it is false in general.

Lemma 1 (the zone of a fixed axis). For a fixed axis LL, the thinnest pair of coaxial cylinders with axis LL that holds the points has the radii min⁡iρi(L)\min_i \rho_i(L) and max⁡iρi(L)\max_i \rho_i(L), so its width is W(L)W(L).

Proof. A point lies between the cylinders of radii r≤Rr \le R about LL exactly when r≤ρi(L)≤Rr \le \rho_i(L) \le R. The constraints over all ii give r≤min⁡iρir \le \min_i \rho_i and R≥max⁡iρiR \ge \max_i \rho_i, and R−rR - r is least when both hold with equality. □\square

So every value the method reports is the width of a zone that holds all points, and W(L)≥CW(L) \ge C for every LL.

Lemma 2 (the linearized radii). Let (e1,e2,u)(e_1, e_2, u) be orthonormal, and let qi−pq_i - p have the coordinates (xi,yi,zi)(x_i, y_i, z_i) in this frame with ρi=xi2+yi2>0\rho_i = \sqrt{x_i^2 + y_i^2} > 0. Let L(δ)L(\delta) be the line through p+δ1e1+δ2e2p + \delta_1 e_1 + \delta_2 e_2 with the direction proportional to u+δ3e1+δ4e2u + \delta_3 e_1 + \delta_4 e_2. Then

ρi(L(δ))=ρi+gi⋅δ+O(∣δ∣2),gi=−1ρi(xi,  yi,  zixi,  ziyi).\rho_i(L(\delta)) = \rho_i + g_i \cdot \delta + O(\lvert \delta \rvert^2), \qquad g_i = -\frac{1}{\rho_i} \bigl( x_i, \; y_i, \; z_i x_i, \; z_i y_i \bigr).

Proof. The plane z=ziz = z_i meets L(δ)L(\delta) at the point (δ1+δ3zi,δ2+δ4zi,zi)(\delta_1 + \delta_3 z_i, \delta_2 + \delta_4 z_i, z_i). The distance from qiq_i to that point is (xi−δ1−δ3zi)2+(yi−δ2−δ4zi)2\sqrt{(x_i - \delta_1 - \delta_3 z_i)^2 + (y_i - \delta_2 - \delta_4 z_i)^2}, and its first-order expansion is ρi−(xi(δ1+δ3zi)+yi(δ2+δ4zi))/ρi\rho_i - (x_i (\delta_1 + \delta_3 z_i) + y_i (\delta_2 + \delta_4 z_i))/\rho_i. The distance to the line differs from the distance to this point by O(∣δ∣2)O(\lvert \delta \rvert^2): the line makes an angle O(∣δ∣)O(\lvert \delta \rvert) with uu, so the segment in the plane z=ziz = z_i is longer than the perpendicular by a factor 1/cos⁡1/\cos of an angle of order ∣δ∣\lvert \delta \rvert, which is 1+O(∣δ∣2)1 + O(\lvert \delta \rvert^2). The constants depend on max⁡i∣zi∣\max_i \lvert z_i \rvert and on min⁡iρi\min_i \rho_i, and they are finite when ρi>0\rho_i > 0 for all ii. □\square

Lemma 3 (each linear program is feasible, bounded and solved). For a box ∣δk∣≤bk\lvert \delta_k \rvert \le b_k, the program

min⁡  R−rsubject tor≤ρi+gi⋅δ≤R    (i=1,…,n),∣δk∣≤bk\min \; R - r \quad \text{subject to} \quad r \le \rho_i + g_i \cdot \delta \le R \;\; (i = 1, \dots, n), \quad \lvert \delta_k \rvert \le b_k

is written in the code with v=δ+b≥0v = \delta + b \ge 0, R=U−PR = U - P and r=Λ+Qr = \Lambda + Q with P,Q≥0P, Q \ge 0, where U=max⁡i(ρi+∑k∣gik∣bk)U = \max_i (\rho_i + \sum_k \lvert g_{ik} \rvert b_k) and Λ=min⁡i(ρi−∑k∣gik∣bk)\Lambda = \min_i (\rho_i - \sum_k \lvert g_{ik} \rvert b_k). Then the right-hand sides are ≥0\ge 0, so v=0,P=Q=0v = 0, P = Q = 0 is feasible; all variables are bounded; and the simplex method with Bland's least-index rule stops at an optimum.

Proof. The constraint ρi+gi⋅(v−b)≤U−P\rho_i + g_i \cdot (v - b) \le U - P becomes gi⋅v+P≤U−ρi+gi⋅bg_i \cdot v + P \le U - \rho_i + g_i \cdot b, and U−ρi+gi⋅b≥U−ρi−∑k∣gik∣bk≥0U - \rho_i + g_i \cdot b \ge U - \rho_i - \sum_k \lvert g_{ik} \rvert b_k \ge 0 by the choice of UU. The other side is similar with Λ\Lambda. The box gives 0≤vk≤2bk0 \le v_k \le 2 b_k, and then P≤U−min⁡i(ρi+gi⋅δ)P \le U - \min_i (\rho_i + g_i \cdot \delta) and Q≤max⁡i(ρi+gi⋅δ)−ΛQ \le \max_i(\rho_i + g_i \cdot \delta) - \Lambda are bounded. Since the origin is a basic feasible solution with the slacks as basis, the simplex method starts there, and with Bland's rule it does not cycle (Bland 1977), so it stops after finitely many pivots at a basis with no improving column, which is optimal. Maximizing P+QP + Q is minimizing R−r=U−Λ−(P+Q)R - r = U - \Lambda - (P + Q). □\square

The code clips the right-hand sides at 00 to absorb rounding, and compares reduced costs and ratios with a tolerance of 10−1110^{-11}.

Lemma 4 (monotone decrease and termination). The accepted widths W(L0)>W(L1)>⋯W(L_0) > W(L_1) > \cdots strictly decrease, and the method stops.

Proof. A new axis is accepted only when its exact width, computed from Lemma 1, is below the current width. Each iteration either accepts a step or divides the box by 44; the loop stops when the box is below a tolerance or after a fixed number of iterations. □\square

Lemma 5 (a step is found away from stationary axes). Let all ρi>0\rho_i > 0 at the current axis, and let Φ(δ)=max⁡i(ρi+gi⋅δ)−min⁡i(ρi+gi⋅δ)\Phi(\delta) = \max_i (\rho_i + g_i \cdot \delta) - \min_i (\rho_i + g_i \cdot \delta), a convex piecewise linear function with Φ(0)=W\Phi(0) = W. If 00 does not minimize Φ\Phi, then for every small enough box the accepted test succeeds.

Proof. Φ\Phi is convex, so if some δ^\hat\delta has Φ(δ^)<Φ(0)\Phi(\hat\delta) < \Phi(0), then along the segment Φ(tδ^/∣δ^∣)≤W−ct\Phi(t \hat\delta / \lvert \hat\delta \rvert) \le W - c t for 0≤t≤∣δ^∣0 \le t \le \lvert \hat\delta \rvert with c=(W−Φ(δ^))/∣δ^∣>0c = (W - \Phi(\hat\delta))/\lvert \hat\delta \rvert > 0. A box of size tt (scaled so that it contains that point) has an LP optimum δ∗\delta^* with Φ(δ∗)≤W−c′t\Phi(\delta^*) \le W - c' t for a constant c′>0c' > 0 that depends only on the box shape. By Lemma 2 and since a maximum and a minimum of functions each within Kt2K t^2 of their linearizations are within Kt2K t^2, W(L(δ∗))≤Φ(δ∗)+2Kt2≤W−c′t+2Kt2<WW(L(\delta^*)) \le \Phi(\delta^*) + 2 K t^2 \le W - c' t + 2 K t^2 < W for t<c′/(2K)t < c'/(2K). The box is divided by 44 after each rejection, so it reaches this size. □\square

So the method only stalls at an axis where 00 minimizes the linearized width, which is the first-order condition for a local minimum of WW. The proof does not show that the iterates converge to such an axis, and it does not show anything about the global minimum.

Why there is no global guarantee. WW is not convex in the axis parameters, so a descent method can stop at a local minimum that is not global, and the result depends on the start. This file does not give a proved instance of such a minimum; the claim is only that nothing here excludes it. Exact algorithms exist: Agarwal, Aronov and Sharir compute the minimum width cylindrical shell exactly in polynomial time of high degree, and approximate it within a constant factor faster. The tests check the local method against grids of axes and do not claim more.

What the tests check. Noise-free points on a cylinder give width below 10−810^{-8}. Points that alternate between radii 44 and 4.054.05 give the width 0.050.05 from a tilted and shifted start. On lobed parts, the result is at least as good as every axis of a grid of directions and positions around the true axis, and no axis of a fine grid around the result is better. The simplex code is compared with the enumeration of all vertices on random small programs.

Complexity

One iteration builds the program in Θ(n)\Theta(n) and solves it. The dense tableau of the code has 2n+42n + 4 rows, so each pivot costs Θ(n2)\Theta(n^2), and kk pivots cost O(kn2)O(k n^2); with ss iterations the time is O(skn2)O(s k n^2) on the real RAM, and the tableau needs Θ(n2)\Theta(n^2) space. Because the dimension is fixed at six, the program can be solved in O(n)O(n) time by Megiddo's method or in expected O(n)O(n) time by Seidel's, which gives O(sn)O(s n). In the tests, ss is a few dozen and kk is small.

For the exact problem, Agarwal, Aronov and Sharir give a polynomial algorithm of high degree for the minimum width cylindrical shell, and a faster algorithm within a constant factor. These are not used in practice for inspection.

Properties

  • Local. The result depends on the start. There is no global guarantee.
  • Safe. Every reported width is the width of a true zone, so it is an upper bound of CC, and it is never worse than the start.
  • Not exact. The answer is a floating point local optimum, with a tolerance on the box and the simplex.
  • Invariant. The method is invariant under rigid motions of the data, up to the choice of the start and of the frame.

Variants and improvements

  • Minimum circumscribed and maximum inscribed cylinders. The same linearization with the objective RR alone, or −r-r alone, gives the reference cylinders for a shaft and for a hole. Carr and Ferreira treat both.
  • Straightness of the median line. Carr and Ferreira also evaluate the straightness of the axis of a cylinder, whose zone is a cylinder of the tolerance diameter.
  • Other local methods. Nonlinear minimax solvers, pattern search over the four axis parameters, and smooth approximations of the maximum (for example a large power of the deviations) all give local optima. The safeguard of line L6 applies to any of them.
  • Exact and approximate algorithms. The algorithm of Agarwal, Aronov and Sharir is exact. A grid of directions with an exact minimum width annulus for each projected set gives an upper bound with an error that shrinks with the grid step.
  • Roundness at several sections. Measuring roundness at a few sections and straightness along a few lines is a cheaper check, but it is not cylindricity.

When to use it

Use it to report cylindricity by the minimum zone, after a least-squares cylinder has given a start, on data of a few hundred to a few thousand points. Report the least-squares zone as well if the drawing asks for the Gaussian association. When the result must be certified as the global minimum, use an exact algorithm or a search over directions with a bound.

Pitfalls

  • A poor start. On a short part, the principal directions may not point along the axis. Start from the CAD axis or from a least-squares cylinder.
  • No box. A full linear step can go far from where the linearization holds and increase the true width. Keep the trust box and the exact check.
  • Points on the axis. The distance is not differentiable there. Real data seldom contain such points.
  • Equating local and global. A local minimum can be reported as the cylindricity of the part only with a statement that it is an upper bound.
  • Scaling the tilt. The tilt moves a point by its height times the angle. Without scaling the tilt box by the length of the part, the program favors tilts on long parts.

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_cylindricity.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-zone-cylindricity/. The authors are listed in prov/HBSSZY.jsonl.

"""Minimum zone cylindricity by sequential linear programming.

The cylindricity of measured points is the least difference R_out - R_in of
two coaxial cylinders that hold the points between them. For a fixed axis the
width is the range of the distances to the axis, so the problem is a
minimization over the four parameters of a line. It is not convex.

The method linearizes the distances about the current axis, solves the linear
program "minimize R_out - R_in" inside a box of trust (a small dense simplex
method below), and accepts the new axis only if the exact width goes down. So
the widths decrease monotonically to a local minimum. There is no guarantee of
reaching the global minimum.
"""

import math


# ---------------------------------------------------------------- vectors

def _sub(a, b):
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def _add(a, b):
    return (a[0] + b[0], a[1] + b[1], a[2] + b[2])


def _scale(a, s):
    return (a[0] * s, a[1] * s, a[2] * s)


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 _unit(a):
    n = math.sqrt(_dot(a, a))
    return (a[0] / n, a[1] / n, a[2] / n)


def _frame(u):
    """Two unit vectors that make (e1, e2, u) orthonormal."""
    t = (1.0, 0.0, 0.0) if abs(u[0]) < 0.9 else (0.0, 1.0, 0.0)
    e1 = _unit(_cross(u, t))
    return e1, _cross(u, e1)


# ---------------------------------------------------------------- widths

def radial_distances(points, p, u):
    """Distances from the points to the line through p with unit direction u."""
    out = []
    for q in points:
        w = _sub(q, p)
        h = _dot(w, u)
        out.append(math.sqrt(_dot(_sub(w, _scale(u, h)), _sub(w, _scale(u, h)))))
    return out


def cylinder_width(points, p, u):
    """Width R_out - R_in of the thinnest coaxial zone with the given axis."""
    d = radial_distances(points, p, u)
    return max(d) - min(d)


# ---------------------------------------------------------------- simplex

def simplex_max(c, a, b, eps=1e-11, max_pivots=100000):
    """Maximize c.x subject to a x <= b, x >= 0, with b >= 0.

    Dense tableau simplex with Bland's rule, which never cycles. The origin is
    feasible because b >= 0, so no first phase is needed.
    """
    n, m = len(c), len(a)
    tab = [list(a[i]) + [1.0 if k == i else 0.0 for k in range(m)] + [float(b[i])] for i in range(m)]
    z = [-float(v) for v in c] + [0.0] * (m + 1)
    basis = [n + i for i in range(m)]
    for _ in range(max_pivots):
        col = next((j for j in range(n + m) if z[j] < -eps), None)
        if col is None:
            break
        row, best = None, None
        for i in range(m):
            if tab[i][col] > eps:
                ratio = tab[i][-1] / tab[i][col]
                if best is None or ratio < best - eps or (abs(ratio - best) <= eps and basis[i] < basis[row]):
                    row, best = i, ratio
        if row is None:
            raise ValueError("unbounded linear program")
        pr = tab[row]
        piv = pr[col]
        pr = [v / piv for v in pr]
        tab[row] = pr
        for i in range(m):
            if i != row:
                f = tab[i][col]
                if f != 0.0:
                    ti = tab[i]
                    tab[i] = [ti[k] - f * pr[k] for k in range(n + m + 1)]
        f = z[col]
        z = [z[k] - f * pr[k] for k in range(n + m + 1)]
        basis[row] = col
    x = [0.0] * n
    for i, j in enumerate(basis):
        if j < n:
            x[j] = tab[i][-1]
    return x


def linearized_step(points, p, u, box_shift, box_tilt):
    """Solve the linear program of one step about the axis (p, u).

    In the frame (e1, e2, u) at p, a point has coordinates (x, y, z) and
    radius rho. Moving the axis to pass through (dx, dy, 0) with direction
    (ta, tb, 1) changes its radius to first order to
        rho - (x dx + y dy) / rho - z (x ta + y tb) / rho.
    The program minimizes R_out - R_in over |dx|, |dy| <= box_shift and
    |ta|, |tb| <= box_tilt. Returns (dx, dy, ta, tb).
    """
    e1, e2 = _frame(u)
    rho, grad = [], []
    for q in points:
        w = _sub(q, p)
        x, y, zz = _dot(w, e1), _dot(w, e2), _dot(w, u)
        r = math.hypot(x, y)
        rho.append(r)
        if r == 0.0:
            grad.append((0.0, 0.0, 0.0, 0.0))
        else:
            grad.append((-x / r, -y / r, -zz * x / r, -zz * y / r))
    box = (box_shift, box_shift, box_tilt, box_tilt)
    # Variables v_k = delta_k + box_k in [0, 2 box_k], then P, Q >= 0 with
    # R_out = U - P and R_in = L + Q, so the origin is feasible.
    spread = [sum(abs(g[k]) * box[k] for k in range(4)) for g in grad]
    upper = max(r + s for r, s in zip(rho, spread))
    lower = min(r - s for r, s in zip(rho, spread))
    rows, rhs = [], []
    for r, g in zip(rho, grad):
        shift = sum(g[k] * box[k] for k in range(4))
        rows.append([g[0], g[1], g[2], g[3], 1.0, 0.0])
        rhs.append(max(0.0, upper - r + shift))
        rows.append([-g[0], -g[1], -g[2], -g[3], 0.0, 1.0])
        rhs.append(max(0.0, r - shift - lower))
    for k in range(4):
        row = [0.0] * 6
        row[k] = 1.0
        rows.append(row)
        rhs.append(2.0 * box[k])
    sol = simplex_max([0.0, 0.0, 0.0, 0.0, 1.0, 1.0], rows, rhs)
    return tuple(sol[k] - box[k] for k in range(4)), (e1, e2)


# ---------------------------------------------------------------- start

def _jacobi3(a):
    a = [row[:] for row in a]
    v = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
    for _ in range(50):
        off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
        if off < 1e-30 * (a[0][0] ** 2 + a[1][1] ** 2 + a[2][2] ** 2 + 1e-300):
            break
        for p, q in ((0, 1), (0, 2), (1, 2)):
            if a[p][q] == 0.0:
                continue
            th = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
            t = math.copysign(1.0, th) / (abs(th) + math.sqrt(th * th + 1.0))
            c = 1.0 / math.sqrt(t * t + 1.0)
            s = t * c
            for k in range(3):
                akp, akq = a[k][p], a[k][q]
                a[k][p], a[k][q] = c * akp - s * akq, s * akp + c * akq
            for k in range(3):
                apk, aqk = a[p][k], a[q][k]
                a[p][k], a[q][k] = c * apk - s * aqk, s * apk + c * aqk
            for k in range(3):
                vkp, vkq = v[k][p], v[k][q]
                v[k][p], v[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
    return [tuple(v[k][i] for k in range(3)) for i in range(3)]


def _circle_center(pts2):
    """Center of the linear algebraic circle fit of planar points."""
    s = [[0.0] * 3 for _ in range(3)]
    t = [0.0] * 3
    for x, y in pts2:
        row = (x, y, 1.0)
        for i in range(3):
            t[i] -= row[i] * (x * x + y * y)
            for j in range(3):
                s[i][j] += row[i] * row[j]
    m = [s[i] + [t[i]] for i in range(3)]
    for col in range(3):
        piv = max(range(col, 3), key=lambda r: abs(m[r][col]))
        m[col], m[piv] = m[piv], m[col]
        if abs(m[col][col]) < 1e-300:
            return 0.0, 0.0
        for r in range(3):
            if r != col:
                f = m[r][col] / m[col][col]
                for k in range(col, 4):
                    m[r][k] -= f * m[col][k]
    d, e = m[0][3] / m[0][0], m[1][3] / m[1][1]
    return -d / 2.0, -e / 2.0


def default_start(points):
    """Try the three principal directions as axes, each with the center of a
    circle fit of the projected points, and keep the thinnest zone."""
    n = len(points)
    c = tuple(sum(q[k] for q in points) / n for k in range(3))
    cov = [[sum((q[i] - c[i]) * (q[j] - c[j]) for q in points) for j in range(3)] for i in range(3)]
    best = None
    for u in _jacobi3(cov):
        e1, e2 = _frame(u)
        pts2 = [(_dot(_sub(q, c), e1), _dot(_sub(q, c), e2)) for q in points]
        cx, cy = _circle_center(pts2)
        p = _add(c, _add(_scale(e1, cx), _scale(e2, cy)))
        w = cylinder_width(points, p, u)
        if best is None or w < best[0]:
            best = (w, p, u)
    return best[1], best[2]


# ---------------------------------------------------------------- method

def minimum_zone_cylindricity(points, start=None, max_iter=300, tol=1e-12):
    """Local minimum zone cylinder of 3D points.

    Returns a dict with the axis point p, the unit direction u, the radii
    r_in and r_out, the width r_out - r_in, and the history of accepted
    widths, which is strictly decreasing.
    """
    points = [tuple(float(v) for v in q) for q in points]
    p, u = start if start is not None else default_start(points)  # @line L1
    u = _unit(u)
    n = len(points)
    cen = tuple(sum(q[k] for q in points) / n for k in range(3))
    p = _add(p, _scale(u, _dot(_sub(cen, p), u)))
    width = cylinder_width(points, p, u)
    history = [width]
    zmax = max(abs(_dot(_sub(q, p), u)) for q in points) or 1.0
    scale = max(math.sqrt(_dot(_sub(q, cen), _sub(q, cen))) for q in points) or 1.0
    trust = max(width, 1e-6 * scale)
    for _ in range(max_iter):  # @line L2
        if trust < tol * scale:
            break
        (dx, dy, ta, tb), (e1, e2) = linearized_step(points, p, u, trust, trust / zmax)  # @line L3
        newp = _add(p, _add(_scale(e1, dx), _scale(e2, dy)))  # @line L4
        newu = _unit(_add(u, _add(_scale(e1, ta), _scale(e2, tb))))
        newp = _add(newp, _scale(newu, _dot(_sub(cen, newp), newu)))
        neww = cylinder_width(points, newp, newu)  # @line L5
        if neww < width - 1e-15 * scale:  # @line L6
            p, u, width = newp, newu, neww
            history.append(width)
            trust *= 2.0
        else:
            trust *= 0.25  # @line L7
    d = radial_distances(points, p, u)
    return {"p": p, "u": u, "r_in": min(d), "r_out": max(d), "width": width, "history": history}  # @line L8


if __name__ == "__main__":
    import random

    rng = random.Random(1)
    pts = []
    for i in range(40):
        t = 2 * math.pi * i / 40
        r = 5 + 0.01 * math.cos(3 * t) + rng.uniform(-0.002, 0.002)
        pts.append((r * math.cos(t), r * math.sin(t), rng.uniform(0, 10)))
    res = minimum_zone_cylindricity(pts)
    print(res["width"], res["u"], len(res["history"]))
test_minimum_zone_cylindricity.py 168 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-zone-cylindricity/. The authors are listed in prov/HBSSZY.jsonl.

import math
import random
import unittest
from itertools import combinations

from minimum_zone_cylindricity import (
    cylinder_width,
    minimum_zone_cylindricity,
    simplex_max,
)


def unit(v):
    n = math.sqrt(sum(x * x for x in v))
    return tuple(x / n for x in v)


def random_rotation(rng):
    u = unit((rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1)))
    t = (1.0, 0.0, 0.0) if abs(u[0]) < 0.9 else (0.0, 1.0, 0.0)
    e1 = unit((u[1] * t[2] - u[2] * t[1], u[2] * t[0] - u[0] * t[2], u[0] * t[1] - u[1] * t[0]))
    e2 = (u[1] * e1[2] - u[2] * e1[1], u[2] * e1[0] - u[0] * e1[2], u[0] * e1[1] - u[1] * e1[0])
    return e1, e2, u


def place(local, frame, origin):
    e1, e2, u = frame
    return [tuple(origin[k] + x * e1[k] + y * e2[k] + z * u[k] for k in range(3)) for x, y, z in local]


def axis_grid(center_p, center_u, tilt, tilt_step, shift, shift_step):
    """Axes whose direction and position lie on grids around a given axis."""
    t = (1.0, 0.0, 0.0) if abs(center_u[0]) < 0.9 else (0.0, 1.0, 0.0)
    u = center_u
    e1 = unit((u[1] * t[2] - u[2] * t[1], u[2] * t[0] - u[0] * t[2], u[0] * t[1] - u[1] * t[0]))
    e2 = (u[1] * e1[2] - u[2] * e1[1], u[2] * e1[0] - u[0] * e1[2], u[0] * e1[1] - u[1] * e1[0])
    nt = int(round(tilt / tilt_step))
    ns = int(round(shift / shift_step))
    for i in range(-nt, nt + 1):
        for j in range(-nt, nt + 1):
            d = unit(tuple(u[k] + i * tilt_step * e1[k] + j * tilt_step * e2[k] for k in range(3)))
            for a in range(-ns, ns + 1):
                for b in range(-ns, ns + 1):
                    p = tuple(center_p[k] + a * shift_step * e1[k] + b * shift_step * e2[k] for k in range(3))
                    yield p, d


def lobed_part(rng, n=30, radius=5.0, height=10.0):
    local = []
    for i in range(n):
        t = 2 * math.pi * i / n
        z = rng.uniform(-height / 2, height / 2)
        r = radius + 0.004 * math.cos(2 * t + 0.3 * z) + 0.002 * z / height + rng.uniform(-0.001, 0.001)
        local.append((r * math.cos(t), r * math.sin(t), z))
    return local


class TestSimplex(unittest.TestCase):
    def test_against_vertex_enumeration(self):
        rng = random.Random(1)
        for _ in range(60):
            n = 3
            m = rng.randint(3, 6)
            a = [[rng.uniform(-1, 2) for _ in range(n)] for _ in range(m)]
            for k in range(n):
                a.append([1.0 if j == k else 0.0 for j in range(n)])
            b = [rng.uniform(0, 5) for _ in range(len(a))]
            c = [rng.uniform(-1, 2) for _ in range(n)]
            x = simplex_max(c, a, b)
            for row, rhs in zip(a, b):
                self.assertLessEqual(sum(r * v for r, v in zip(row, x)), rhs + 1e-9)
            self.assertTrue(all(v >= -1e-12 for v in x))
            # Brute force: every vertex is the solution of n tight constraints.
            cons = [(row, rhs) for row, rhs in zip(a, b)]
            cons += [([-1.0 if j == k else 0.0 for j in range(n)], 0.0) for k in range(n)]
            best = -math.inf
            for sub in combinations(cons, n):
                mat = [list(r) + [h] for r, h in sub]
                ok = True
                for col in range(n):
                    piv = max(range(col, n), key=lambda r: abs(mat[r][col]))
                    if abs(mat[piv][col]) < 1e-12:
                        ok = False
                        break
                    mat[col], mat[piv] = mat[piv], mat[col]
                    for r in range(n):
                        if r != col:
                            f = mat[r][col] / mat[col][col]
                            mat[r] = [mat[r][k] - f * mat[col][k] for k in range(n + 1)]
                if not ok:
                    continue
                v = [mat[i][n] / mat[i][i] for i in range(n)]
                if all(sum(r * w for r, w in zip(row, v)) <= rhs + 1e-9 for row, rhs in cons):
                    best = max(best, sum(ci * vi for ci, vi in zip(c, v)))
            self.assertAlmostEqual(sum(ci * vi for ci, vi in zip(c, x)), best, places=7)


class TestCylindricity(unittest.TestCase):
    def test_exact_cylinder(self):
        rng = random.Random(2)
        for _ in range(10):
            frame = random_rotation(rng)
            origin = tuple(rng.uniform(-3, 3) for _ in range(3))
            r = rng.uniform(1, 6)
            local = []
            for _ in range(25):
                t = rng.uniform(0, 2 * math.pi)
                local.append((r * math.cos(t), r * math.sin(t), rng.uniform(-4, 4)))
            res = minimum_zone_cylindricity(place(local, frame, origin))
            self.assertLess(res["width"], 1e-8)
            self.assertAlmostEqual(res["r_out"], r, delta=1e-6)

    def test_alternating_contacts(self):
        # Points alternate between radii 4 and 4.05 at eight angles on three
        # levels. The true axis gives width 0.05, and the method must reach it
        # from a tilted and shifted start.
        rng = random.Random(3)
        local = []
        for z in (-3.0, 0.0, 3.0):
            for k in range(8):
                t = math.pi * k / 4 + 0.1 * z
                r = 4.0 if k % 2 == 0 else 4.05
                local.append((r * math.cos(t), r * math.sin(t), z))
        frame = random_rotation(rng)
        origin = (1.0, -2.0, 0.5)
        pts = place(local, frame, origin)
        e1, e2, u = frame
        start_u = unit(tuple(u[k] + 0.01 * e1[k] - 0.02 * e2[k] for k in range(3)))
        start_p = tuple(origin[k] + 0.03 * e1[k] for k in range(3))
        res = minimum_zone_cylindricity(pts, start=(start_p, start_u))
        self.assertAlmostEqual(res["width"], 0.05, delta=1e-9)
        self.assertAlmostEqual(cylinder_width(pts, origin, u), 0.05, delta=1e-12)

    def test_history_decreases(self):
        rng = random.Random(4)
        pts = place(lobed_part(rng), random_rotation(rng), (0.0, 0.0, 0.0))
        h = minimum_zone_cylindricity(pts)["history"]
        for a, b in zip(h, h[1:]):
            self.assertLess(b, a)

    def test_against_grid_around_true_axis(self):
        rng = random.Random(5)
        for _ in range(2):
            frame = random_rotation(rng)
            origin = tuple(rng.uniform(-1, 1) for _ in range(3))
            pts = place(lobed_part(rng), frame, origin)
            res = minimum_zone_cylindricity(pts)
            grid_best = min(
                cylinder_width(pts, p, d)
                for p, d in axis_grid(origin, frame[2], 0.0006, 0.0002, 0.006, 0.002)
            )
            # The local method does at least as well as the grid.
            self.assertLessEqual(res["width"], grid_best + 1e-9)

    def test_no_better_axis_near_the_result(self):
        rng = random.Random(6)
        pts = place(lobed_part(rng), random_rotation(rng), (0.5, 0.5, 0.5))
        res = minimum_zone_cylindricity(pts)
        for step in (1e-3, 1e-5):
            for p, d in axis_grid(res["p"], res["u"], 2 * step, step, 2 * step, step):
                self.assertGreaterEqual(cylinder_width(pts, p, d), res["width"] - 1e-9)


if __name__ == "__main__":
    unittest.main()

History

Cylindricity was evaluated in early coordinate measuring machine software by least-squares cylinders, which overstate the minimum zone. Carr and Ferreira, in 1995, wrote the minimum zone, minimum circumscribed and maximum inscribed cylinders as sequences of linear programs, after their linear programming treatment of flatness and straightness in part I of the same work. In computational geometry the same problem is the minimum width cylindrical shell, which Agarwal, Aronov and Sharir solved exactly in polynomial time in 2001.

References

  1. Kirsten Carr and Placid Ferreira, Verification of form tolerances part II, cylindricity and straightness of a median line, Precision Engineering 17(2), 1995, 144 to 156, the formulation of the minimum zone cylinder by linearized distances to the axis and a sequence of linear programs that converge to a local optimum, and the minimum circumscribed and maximum inscribed cylinders
  2. Kirsten Carr and Placid Ferreira, Verification of form tolerances part I, basic issues, flatness, and straightness, Precision Engineering 17(2), 1995, 131 to 143, the linear programming formulation of the minimum zone for flatness and straightness that part II extends
  3. Pankaj K. Agarwal, Boris Aronov and Micha Sharir, Exact and approximation algorithms for minimum-width cylindrical shells, Discrete and Computational Geometry 26(3), 2001, 307 to 320, the exact minimum width cylindrical shell in polynomial time of high degree, and a faster constant factor approximation
  4. Robert G. Bland, New finite pivoting rules for the simplex method, Mathematics of Operations Research 2(2), 1977, pages 103 to 107, the least-index rule and the proof that it does not cycle
  5. 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 cylindricity tolerance zone between two coaxial cylinders); 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.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