Algorithm Search⌘K

Algorithmadvanced

Taubin's gradient-weighted fitting

Also called Taubin fit, gradient-weighted algebraic fit.

Taubin's fit of implicit curves and surfaces that divides the algebraic error by the gradient norm, one generalized eigenproblem whose answer is close to the geometric fit.

Time
Θ(m n² d + s n³) worst
Space
Θ(n²) extra
Where
d = the dimension of the space; m = the number of points; n = the number of basis functions; s = the number of Jacobi sweeps
Properties
deterministicnot exactiterative
Origin
Gabriel Taubin, 1991

Taubin's fit is an algorithm that fits an implicit curve or surface f(x)=0f(x) = 0, with ff linear in its coefficients, to data points by minimizing the first-order distance ∣f(x)∣/∣∇f(x)∣\lvert f(x) \rvert / \lvert \nabla f(x) \rvert in an averaged form. The plain algebraic fit minimizes ∑if(xi)2\sum_i f(x_i)^2, whose terms are the squared distances weighted by ∣∇f∣2\lvert \nabla f \rvert^2, so its answer depends on how ff is scaled and is biased. Dividing each algebraic distance by the gradient removes that weight to first order, because ∣f(x)∣/∣∇f(x)∣\lvert f(x) \rvert / \lvert \nabla f(x) \rvert equals the Euclidean distance from xx to the curve up to an error of order δ2\delta^2. Taubin then divides the sum of the f(xi)2f(x_i)^2 by the sum of the ∣∇f(xi)∣2\lvert \nabla f(x_i) \rvert^2, not term by term. Both sums are quadratic forms in the coefficient vector aa, so the minimum is the smallest eigenvalue of one generalized eigenvalue problem Ma=λNaM a = \lambda N a, solved directly without iteration. The fit returns the exact curve on noise-free data, it is invariant under rotations, translations and scaling, and its bias is much smaller than that of the plain algebraic fit. It is still not the geometric fit, which minimizes the orthogonal distances themselves and needs iteration, and it is the usual starting point for that fit.

In plain words

To fit a curve to points, a simple method uses a formula that is zero on the curve and asks the formula to be close to zero at every point. The number that the formula gives is not a distance, though. Where the formula changes fast, a point near the curve already gets a large number, and where it changes slowly, a point far from the curve gets a small one.

Taubin's idea is to divide by how fast the formula changes there. Near the curve, the result is almost the true distance. He also divides the total of the values by the total of the rates, and not each value by its own rate, so the best curve can be found in one step of linear algebra. The result is nearly as good as a fit with true distances, which needs a slower search.

The problem

The input is mm points x1,…,xmx_1, \dots, x_m in Rd\mathbb{R}^d and a family of implicit curves or surfaces fa(x)=∑j=1najφj(x)=0f_a(x) = \sum_{j=1}^{n} a_j \varphi_j(x) = 0, given by nn linearly independent polynomial basis functions φj\varphi_j: the six monomials x2,xy,y2,x,y,1x^2, xy, y^2, x, y, 1 for conics, ∣x∣2,x1,…,xd,1\lvert x \rvert^2, x_1, \dots, x_d, 1 for circles and spheres, all monomials up to degree kk for implicit polynomials. The output is a unit coefficient vector aa that minimizes Taubin's approximate mean square distance

q(a)=∑ifa(xi)2∑i∣∇fa(xi)∣2,q(a) = \frac{\sum_i f_a(x_i)^2}{\sum_i \lvert \nabla f_a(x_i) \rvert^2} ,

and the minimum value. This is one choice of the normalization in the template of algebraic distance fitting: the constraint aTNa=1a^{\mathsf T} N a = 1 with NN built from the gradients at the data. It is a solution method for one form of curve fitting.

The algorithm

Let J(x)J(x) be the n×dn \times d Jacobian of the basis, with row jj equal to ∇φj(x)\nabla \varphi_j(x). Then fa(xi)=φ(xi)Taf_a(x_i) = \varphi(x_i)^{\mathsf T} a and ∇fa(xi)=J(xi)Ta\nabla f_a(x_i) = J(x_i)^{\mathsf T} a, so q(a)=aTMa/aTNaq(a) = a^{\mathsf T} M a / a^{\mathsf T} N a with the two matrices below.

  1. TAUBIN-FIT(x_1..x_m, φ)
  2. 1M ← 0, N ← 0 ▷ n × n
  3. 2for i ← 1 to m do
  4. 3M ← M + φ(x_i) φ(x_i)ᵀ
  5. 4N ← N + J(x_i) J(x_i)ᵀ
  6. 5split a = (b, c), with c the coefficient of the constant basis function
  7. 6M' ← M_bb − M_bc M_cb / M_cc ▷ c is eliminated
  8. 7L ← Cholesky factor of N_bb ▷ N_bb = L Lᵀ
  9. 8(λ, y) ← smallest eigenpair of L⁻¹ M' L⁻ᵀ
  10. 9b ← L⁻ᵀ y, c ← −M_cb b / M_cc
  11. 10return a ← (b, c) / |(b, c)| and λ

Why L5 and L6. The gradient of a constant is 00, so the row and column of the constant coefficient in NN are zero and NN is singular. That coefficient appears only in the numerator, as a quadratic in cc with leading coefficient Mcc=mM_{cc} = m for the basis function 11, so the best cc for a given bb is −Mcbb/Mcc-M_{cb} b / M_{cc}, and what remains of the numerator is the Schur complement bTM′bb^{\mathsf T} M' b. A basis with no constant skips these two lines.

Why L7 to L9. NbbN_{bb} is positive definite when no nonconstant member of the family has a zero gradient at all the data points; for conics this holds as soon as three points are not on one line. With the Cholesky factor LL and y=LTby = L^{\mathsf T} b, the quotient becomes the ordinary Rayleigh quotient yTCy/yTyy^{\mathsf T} C y / y^{\mathsf T} y of the symmetric matrix C=L−1M′L−TC = L^{-1} M' L^{-\mathsf T}, whose minimum is the smallest eigenvalue of CC. The code finds it with the Jacobi eigenvalue algorithm; a library would use a symmetric eigensolver or the QZ algorithm on (M,N)(M, N) directly.

The distance it minimizes. Taubin's fit minimizes neither the algebraic distance nor the geometric distance. The first-order distance ∣f∣/∣∇f∣\lvert f \rvert / \lvert \nabla f \rvert of a point at distance δ\delta from the curve is δ+O(δ2)\delta + O(\delta^2), so the Sampson cost ∑if(xi)2/∣∇f(xi)∣2\sum_i f(x_i)^2 / \lvert \nabla f(x_i) \rvert^2 is the geometric cost up to higher order terms. Taubin's quotient of sums is a further approximation of the Sampson cost: it treats the gradient as if it had the same size at all data points. The returned λ\lambda is a weighted mean of the squared first-order distances, with weights ∣∇f(xi)∣2\lvert \nabla f(x_i) \rvert^2, and serves as an estimate of the mean squared distance.

Example

A noise-free ellipse. The six rational points (2,0)(2, 0), (8/5,3/5)(8/5, 3/5), (6/5,4/5)(6/5, 4/5), (0,1)(0, 1), (−6/5,4/5)(-6/5, 4/5) and (6/5,−4/5)(6/5, -4/5) lie on the ellipse x2+4y2−4=0x^2 + 4y^2 - 4 = 0. With the conic basis x2,xy,y2,x,y,1x^2, xy, y^2, x, y, 1, the code returns a vector proportional to (1,0,4,0,0,−4)(1, 0, 4, 0, 0, -4) up to rounding of order 10−1510^{-15}, with λ≈2⋅10−17\lambda \approx 2 \cdot 10^{-17}. In exact arithmetic the design matrix of these points has a one-dimensional null space spanned by (1,0,4,0,0,−4)(1, 0, 4, 0, 0, -4), so by Theorem 2 below the fit is exactly this ellipse.

Short circular arcs. Twenty points were spaced evenly on an arc of the unit circle and moved by independent normal noise of standard deviation σ\sigma in each coordinate; 10001000 samples were drawn with seed 2026. The table gives the median radius of the Kasa fit (the algebraic fit with the coefficient of x2+y2x^2 + y^2 fixed), of the Taubin fit with the circle basis, and of the geometric fit (Gauss-Newton started at the Kasa circle).

arc σ\sigma Kasa Taubin geometric
6060 degrees 0.020.02 0.8680.868 0.9980.998 0.9990.999
6060 degrees 0.050.05 0.5460.546 0.9920.992 1.0061.006
full circle 0.050.05 1.0021.002 1.0021.002 1.0011.001

On the short arc the algebraic fit shrinks the circle badly, and the Taubin fit stays close to the geometric fit. On the full circle all three agree.

An elliptic arc. Thirty points on the quarter of the ellipse x2/4+y2=1x^2/4 + y^2 = 1 in the first quadrant, with normal noise σ=0.01\sigma = 0.01 (500 samples, seed 2026): the general conic fit with the normalization ∣a∣=1\lvert a \rvert = 1 returned a curve that is not an ellipse in 358358 samples, and the Taubin fit in 1111. With σ=0.03\sigma = 0.03 the counts were 415415 and 138138. The Taubin fit does not force an ellipse; when the type must be an ellipse, the constraint of Fitzgibbon, Pilu and Fisher on the algebraic fit page does. All numbers in this section are measured on synthetic data.

Correctness

The proofs are in the correctness file. In outline:

  • First-order distance. If yy is the nearest point of {f=0}\{f = 0\} to xx, at distance δ\delta, with ∣∇f(y)∣=g>0\lvert \nabla f(y) \rvert = g > 0 and the Hessian of ff bounded by KK near yy, then ∣∣f(x)∣/∣∇f(x)∣−δ∣≤3Kδ2/g\bigl| \lvert f(x) \rvert / \lvert \nabla f(x) \rvert - \delta \bigr| \le 3 K \delta^2 / g when Kδ≤g/2K\delta \le g/2. The proof is a first-order Taylor expansion at yy, using that x−yx - y is parallel to ∇f(y)\nabla f(y).
  • The eigen step. q(a)=aTMa/aTNaq(a) = a^{\mathsf T} M a / a^{\mathsf T} N a; eliminating the constant gives the Schur complement M′M', and the change of variables y=LTby = L^{\mathsf T} b turns the quotient into a symmetric Rayleigh quotient. So the algorithm returns a global minimizer of qq, and M′b=λNbbbM' b = \lambda N_{bb} b.
  • Exact on noise-free data. If all points lie on fa∗=0f_{a^*} = 0 and they determine the curve (the null space of the design matrix is spanned by a∗a^*), then λ=0\lambda = 0 and the fit returns ±a∗/∣a∗∣\pm a^* / \lvert a^* \rvert. The tests check this on rational points of ellipses, hyperbolas and circles, with the null space computed in exact arithmetic.
  • Invariance. For a family closed under similarities, such as all polynomials of degree at most kk, moving, rotating or scaling the data moves, rotates or scales the fitted curve in the same way, because the cost of f∘T−1f \circ T^{-1} on the moved points is a constant times the cost of ff.

Not proved here: how close Taubin's quotient of sums is to the Sampson cost, and the size of the statistical bias of the fit. Chernov's book analyses the bias of the circle fits; there the Taubin fit has a much smaller bias than the Kasa fit and a smaller one than the Pratt fit, which matches the measured table.

Proof: The first-order distance approximates the geometric distance to second order, the Taubin fit is the smallest eigenvector of the reduced generalized eigenproblem, it is exact on noise-free data, and it is invariant under similaritiesfull

Setup. The basis functions φ1,…,φn\varphi_1, \dots, \varphi_n are polynomials on Rd\mathbb{R}^d, linearly independent, and fa=∑jajφjf_a = \sum_j a_j \varphi_j. The data are x1,…,xmx_1, \dots, x_m. J(x)J(x) is the n×dn \times d matrix with row jj equal to ∇φj(x)T\nabla \varphi_j(x)^{\mathsf T}, so ∇fa(x)=J(x)Ta\nabla f_a(x) = J(x)^{\mathsf T} a. M=∑iφ(xi)φ(xi)TM = \sum_i \varphi(x_i) \varphi(x_i)^{\mathsf T}, N=∑iJ(xi)J(xi)TN = \sum_i J(x_i) J(x_i)^{\mathsf T}, and DD is the m×nm \times n matrix with rows φ(xi)T\varphi(x_i)^{\mathsf T}, so M=DTDM = D^{\mathsf T} D. Termination is clear: the algorithm has one loop over the points, one Cholesky factorization and one eigen solve; the Jacobi solver of the code stops after a fixed maximum number of sweeps.

Lemma 1 (first-order distance). Let Z={f=0}Z = \{ f = 0 \} for a C2C^2 function ff, let xx be a point, and let y∈Zy \in Z be a nearest point of ZZ to xx, at distance δ=∣x−y∣\delta = \lvert x - y \rvert. Let g=∣∇f(y)∣>0g = \lvert \nabla f(y) \rvert > 0, and let KK bound the operator norm of the Hessian of ff on the ball of radius δ\delta about yy. If Kδ≤g/2K \delta \le g/2, then

∣∣f(x)∣∣∇f(x)∣−δ∣≤3Kg δ2.\left| \frac{\lvert f(x) \rvert}{\lvert \nabla f(x) \rvert} - \delta \right| \le \frac{3 K}{g}\, \delta^2 .

Proof. Since ∇f(y)≠0\nabla f(y) \ne 0, ZZ is a smooth hypersurface near yy, and yy minimizes ∣x−z∣2\lvert x - z \rvert^2 over z∈Zz \in Z. By a Lagrange multiplier, x−y=μ∇f(y)x - y = \mu \nabla f(y) for some μ\mu, so ∇f(y)⋅(x−y)=±gδ\nabla f(y) \cdot (x - y) = \pm g \delta. By Taylor's theorem with the remainder bounded by KK, f(x)=f(y)+∇f(y)⋅(x−y)+Rf(x) = f(y) + \nabla f(y) \cdot (x - y) + R with f(y)=0f(y) = 0 and ∣R∣≤Kδ2/2\lvert R \rvert \le K \delta^2 / 2, so ∣∣f(x)∣−gδ∣≤Kδ2/2\bigl| \lvert f(x) \rvert - g \delta \bigr| \le K \delta^2 / 2. Also ∣∇f(x)−∇f(y)∣≤Kδ\lvert \nabla f(x) - \nabla f(y) \rvert \le K \delta, so ∣∣∇f(x)∣−g∣≤Kδ\bigl| \lvert \nabla f(x) \rvert - g \bigr| \le K \delta, and ∣∇f(x)∣≥g−Kδ≥g/2\lvert \nabla f(x) \rvert \ge g - K\delta \ge g/2. Then

∣∣f(x)∣−δ∣∇f(x)∣∣≤∣∣f(x)∣−gδ∣+δ∣g−∣∇f(x)∣∣≤32Kδ2,\bigl| \lvert f(x) \rvert - \delta \lvert \nabla f(x) \rvert \bigr| \le \bigl| \lvert f(x) \rvert - g \delta \bigr| + \delta \bigl| g - \lvert \nabla f(x) \rvert \bigr| \le \tfrac{3}{2} K \delta^2 ,

and division by ∣∇f(x)∣≥g/2\lvert \nabla f(x) \rvert \ge g/2 gives the claim. □\square

So ∣f∣/∣∇f∣\lvert f \rvert / \lvert \nabla f \rvert is the geometric distance up to an error of order δ2\delta^2, and ∑if(xi)2/∣∇f(xi)∣2\sum_i f(x_i)^2 / \lvert \nabla f(x_i) \rvert^2 (the Sampson cost) is the sum of squared distances up to terms of order δ3\delta^3. Taubin's cost replaces the sum of the ratios by the ratio of the sums. That step is an approximation and is not proved to be close here; when ∣∇f∣\lvert \nabla f \rvert is the same at all data points the two agree up to the factor mm.

Lemma 2 (the cost as a quotient). For every aa with aTNa>0a^{\mathsf T} N a > 0,

q(a)=∑ifa(xi)2∑i∣∇fa(xi)∣2=aTMaaTNa.q(a) = \frac{\sum_i f_a(x_i)^2}{\sum_i \lvert \nabla f_a(x_i) \rvert^2} = \frac{a^{\mathsf T} M a}{a^{\mathsf T} N a} .

Proof. fa(xi)=φ(xi)Taf_a(x_i) = \varphi(x_i)^{\mathsf T} a, so fa(xi)2=aTφ(xi)φ(xi)Taf_a(x_i)^2 = a^{\mathsf T} \varphi(x_i) \varphi(x_i)^{\mathsf T} a. ∇fa(xi)=J(xi)Ta\nabla f_a(x_i) = J(x_i)^{\mathsf T} a, so ∣∇fa(xi)∣2=aTJ(xi)J(xi)Ta\lvert \nabla f_a(x_i) \rvert^2 = a^{\mathsf T} J(x_i) J(x_i)^{\mathsf T} a. Sum over ii. □\square

Lemma 3 (eliminating the constant). Let φn=κ≠0\varphi_n = \kappa \ne 0 be constant and the others not, write a=(b,c)a = (b, c) with c=anc = a_n, and let M′=Mbb−MbcMcb/MccM' = M_{bb} - M_{bc} M_{cb} / M_{cc} as in line L6. Then Mcc=mκ2>0M_{cc} = m \kappa^2 > 0, aTNa=bTNbbba^{\mathsf T} N a = b^{\mathsf T} N_{bb} b, and for fixed bb the numerator aTMaa^{\mathsf T} M a is smallest at c=−Mcbb/Mccc = -M_{cb} b / M_{cc}, where it equals bTM′b≥0b^{\mathsf T} M' b \ge 0. So min⁡aq(a)=min⁡b≠0bTM′b/bTNbbb\min_a q(a) = \min_{b \ne 0} b^{\mathsf T} M' b / b^{\mathsf T} N_{bb} b, and a minimizer bb of the right side gives the minimizer (b,−Mcbb/Mcc)(b, -M_{cb} b / M_{cc}) of the left side.

Proof. ∇φn=0\nabla \varphi_n = 0, so row and column nn of NN are zero, which gives the formula for aTNaa^{\mathsf T} N a; also aTNa>0a^{\mathsf T} N a > 0 forces b≠0b \ne 0. Next, aTMa=bTMbbb+2c Mcbb+c2Mcca^{\mathsf T} M a = b^{\mathsf T} M_{bb} b + 2 c\, M_{cb} b + c^2 M_{cc} is a quadratic in cc with positive leading coefficient; its minimum is at the stated cc, with value bTMbbb−(Mcbb)2/Mcc=bTM′bb^{\mathsf T} M_{bb} b - (M_{cb} b)^2 / M_{cc} = b^{\mathsf T} M' b, which is at least 00 because it is a value of aTMa=∥Da∥2a^{\mathsf T} M a = \lVert D a \rVert^2. The denominator does not depend on cc, so minimizing qq over cc first and then over bb gives the claim. Without a constant basis function, take M′=MM' = M and skip this step. □\square

Lemma 4 (the eigen step). Let Nbb=LLTN_{bb} = L L^{\mathsf T} with LL lower triangular and invertible (line L7, which fails exactly when NbbN_{bb} is not positive definite), and C=L−1M′L−TC = L^{-1} M' L^{-\mathsf T}. If yy is a unit eigenvector of the smallest eigenvalue λ\lambda of CC and b=L−Tyb = L^{-\mathsf T} y, then bb minimizes bTM′b/bTNbbbb^{\mathsf T} M' b / b^{\mathsf T} N_{bb} b, the minimum is λ≥0\lambda \ge 0, and M′b=λNbbbM' b = \lambda N_{bb} b.

Proof. The map b↦y=LTbb \mapsto y = L^{\mathsf T} b is a bijection of the nonzero vectors, and bTM′b/bTNbbb=yTCy/yTyb^{\mathsf T} M' b / b^{\mathsf T} N_{bb} b = y^{\mathsf T} C y / y^{\mathsf T} y. CC is symmetric, so by the spectral theorem this Rayleigh quotient has minimum λ\lambda, reached at yy. λ≥0\lambda \ge 0 because M′M' is positive semidefinite by Lemma 3. Finally M′b=LCLTb=LCy=λLy=λLLTb=λNbbbM' b = L C L^{\mathsf T} b = L C y = \lambda L y = \lambda L L^{\mathsf T} b = \lambda N_{bb} b. □\square

Theorem 1 (correctness). If NbbN_{bb} is positive definite, the algorithm returns a unit vector aa that minimizes qq over all aa with aTNa>0a^{\mathsf T} N a > 0, and λ=q(a)\lambda = q(a).

Proof. Lemmas 3 and 4 give the minimizer (b,c)(b, c); line L10 only scales it, and qq does not change under scaling. □\square

Theorem 2 (exact on noise-free data). Suppose every xix_i lies on fa∗=0f_{a^*} = 0, where a∗a^* has a nonconstant part b∗≠0b^* \ne 0, that NbbN_{bb} is positive definite, and that the null space of DD is spanned by a∗a^*. Then λ=0\lambda = 0 and the algorithm returns ±a∗/∣a∗∣\pm a^* / \lvert a^* \rvert.

Proof. Da∗=0D a^* = 0, so q(a∗)=0q(a^*) = 0; b∗≠0b^* \ne 0 gives a∗TNa∗>0a^{*\mathsf T} N a^* > 0. Since q≥0q \ge 0, the minimum is 00, so λ=0\lambda = 0 by Theorem 1. The returned aa has q(a)=0q(a) = 0, so ∥Da∥2=aTMa=0\lVert D a \rVert^2 = a^{\mathsf T} M a = 0, and aa is in the null space of DD, which is the span of a∗a^*. It is a unit vector, so it is ±a∗/∣a∗∣\pm a^* / \lvert a^* \rvert. □\square

Theorem 3 (invariance). Let T(x)=sRx+tT(x) = s R x + t with s>0s > 0, RR orthogonal, and suppose that f↦f∘T−1f \mapsto f \circ T^{-1} maps the span of the basis onto itself (true for all polynomials of degree at most kk, and for the circle and sphere family A∣x∣2+B⋅x+CA \lvert x \rvert^2 + B \cdot x + C). If ff minimizes Taubin's cost for the points xix_i, then f∘T−1f \circ T^{-1} minimizes it for the points T(xi)T(x_i), and its zero set is the image under TT of the zero set of ff.

Proof. Let g=f∘T−1g = f \circ T^{-1}. Then g(Txi)=f(xi)g(T x_i) = f(x_i), and by the chain rule ∇g(Tx)=s−1R ∇f(x)\nabla g(T x) = s^{-1} R\, \nabla f(x), so ∣∇g(Txi)∣=∣∇f(xi)∣/s\lvert \nabla g(T x_i) \rvert = \lvert \nabla f(x_i) \rvert / s. Hence the cost of gg on the moved points is s2s^2 times the cost of ff on the old points. The map f↦f∘T−1f \mapsto f \circ T^{-1} is a linear bijection of the family, so it maps minimizers to minimizers. Finally g(z)=0g(z) = 0 exactly when f(T−1z)=0f(T^{-1} z) = 0. □\square

■\blacksquare

Complexity

Building MM costs Θ(mn2)\Theta(m n^2) and building NN costs Θ(mn2d)\Theta(m n^2 d). The Cholesky factorization and the two triangular solves of line L8 cost Θ(n3)\Theta(n^3), and each Jacobi sweep costs Θ(n3)\Theta(n^3), so the total is Θ(mn2d+sn3)\Theta(m n^2 d + s n^3) on the real RAM, with ss sweeps, usually fewer than ten. For a conic n=6n = 6 and for a quadric surface n=10n = 10, so the cost is linear in the number of points with a small constant. The extra space is Θ(n2)\Theta(n^2); the points are read once.

Properties

  • Direct. No starting guess and no iteration other than the eigensolver.
  • Exact on exact data, and invariant under rotations, translations and uniform scaling of the data, for families closed under these maps.
  • Approximate distance. It minimizes a quotient of sums of algebraic distances and squared gradients, an approximation of the first-order distance, not the geometric distance.
  • Small bias. Much smaller than the bias of the plain algebraic fit in the measured and the published circle results, but not zero.
  • No type control. The best member of the family is returned, whatever its type: a hyperbola may fit an elliptic arc, and a circle fit may return a line (A=0A = 0).

Variants and improvements

  • Sampson fit. Minimize ∑if(xi)2/∣∇f(xi)∣2\sum_i f(x_i)^2 / \lvert \nabla f(x_i) \rvert^2 itself, by refitting with the weights 1/∣∇faold(xi)∣21 / \lvert \nabla f_{a_{\text{old}}}(x_i) \rvert^2 from the previous estimate, or by Gauss-Newton. Sampson did this for conics in 1982.
  • Hyper fit. A different NN, found by Al-Sharadqah and Chernov for circles, removes the leading term of the bias; it is in Chernov's book.
  • Geometric fit. Use the Taubin result as the start of a Gauss-Newton or Levenberg-Marquardt fit of the orthogonal distances, as on the geometric primitive fitting page.
  • Ellipse-specific fit. When the curve must be an ellipse, the constraint 4ac−b2=14ac - b^2 = 1 of Fitzgibbon, Pilu and Fisher replaces NN.
  • Space curves. Taubin also fits curves in space as the intersection of two implicit surfaces, with the same first-order distance built from both gradients.

When to use it

Use it for circles, spheres, conics and quadrics when a fast fit without a starting guess is needed and the points may cover only part of the curve, as for fillets, holes and partial cylinders in reverse engineering and for the reference features of inspection. Use the plain algebraic fit only when the points cover the whole curve and speed matters most. Use the geometric fit after it when the result goes into a dimension or a tolerance check, since standards define those by orthogonal distances.

Pitfalls

  • A singular NN. The constant must be eliminated, as in lines L5 and L6; a general eigensolver on a singular NN returns infinite eigenvalues or garbage. Points on a line make NbbN_{bb} singular for conics, and the code raises an error.
  • Wrong type of curve. The fit may return a hyperbola for an elliptic arc, or a pair of lines. Check the type before use.
  • Outliers. One point far from the curve can dominate both sums. Remove outliers first, for example by RANSAC.
  • Conditioning. As with every polynomial fit, center and scale the data before forming MM and NN; the invariance theorem says the answer does not change in exact arithmetic, but rounding does.
  • Reading λ\lambda as an error. λ\lambda is a weighted mean of squared first-order distances, not the mean or the largest geometric distance. For a tolerance check compute the true distances.

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.

re1lin.pyI0RawGitHub
# 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]
taubin_fitting.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/taubin-fitting/. The authors are listed in prov/4TBMTK.jsonl.

"""Taubin's gradient-weighted algebraic fit (Taubin, 1991).

The model is an implicit curve or surface f(x) = sum_j a_j phi_j(x) = 0, with
fixed polynomial basis functions phi_j. The fit minimizes

    sum_i f(x_i)^2 / sum_i |grad f(x_i)|^2 = a^T M a / a^T N a,

with M = sum_i phi(x_i) phi(x_i)^T and N = sum_i J(x_i) J(x_i)^T, where J is
the Jacobian of phi. The minimum is the smallest eigenvalue of M a = lambda N a.
N is singular when the basis holds a constant function, so the constant
coefficient is eliminated first (a Schur complement of M), and the rest is a
symmetric eigenproblem after a Cholesky factorization of N.

A basis function is a polynomial, stored as a dict from exponent tuples to
coefficients: {(2, 0): 1, (0, 2): 1} is x^2 + y^2.
"""

from typing import Dict, List, Sequence, Tuple

from re1lin import cholesky, dot, jacobi_eigen, lower_solve, norm, transpose, upper_solve_t

Poly = Dict[Tuple[int, ...], object]


def monomials(dim: int, degree: int) -> List[Poly]:
    """All monomials of total degree at most degree in dim variables, highest degree first, the constant last."""
    out: List[Tuple[int, ...]] = []

    def rec(prefix: Tuple[int, ...], left: int, k: int) -> None:
        if k == dim - 1:
            out.append(prefix + (left,))
            return
        for e in range(left, -1, -1):
            rec(prefix + (e,), left - e, k + 1)

    for total in range(degree, -1, -1):
        rec((), total, 0)
    return [{e: 1} for e in out]


def conic_basis() -> List[Poly]:
    """x^2, xy, y^2, x, y, 1: the general conic."""
    return monomials(2, 2)


def circle_basis(dim: int = 2) -> List[Poly]:
    """|x|^2, x_1, ..., x_dim, 1: circles (dim 2) or spheres (dim 3), with lines or planes as limits."""
    sq = {tuple(2 if k == j else 0 for k in range(dim)): 1 for j in range(dim)}
    lin = [{tuple(1 if k == j else 0 for k in range(dim)): 1} for j in range(dim)]
    return [sq] + lin + [{tuple([0] * dim): 1}]


def evaluate(p: Poly, x: Sequence):
    total = 0
    for e, c in p.items():
        t = c
        for xk, ek in zip(x, e):
            if ek:
                t = t * xk ** ek
        total += t
    return total


def gradient(p: Poly, x: Sequence) -> list:
    g = []
    for k in range(len(x)):
        s = 0
        for e, c in p.items():
            if e[k] == 0:
                continue
            t = c * e[k]
            for j, (xj, ej) in enumerate(zip(x, e)):
                ej = ej - 1 if j == k else ej
                if ej:
                    t = t * xj ** ej
            s += t
        g.append(s)
    return g


def implicit_value(a: Sequence[float], basis: List[Poly], x: Sequence) -> float:
    """f(x) = sum_j a_j phi_j(x)."""
    return sum(aj * evaluate(p, x) for aj, p in zip(a, basis))


def first_order_distance(a: Sequence[float], basis: List[Poly], x: Sequence) -> float:
    """|f(x)| / |grad f(x)|, the first-order approximation of the distance from x to f = 0."""
    g = [0.0] * len(x)
    for aj, p in zip(a, basis):
        for k, v in enumerate(gradient(p, x)):
            g[k] += aj * v
    return abs(float(implicit_value(a, basis, x))) / norm(g)


def taubin_fit(points: Sequence[Sequence], basis: List[Poly]) -> Tuple[List[float], float]:
    """Taubin's fit of the implicit curve sum_j a_j phi_j(x) = 0 to the points.

    Precondition: the basis functions are linearly independent, at most one of
    them is a constant and then it is the last one, and no nonzero combination
    of the nonconstant ones has a zero gradient at every point (N restricted to
    them is positive definite); otherwise ValueError. Points may be int,
    Fraction or float; M and N are then exact, the eigen step is in floats.
    Returns (a, lam): unit coefficients and the smallest eigenvalue lam, the
    minimum of sum f^2 / sum |grad f|^2.
    Cost: Theta(m n^2 d) to build M and N for m points, n basis functions in
    dimension d, plus Theta(n^3) per Jacobi sweep.
    """
    n = len(basis)
    consts = [j for j, p in enumerate(basis) if all(sum(e) == 0 for e in p)]
    if len(consts) > 1 or (consts and consts[0] != n - 1):
        raise ValueError("at most one constant basis function, placed last")
    M = [[0] * n for _ in range(n)]                                     # @line L1
    N = [[0] * n for _ in range(n)]
    for x in points:                                                    # @line L2
        u = [evaluate(p, x) for p in basis]
        J = [gradient(p, x) for p in basis]
        for j in range(n):
            for k in range(n):
                M[j][k] += u[j] * u[k]                                  # @line L3
                N[j][k] += dot(J[j], J[k])                              # @line L4
    nb = n - 1 if consts else n                                         # @line L5
    if consts:
        mcc = float(M[n - 1][n - 1])
        Mp = [[float(M[j][k]) - float(M[j][n - 1]) * float(M[n - 1][k]) / mcc for k in range(nb)]
              for j in range(nb)]                                       # @line L6
    else:
        Mp = [[float(M[j][k]) for k in range(nb)] for j in range(nb)]
    Nb = [[float(N[j][k]) for k in range(nb)] for j in range(nb)]
    L = cholesky(Nb, 1e-12)                                             # @line L7
    X = transpose([lower_solve(L, col) for col in Mp])  # X = L^-1 M', solved column by column (M' is symmetric)
    C = [lower_solve(L, row) for row in X]              # column k of C^T is L^-1 (row k of X), so C = L^-1 M' L^-T
    C = [[(C[j][k] + C[k][j]) / 2 for k in range(nb)] for j in range(nb)]
    vals, vecs = jacobi_eigen(C)                                        # @line L8
    lam, y = vals[0], vecs[0]
    b = upper_solve_t(L, y)                                             # @line L9
    a = list(b)
    if consts:
        a.append(-sum(float(M[n - 1][k]) * b[k] for k in range(nb)) / mcc)
    s = norm(a)
    return [v / s for v in a], max(lam, 0.0)                            # @line L10
test_taubin_fitting.py 274 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/taubin-fitting/. The authors are listed in prov/4TBMTK.jsonl.

import random
import unittest
from fractions import Fraction as F
from math import cos, pi, sin, sqrt

from re1lin import nullspace
from taubin_fitting import (circle_basis, conic_basis, first_order_distance, monomials, taubin_fit)


# ---- independent helpers, written out by hand for conics ----


def conic_row(p):
    x, y = p
    return [x * x, x * y, y * y, x, y, 1]


def conic_grad_rows(p):
    x, y = p
    return [(2 * x, 0), (y, x), (0, 2 * y), (1, 0), (0, 1), (0, 0)]


def taubin_cost(a, pts):
    """sum f^2 / sum |grad f|^2 for the conic with coefficients a."""
    num = sum(sum(c * v for c, v in zip(a, conic_row(p))) ** 2 for p in pts)
    den = 0.0
    for p in pts:
        g = conic_grad_rows(p)
        gx = sum(c * r[0] for c, r in zip(a, g))
        gy = sum(c * r[1] for c, r in zip(a, g))
        den += gx * gx + gy * gy
    return float(num) / float(den)


def same_up_to_sign(a, b, tol):
    nb = sqrt(sum(float(v) ** 2 for v in b))
    bu = [float(v) / nb for v in b]
    d1 = max(abs(x - y) for x, y in zip(a, bu))
    d2 = max(abs(x + y) for x, y in zip(a, bu))
    return min(d1, d2) <= tol


def circle_of(a):
    A, B, C, D = a
    cx, cy = -B / (2 * A), -C / (2 * A)
    return cx, cy, sqrt(cx * cx + cy * cy - D / A)


def rational_unit_circle(s):
    s = F(s)
    return (1 - s * s) / (1 + s * s), 2 * s / (1 + s * s)


def rational_unit_hyperbola(s):
    s = F(s)
    return (s + 1 / s) / 2, (s - 1 / s) / 2


def affine_conic(B, h, signs):
    """Coefficients of sum_k signs[k] * (B_k . p + h_k)^2 - 1 on x^2, xy, y^2, x, y, 1."""
    a = [F(0)] * 6
    for k in range(2):
        b0, b1, hk, sg = B[k][0], B[k][1], h[k], signs[k]
        a[0] += sg * b0 * b0
        a[1] += sg * 2 * b0 * b1
        a[2] += sg * b1 * b1
        a[3] += sg * 2 * b0 * hk
        a[4] += sg * 2 * b1 * hk
        a[5] += sg * hk * hk
    a[5] -= 1
    return a


class TestWorkedExample(unittest.TestCase):
    def test_ellipse_of_the_page(self):
        pts = [(F(2), F(0)), (F(8, 5), F(3, 5)), (F(6, 5), F(4, 5)), (F(0), F(1)), (F(-6, 5), F(4, 5)),
               (F(6, 5), F(-4, 5))]
        truth = [1, 0, 4, 0, 0, -4]
        # exact: the design matrix has the one-dimensional null space spanned by the true conic
        ns = nullspace([conic_row(p) for p in pts])
        self.assertEqual(len(ns), 1)
        self.assertEqual([v / ns[0][0] for v in ns[0]], truth)
        a, lam = taubin_fit(pts, conic_basis())
        self.assertTrue(same_up_to_sign(a, truth, 1e-10))
        self.assertLess(lam, 1e-12)

    def test_monomials(self):
        self.assertEqual(len(monomials(2, 2)), 6)
        self.assertEqual(len(monomials(3, 2)), 10)
        self.assertEqual(len(monomials(3, 4)), 35)
        self.assertEqual(monomials(2, 2)[-1], {(0, 0): 1})
        self.assertEqual(monomials(2, 2)[0], {(2, 0): 1})


class TestNoiseFree(unittest.TestCase):
    def test_random_ellipses_and_hyperbolas_exact(self):
        rng = random.Random(7)
        for trial in range(40):
            while True:
                B = [[F(rng.randint(-4, 4), rng.randint(1, 3)) for _ in range(2)] for _ in range(2)]
                if B[0][0] * B[1][1] - B[0][1] * B[1][0] != 0:
                    break
            h = [F(rng.randint(-5, 5), rng.randint(1, 3)) for _ in range(2)]
            hyper = trial % 2 == 1
            signs = (1, -1) if hyper else (1, 1)
            truth = affine_conic(B, h, signs)
            det = B[0][0] * B[1][1] - B[0][1] * B[1][0]
            inv = [[B[1][1] / det, -B[0][1] / det], [-B[1][0] / det, B[0][0] / det]]
            params = rng.sample([F(n, d) for n in range(-9, 10) for d in (1, 2, 3, 5) if n != 0], 7)
            pts = []
            for s in params:
                q = rational_unit_hyperbola(s) if hyper else rational_unit_circle(s)
                q = (q[0] - h[0], q[1] - h[1])          # p = B^-1 (q - h)
                pts.append((inv[0][0] * q[0] + inv[0][1] * q[1], inv[1][0] * q[0] + inv[1][1] * q[1]))
            # exact: every point is on the true conic, and the points fix it
            for p in pts:
                self.assertEqual(sum(c * v for c, v in zip(truth, conic_row(p))), 0)
            self.assertEqual(len(nullspace([conic_row(p) for p in pts])), 1)
            a, lam = taubin_fit(pts, conic_basis())
            self.assertTrue(same_up_to_sign(a, truth, 1e-7), (trial, a, truth))
            self.assertLess(lam, 1e-9)

    def test_five_points_fix_a_conic(self):
        pts = [(F(x), F(y)) for x, y in [(2, 0), (F(6, 5), F(4, 5)), (0, 1), (F(-6, 5), F(4, 5)), (-2, 0)]]
        a, lam = taubin_fit(pts, conic_basis())
        self.assertTrue(same_up_to_sign(a, [1, 0, 4, 0, 0, -4], 1e-9))

    def test_circle_on_a_short_arc(self):
        units = [(F(4, 5), F(3, 5)), (F(12, 13), F(5, 13)), (F(15, 17), F(8, 17)), (F(24, 25), F(7, 25)), (1, 0)]
        pts = [(3 + 5 * c, -2 + 5 * s) for c, s in units]
        cx, cy, r = circle_of(taubin_fit(pts, circle_basis())[0])
        self.assertAlmostEqual(cx, 3, places=8)
        self.assertAlmostEqual(cy, -2, places=8)
        self.assertAlmostEqual(r, 5, places=8)

    def test_sphere(self):
        units = [(1, 2, 2), (2, 3, 6), (2, 6, 9), (1, 4, 8), (4, 4, 7), (6, 6, 7), (-1, 2, -2)]
        pts = []
        for u in units:
            n = sqrt(sum(v * v for v in u))
            pts.append(tuple(c + 2 * F(v) / int(round(n)) for c, v in zip((1, -1, 3), u)))
        a, lam = taubin_fit(pts, circle_basis(3))
        A = a[0]
        c = [-a[k] / (2 * A) for k in (1, 2, 3)]
        r = sqrt(sum(v * v for v in c) - a[4] / A)
        for got, want in zip(c, (1, -1, 3)):
            self.assertAlmostEqual(got, want, places=8)
        self.assertAlmostEqual(r, 2, places=8)

    def test_family_without_constant(self):
        # lines through the origin, a x + b y = 0: no constant, the elimination step is skipped
        basis = [{(1, 0): 1}, {(0, 1): 1}]
        pts = [(4, 3), (8, 6), (-4, -3), (F(2), F(3, 2))]
        a, lam = taubin_fit(pts, basis)
        self.assertTrue(same_up_to_sign(a, [3, -4], 1e-12))


class TestEdgeCases(unittest.TestCase):
    def test_collinear_points_are_rejected_for_conics(self):
        pts = [(i, 2 * i + 1) for i in range(6)]
        with self.assertRaises(ValueError):
            taubin_fit(pts, conic_basis())

    def test_two_constants_are_rejected(self):
        with self.assertRaises(ValueError):
            taubin_fit([(0, 0), (1, 0), (0, 1)], [{(1, 0): 1}, {(0, 0): 1}, {(0, 0): 2}])

    def test_constant_not_last_is_rejected(self):
        with self.assertRaises(ValueError):
            taubin_fit([(0, 0), (1, 0), (0, 1)], [{(0, 0): 1}, {(1, 0): 1}, {(0, 1): 1}])


class TestFirstOrderDistance(unittest.TestCase):
    def test_circle_closed_form(self):
        basis = circle_basis()
        a = [1, 0, 0, -1]
        for d in (0.1, 0.01, 0.001, -0.01):
            got = first_order_distance(a, basis, (1 + d, 0.0))
            self.assertAlmostEqual(got - abs(d), -d * d / (2 * (1 + d)) * (1 if d > 0 else -1), places=12)
            self.assertLessEqual(abs(got - abs(d)), d * d)

    def test_ellipse_against_brute_force_distance(self):
        # f = x^2 / 4 + y^2 - 1: Hessian bound K = 2, gradient on the curve at least g = 1, bound 6 delta^2
        basis = conic_basis()
        a = [0.25, 0, 1, 0, 0, -1]
        rng = random.Random(11)

        def dist(p):
            best = min(range(4000), key=lambda k: (p[0] - 2 * cos(2 * pi * k / 4000)) ** 2
                       + (p[1] - sin(2 * pi * k / 4000)) ** 2)
            lo, hi = 2 * pi * (best - 1) / 4000, 2 * pi * (best + 1) / 4000
            for _ in range(80):
                m1, m2 = lo + (hi - lo) / 3, hi - (hi - lo) / 3
                f1 = (p[0] - 2 * cos(m1)) ** 2 + (p[1] - sin(m1)) ** 2
                f2 = (p[0] - 2 * cos(m2)) ** 2 + (p[1] - sin(m2)) ** 2
                if f1 < f2:
                    hi = m2
                else:
                    lo = m1
            t = (lo + hi) / 2
            return sqrt((p[0] - 2 * cos(t)) ** 2 + (p[1] - sin(t)) ** 2)

        for _ in range(60):
            t = rng.uniform(0, 2 * pi)
            nx, ny = cos(t) / 2, 2 * sin(t) / 2       # gradient direction at (2 cos t, sin t)
            nn = sqrt(nx * nx + ny * ny)
            s = rng.uniform(-0.05, 0.05)
            p = (2 * cos(t) + s * nx / nn, sin(t) + s * ny / nn)
            delta = dist(p)
            self.assertLessEqual(abs(first_order_distance(a, basis, p) - delta), 6 * delta * delta + 1e-12)


class TestRandomizedNoisy(unittest.TestCase):
    def test_global_minimum_against_other_coefficients(self):
        rng = random.Random(2026)
        for trial in range(25):
            pts = []
            a0, b0 = rng.uniform(1, 3), rng.uniform(0.5, 1.5)
            for i in range(25):
                t = rng.uniform(0, 1.5 * pi)
                pts.append((a0 * cos(t) + rng.gauss(0, 0.05), b0 * sin(t) + rng.gauss(0, 0.05)))
            a, lam = taubin_fit(pts, conic_basis())
            q = taubin_cost(a, pts)
            self.assertAlmostEqual(q, lam, delta=1e-9 * max(1.0, lam))
            self.assertLessEqual(q, taubin_cost([1 / a0 ** 2, 0, 1 / b0 ** 2, 0, 0, -1], pts) + 1e-12)
            for _ in range(200):
                other = [v + rng.gauss(0, 0.05) for v in a]
                self.assertLessEqual(q, taubin_cost(other, pts) + 1e-12)
                other = [rng.gauss(0, 1) for _ in a]
                self.assertLessEqual(q, taubin_cost(other, pts) + 1e-12)

    def test_generalized_eigen_equation(self):
        rng = random.Random(5)
        pts = [(rng.uniform(-2, 2), rng.uniform(-1, 1)) for _ in range(30)]
        a, lam = taubin_fit(pts, conic_basis())
        M = [[0.0] * 6 for _ in range(6)]
        N = [[0.0] * 6 for _ in range(6)]
        for p in pts:
            u = conic_row(p)
            g = conic_grad_rows(p)
            for j in range(6):
                for k in range(6):
                    M[j][k] += u[j] * u[k]
                    N[j][k] += g[j][0] * g[k][0] + g[j][1] * g[k][1]
        for j in range(6):
            lhs = sum(M[j][k] * a[k] for k in range(6))
            rhs = lam * sum(N[j][k] * a[k] for k in range(6))
            self.assertAlmostEqual(lhs, rhs, delta=1e-8 * max(1.0, max(abs(v) for v in M[j])))

    def test_invariance_under_similarity(self):
        rng = random.Random(3)
        for _ in range(20):
            pts = []
            for i in range(15):
                t = rng.uniform(0, pi / 2)
                pts.append((1 + 2 * cos(t) + rng.gauss(0, 0.03), -1 + 2 * sin(t) + rng.gauss(0, 0.03)))
            cx, cy, r = circle_of(taubin_fit(pts, circle_basis())[0])
            th, s, tx, ty = rng.uniform(0, 2 * pi), rng.uniform(0.2, 5), rng.uniform(-9, 9), rng.uniform(-9, 9)

            def T(p):
                return (s * (cos(th) * p[0] - sin(th) * p[1]) + tx, s * (sin(th) * p[0] + cos(th) * p[1]) + ty)

            dx, dy, dr = circle_of(taubin_fit([T(p) for p in pts], circle_basis())[0])
            ex, ey = T((cx, cy))
            self.assertAlmostEqual(dx, ex, delta=1e-7 * s)
            self.assertAlmostEqual(dy, ey, delta=1e-7 * s)
            self.assertAlmostEqual(dr, s * r, delta=1e-7 * s)


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

History

Bookstein fitted conics by algebraic distance in 1979, and Sampson in 1982 proposed dividing the algebraic distance by the gradient norm and refining Bookstein's fit iteratively with this weight. Taubin's 1991 paper took the same first-order distance for implicit curves and surfaces of any degree and for space curves, and observed that replacing the mean of the quotients by a quotient of means turns the fit into a single generalized eigenproblem; he used it to segment edge maps and range images. Chernov and coworkers later analysed the statistical bias of the algebraic circle fits and found that the Taubin fit has a much smaller bias than the Kasa fit and a smaller one than the Pratt fit, and Al-Sharadqah and Chernov derived the hyper fit, which removes the leading bias term.

References

  1. Gabriel Taubin, Estimation of planar curves, surfaces, and nonplanar space curves defined by implicit equations with applications to edge and range image segmentation, IEEE Transactions on Pattern Analysis and Machine Intelligence 13(11), 1991, 1115 to 1138, the first-order approximation of the distance to an implicit curve or surface, the approximate mean square distance as a quotient, its minimization as a generalized eigenproblem, and the use in segmentation
  2. Paul D. Sampson, Fitting conic sections to very scattered data, an iterative refinement of the Bookstein algorithm, Computer Graphics and Image Processing 18(1), 1982, 97 to 108, the algebraic distance divided by the gradient norm as an approximate distance for conics, minimized by reweighted algebraic fits
  3. Nikolai Chernov, Circular and Linear Regression, Fitting Circles and Lines by Least Squares, CRC Press, 2010, the Taubin circle fit, its comparison with the Kasa and Pratt fits, and the statistical analysis of the bias of algebraic circle fits

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