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.
- Solves
- Form error evaluation
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kirsten Carr, Placid Ferreira, 1995
Minimum zone cylindricity computes the cylindricity of a measured cylindrical feature: the least radial gap 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 in , measured on a nominally cylindrical surface and corrected for the probe radius. For a line , let be the distance from to . The zone shape is the region between two coaxial cylinders, and the objective is the least width
the minimum zone cylindricity. The output is an axis and the two radii. The method below returns an axis with the width 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 . It is a good start for this method.
The algorithm
MIN-ZONE-CYLINDER(q_1..q_n)- 1
(p, u) ← start axis; W ← width about (p, u); b ← W - 2
repeat - 3
δ ← solution of the LP: minimize R − r subject to r ≤ ρ_i + g_i·δ ≤ R for all i, and δ in the box of size b- 4
(p', u') ← axis moved by δ - 5
W' ← max_i ρ_i(p', u') − min_i ρ_i(p', u') - 6
if W' < W then (p, u, W) ← (p', u', W'); b ← 2b - 7
else b ← b/4 - 8
until 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 at , let have coordinates and . Moving the axis to pass through with the direction changes the distance to first order to
The program has six variables, , and , and 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 , 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 , at eight angles on each level, alternately at radius and about a known axis, and the set is moved by a random rigid motion. From a start tilted by about radians and shifted by , the method returns the width to , the true axis.
A lobed shaft. Forty points on a shaft of radius and length with a three-lobe error of amplitude and uniform noise of , seed 1. From the default start, the method stops after six accepted steps at the width . 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 .
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 and , so every reported value is the width of a zone that holds all points and is at least .
- 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 . 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 in . An axis is a line through a point with unit direction . Let be the distance from to . The cylindricity in the minimum zone sense is
The method returns an axis and the value . 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 is not proved, and it is false in general.
Lemma 1 (the zone of a fixed axis). For a fixed axis , the thinnest pair of coaxial cylinders with axis that holds the points has the radii and , so its width is .
Proof. A point lies between the cylinders of radii about exactly when . The constraints over all give and , and is least when both hold with equality.
So every value the method reports is the width of a zone that holds all points, and for every .
Lemma 2 (the linearized radii). Let be orthonormal, and let have the coordinates in this frame with . Let be the line through with the direction proportional to . Then
Proof. The plane meets at the point . The distance from to that point is , and its first-order expansion is . The distance to the line differs from the distance to this point by : the line makes an angle with , so the segment in the plane is longer than the perpendicular by a factor of an angle of order , which is . The constants depend on and on , and they are finite when for all .
Lemma 3 (each linear program is feasible, bounded and solved). For a box , the program
is written in the code with , and with , where and . Then the right-hand sides are , so is feasible; all variables are bounded; and the simplex method with Bland's least-index rule stops at an optimum.
Proof. The constraint becomes , and by the choice of . The other side is similar with . The box gives , and then and 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 is minimizing .
The code clips the right-hand sides at to absorb rounding, and compares reduced costs and ratios with a tolerance of .
Lemma 4 (monotone decrease and termination). The accepted widths 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 ; the loop stops when the box is below a tolerance or after a fixed number of iterations.
Lemma 5 (a step is found away from stationary axes). Let all at the current axis, and let , a convex piecewise linear function with . If does not minimize , then for every small enough box the accepted test succeeds.
Proof. is convex, so if some has , then along the segment for with . A box of size (scaled so that it contains that point) has an LP optimum with for a constant that depends only on the box shape. By Lemma 2 and since a maximum and a minimum of functions each within of their linearizations are within , for . The box is divided by after each rejection, so it reaches this size.
So the method only stalls at an axis where minimizes the linearized width, which is the first-order condition for a local minimum of . 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. 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 . Points that alternate between radii and give the width 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 and solves it. The dense tableau of the code has rows, so each pivot costs , and pivots cost ; with iterations the time is on the real RAM, and the tableau needs space. Because the dimension is fixed at six, the program can be solved in time by Megiddo's method or in expected time by Seidel's, which gives . In the tests, is a few dozen and 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 , 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 alone, or 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.
# 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
- 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
- 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
- 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
- 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
- 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.
| 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 HBSSZY Edit this page History Report an error Markdown