Algorithm Search⌘K

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
Properties
deterministicnot exactiterative
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 x1,…,xmx_1, \dots, x_m in R3\mathbb{R}^3, usually one region of a primitive segmentation, and a type of surface. The output is the parameters θ\theta of a surface S(θ)S(\theta) of that type that minimize

F(θ)=∑i=1md(xi,S(θ))2,F(\theta) = \sum_{i=1}^{m} d(x_i, S(\theta))^2 ,

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 FF is the maximum likelihood estimate of the surface.

With w=x−pw = x - p, h=w⋅uh = w \cdot u and ρ=∣w−hu∣\rho = \lvert w - h u \rvert for a point pp and a unit axis uu, the signed distances are:

surface parameters count signed distance
sphere center cc, radius rr 44 ∣x−c∣−r\lvert x - c \rvert - r
cylinder axis (p,u)(p, u), radius rr 55 ρ−r\rho - r
cone apex pp, axis uu, half angle α\alpha 66 ρcos⁡α−hsin⁡α\rho \cos \alpha - h \sin \alpha
torus center pp, axis uu, radii R>rR > r 77 (ρ−R)2+h2−r\sqrt{(\rho - R)^2 + h^2} - r

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 uu do not count), which gives the counts.

The algorithm

  1. GEOMETRIC-FIT(x_1..x_m, type)
  2. 1θ ← start from an algebraic or Taubin fit; μ ← μ_0
  3. 2repeat
  4. 3r_i ← signed orthogonal distance from x_i to S(θ), for every i
  5. 4J ← Jacobian of r with respect to the local parameters of θ
  6. 5solve (Jᵀ J + μ I) Δ = −Jᵀ r
  7. 6θ' ← θ ⊕ Δ ▷ move along the local parameters
  8. 7if Σ r_i(θ')² < Σ r_i(θ)² then θ ← θ'; μ ← μ / 10
  9. 8else μ ← 10 μ
  10. 9until the gain of an accepted step or the step is below a tolerance
  11. 10return θ

Line L1. For a sphere the start is the linear algebraic fit of ∣x∣2+b⋅x+e=0\lvert x \rvert^2 + b \cdot x + e = 0. 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 ∑ininiT\sum_i n_i n_i^{\mathsf T}. 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 (u,e1,e2)(u, e_1, e_2): two moves of the axis point normal to uu, two tilts of uu, and a change of rr, then puts the axis point back at the projection of the centroid. The Jacobian row of point ii is (−w1/ρ,−w2/ρ,−hw1/ρ,−hw2/ρ,−1)(-w_1/\rho, -w_2/\rho, -h w_1/\rho, -h w_2/\rho, -1) with w1=w⋅e1w_1 = w \cdot e_1, w2=w⋅e2w_2 = w \cdot e_2. This removes the freedom of sliding along the axis, which would make JTJJ^{\mathsf T} J singular.

Lines L5, L7 and L8. For μ→0\mu \to 0 line L5 is a Gauss-Newton step, and for large μ\mu it is a short step down the gradient. A step is kept only if it lowers the cost; otherwise μ\mu grows and the next step is shorter. This is the Levenberg form with μI\mu I; Marquardt's form scales by the diagonal of JTJJ^{\mathsf T} J.

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 ρn\rho n nearest the origin, the unit normal nn there and the curvature κ=1/r\kappa = 1/r. Then

κ2(∣x−c∣2−r2)=κ2∣x−ρn∣2−(x−ρn)⋅n=d+κ2d2\tfrac{\kappa}{2} \bigl( \lvert x - c \rvert^2 - r^2 \bigr) = \tfrac{\kappa}{2} \lvert x - \rho n \rvert^2 - (x - \rho n) \cdot n = d + \tfrac{\kappa}{2} d^2

for the signed distance dd. The middle form is smooth at κ=0\kappa = 0, where it is the distance to the plane x⋅n=ρx \cdot n = \rho, and it equals the true distance up to the term κd2/2\kappa d^2 / 2. 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 3030 degrees of the unit sphere, with independent normal noise σ=0.01\sigma = 0.01 in each coordinate, 300300 samples, seed 2026. The algebraic fit, which is the start of line L1, has a median radius of 0.9500.950, and the geometric fit 1.0021.002. 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 22 and height 33 with axis zz, noise σ=0.01\sigma = 0.01, 100100 samples, started from the direction search of line L1 with 400400 directions. The fitted radius had median 1.99981.9998 and ranged over [1.9925,2.0063][1.9925, 2.0063], and the axis was off by a median of 0.150.15 degrees and at most 0.410.41 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 10−810^{-8} 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. JTJ+μIJ^{\mathsf T} J + \mu I is positive definite for μ>0\mu > 0, and when the gradient JTrJ^{\mathsf T} r is not zero, every large enough μ\mu 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 x1,…,xmx_1, \dots, x_m in R3\mathbb{R}^3 (or R2\mathbb{R}^2 for circles). A surface S(θ)S(\theta) has parameters θ\theta, and ri(θ)r_i(\theta) is the signed orthogonal distance from xix_i to S(θ)S(\theta). The cost is F(θ)=∑iri(θ)2F(\theta) = \sum_i r_i(\theta)^2. For a point xx, a unit axis uu and a point pp (on the axis, or the center or the apex), write w=x−pw = x - p, h=w⋅uh = w \cdot u, and ρ=∣w−hu∣\rho = \lvert w - h u \rvert, the distance from xx to the axis.

Lemma 1 (orthogonal distances). The distance from xx to the surface is: (a) sphere with center cc and radius rr: ∣∣x−c∣−r∣\lvert \lvert x - c \rvert - r \rvert; (b) cylinder with axis (p,u)(p, u) and radius rr: ∣ρ−r∣\lvert \rho - r \rvert; (c) cone with apex pp, axis uu and half angle α∈(0,π/2)\alpha \in (0, \pi/2), for a point whose nearest point is not the apex, that is ρsin⁡α+hcos⁡α≥0\rho \sin \alpha + h \cos \alpha \ge 0: ∣ρcos⁡α−hsin⁡α∣\lvert \rho \cos \alpha - h \sin \alpha \rvert; (d) torus with center pp, axis uu, major radius RR and minor radius r<Rr < R, for ρ>0\rho > 0: ∣(ρ−R)2+h2−r∣\bigl| \sqrt{(\rho - R)^2 + h^2} - r \bigr|.

Proof. (a) For yy on the sphere, ∣x−y∣≥∣∣x−c∣−∣y−c∣∣\lvert x - y \rvert \ge \bigl| \lvert x - c \rvert - \lvert y - c \rvert \bigr| by the triangle inequality, with equality for y=c+r(x−c)/∣x−c∣y = c + r (x - c)/\lvert x - c \rvert (any yy if x=cx = c). For (b), (c) and (d), each surface is a surface of revolution about the axis, so a nearest point of SS to xx lies in the half plane through the axis and xx (rotating any point of SS about the axis into that half plane does not increase its distance to xx, since only the angle between the two points about the axis changes, and the distance is smallest when the angle is 00). In that half plane, with coordinates (ρ,h)(\rho, h), the profile is: (b) the line ρ=r\rho = r, at distance ∣ρ−r∣\lvert \rho - r \rvert; (c) the ray from the origin in the direction (sin⁡α,cos⁡α)(\sin \alpha, \cos \alpha), whose line has unit normal (cos⁡α,−sin⁡α)(\cos \alpha, -\sin \alpha), so the distance to the line is ∣ρcos⁡α−hsin⁡α∣\lvert \rho \cos \alpha - h \sin \alpha \rvert, and the foot of the perpendicular is on the ray exactly when the component along the ray, ρsin⁡α+hcos⁡α\rho \sin \alpha + h \cos \alpha, is ≥0\ge 0; (d) the circle of center (R,0)(R, 0) and radius rr, at distance ∣∣(ρ−R,h)∣−r∣\bigl| \lvert (\rho - R, h) \rvert - r \bigr| by (a). The half plane on the other side of the axis gives the profile at (−ρ,h)(-\rho, h), which is not closer: for (d), ∣(−ρ−R,h)∣≥∣(ρ−R,h)∣\lvert (-\rho - R, h) \rvert \ge \lvert (\rho - R, h) \rvert. □\square

The code uses the signed versions ri=∣xi−c∣−rr_i = \lvert x_i - c \rvert - r and ri=ρi−rr_i = \rho_i - r.

Lemma 2 (Jacobians). For the sphere with θ=(c,r)\theta = (c, r), ∂ri/∂c=−(xi−c)T/∣xi−c∣\partial r_i / \partial c = -(x_i - c)^{\mathsf T} / \lvert x_i - c \rvert and ∂ri/∂r=−1\partial r_i / \partial r = -1. For the cylinder, let (u,e1,e2)(u, e_1, e_2) be orthonormal, and let the local step Δ=(α,β,γ,δ,ε)\Delta = (\alpha, \beta, \gamma, \delta, \varepsilon) move the axis point to p+αe1+βe2p + \alpha e_1 + \beta e_2, the direction to (u+γe1+δe2)/∣u+γe1+δe2∣(u + \gamma e_1 + \delta e_2)/\lvert u + \gamma e_1 + \delta e_2 \rvert, and the radius to r+εr + \varepsilon. With w1=w⋅e1w_1 = w \cdot e_1, w2=w⋅e2w_2 = w \cdot e_2 and ρ=w12+w22>0\rho = \sqrt{w_1^2 + w_2^2} > 0, the derivative of rir_i at Δ=0\Delta = 0 is (−w1/ρ,−w2/ρ,−hw1/ρ,−hw2/ρ,−1)(-w_1/\rho, -w_2/\rho, -h w_1/\rho, -h w_2/\rho, -1).

Proof. The sphere case is the gradient of ∣x−c∣\lvert x - c \rvert. For the cylinder, ρ2=∣w∣2−(w⋅u)2/∣u∣2\rho^2 = \lvert w \rvert^2 - (w \cdot u)^2 / \lvert u \rvert^2 for any nonzero direction uu. After the step, w′=w−αe1−βe2w' = w - \alpha e_1 - \beta e_2 and u′=u+γe1+δe2u' = u + \gamma e_1 + \delta e_2 (the normalization does not change ρ\rho). To first order in Δ\Delta: ∣w′∣2=∣w∣2−2αw1−2βw2\lvert w' \rvert^2 = \lvert w \rvert^2 - 2 \alpha w_1 - 2 \beta w_2, w′⋅u′=h+γw1+δw2w' \cdot u' = h + \gamma w_1 + \delta w_2 (as e1⋅u=e2⋅u=0e_1 \cdot u = e_2 \cdot u = 0), and ∣u′∣2=1+O(∣Δ∣2)\lvert u' \rvert^2 = 1 + O(\lvert \Delta \rvert^2). So ρ′2=ρ2−2αw1−2βw2−2h(γw1+δw2)+O(∣Δ∣2)\rho'^2 = \rho^2 - 2 \alpha w_1 - 2 \beta w_2 - 2 h (\gamma w_1 + \delta w_2) + O(\lvert \Delta \rvert^2), and ρ′=ρ+(ρ′2−ρ2)/(2ρ)+O(∣Δ∣2)\rho' = \rho + (\rho'^2 - \rho^2)/(2 \rho) + O(\lvert \Delta \rvert^2) gives the row. Moving the axis point along uu afterwards, as the code does, does not change any distance. □\square

Lemma 3 (the Levenberg step descends). Let g=JTrg = J^{\mathsf T} r (half the gradient of FF in local coordinates), μ>0\mu > 0, and Δ=−(JTJ+μI)−1g\Delta = -(J^{\mathsf T} J + \mu I)^{-1} g. Then the matrix is positive definite, so line L5 has a unique solution, and if g≠0g \ne 0 there is μ0\mu_0 such that every μ≥μ0\mu \ge \mu_0 gives F(θ⊕Δ)<F(θ)F(\theta \oplus \Delta) < F(\theta), where θ⊕Δ\theta \oplus \Delta is the retraction of line L6, a smooth map with θ⊕0=θ\theta \oplus 0 = \theta whose derivative in Δ\Delta at 00 is the one used for JJ.

Proof. vT(JTJ+μI)v=∣Jv∣2+μ∣v∣2>0v^{\mathsf T} (J^{\mathsf T} J + \mu I) v = \lvert J v \rvert^2 + \mu \lvert v \rvert^2 > 0 for v≠0v \ne 0. Let Λ\Lambda be the largest eigenvalue of JTJJ^{\mathsf T} J. Then ∣Δ∣≤∣g∣/μ\lvert \Delta \rvert \le \lvert g \rvert / \mu and gTΔ=−gT(JTJ+μI)−1g≤−∣g∣2/(Λ+μ)g^{\mathsf T} \Delta = -g^{\mathsf T} (J^{\mathsf T} J + \mu I)^{-1} g \le -\lvert g \rvert^2 / (\Lambda + \mu). By Taylor's theorem on the smooth function Δ↦F(θ⊕Δ)\Delta \mapsto F(\theta \oplus \Delta), whose gradient at 00 is 2g2 g, there is KK with F(θ⊕Δ)≤F(θ)+2gTΔ+K∣Δ∣2F(\theta \oplus \Delta) \le F(\theta) + 2 g^{\mathsf T} \Delta + K \lvert \Delta \rvert^2 for ∣Δ∣≤1\lvert \Delta \rvert \le 1. So F(θ⊕Δ)−F(θ)≤−2∣g∣2/(Λ+μ)+K∣g∣2/μ2F(\theta \oplus \Delta) - F(\theta) \le -2 \lvert g \rvert^2 / (\Lambda + \mu) + K \lvert g \rvert^2 / \mu^2, and the bound on ∣Δ∣\lvert \Delta \rvert makes ∣Δ∣≤1\lvert \Delta \rvert \le 1 for μ≥∣g∣\mu \ge \lvert g \rvert. The right side is negative exactly when K(Λ+μ)<2μ2K (\Lambda + \mu) < 2 \mu^2, and for μ>max⁡(Λ,K)\mu > \max(\Lambda, K) we have K(Λ+μ)<K⋅2μ<2μ2K (\Lambda + \mu) < K \cdot 2 \mu < 2 \mu^2. So μ0=max⁡(∣g∣,Λ,K)+1\mu_0 = \max(\lvert g \rvert, \Lambda, K) + 1 works. □\square

Theorem 1 (monotone, terminating). The accepted costs form a strictly decreasing sequence bounded below by 00, 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 μ\mu passes its bound, which by Lemma 3 can happen at a point with g≠0g \ne 0 only if the bound is below μ0\mu_0, and otherwise means the point is stationary.

Proof. Line L7 accepts a step only if it lowers FF; line L8 raises μ\mu by a factor of 1010, so by Lemma 3 a point with g≠0g \ne 0 sees an accepted step after finitely many rejections, unless the bound on μ\mu is reached first. The other stopping rules are counted. □\square

Theorem 2 (a noise-free sphere is recovered exactly). If m≥4m \ge 4 points lie on a sphere (c∗,r∗)(c^*, r^*) and are not coplanar, the algebraic start of line L1 is (c∗,r∗)(c^*, r^*), and the loop returns it.

Proof. The algebraic fit solves the linear least squares problem for (b,e)(b, e) in ∣x∣2+b⋅x+e=0\lvert x \rvert^2 + b \cdot x + e = 0. Its design matrix has the rows (xiT,1)(x_i^{\mathsf T}, 1), which have full column rank 44 exactly when the points are not coplanar, so the solution is unique. The values b=−2c∗b = -2 c^*, e=∣c∗∣2−r∗2e = \lvert c^* \rvert^2 - r^{*2} give zero residuals, so they are that solution, and c=−b/2=c∗c = -b/2 = c^*, r=∣c∣2−e=r∗r = \sqrt{\lvert c \rvert^2 - e} = r^*. At this start ri=0r_i = 0 for all ii, so g=0g = 0 and Δ=0\Delta = 0; no step lowers F=0F = 0, the loop only raises μ\mu, and it returns the start. In floating point the same holds up to rounding. □\square

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 ρn\rho n nearest the origin, with unit normal nn there pointing to the center, and its curvature κ=1/r\kappa = 1/r, so that c=(ρ+1/κ)nc = (\rho + 1/\kappa) n. Then for every xx, with d=∣x−c∣−rd = \lvert x - c \rvert - r,

κ2(∣x−c∣2−r2)=κ2∣x−ρn∣2−(x−ρn)⋅n=d+κ2d2,\frac{\kappa}{2} \bigl( \lvert x - c \rvert^2 - r^2 \bigr) = \frac{\kappa}{2} \lvert x - \rho n \rvert^2 - (x - \rho n) \cdot n = d + \frac{\kappa}{2} d^2 ,

and as κ→0\kappa \to 0 with ρ\rho and nn fixed the middle expression tends to ρ−x⋅n\rho - x \cdot n, the signed distance to the plane x⋅n=ρx \cdot n = \rho.

Proof. With c=ρn+rnc = \rho n + r n, ∣x−c∣2−r2=∣x−ρn∣2−2r(x−ρn)⋅n\lvert x - c \rvert^2 - r^2 = \lvert x - \rho n \rvert^2 - 2 r (x - \rho n) \cdot n; multiply by κ/2=1/(2r)\kappa / 2 = 1/(2r). Also ∣x−c∣2−r2=d(d+2r)\lvert x - c \rvert^2 - r^2 = d (d + 2r), and κ2d(d+2r)=d+κ2d2\frac{\kappa}{2} d (d + 2 r) = d + \frac{\kappa}{2} d^2. The limit is read off the middle expression. □\square

■\blacksquare

Complexity

One iteration computes mm distances and Jacobian rows in Θ(mk)\Theta(m k), forms JTJJ^{\mathsf T} J in Θ(mk2)\Theta(m k^2) and solves a k×kk \times k system in Θ(k3)\Theta(k^3), with k≤7k \le 7. With ss iterations the time is Θ(s(mk2+k3))\Theta(s (m k^2 + k^3)) on the real RAM, linear in the number of points; from a good start, ss is usually below twenty. The extra space is Θ(mk)\Theta(m k) for JJ, or Θ(k2)\Theta(k^2) if JTJJ^{\mathsf T} J and JTrJ^{\mathsf T} r are accumulated row by row. The direction search for a cylinder start costs Θ(Dm)\Theta(D m) for DD 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 JTJJ^{\mathsf T} J 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.

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

  1. 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
  2. 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
  3. 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.

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