Algorithmadvanced
Least-squares fitting of spheres, cylinders, cones and tori
Also called faithful primitive fitting, Lukacs-Martin-Marshall fitting.
Fits spheres, cylinders, cones and tori by minimizing the sum of squared orthogonal distances, with Levenberg-Marquardt steps from an algebraic start.
- Time
- Θ(s (m k² + k³)) worst
- Space
- Θ(m k) extra
- Where
- k = the number of shape parameters (4 for a sphere, 5 for a cylinder, 6 for a cone, 7 for a torus); m = the number of points; s = the number of iterations
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Gábor Lukács, Ralph R. Martin, A. David Marshall, 1998
Geometric primitive fitting finds the sphere, cylinder, cone or torus that minimizes the sum of the squared orthogonal distances from a set of measured points to the surface. The orthogonal (geometric) distance is the length of the shortest segment from a point to the surface, so it is the error a measuring machine sees. It does not depend on how the surface is written, and the fit is invariant under rigid motions of the data. The price is that the problem is nonlinear in the shape parameters, so it is solved iteratively, by Gauss-Newton or Levenberg-Marquardt steps, from a starting value given by a linear algebraic fit or a Taubin fit. For these four surfaces of revolution the distance has a closed form, which makes each step cheap. Lukács, Martin and Marshall (1998) added faithful parameterizations: the parameters stay finite and smooth when a cone tends to a cylinder or a sphere of growing radius tends to a plane, so one fit can decide between a primitive and its limit. In reverse engineering this step turns each segmented region of a scan into an exact surface of the CAD model, and in inspection it gives the least-squares reference features of a part.
In plain words
A scanner measures many points on a part, say on a hole. We want the cylinder that the points came from: its axis, and its radius. For any guessed cylinder, each point has a distance to it, measured straight across to the surface. We look for the cylinder that makes the sum of the squared distances as small as possible.
There is no formula that gives this cylinder at once. So we start from a rough guess, found by a fast method that is a little biased, and improve it step by step. Each step looks at how the distances change when the cylinder moves, tilts or grows a little, and moves it the way that makes them smaller. Spheres, cones and doughnut shapes work the same way. A few steps are usually enough.
The problem
The input is a set of points in , usually one region of a primitive segmentation, and a type of surface. The output is the parameters of a surface of that type that minimize
the sum of squared orthogonal distances. This is the geometric distance; the algebraic fit minimizes the values of an implicit equation and the Taubin fit a first-order approximation of the distance, and both are biased under noise. With independent normal noise of equal size in all directions, the minimizer of is the maximum likelihood estimate of the surface.
With , and for a point and a unit axis , the signed distances are:
| surface | parameters | count | signed distance |
|---|---|---|---|
| sphere | center , radius | ||
| cylinder | axis , radius | ||
| cone | apex , axis , half angle | ||
| torus | center , axis , radii |
The cone formula holds for points whose nearest point is not the apex. A line on the axis has four parameters (a point moving along the axis and the length of do not count), which gives the counts.
The algorithm
GEOMETRIC-FIT(x_1..x_m, type)- 1
θ ← start from an algebraic or Taubin fit; μ ← μ_0 - 2
repeat - 3
r_i ← signed orthogonal distance from x_i to S(θ), for every i - 4
J ← Jacobian of r with respect to the local parameters of θ - 5
solve (Jᵀ J + μ I) Δ = −Jᵀ r - 6
θ' ← θ ⊕ Δ ▷ move along the local parameters - 7
if Σ r_i(θ')² < Σ r_i(θ)² then θ ← θ'; μ ← μ / 10 - 8
else μ ← 10 μ - 9
until the gain of an accepted step or the step is below a tolerance - 10
return θ
Line L1. For a sphere the start is the linear algebraic fit of . For a cylinder the code tries axis directions spread over the half sphere, fits a circle to the points projected on the plane normal to each, and keeps the best; when the points have normals, as from normal estimation, the axis is the direction most nearly normal to all of them, the smallest eigenvector of . Cones and tori need starting values too; the paper of Lukács, Martin and Marshall gives methods for them, which this page does not reproduce, and the code fits spheres and cylinders only.
Lines L4 and L6, the local parameters. A cylinder has a point on its axis and a unit direction, six numbers for five degrees of freedom. The code steps in a frame : two moves of the axis point normal to , two tilts of , and a change of , then puts the axis point back at the projection of the centroid. The Jacobian row of point is with , . This removes the freedom of sliding along the axis, which would make singular.
Lines L5, L7 and L8. For line L5 is a Gauss-Newton step, and for large it is a short step down the gradient. A step is kept only if it lowers the cost; otherwise grows and the next step is shorter. This is the Levenberg form with ; Marquardt's form scales by the diagonal of .
Faithful parameters. Writing a sphere by its center fails near a plane: the center runs off to infinity. Lukács, Martin and Marshall write it by its point nearest the origin, the unit normal there and the curvature . Then
for the signed distance . The middle form is smooth at , where it is the distance to the plane , and it equals the true distance up to the term . The paper treats the cylinder, cone and torus in a similar way, with the plane, the cylinder and the sphere as limits.
Example
A spherical cap. Forty points on a cap of half angle degrees of the unit sphere, with independent normal noise in each coordinate, samples, seed 2026. The algebraic fit, which is the start of line L1, has a median radius of , and the geometric fit . On a small cap the algebraic fit shrinks the sphere, as it shrinks a circle on a short arc, and the geometric fit removes most of that bias.
A half cylinder without normals. Sixty points on half of a cylinder of radius and height with axis , noise , samples, started from the direction search of line L1 with directions. The fitted radius had median and ranged over , and the axis was off by a median of degrees and at most degrees.
Noise-free data. On points that lie exactly on a sphere, the start is already the sphere (Theorem 2 of the correctness file), and the loop leaves it unchanged. On points that lie exactly on a cylinder, the tests start from the direction search and reach the true cylinder to on random cylinders with rational points; that is measured, not proved.
These numbers are measured on synthetic data.
Correctness
The correctness file proves:
- The distance formulas of the table, by reducing each surface of revolution to its profile in the half plane through the axis and the point.
- The Jacobians, including the rows of the local cylinder parameterization.
- Monotone descent. is positive definite for , and when the gradient is not zero, every large enough gives a step that lowers the cost. So the accepted costs strictly decrease, converge, and the loop stops.
- Exact recovery of a sphere from at least four noise-free points that are not coplanar: the algebraic start is the true sphere, where the gradient is zero.
- The faithful sphere distance identity above and its plane limit.
Not proved here: that the loop reaches the global minimum. The cost of a cylinder, cone or torus fit has local minima, and the result depends on the start. Near a minimizer with zero residuals and a Jacobian of full rank, Gauss-Newton converges quadratically; that is a standard result in Nocedal and Wright, Chapter 10. The statistical properties of the geometric fit (consistency, and a bias much smaller than that of algebraic fits) are studied for circles in Chernov's book, cited on the algebraic fit page.
Proof: The orthogonal distances to the sphere, cylinder, cone and torus, the Jacobians of the local parameterization, the monotone descent of the Levenberg steps, exact recovery of a sphere from noise-free data, and the faithful sphere distancefull
Setup. The data are points in (or for circles). A surface has parameters , and is the signed orthogonal distance from to . The cost is . For a point , a unit axis and a point (on the axis, or the center or the apex), write , , and , the distance from to the axis.
Lemma 1 (orthogonal distances). The distance from to the surface is: (a) sphere with center and radius : ; (b) cylinder with axis and radius : ; (c) cone with apex , axis and half angle , for a point whose nearest point is not the apex, that is : ; (d) torus with center , axis , major radius and minor radius , for : .
Proof. (a) For on the sphere, by the triangle inequality, with equality for (any if ). For (b), (c) and (d), each surface is a surface of revolution about the axis, so a nearest point of to lies in the half plane through the axis and (rotating any point of about the axis into that half plane does not increase its distance to , since only the angle between the two points about the axis changes, and the distance is smallest when the angle is ). In that half plane, with coordinates , the profile is: (b) the line , at distance ; (c) the ray from the origin in the direction , whose line has unit normal , so the distance to the line is , and the foot of the perpendicular is on the ray exactly when the component along the ray, , is ; (d) the circle of center and radius , at distance by (a). The half plane on the other side of the axis gives the profile at , which is not closer: for (d), .
The code uses the signed versions and .
Lemma 2 (Jacobians). For the sphere with , and . For the cylinder, let be orthonormal, and let the local step move the axis point to , the direction to , and the radius to . With , and , the derivative of at is .
Proof. The sphere case is the gradient of . For the cylinder, for any nonzero direction . After the step, and (the normalization does not change ). To first order in : , (as ), and . So , and gives the row. Moving the axis point along afterwards, as the code does, does not change any distance.
Lemma 3 (the Levenberg step descends). Let (half the gradient of in local coordinates), , and . Then the matrix is positive definite, so line L5 has a unique solution, and if there is such that every gives , where is the retraction of line L6, a smooth map with whose derivative in at is the one used for .
Proof. for . Let be the largest eigenvalue of . Then and . By Taylor's theorem on the smooth function , whose gradient at is , there is with for . So , and the bound on makes for . The right side is negative exactly when , and for we have . So works.
Theorem 1 (monotone, terminating). The accepted costs form a strictly decreasing sequence bounded below by , so they converge. The loop stops: after at most the fixed number of iterations, or when an accepted step gains less than the relative tolerance, or when passes its bound, which by Lemma 3 can happen at a point with only if the bound is below , and otherwise means the point is stationary.
Proof. Line L7 accepts a step only if it lowers ; line L8 raises by a factor of , so by Lemma 3 a point with sees an accepted step after finitely many rejections, unless the bound on is reached first. The other stopping rules are counted.
Theorem 2 (a noise-free sphere is recovered exactly). If points lie on a sphere and are not coplanar, the algebraic start of line L1 is , and the loop returns it.
Proof. The algebraic fit solves the linear least squares problem for in . Its design matrix has the rows , which have full column rank exactly when the points are not coplanar, so the solution is unique. The values , give zero residuals, so they are that solution, and , . At this start for all , so and ; no step lowers , the loop only raises , and it returns the start. In floating point the same holds up to rounding.
For the cylinder, cone and torus there is no such statement: the cost has local minima, and recovery depends on the start. The page measures it; it is not proved.
Lemma 4 (the faithful sphere distance). Write a sphere through its point nearest the origin, with unit normal there pointing to the center, and its curvature , so that . Then for every , with ,
and as with and fixed the middle expression tends to , the signed distance to the plane .
Proof. With , ; multiply by . Also , and . The limit is read off the middle expression.
Complexity
One iteration computes distances and Jacobian rows in , forms in and solves a system in , with . With iterations the time is on the real RAM, linear in the number of points; from a good start, is usually below twenty. The extra space is for , or if and are accumulated row by row. The direction search for a cylinder start costs for directions.
Properties
- Geometric. It minimizes true orthogonal distances, as inspection standards require, and is invariant under rigid motions.
- Local. It converges to a local minimum near the start. A bad start, from a wrong segment or too few points, gives a wrong surface with a small cost.
- Not exact in general. It is an iterative numerical method; only the sphere on noise-free data has an exact answer from its start.
- Degenerate cases are real. A cylinder fitted to a nearly flat patch has a huge radius and a badly determined axis; a cone with a tiny angle is nearly a cylinder. Faithful parameters keep the fit well posed across these limits, and model selection must then decide which type to keep.
Variants and improvements
- Fit on the faithful approximate distance first. Lukács, Martin and Marshall minimize the approximate distance of the identity above, which is cheaper and smooth across the limits, and use the result for the final geometric fit.
- Orthogonal distance regression of general implicit surfaces. For surfaces with no closed-form distance, each iteration also computes the foot points, as in the methods collected by Ahn and in point projection onto a surface.
- Robust fits. Replace the squares by a robust loss, or fit only to the inliers found by RANSAC and efficient RANSAC shape detection.
- Constraints. Fitting several primitives together with parallel axes, equal radii or tangency is constrained primitive fitting.
- Metrology fits. The NIST algorithm testing system described by Shakarji gives reference orthogonal fits of lines, planes, circles, spheres, cylinders, cones and tori used to test the software of coordinate measuring machines.
When to use it
Use it as the final fit of every region in reverse engineering and for the least-squares reference feature of a measured part, after a fast algebraic or Taubin fit has given the start. Use the algebraic or Taubin fit alone when speed matters more than the last bit of accuracy, for example inside the inner loop of RANSAC.
Pitfalls
- Gauge freedom. Parameterizing a cylinder by a free axis point and a free direction vector makes singular; Gauss-Newton then fails or drifts along the axis. Use local parameters, or fix the axis point to the plane through the centroid normal to the axis.
- Points on the axis. The distance to a cylinder or a torus is not differentiable on the axis. Real data seldom lie there, but synthetic tests can.
- Wrong sheet of a cone. The cone formula is for the half cone of the apex; points behind the apex measure the distance to the apex. Check where the feet lie.
- A start from too short a patch. On a cylinder patch of a few degrees the axis direction is poorly determined; the direction search and the normals both become unreliable, and the fit may converge to a plane-like cylinder of huge radius.
- Reporting the cost as a form error. The root mean square distance is not the form error of a tolerance, which is a minimum zone value.
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/geometric-primitive-fitting/. The authors are listed in prov/8FSGZT.jsonl.
"""Geometric (orthogonal distance) least-squares fitting of spheres and cylinders.
The fit minimizes the sum of the squared orthogonal distances from the points
to the surface, by Levenberg-Marquardt steps on a local parameterization:
- sphere: center c and radius r, distance |x - c| - r;
- cylinder: a point p on the axis, a unit axis direction u and a radius r,
distance |(x - p) - ((x - p) . u) u| - r. A step moves p in the two
directions normal to u, tilts u in those two directions and changes r,
so the parameters have no gauge freedom.
The starting value comes from an algebraic fit (spheres) or from a search
over axis directions with an algebraic circle fit in the plane normal to the
axis (cylinders), or from the axis of the point normals when they are given.
"""
from math import cos, pi, sin, sqrt
from typing import Callable, List, Optional, Sequence, Tuple
from re1lin import add, cross, dot, gram, jacobi_eigen, norm, scale, solve, sub
Vec = Tuple[float, ...]
# ---- distances ----
def sphere_distance(c: Sequence[float], r: float, x: Sequence[float]) -> float:
return norm(sub(x, c)) - r
def cylinder_distance(p: Sequence[float], u: Sequence[float], r: float, x: Sequence[float]) -> float:
w = sub(x, p)
return norm(sub(w, scale(dot(w, u), u))) - r
# ---- the Levenberg-Marquardt loop of the pseudocode ----
def levenberg_marquardt(theta, residuals: Callable, retract: Callable, mu: float = 1e-3, max_iter: int = 500,
tol: float = 1e-15) -> Tuple[object, List[float]]:
"""Minimize sum r_i(theta)^2 by Levenberg steps (J^T J + mu I) delta = -J^T r.
residuals(theta) returns (r, J) with J the Jacobian in the local
coordinates that retract(theta, delta) uses. Returns the final theta and
the history of the accepted costs, which is strictly decreasing.
Cost: Theta(m k^2 + k^3) per step for m residuals and k local parameters.
"""
r, J = residuals(theta)
cost = sum(v * v for v in r)
history = [cost]
k = len(J[0])
for _ in range(max_iter): # @line L2
A = gram(J)
for i in range(k):
A[i][i] += mu
g = [sum(J[t][i] * r[t] for t in range(len(r))) for i in range(k)]
delta = solve(A, [-v for v in g]) # @line L5
if delta is None:
break
new = retract(theta, delta) # @line L6
r2, J2 = residuals(new)
cost2 = sum(v * v for v in r2)
if cost2 < cost: # @line L7
gain = cost - cost2
theta, r, J, cost = new, r2, J2, cost2
history.append(cost)
mu = max(mu / 10, 1e-12)
if gain <= tol * max(cost, 1e-300) or cost < 1e-28: # @line L9
break
else:
mu *= 10 # @line L8
if mu > 1e16:
break
return theta, history # @line L10
# ---- sphere ----
def algebraic_sphere(points: Sequence[Sequence[float]]) -> Tuple[Vec, float]:
"""Kasa fit: least squares of |x|^2 + b . x + e over the points, a linear problem."""
d = len(points[0])
rows = [tuple(float(v) for v in x) + (1.0,) for x in points]
rhs = [-sum(float(v) ** 2 for v in x) for x in points]
A = gram(rows)
b = [sum(row[i] * t for row, t in zip(rows, rhs)) for i in range(d + 1)]
s = solve(A, b, 1e-300)
if s is None:
raise ValueError("degenerate points for a sphere")
c = tuple(-v / 2 for v in s[:d])
rr = dot(c, c) - s[d]
return c, sqrt(max(rr, 0.0))
def fit_sphere(points: Sequence[Sequence[float]], start: Optional[Tuple[Vec, float]] = None
) -> Tuple[Vec, float, List[float]]:
"""Geometric sphere (or circle, in the plane) fit.
Precondition: at least d + 1 points, not all on one hyperplane (else ValueError).
Returns (center, radius, cost history).
Cost: Theta(m) per step for m points in a fixed dimension d.
"""
pts = [tuple(float(v) for v in x) for x in points]
d = len(pts[0])
if len(pts) < d + 1:
raise ValueError("too few points")
c, r = start if start is not None else algebraic_sphere(pts) # @line L1
theta = tuple(c) + (r,)
def residuals(th):
res, jac = [], []
cc, rad = th[:d], th[d]
for x in pts:
w = sub(x, cc)
n = norm(w) or 1e-300
res.append(n - rad) # @line L3
jac.append(tuple(-v / n for v in w) + (-1.0,)) # @line L4
return res, jac
def retract(th, delta):
return tuple(a + b for a, b in zip(th, delta))
theta, hist = levenberg_marquardt(theta, residuals, retract)
return theta[:d], abs(theta[d]), hist
# ---- cylinder ----
def frame(u: Sequence[float]) -> Tuple[Vec, Vec]:
"""Two unit vectors e1, e2 with (u, e1, e2) orthonormal, a fixed function of u."""
k = min(range(3), key=lambda i: abs(u[i]))
a = [0.0, 0.0, 0.0]
a[k] = 1.0
e1 = cross(u, a)
e1 = scale(1 / norm(e1), e1)
return e1, cross(u, e1)
def _circle_in_plane(pts, u):
e1, e2 = frame(u)
q = [(dot(x, e1), dot(x, e2)) for x in pts]
(a, b), r = algebraic_sphere(q)
cost = sum((sqrt((x - a) ** 2 + (y - b) ** 2) - r) ** 2 for x, y in q)
return cost, add(scale(a, e1), scale(b, e2)), r
def start_cylinder(points: Sequence[Sequence[float]], normals: Optional[Sequence[Sequence[float]]] = None,
directions: int = 400) -> Tuple[Vec, Vec, float]:
"""A starting cylinder: axis from the normals, or the best of a set of directions on the half sphere."""
pts = [tuple(float(v) for v in x) for x in points]
if normals is not None:
vals, vecs = jacobi_eigen(gram([tuple(float(v) for v in n) for n in normals]))
cands = [tuple(vecs[0])]
else:
cands = []
for i in range(directions): # Fibonacci points on the upper half sphere
z = (i + 0.5) / directions
t = i * pi * (3 - sqrt(5))
s = sqrt(1 - z * z)
cands.append((s * cos(t), s * sin(t), z))
best = min((_circle_in_plane(pts, u) + (u,) for u in cands), key=lambda t: t[0])
_, p, r, u = best
return p, u, r
def fit_cylinder(points: Sequence[Sequence[float]], normals: Optional[Sequence[Sequence[float]]] = None,
start: Optional[Tuple[Vec, Vec, float]] = None) -> Tuple[Vec, Vec, float, List[float]]:
"""Geometric cylinder fit.
Precondition: at least 5 points in space, not all on one line or circle.
Returns (point on the axis nearest the centroid, unit axis, radius, cost history).
Cost per step: Theta(m) for m points (5 local parameters).
"""
pts = [tuple(float(v) for v in x) for x in points]
if len(pts) < 5:
raise ValueError("a cylinder needs at least 5 points")
centroid = scale(1 / len(pts), tuple(sum(x[i] for x in pts) for i in range(3)))
p, u, r = start if start is not None else start_cylinder(pts, normals) # @line L1
u = scale(1 / norm(u), u)
p = add(p, scale(dot(sub(centroid, p), u), u))
def residuals(th):
p0, u0, rad = th
e1, e2 = frame(u0)
res, jac = [], []
for x in pts:
w = sub(x, p0)
w1, w2, wu = dot(w, e1), dot(w, e2), dot(w, u0)
rho = sqrt(w1 * w1 + w2 * w2) or 1e-300
res.append(rho - rad) # @line L3
jac.append((-w1 / rho, -w2 / rho, -wu * w1 / rho, -wu * w2 / rho, -1.0)) # @line L4
return res, jac
def retract(th, delta):
p0, u0, rad = th
e1, e2 = frame(u0)
p1 = add(p0, add(scale(delta[0], e1), scale(delta[1], e2)))
u1 = add(u0, add(scale(delta[2], e1), scale(delta[3], e2)))
u1 = scale(1 / norm(u1), u1)
p1 = add(p1, scale(dot(sub(centroid, p1), u1), u1))
return p1, u1, rad + delta[4]
(p, u, r), hist = levenberg_marquardt((p, u, r), residuals, retract)
return p, u, abs(r), hist
re1lin.py 221 lines
# SPDX-License-Identifier: MIT
# Shared helper of the re1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the re1 fitting pages.
Vectors are tuples or lists of numbers, matrices are lists of rows. The
elimination routines work with int, Fraction or float entries: with Fraction
they are exact. The Jacobi routine is float only. The helper holds no
fitting algorithm of any page.
"""
from fractions import Fraction
from math import atan2, cos, sin, sqrt
from typing import List, Optional, Sequence, Tuple
Vec = Sequence
Mat = List[List]
# ---- vectors ----
def dot(a: Vec, b: Vec):
return sum(x * y for x, y in zip(a, b))
def add(a: Vec, b: Vec) -> tuple:
return tuple(x + y for x, y in zip(a, b))
def sub(a: Vec, b: Vec) -> tuple:
return tuple(x - y for x, y in zip(a, b))
def scale(s, a: Vec) -> tuple:
return tuple(s * x for x in a)
def norm(a: Vec) -> float:
return sqrt(float(dot(a, a)))
def cross(a: Vec, b: Vec) -> tuple:
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])
# ---- matrices ----
def zeros(n: int, m: int, z=0) -> Mat:
return [[z] * m for _ in range(n)]
def transpose(a: Mat) -> Mat:
return [list(r) for r in zip(*a)]
def mat_vec(a: Mat, x: Vec) -> list:
return [dot(r, x) for r in a]
def mat_mul(a: Mat, b: Mat) -> Mat:
bt = transpose(b)
return [[dot(r, c) for c in bt] for r in a]
def gram(rows: Sequence[Vec]) -> Mat:
"""The matrix sum over the rows u of u u^T."""
n = len(rows[0])
g = zeros(n, n)
for u in rows:
for i in range(n):
if u[i] == 0:
continue
for j in range(n):
g[i][j] += u[i] * u[j]
return g
# ---- elimination (exact with Fraction) ----
def solve(a: Mat, b: Vec, tol: float = 0.0) -> Optional[list]:
"""Solve a x = b for a square a by Gaussian elimination with partial pivoting.
Returns None when a pivot has absolute value at most tol (singular
matrix). With Fraction entries and tol = 0 the answer is exact.
"""
n = len(a)
m = [list(a[i]) + [b[i]] for i in range(n)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if abs(m[p][c]) <= tol:
return None
m[c], m[p] = m[p], m[c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
if f != 0:
for k in range(c, n + 1):
m[r][k] -= f * m[c][k]
x = [0] * n
for r in range(n - 1, -1, -1):
s = m[r][n] - sum(m[r][k] * x[k] for k in range(r + 1, n))
x[r] = s / m[r][r]
return x
def lstsq(a: Mat, b: Vec, tol: float = 0.0) -> Optional[list]:
"""Least squares solution of a x = b by the normal equations (a^T a) x = a^T b."""
at = transpose(a)
return solve(mat_mul(at, a), mat_vec(at, b), tol)
def nullspace(a: Mat) -> List[list]:
"""A basis of the null space of a, by reduced row echelon form. Exact for Fraction entries."""
m = [[Fraction(x) for x in r] for r in a]
rows, cols = len(m), len(m[0])
piv = []
r = 0
for c in range(cols):
p = next((i for i in range(r, rows) if m[i][c] != 0), None)
if p is None:
continue
m[r], m[p] = m[p], m[r]
inv = 1 / m[r][c]
m[r] = [x * inv for x in m[r]]
for i in range(rows):
if i != r and m[i][c] != 0:
f = m[i][c]
m[i] = [x - f * y for x, y in zip(m[i], m[r])]
piv.append(c)
r += 1
if r == rows:
break
free = [c for c in range(cols) if c not in piv]
basis = []
for f in free:
v = [Fraction(0)] * cols
v[f] = Fraction(1)
for i, c in enumerate(piv):
v[c] = -m[i][f]
basis.append(v)
return basis
def rank(a: Mat) -> int:
return len(a[0]) - len(nullspace(a))
# ---- symmetric matrices (float) ----
def cholesky(a: Mat, rtol: float = 0.0) -> Mat:
"""Lower triangular l with l l^T = a, for a symmetric positive definite a.
Raises ValueError when a pivot is at most rtol times the largest diagonal entry.
"""
n = len(a)
l = zeros(n, n, 0.0)
big = max(abs(float(a[i][i])) for i in range(n))
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(l[i][k] * l[j][k] for k in range(j))
if i == j:
if s <= rtol * big:
raise ValueError("matrix is not positive definite")
l[i][i] = sqrt(s)
else:
l[i][j] = s / l[j][j]
return l
def lower_solve(l: Mat, b: Vec) -> list:
x = []
for i in range(len(l)):
x.append((b[i] - sum(l[i][k] * x[k] for k in range(i))) / l[i][i])
return x
def upper_solve_t(l: Mat, b: Vec) -> list:
"""Solve l^T x = b for a lower triangular l."""
n = len(l)
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (b[i] - sum(l[k][i] * x[k] for k in range(i + 1, n))) / l[i][i]
return x
def jacobi_eigen(a: Mat, sweeps: int = 100, eps: float = 1e-15) -> Tuple[list, Mat]:
"""Eigenvalues and eigenvectors of a symmetric matrix by cyclic Jacobi rotations.
Returns (values, vectors) with the values in ascending order and
vectors[k] the unit eigenvector of values[k].
"""
n = len(a)
s = [[float(x) for x in r] for r in a]
v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
for _ in range(sweeps):
off = sum(s[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
if off <= eps * eps * max(1.0, sum(s[i][i] ** 2 for i in range(n))):
break
for p in range(n - 1):
for q in range(p + 1, n):
if s[p][q] == 0.0:
continue
th = 0.5 * atan2(2 * s[p][q], s[q][q] - s[p][p])
c, sn = cos(th), sin(th)
for k in range(n):
skp, skq = s[k][p], s[k][q]
s[k][p] = c * skp - sn * skq
s[k][q] = sn * skp + c * skq
for k in range(n):
spk, sqk = s[p][k], s[q][k]
s[p][k] = c * spk - sn * sqk
s[q][k] = sn * spk + c * sqk
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - sn * vkq
v[k][q] = sn * vkp + c * vkq
order = sorted(range(n), key=lambda i: s[i][i])
return [s[i][i] for i in order], [[v[k][i] for k in range(n)] for i in order]
test_geometric_primitive_fitting.py 193 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/geometric-primitive-fitting/. The authors are listed in prov/8FSGZT.jsonl.
import random
import unittest
from fractions import Fraction as F
from math import cos, pi, sin, sqrt
from geometric_primitive_fitting import (algebraic_sphere, cylinder_distance, fit_cylinder, fit_sphere,
sphere_distance)
from re1lin import solve
def rational_unit_vector(a, b):
"""Inverse stereographic projection of the rational point (a, b): a rational point of the unit sphere."""
a, b = F(a), F(b)
s = a * a + b * b + 1
return (2 * a / s, 2 * b / s, (a * a + b * b - 1) / s)
def rational_frame(q):
"""The rotation matrix of the integer quaternion q, with rational entries; its columns are orthonormal."""
a, b, c, d = q
s = F(a * a + b * b + c * c + d * d)
R = [[a * a + b * b - c * c - d * d, 2 * (b * c - a * d), 2 * (b * d + a * c)],
[2 * (b * c + a * d), a * a - b * b + c * c - d * d, 2 * (c * d - a * b)],
[2 * (b * d - a * c), 2 * (c * d + a * b), a * a - b * b - c * c + d * d]]
cols = [tuple(R[i][j] / s for i in range(3)) for j in range(3)]
return cols
def unit_circle(s):
s = F(s)
return (1 - s * s) / (1 + s * s), 2 * s / (1 + s * s)
def dist2_to_axis(x, p, u):
w = [a - b for a, b in zip(x, p)]
h = sum(a * b for a, b in zip(w, u))
return sum(a * a for a in w) - h * h
def strictly_decreasing(h):
return all(b < a for a, b in zip(h, h[1:]))
class TestWorkedExamples(unittest.TestCase):
def test_noise_free_sphere_start_is_exact(self):
c, r = (F(1), F(-2), F(1, 2)), F(3)
pts = [tuple(ci + r * vi for ci, vi in zip(c, rational_unit_vector(a, b)))
for a, b in [(0, 0), (F(1, 2), 0), (0, F(1, 3)), (F(-1, 4), F(1, 5)), (F(2, 7), F(-1, 3)), (1, 1)]]
for x in pts:
self.assertEqual(sum((a - b) ** 2 for a, b in zip(x, c)), r * r)
# the algebraic system, solved exactly with fractions, gives the true sphere (Theorem 2)
rows = [tuple(x) + (1,) for x in pts]
A = [[sum(u[i] * u[j] for u in rows) for j in range(4)] for i in range(4)]
rhs = [-sum(u[i] * sum(v * v for v in x) for u, x in zip(rows, pts)) for i in range(4)]
s = solve(A, rhs)
self.assertEqual([-v / 2 for v in s[:3]], list(c))
self.assertEqual(sum(v * v for v in c) - s[3], r * r)
gc, gr, hist = fit_sphere(pts)
for a, b in zip(gc, c):
self.assertAlmostEqual(a, float(b), places=10)
self.assertAlmostEqual(gr, 3, places=10)
self.assertLess(hist[-1], 1e-24)
def test_circle_in_the_plane(self):
pts = [(5 + 2 * x, -1 + 2 * y) for x, y in map(unit_circle, [0, F(1, 4), F(1, 3), F(1, 2)])]
c, r, _ = fit_sphere(pts)
self.assertAlmostEqual(c[0], 5, places=10)
self.assertAlmostEqual(c[1], -1, places=10)
self.assertAlmostEqual(r, 2, places=10)
class TestNoiseFree(unittest.TestCase):
def test_random_sphere_caps(self):
rng = random.Random(1)
for _ in range(30):
c = tuple(F(rng.randint(-20, 20), rng.randint(1, 4)) for _ in range(3))
r = F(rng.randint(1, 30), rng.randint(1, 3))
pts = [tuple(ci + r * vi for ci, vi in zip(c, rational_unit_vector(F(rng.randint(-20, 20), 50),
F(rng.randint(-20, 20), 50))))
for _ in range(12)]
gc, gr, hist = fit_sphere(pts)
self.assertTrue(strictly_decreasing(hist))
for a, b in zip(gc, c):
self.assertAlmostEqual(a, float(b), delta=1e-8 * float(r))
self.assertAlmostEqual(gr, float(r), delta=1e-8 * float(r))
def test_random_cylinders(self):
rng = random.Random(2)
quats = [(1, 2, 3, 4), (2, -1, 0, 3), (5, 1, -2, 1), (1, 0, 0, 0), (3, 3, -1, 2), (0, 1, 2, -2)]
for trial in range(12):
u, e1, e2 = rational_frame(quats[trial % len(quats)] if trial < 6 else
tuple(rng.randint(-5, 5) or 1 for _ in range(4)))
p = tuple(F(rng.randint(-10, 10)) for _ in range(3))
r = F(rng.randint(2, 20), rng.randint(1, 4))
pts = []
for _ in range(30):
cs, sn = unit_circle(F(rng.randint(-30, 30), 20))
t = F(rng.randint(-40, 40), 10)
pts.append(tuple(pi_ + r * (cs * a + sn * b) + t * c for pi_, a, b, c in zip(p, e1, e2, u)))
for x in pts:
self.assertEqual(dist2_to_axis(x, p, u), r * r)
normals = None if trial % 2 == 0 else [
tuple(float(v) for v in [(xi - pi_) - sum((xj - pj) * uj for xj, pj, uj in zip(x, p, u)) * ui
for xi, pi_, ui in zip(x, p, u)]) for x in pts]
gp, gu, gr, hist = fit_cylinder(pts, normals)
self.assertTrue(strictly_decreasing(hist))
fu = [float(v) for v in u]
self.assertGreater(abs(sum(a * b for a, b in zip(gu, fu))), 1 - 1e-12)
self.assertAlmostEqual(gr, float(r), delta=1e-8 * float(r))
self.assertLess(sqrt(max(0.0, dist2_to_axis(gp, [float(v) for v in p], fu))), 1e-8 * float(r))
class TestDistances(unittest.TestCase):
def test_cylinder_distance_against_brute_force(self):
rng = random.Random(3)
for _ in range(30):
x = tuple(rng.uniform(-3, 3) for _ in range(3))
# cylinder: axis z through (1, 0, 0), radius 1; brute force over a fine grid of the surface near x
best = min(sqrt((x[0] - 1 - cos(t)) ** 2 + (x[1] - sin(t)) ** 2)
for t in (2 * pi * k / 20000 for k in range(20000)))
self.assertAlmostEqual(abs(cylinder_distance((1, 0, 0), (0, 0, 1), 1, x)), best, places=6)
def test_sphere_distance(self):
self.assertEqual(sphere_distance((0, 0, 0), 1, (0, 0, 3)), 2)
self.assertEqual(sphere_distance((0, 0, 0), 2, (0, 1, 0)), -1)
class TestEdgeCases(unittest.TestCase):
def test_too_few_points(self):
with self.assertRaises(ValueError):
fit_sphere([(0, 0, 0), (1, 0, 0), (0, 1, 0)])
with self.assertRaises(ValueError):
fit_cylinder([(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)])
def test_coplanar_points_have_no_sphere(self):
with self.assertRaises(ValueError):
algebraic_sphere([(1, 0, 0), (0, 1, 0), (-1, 0, 0), (0, -1, 0), (F(3, 5), F(4, 5), 0)])
class TestRandomizedNoisy(unittest.TestCase):
def cost_sphere(self, pts, c, r):
return sum((sqrt(sum((a - b) ** 2 for a, b in zip(x, c))) - r) ** 2 for x in pts)
def test_sphere_local_minimum_and_better_than_truth(self):
rng = random.Random(2026)
for _ in range(20):
pts = []
for _ in range(40):
z = rng.uniform(0.5, 1)
ph = rng.uniform(0, 2 * pi)
s = sqrt(1 - z * z)
pts.append((s * cos(ph) + rng.gauss(0, 0.02), s * sin(ph) + rng.gauss(0, 0.02),
z + rng.gauss(0, 0.02)))
c, r, hist = fit_sphere(pts)
self.assertTrue(strictly_decreasing(hist))
best = self.cost_sphere(pts, c, r)
self.assertAlmostEqual(best, hist[-1], delta=1e-12)
self.assertLessEqual(best, self.cost_sphere(pts, (0, 0, 0), 1) + 1e-15)
ac, ar = algebraic_sphere(pts)
self.assertLessEqual(best, self.cost_sphere(pts, ac, ar) + 1e-15)
for _ in range(100):
dc = tuple(v + rng.gauss(0, 1e-3) for v in c)
self.assertLessEqual(best, self.cost_sphere(pts, dc, r + rng.gauss(0, 1e-3)) + 1e-15)
# the gradient of the independent cost function vanishes (central differences)
for k in range(4):
th = list(c) + [r]
hi, lo = list(th), list(th)
hi[k] += 1e-6
lo[k] -= 1e-6
g = (self.cost_sphere(pts, hi[:3], hi[3]) - self.cost_sphere(pts, lo[:3], lo[3])) / 2e-6
self.assertLess(abs(g), 1e-6)
def test_cylinder_noisy_close_to_truth(self):
rng = random.Random(5)
for _ in range(6):
pts = []
for _ in range(60):
t, h = rng.uniform(0, pi), rng.uniform(0, 3)
pts.append((2 * cos(t) + rng.gauss(0, 0.01), 2 * sin(t) + rng.gauss(0, 0.01), h + rng.gauss(0, 0.01)))
p, u, r, hist = fit_cylinder(pts)
self.assertTrue(strictly_decreasing(hist))
self.assertGreater(abs(u[2]), cos(pi / 180))
self.assertAlmostEqual(r, 2, delta=0.02)
cost = sum(cylinder_distance(p, u, r, x) ** 2 for x in pts)
truth = sum(cylinder_distance((0, 0, 0), (0, 0, 1), 2, x) ** 2 for x in pts)
self.assertLessEqual(cost, truth + 1e-15)
if __name__ == "__main__":
unittest.main()
History
Fitting circles and spheres by orthogonal distance is old in metrology and statistics; the algebraic fits of Kasa, Bookstein and Pratt were mainly used to find starting values. In 1998 Lukács, Martin and Marshall gave geometric fits of spheres, cylinders, cones and tori for the segmentation of range data in reverse engineering, with parameterizations that remain valid as one type degenerates into another and approximate distances for good starting values. The same year Shakarji described the orthogonal fits of the NIST algorithm testing system for coordinate measuring machines. Ahn's 2004 monograph treats orthogonal distance fitting of general curves and surfaces.
References
- Gábor Lukács, Ralph Martin and Dave Marshall, Faithful least-squares fitting of spheres, cylinders, cones and tori for reliable segmentation, Computer Vision ECCV 98, Lecture Notes in Computer Science 1406, Springer, 1998, 671 to 686, the faithful parameterizations of the sphere, cylinder, cone and torus, the approximate distances that tend to the plane distance, the starting values and the Levenberg-Marquardt fit
- Craig M. Shakarji, Least-squares fitting algorithms of the NIST algorithm testing system, Journal of Research of the National Institute of Standards and Technology 103(6), 1998, 633 to 641, orthogonal distance fits of lines, planes, circles, spheres, cylinders, cones and tori for coordinate metrology, with their distance functions, parameterizations and the Levenberg-Marquardt method
- Jorge Nocedal and Stephen J. Wright, Numerical Optimization, second edition, Springer, 2006, Chapter 10, nonlinear least squares (the Gauss-Newton and Levenberg-Marquardt methods and their local convergence)
Where this leads
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 8FSGZT Edit this page History Report an error Markdown