Algorithm Search⌘K

Algorithmresearch

Squared distance minimization

Also called SDM fitting, curvature-based squared distance minimization.

Wang, Pottmann and Liu's B-spline fitting that minimises a local quadratic model of the squared distance, which converges faster than point distance methods.

Time
Θ(s (b + 1) (S p² + m (S + k p²)) + s (m p² + n p²)) worst
Space
Θ(m + n p + S) extra
Where
S = the number of curve samples for the foot points; b = the number of energy evaluations per iteration; k = the number of Newton steps per foot point; m = the number of data points; n = the number of control points; p = the degree; s = the number of iterations
Properties
deterministicnot exactiterative
Origin
Wenping Wang, Helmut Pottmann, Yang Liu, 2006

Squared distance minimization (SDM) is an algorithm that fits a B-spline curve to a cloud of points by minimizing, at each step, a quadratic model of the squared distance from each point to the curve that takes the curvature of the curve into account. Parameter correction, which Wang, Pottmann and Liu call point distance minimization (PDM), models the squared distance from a data point XkX_k to the moving curve by the squared distance to its current foot point KkK_k, a model that is correct only far from the curve. Tangent distance minimization (TDM) uses the squared distance to the tangent line at KkK_k, which is correct only for points on a straight curve. SDM uses the second-order approximation of the squared distance function derived by Pottmann and Hofer: in the frame of the tangent TT and the normal NN at the foot point, with signed distance dd and radius of curvature ρ\rho,

F(y)≈dd−ρ((y−K)⋅T)2+((y−K)⋅N)2.F(y) \approx \frac{d}{d - \rho} \bigl( (y - K) \cdot T \bigr)^2 + \bigl( (y - K) \cdot N \bigr)^2 .

Both PDM and TDM are limits of this model. Since the model is quadratic in the control points, each SDM step is one linear least-squares problem, like a PDM step, but it converges in a few steps where PDM needs hundreds. Wang, Pottmann and Liu (2006) introduced the method and analyzed it as a quasi-Newton method; with a step-length control, as in the code here, the true error never increases.

In plain words

To fit a smooth curve to many points, we start from a rough curve and improve it step by step. At each step, every point pulls on the curve. The question is how hard each point should pull, and in which direction.

If a point pulls the curve straight toward itself, as in parameter correction, the curve also slides along itself, which does nothing useful and slows the fit down. If a point only pulls in the direction across the curve, the curve can slide freely, and the fit may jump. SDM uses the bend of the curve to decide. A point on the outside of a bend, or far away, also pulls a little along the curve; a point close to the curve on the inside of a bend pulls only across. With this rule the curve settles in a handful of steps.

The problem

Input. Points X1,…,XmX_1, \dots, X_m in the plane, a degree p≥2p \ge 2, a clamped knot vector UU with nn basis functions on [a,b][a, b], a starting control polygon PP, and a smoothing weight μ≥0\mu \ge 0.

Output. Control points PP of the curve CP(t)=∑iNi,p(t)PiC_P(t) = \sum_i N_{i,p}(t) P_i that make

f(P)=∑k=1mdist⁡(Xk,CP)2+μR(P)f(P) = \sum_{k=1}^{m} \operatorname{dist}(X_k, C_P)^2 + \mu R(P)

small, where dist⁡\operatorname{dist} is the orthogonal distance to the curve and R(P)=∑i∣Pi+1−2Pi+Pi−1∣2R(P) = \sum_i \lvert P_{i+1} - 2 P_i + P_{i-1} \rvert^2 is a roughness term. This is curve fitting with the geometric error, the same objective as parameter correction. It is nonlinear, and in general it has many local minima.

The algorithm

At a foot point K=C(t)K = C(t) with C′(t)≠0C'(t) \ne 0, let TT be the unit tangent, NN the unit normal (TT turned left by 9090 degrees), κ\kappa the signed curvature, so that the center of curvature is K+N/κK + N/\kappa and ρ=1/κ\rho = 1/\kappa, and d=(X−K)⋅Nd = (X - K) \cdot N the signed distance. The SDM weight is

w=dd−ρ=κdκd−1,w = \frac{d}{d - \rho} = \frac{\kappa d}{\kappa d - 1} ,

set to 00 when 0≤κd<10 \le \kappa d < 1, and to 11 when the foot point is an end of the curve.

  1. SDM(X_1..X_m, U, p, P, μ)
  2. 1P ← the starting control points
  3. 2repeat
  4. 3for each k: t_k ← foot point of X_k on C_P; K_k, T_k, N_k, κ_k, d_k at t_k
  5. 4w_k ← κ_k d_k / (κ_k d_k − 1), or 0 if 0 ≤ κ_k d_k < 1, or 1 at an end of the curve
  6. 5Q ← argmin over Q of Σ_k [ w_k ((C_Q(t_k) − X_k)·T_k)² + ((C_Q(t_k) − X_k)·N_k)² ] + μ R(Q)
  7. 6α ← 1; while f(P + α(Q − P)) > f(P) do α ← α / 2
  8. 7P ← P + α (Q − P)
  9. 8until the decrease of f is below a tolerance
  10. 9return P

Line L3. The foot point is a point projection problem: the code samples the curve, takes the nearest sample, and refines it with Newton steps on (C(t)−Xk)⋅C′(t)=0(C(t) - X_k) \cdot C'(t) = 0. TT, NN and κ=(C′×C′′)/∣C′∣3\kappa = (C' \times C'') / \lvert C' \rvert^3 come from the first two derivatives of the B-spline, as in the Frenet frame.

Line L4, the weight. At a true foot point κd≤1\kappa d \le 1, because the second derivative of ∣X−C(t)∣2\lvert X - C(t) \rvert^2 there is 2∣C′∣2(1−κd)≥02 \lvert C' \rvert^2 (1 - \kappa d) \ge 0. For a point on the outer side of the bend, κd<0\kappa d < 0 and ww lies in (0,1)(0, 1). For a point on the inner side, between the curve and its center of curvature, 0<κd<10 < \kappa d < 1 and the formula gives a negative ww: the true squared distance is not convex there. SDM then uses w=0w = 0, which is the tangent distance term; Wang, Pottmann and Liu treat this case the same way. When the foot point is an end of the curve, the distance is to that end point, and w=1w = 1 makes the term the squared distance to the end point.

Line L5. The term of point kk is a quadratic function of the new control points QQ, because CQ(tk)C_Q(t_k) is linear in QQ. So the minimum solves a linear system with 2n2n unknowns. Unlike in PDM, the two coordinates are coupled through TkT_k and NkN_k. Points with wk=0w_k = 0 do not constrain a slide along the curve; when all weights are 00, as on straight data, the system is singular, and the code adds a tiny damping term ν∣Q−P∣2\nu \lvert Q - P \rvert^2, as in Levenberg-Marquardt.

Lines L6 and L7. The model is accurate only near the current curve, so a full step can be too long. The code halves the step until the true energy ff does not increase; Wang, Pottmann and Liu discuss step control and regularization too. This makes the energy history monotone by construction.

Example

A quarter circle. The 2121 points (cos⁡φk,sin⁡φk)(\cos \varphi_k, \sin \varphi_k) with φk=π2(k/20)2\varphi_k = \tfrac{\pi}{2} (k/20)^2 are fitted by a cubic B-spline with the knots (0,0,0,0,12,1,1,1,1)(0, 0, 0, 0, \tfrac12, 1, 1, 1, 1) and μ=0\mu = 0, starting from the least-squares fit with chord-length parameters. The table gives the true squared distance error after each iteration; the parameter correction column uses the same start with all parameters corrected, the two end parameters included. The parameter correction page keeps the end parameters fixed, so its numbers for the same start are different.

iteration SDM parameter correction
0 6.634×10−76.634 \times 10^{-7} 6.634×10−76.634 \times 10^{-7}
1 4.077×10−94.077 \times 10^{-9} 6.489×10−76.489 \times 10^{-7}
2 1.587×10−91.587 \times 10^{-9} 6.403×10−76.403 \times 10^{-7}
3 1.552×10−91.552 \times 10^{-9} 6.326×10−76.326 \times 10^{-7}
10 1.545×10−91.545 \times 10^{-9} 5.920×10−75.920 \times 10^{-7}
200 1.492×10−71.492 \times 10^{-7}

SDM took full steps every time and reached in one step an error 3636 times smaller than parameter correction reached in 200200. The largest distance from a data point to the final SDM curve is 1.6×10−51.6 \times 10^{-5}.

A poor start. From the fit with uniform parameters, whose error is 5.231×10−55.231 \times 10^{-5}, SDM needed step halving in some iterations and stopped at 1.12×10−61.12 \times 10^{-6}, a local minimum: the curve starts beyond the first data point, and parameter correction from there makes no progress either. Parameter correction from the same uniform start was still at 1.604×10−51.604 \times 10^{-5} after 200200 iterations.

Noisy data. Forty points with noise σ=0.005\sigma = 0.005 on three quarters of a wavy loop, r=1+0.3cos⁡2φr = 1 + 0.3 \cos 2\varphi for 0≤φ≤3π20 \le \varphi \le \tfrac{3\pi}{2}, cubic with 88 control points, μ=10−6\mu = 10^{-6}, five noise samples: in 1515 iterations each, 6060 of the 7575 steps were full steps, and the energy fell from between 0.0220.022 and 0.0250.025 to between 0.00090.0009 and 0.00190.0019.

All numbers are measured with the code of this page.

Correctness

The correctness file proves:

  • The second-order model. If X=K+dNX = K + d N has the unique foot point KK on a C2C^2 curve, with κd<1\kappa d < 1, then the squared distance function FF satisfies F(X+v)=dd−ρ(v⋅T)2+(d+v⋅N)2+o(∣v∣2)F(X + v) = \frac{d}{d - \rho} (v \cdot T)^2 + (d + v \cdot N)^2 + o(\lvert v \rvert^2), the formula of the lead.
  • The limits. As d→0d \to 0 or κ→0\kappa \to 0, the weight tends to 00 and the model to the squared distance to the tangent line (TDM). As ∣d∣→∞\lvert d \rvert \to \infty on the outer side, the weight tends to 11 and the model to the squared distance to the foot point (PDM). With the clamp, 0≤w<10 \le w < 1 at every interior foot point.
  • The step. The model of line L5 is a sum of squares of linear functions of QQ, so its minimizers solve a linear system; with damping ν>0\nu > 0 the solution is unique.
  • Monotone energy. With the step control of line L6, ff never increases, and the loop stops.
  • Fixed point on exact data. If every data point lies on the current curve, the current control points minimize the model, so a nonsingular SDM step returns them unchanged.

Not proved here: that SDM converges, how fast, or to which minimum. Wang, Pottmann and Liu interpret SDM as a quasi-Newton method, TDM as the Gauss-Newton method and PDM as an alternating method with linear convergence, and report fast convergence of SDM in their experiments; the examples above agree, but they are measurements.

Proof: The SDM model is the second-order Taylor model of the squared distance, its weight lies between the tangent and the point distance, each step is a convex least-squares problem, the energy never increases, and exact data give a fixed pointfull

Setup. C:[a,b]→R2C : [a, b] \to \mathbb{R}^2 is a C2C^2 curve with C′(t)≠0C'(t) \ne 0. At a parameter tt let T=C′/∣C′∣T = C'/\lvert C' \rvert, let NN be TT turned left by 9090 degrees, and let κ\kappa be the signed curvature, so that

C′′=(∣C′∣)′ T+κ∣C′∣2N.(1)C'' = \bigl( \lvert C' \rvert \bigr)' \, T + \kappa \lvert C' \rvert^2 N . \tag{1}

For a point XX, F(X)=min⁡s∈[a,b]∣X−C(s)∣2F(X) = \min_{s \in [a, b]} \lvert X - C(s) \rvert^2 is the squared distance to the curve. A foot point of XX is a parameter t0t_0 where the minimum is attained; write K=C(t0)K = C(t_0) and d=(X−K)⋅Nd = (X - K) \cdot N. The SDM weight is w=κd/(κd−1)w = \kappa d / (\kappa d - 1); when κ≠0\kappa \ne 0 and ρ=1/κ\rho = 1/\kappa, this is d/(d−ρ)d / (d - \rho).

Lemma 1 (foot point conditions). If t0t_0 is a foot point of XX inside (a,b)(a, b), then X−K=dNX - K = d N and κd≤1\kappa d \le 1.

Proof. Let g(t)=∣X−C(t)∣2g(t) = \lvert X - C(t) \rvert^2. Since t0t_0 is an interior minimum, g′(t0)=−2(X−K)⋅C′(t0)=0g'(t_0) = -2 (X - K) \cdot C'(t_0) = 0, so X−KX - K is normal to the curve and equals dNd N. Also g′′(t0)≥0g''(t_0) \ge 0. Now g′′=2∣C′∣2−2(X−C)⋅C′′g'' = 2 \lvert C' \rvert^2 - 2 (X - C) \cdot C'', and by (1), (X−K)⋅C′′=dN⋅C′′=κd∣C′∣2(X - K) \cdot C'' = d N \cdot C'' = \kappa d \lvert C' \rvert^2. So g′′(t0)=2∣C′∣2(1−κd)≥0g''(t_0) = 2 \lvert C' \rvert^2 (1 - \kappa d) \ge 0, and κd≤1\kappa d \le 1. □\square

Theorem 1 (the second-order model). Let t0t_0 be the only foot point of XX, inside (a,b)(a, b), with κd<1\kappa d < 1. Then FF is C2C^2 near XX, and for small vv

F(X+v)=w(v⋅T)2+(d+v⋅N)2+o(∣v∣2).(2)F(X + v) = w (v \cdot T)^2 + (d + v \cdot N)^2 + o(\lvert v \rvert^2) . \tag{2}

Proof. Let G(t,Y)=(C(t)−Y)⋅C′(t)G(t, Y) = (C(t) - Y) \cdot C'(t). Then G(t0,X)=0G(t_0, X) = 0 and, by the computation of Lemma 1, ∂G/∂t=∣C′∣2+(C−Y)⋅C′′=∣C′∣2(1−κd)>0\partial G / \partial t = \lvert C' \rvert^2 + (C - Y) \cdot C'' = \lvert C' \rvert^2 (1 - \kappa d) > 0 at (t0,X)(t_0, X). By the implicit function theorem there is a C1C^1 function t(Y)t(Y) near XX with t(X)=t0t(X) = t_0 and G(t(Y),Y)=0G(t(Y), Y) = 0, and it is the only zero of G(⋅,Y)G(\cdot, Y) near t0t_0.

It is also the foot point of YY. Take Yj→XY_j \to X and foot points sjs_j of YjY_j. Every limit point ss of (sj)(s_j) satisfies ∣X−C(s)∣2=lim⁡F(Yj)=F(X)\lvert X - C(s) \rvert^2 = \lim F(Y_j) = F(X), because FF is continuous (it is a minimum of functions that are 11-Lipschitz in the distance). So ss is a foot point of XX, and s=t0s = t_0. Hence sj→t0s_j \to t_0, so sjs_j is an interior minimum of ∣Yj−C(s)∣2\lvert Y_j - C(s) \rvert^2, a zero of G(⋅,Yj)G(\cdot, Y_j) near t0t_0, and equal to t(Yj)t(Y_j) for large jj. So F(Y)=∣Y−C(t(Y))∣2F(Y) = \lvert Y - C(t(Y)) \rvert^2 near XX.

Differentiate: ∇F(Y)=2(Y−C(t))−2((Y−C(t))⋅C′(t))∇t=2(Y−C(t(Y)))\nabla F(Y) = 2 (Y - C(t)) - 2 \bigl( (Y - C(t)) \cdot C'(t) \bigr) \nabla t = 2 (Y - C(t(Y))), since the factor in parentheses is −G=0-G = 0. This is C1C^1, so FF is C2C^2, with ∇2F=2(I−C′ ∇tT)\nabla^2 F = 2 (I - C' \, \nabla t^{\mathsf T}). Differentiating G(t(Y),Y)=0G(t(Y), Y) = 0 gives ∂G∂t∇t−C′=0\frac{\partial G}{\partial t} \nabla t - C' = 0, so at XX

∇t=C′∣C′∣2(1−κd),∇2F(X)=2(I−TTT1−κd)=2(w TTT+NNT),\nabla t = \frac{C'}{\lvert C' \rvert^2 (1 - \kappa d)}, \qquad \nabla^2 F(X) = 2 \Bigl( I - \frac{T T^{\mathsf T}}{1 - \kappa d} \Bigr) = 2 \Bigl( w \, T T^{\mathsf T} + N N^{\mathsf T} \Bigr),

using I=TTT+NNTI = T T^{\mathsf T} + N N^{\mathsf T} and 1−11−κd=κdκd−1=w1 - \frac{1}{1 - \kappa d} = \frac{\kappa d}{\kappa d - 1} = w. Taylor's theorem with F(X)=d2F(X) = d^2 and ∇F(X)=2dN\nabla F(X) = 2 d N gives

F(X+v)=d2+2d (v⋅N)+w(v⋅T)2+(v⋅N)2+o(∣v∣2),F(X + v) = d^2 + 2 d \, (v \cdot N) + w (v \cdot T)^2 + (v \cdot N)^2 + o(\lvert v \rvert^2),

which is (2). With y=X+vy = X + v, (y−K)⋅T=v⋅T(y - K) \cdot T = v \cdot T and (y−K)⋅N=d+v⋅N(y - K) \cdot N = d + v \cdot N, so (2) is the model w((y−K)⋅T)2+((y−K)⋅N)2w ((y - K) \cdot T)^2 + ((y - K) \cdot N)^2 of the page. □\square

Theorem 2 (the weight and its limits). Let x=κdx = \kappa d.

  1. If x<0x < 0, then 0<w<10 < w < 1. If 0<x<10 < x < 1, then w<0w < 0. If x=0x = 0, then w=0w = 0.
  2. w→0w \to 0 as x→0x \to 0, that is, as d→0d \to 0 or κ→0\kappa \to 0, and then the model tends to ((y−K)⋅N)2((y - K) \cdot N)^2, the squared distance to the tangent line (TDM).
  3. w→1w \to 1 as x→−∞x \to -\infty, that is, as the point moves far away on the outer side, and then the model tends to ∣y−K∣2\lvert y - K \rvert^2, the squared distance to the foot point (PDM).
  4. With the clamp of line L4 (w=0w = 0 when 0≤x<10 \le x < 1), every interior foot point gets a weight in [0,1)[0, 1), and the end feet get w=1w = 1.

Proof. For x<0x < 0, w=∣x∣/(∣x∣+1)∈(0,1)w = \lvert x \rvert / (\lvert x \rvert + 1) \in (0, 1). For 0<x<10 < x < 1, the numerator is positive and the denominator negative. The limits follow from the continuity of x/(x−1)x / (x - 1) at 00 and from x/(x−1)=1/(1−1/x)→1x / (x - 1) = 1 / (1 - 1/x) \to 1. The two limit models follow by putting w=0w = 0 or w=1w = 1 in the model, with ∣y−K∣2=((y−K)⋅T)2+((y−K)⋅N)2\lvert y - K \rvert^2 = ((y - K) \cdot T)^2 + ((y - K) \cdot N)^2. By Lemma 1, x≤1x \le 1 at an interior foot point; x=1x = 1 makes the formula undefined and x∈[0,1)x \in [0, 1) is clamped to 00, so the weight lies in [0,1)[0, 1). □\square

Item 1 shows why line L4 clamps: for 0<κd<10 < \kappa d < 1, the true squared distance is not convex in the direction TT, and an unclamped model would have no minimum.

Theorem 3 (the step). Fix the foot parameters tkt_k, the frames and the weights wk∈[0,1]w_k \in [0, 1] of lines L3 and L4. The function

M(Q)=∑k[wk((CQ(tk)−Xk)⋅Tk)2+((CQ(tk)−Xk)⋅Nk)2]+μR(Q)+ν∣Q−P∣2M(Q) = \sum_k \Bigl[ w_k \bigl( (C_Q(t_k) - X_k) \cdot T_k \bigr)^2 + \bigl( (C_Q(t_k) - X_k) \cdot N_k \bigr)^2 \Bigr] + \mu R(Q) + \nu \lvert Q - P \rvert^2

with μ,ν≥0\mu, \nu \ge 0 is a convex quadratic function of the control points QQ. Its minimizers are the solutions of a linear system AQ=rA Q = r with AA symmetric positive semidefinite, and for ν>0\nu > 0 the minimizer is unique.

Proof. CQ(tk)=∑iNi,p(tk)QiC_Q(t_k) = \sum_i N_{i,p}(t_k) Q_i is linear in QQ, so each term in brackets, each second difference in R(Q)R(Q), and each coordinate of Q−PQ - P is an affine function ℓ(Q)=c⋅Q−e\ell(Q) = c \cdot Q - e. So M=∑jωjℓj(Q)2M = \sum_j \omega_j \ell_j(Q)^2 with weights ωj≥0\omega_j \ge 0. Then M(Q)=QTAQ−2rTQ+constM(Q) = Q^{\mathsf T} A Q - 2 r^{\mathsf T} Q + \text{const} with A=∑jωjcjcjTA = \sum_j \omega_j c_j c_j^{\mathsf T} positive semidefinite, so MM is convex, and ∇M=2(AQ−r)=0\nabla M = 2 (A Q - r) = 0 characterizes its minimizers. For ν>0\nu > 0 the coordinates of Q−PQ - P add νI\nu I to AA, so AA is positive definite and the solution is unique. □\square

When ν=0\nu = 0 and all wk=0w_k = 0, a move of each CQ(tk)C_Q(t_k) along TkT_k costs nothing in the data terms; on straight data this move can be a slide of the whole curve along the line, which RR does not see either, so AA is singular. This is why the code adds a small ν\nu.

Theorem 4 (monotone energy and termination). Let ff be the energy that the code computes, the sum over the data points of the squared distance to the computed foot point plus μR\mu R. The accepted energies f0,f1,…f_0, f_1, \dots satisfy fj+1≤fjf_{j+1} \le f_j, and the algorithm stops.

Proof. Line L6 tries α=1,12,14,…\alpha = 1, \frac12, \frac14, \dots and accepts a trial only when its energy is at most the current fjf_j; the code stops the halving when α\alpha falls below a fixed minimum step, and if no trial was accepted the algorithm returns the current PP without a change. So every accepted energy is at most the one before it. Each iteration does at most ⌈log⁡2(1/αmin⁡)⌉+2\lceil \log_2 (1 / \alpha_{\min}) \rceil + 2 energy evaluations, each with a fixed amount of work, and the outer loop runs at most the iteration limit. □\square

When the computed foot points are global nearest points, ff is the true ∑kF(Xk)+μR\sum_k F(X_k) + \mu R, and the theorem holds for the true energy.

Theorem 5 (exact data give a fixed point). Let μ=0\mu = 0, let every data point lie on the regular curve CPC_P, and let the foot points be computed exactly. Then Q=PQ = P minimizes MM, it is the only minimizer when ν>0\nu > 0 or when AA is nonsingular, and SDM returns PP unchanged with energy 00.

Proof. Each XkX_k has distance 00, so its foot point is a parameter with CP(tk)=XkC_P(t_k) = X_k. At Q=PQ = P every data term vanishes, and so does ν∣Q−P∣2\nu \lvert Q - P \rvert^2, so M(P)=0≤M(Q)M(P) = 0 \le M(Q) for every QQ. When the minimizer is unique (Theorem 3), it is PP, the step Q−PQ - P is 00, and the energy stays 00. □\square

What is not proved. Nothing here shows that the iterates converge, how fast, or to which local minimum. Wang, Pottmann and Liu relate SDM to a quasi-Newton method and TDM to the Gauss-Newton method; the fast convergence on the page is measured, not proved. ■\blacksquare

Complexity

Each iteration computes mm foot points: one sampling of the curve costs Θ(Sp2)\Theta(S p^2), comparing each point with the samples Θ(S)\Theta(S) and kk Newton steps Θ(kp2)\Theta(k p^2). Each term of line L5 touches 2(p+1)2(p + 1) unknowns, so the system has band width Θ(p)\Theta(p) in a suitable order, costs Θ(mp2)\Theta(m p^2) to build and Θ(np2)\Theta(n p^2) to solve. Each energy evaluation of line L6 costs another foot point pass. With bb energy evaluations per iteration and ss iterations this gives the bound in the front matter on the real RAM. The code of this page uses a dense solver, Θ(n3)\Theta(n^3) per iteration, which is fine for small nn.

Properties

  • Fast in practice. Near a solution SDM takes full steps and converges in a few iterations, where parameter correction needs hundreds.
  • Geometric. It minimizes the orthogonal distance, invariant under rigid motions of the data and the curve together.
  • Local. It finds a local minimum near the start; the start curve, the knots and the degree matter.
  • No explicit parameters. The data parameters are recomputed as foot points in every step, so they never enter the unknowns; the curve can slide along itself freely when this lowers the error.
  • Curvature dependent. It needs the second derivative of the curve, so the degree must be at least 22, and the weights jump at the boundary of the clamped region 0≤κd<10 \le \kappa d < 1.

Variants and improvements

  • Tangent distance minimization. w=0w = 0 for every point: the Gauss-Newton method for the orthogonal distance, used in point-to-plane ICP for registration. Fast near the solution, unstable far from it without step control.
  • Point distance minimization. w=1w = 1 with both terms, which is parameter correction.
  • Space curves. For a curve in space, the model has a third term along the binormal; Wang, Pottmann and Liu give the space curve form.
  • Surfaces. For a surface, the model in the frame of the principal directions is dd−ρ1x12+dd−ρ2x22+x32\frac{d}{d - \rho_1} x_1^2 + \frac{d}{d - \rho_2} x_2^2 + x_3^2, with the principal radii of curvature ρ1\rho_1, ρ2\rho_2 and the normal coordinate x3x_3; Pottmann and Hofer derive it, and it is used for B-spline surface fitting and for registration with curvature information.
  • Active curves and knot insertion. The fit can start from a simple curve around the data and add control points where the error stays large; Wang, Pottmann and Liu also add knots during the fit.
  • Regularization. A fairness term such as μR\mu R or the bending energy keeps the curve smooth and the system well posed.

When to use it

Use SDM to fit a B-spline curve or surface to an unordered point cloud with a geometric error, when the data have no natural parameters, or when parameter correction is too slow. It needs a start that is roughly right, such as a fit with chord-length parameters for ordered points, or a simple curve placed around the data for unordered points. In reverse engineering it is a method for free-form regions, after the regions of simple surfaces have gone to geometric primitive fitting.

Pitfalls

  • Bad start. Far from the data the model is poor, steps are cut short, and the fit can stop in a wrong local minimum, as in the uniform-start example.
  • Curve grows past the data. Nothing holds the ends of the curve to the first and the last data point; the curve can extend beyond them while the error falls. Trim, or add end conditions.
  • Points near the center of curvature. When κd\kappa d is close to 11, the foot point is close to not being unique, and a small move of the curve moves it far. Such points often belong to another part of the curve.
  • Singular systems. With many points in the tangent distance case the system can be singular along the curve; use damping or regularization.
  • Noise and many control points. With many control points, the curve fits the noise; use the smoothing term or fewer control points.

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]
squared_distance_minimization.py 278 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/squared-distance-minimization/. The authors are listed in prov/YVZM72.jsonl.

"""Squared distance minimization (SDM) for fitting a planar B-spline curve.

Each iteration computes the foot point K_k of every data point X_k on the
current curve, with the unit tangent T_k, the unit normal N_k (T turned by
90 degrees to the left), the signed curvature kappa_k and the signed distance
d_k = (X_k - K_k) . N_k. Near X_k the squared distance to the curve is, to
second order, w ((y - K) . T)^2 + ((y - K) . N)^2 with

    w = d / (d - rho) = kappa d / (kappa d - 1),   rho = 1 / kappa.

SDM puts the curve displacement into this model: it minimizes

    sum_k [ w_k ((C_Q(t_k) - X_k) . T_k)^2 + ((C_Q(t_k) - X_k) . N_k)^2 ] + mu R(Q)

over the new control points Q (plus a tiny damping term |Q - P|^2), a linear
least-squares problem, with w_k set
to 0 when 0 <= kappa d < 1 (the model is then the tangent distance) and to 1
when the foot point is an end of the curve (the model is then the distance to
that end point). R is the sum of the squared second differences of the control
points. A step is shortened by halving until the true energy

    f(P) = sum_k dist(X_k, C_P)^2 + mu R(P)

does not grow, so the energy never increases.
"""

from math import sqrt
from typing import List, Optional, Sequence, Tuple

from re1lin import dot, solve, sub

Point = Tuple[float, float]


# ---- B-spline evaluation ----


def find_span(U: Sequence[float], p: int, t: float) -> int:
    n = len(U) - p - 2
    if t >= U[n + 1]:
        return n
    if t <= U[p]:
        return p
    lo, hi = p, n + 1
    while hi - lo > 1:
        mid = (lo + hi) // 2
        if t < U[mid]:
            hi = mid
        else:
            lo = mid
    return lo


def basis_row(U: Sequence[float], p: int, t: float) -> List[float]:
    """All B-spline values N_{i,p}(t), by the Cox-de Boor recursion on the span of t."""
    n = len(U) - p - 2
    s = find_span(U, p, t)
    b = [0.0] * (p + 1)
    b[0] = 1.0
    left, right = [0.0] * (p + 1), [0.0] * (p + 1)
    for j in range(1, p + 1):
        left[j] = t - U[s + 1 - j]
        right[j] = U[s + j] - t
        saved = 0.0
        for r in range(j):
            tmp = b[r] / (right[r + 1] + left[j - r])
            b[r] = saved + right[r + 1] * tmp
            saved = left[j - r] * tmp
        b[j] = saved
    row = [0.0] * (n + 1)
    for a in range(p + 1):
        row[s - p + a] = b[a]
    return row


def _derivative(P, U, p):
    Q = []
    for i in range(len(P) - 1):
        h = U[i + p + 1] - U[i + 1]
        Q.append(tuple(p * (a - b) / h if h > 0 else 0.0 for a, b in zip(P[i + 1], P[i])))
    return Q, list(U[1:-1]), p - 1


def _evaluate(P, U, p, t):
    row = basis_row(U, p, t)
    return tuple(sum(r * c[j] for r, c in zip(row, P)) for j in range(len(P[0])))


class Curve:
    """A clamped planar B-spline curve with its first two derivatives."""

    def __init__(self, P: Sequence[Point], U: Sequence[float], p: int):
        if p < 2:
            raise ValueError("SDM needs curvature, so the degree must be at least 2")
        self.P, self.U, self.p = [tuple(map(float, x)) for x in P], list(map(float, U)), p
        self.d1 = _derivative(self.P, self.U, p)
        self.d2 = _derivative(*self.d1)
        self.a, self.b = self.U[p], self.U[len(self.U) - p - 1]

    def point(self, t: float) -> Point:
        return _evaluate(self.P, self.U, self.p, t)

    def first(self, t: float) -> Point:
        return _evaluate(*self.d1, t)

    def second(self, t: float) -> Point:
        return _evaluate(*self.d2, t)


def foot_point(curve: Curve, x: Point, table: Sequence[Tuple[float, Point]], newton_steps: int = 30) -> float:
    """The parameter of a nearest curve point to x: best sample, then Newton steps, never farther."""
    def dist2(t):
        e = sub(curve.point(t), x)
        return dot(e, e)

    best_t, best = min(((s, dot(sub(c, x), sub(c, x))) for s, c in table), key=lambda v: v[1])
    t = best_t
    for _ in range(newton_steps):
        e = sub(curve.point(t), x)
        c1, c2 = curve.first(t), curve.second(t)
        g, h = dot(e, c1), dot(c1, c1) + dot(e, c2)
        if h <= 0.0:
            break
        tn = min(curve.b, max(curve.a, t - g / h))
        done = abs(tn - t) <= 1e-15 * max(1.0, abs(t))
        t = tn
        if done:
            break
    return t if dist2(t) <= best else best_t


def sample_table(curve: Curve, samples: int) -> List[Tuple[float, Point]]:
    return [(s, curve.point(s)) for s in (curve.a + (curve.b - curve.a) * i / samples for i in range(samples + 1))]


# ---- the local model ----


def frame(curve: Curve, t: float) -> Tuple[Point, Point, float]:
    """Unit tangent T, unit normal N (T turned left) and signed curvature kappa at C(t)."""
    c1, c2 = curve.first(t), curve.second(t)
    speed = sqrt(dot(c1, c1))
    T = (c1[0] / speed, c1[1] / speed)
    N = (-T[1], T[0])
    kappa = (c1[0] * c2[1] - c1[1] * c2[0]) / speed ** 3
    return T, N, kappa


def sdm_weight(kappa: float, d: float) -> float:
    """w = d / (d - rho) = kappa d / (kappa d - 1), set to 0 when 0 <= kappa d < 1."""
    kd = kappa * d
    if kd >= 0.0:
        return 0.0
    return kd / (kd - 1.0)


def squared_distance_model(K: Point, T: Point, N: Point, kappa: float, y: Point) -> float:
    """The second-order model of the squared distance to the curve at y, for a point whose foot is K."""
    v = sub(y, K)
    d = dot(v, N)
    kd = kappa * d
    w = kd / (kd - 1.0)
    return w * dot(v, T) ** 2 + d * d


# ---- energy ----


def roughness(P: Sequence[Point]) -> float:
    return sum((P[i + 1][j] - 2 * P[i][j] + P[i - 1][j]) ** 2 for i in range(1, len(P) - 1) for j in range(2))


def energy(X: Sequence[Point], P: Sequence[Point], U: Sequence[float], p: int, mu: float = 0.0,
           samples: int = 64) -> float:
    """f(P) = sum of squared distances from the points to C_P, plus mu times the roughness."""
    curve = Curve(P, U, p)
    table = sample_table(curve, samples)
    total = 0.0
    for x in X:
        e = sub(curve.point(foot_point(curve, x, table)), x)
        total += dot(e, e)
    return total + mu * roughness(P)


# ---- SDM ----


def sdm_step(X: Sequence[Point], P: Sequence[Point], U: Sequence[float], p: int, mu: float,
             samples: int, damping: float = 0.0) -> List[Point]:
    """The minimizer of the SDM model: one linear least-squares problem in 2n unknowns.

    damping adds damping * (largest diagonal entry) * |Q - P|^2, which keeps the
    system nonsingular when tangential moves cost nothing, as on straight data.
    """
    curve = Curve(P, U, p)
    table = sample_table(curve, samples)
    n1 = len(P)
    m2 = 2 * n1
    A = [[0.0] * m2 for _ in range(m2)]
    rhs = [0.0] * m2

    def add_row(coef, target, weight):
        nz = [i for i in range(m2) if coef[i] != 0.0]
        for i in nz:
            rhs[i] += weight * coef[i] * target
            for j in nz:
                A[i][j] += weight * coef[i] * coef[j]

    for x in X:
        t = foot_point(curve, x, table)                                         # @line L3
        K = curve.point(t)
        T, N, kappa = frame(curve, t)
        d = dot(sub(x, K), N)
        end = t <= curve.a or t >= curve.b
        w = 1.0 if end else sdm_weight(kappa, d)                                 # @line L4
        row = basis_row(U, p, t)
        for direction, weight in ((T, w), (N, 1.0)):
            if weight == 0.0:
                continue
            coef = [0.0] * m2
            for i in range(n1):
                coef[2 * i] = row[i] * direction[0]
                coef[2 * i + 1] = row[i] * direction[1]
            add_row(coef, dot(x, direction), weight)
    if mu > 0.0:
        for i in range(1, n1 - 1):
            for j in range(2):
                coef = [0.0] * m2
                coef[2 * (i - 1) + j], coef[2 * i + j], coef[2 * (i + 1) + j] = 1.0, -2.0, 1.0
                add_row(coef, 0.0, mu)
    big = max(A[i][i] for i in range(m2))
    if damping > 0.0:
        for i in range(n1):
            for j in range(2):
                A[2 * i + j][2 * i + j] += damping * big
                rhs[2 * i + j] += damping * big * P[i][j]
    sol = solve(A, rhs, 1e-14 * big)                                            # @line L5
    if sol is None:
        raise ValueError("the SDM system is singular; use a positive damping")
    return [(sol[2 * i], sol[2 * i + 1]) for i in range(n1)]


def squared_distance_minimization(X: Sequence[Point], P: Sequence[Point], U: Sequence[float], p: int,
                                  mu: float = 1e-6, iterations: int = 50, tol: float = 1e-12,
                                  samples: int = 64, min_step: float = 1e-6, damping: float = 1e-10
                                  ) -> Tuple[List[Point], List[float], List[float]]:
    """Fit a planar clamped B-spline curve of degree p >= 2 to the points X by SDM.

    P is the starting control polygon. Returns (control points, history of the
    energy f, accepted step lengths). The energy history never increases.
    Precondition: the SDM systems are nonsingular (damping > 0 is enough).
    Cost per iteration: Theta(S p^2 + m (S + k p^2) + m n^2 + n^3) with the dense
    system used here, plus the same for each energy evaluation of the step search.
    """
    X = [tuple(map(float, x)) for x in X]
    P = [tuple(map(float, q)) for q in P]                                       # @line L1
    f = energy(X, P, U, p, mu, samples)
    history, steps = [f], []
    for _ in range(iterations):                                                 # @line L2
        target = sdm_step(X, P, U, p, mu, samples, damping)
        alpha = 1.0                                                             # @line L6
        while True:
            trial = [tuple(a + alpha * (b - a) for a, b in zip(q, r)) for q, r in zip(P, target)]
            ft = energy(X, trial, U, p, mu, samples)
            if ft <= f or alpha < min_step:
                break
            alpha /= 2
        if ft > f:
            break
        P, gain, f = trial, f - ft, ft                                          # @line L7
        history.append(f)
        steps.append(alpha)
        if gain <= tol * max(f, 1e-300):                                        # @line L8
            break
    return P, history, steps                                                    # @line L9
test_squared_distance_minimization.py 187 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/squared-distance-minimization/. The authors are listed in prov/YVZM72.jsonl.

import random
import unittest
from math import cos, pi, sin, sqrt

from re1lin import solve
from squared_distance_minimization import (Curve, basis_row, energy, frame, sdm_step, sdm_weight,
                                           squared_distance_minimization, squared_distance_model)

CUBIC_U = [0, 0, 0, 0, 0.5, 1, 1, 1, 1]


def lsq_fit(X, t, U, p):
    """Independent least-squares fit for fixed parameters, for the starting curves."""
    rows = [basis_row(U, p, s) for s in t]
    n = len(rows[0])
    A = [[sum(r[i] * r[j] for r in rows) for j in range(n)] for i in range(n)]
    cols = [solve(A, [sum(r[i] * x[c] for r, x in zip(rows, X)) for i in range(n)]) for c in range(2)]
    return [(cols[0][i], cols[1][i]) for i in range(n)]


def chord(X):
    acc = [0.0]
    for a, b in zip(X, X[1:]):
        acc.append(acc[-1] + sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2))
    return [s / acc[-1] for s in acc]


def polyline_distance(curve, q, n=3000):
    """Oracle: nearest sample of a dense polyline, refined by golden section on the true curve."""
    ts = [curve.a + (curve.b - curve.a) * i / n for i in range(n + 1)]

    def dist(t):
        c = curve.point(t)
        return sqrt((c[0] - q[0]) ** 2 + (c[1] - q[1]) ** 2)

    i = min(range(n + 1), key=lambda j: dist(ts[j]))
    lo, hi = ts[max(0, i - 1)], ts[min(n, i + 1)]
    g = (sqrt(5) - 1) / 2
    for _ in range(80):
        a, b = hi - g * (hi - lo), lo + g * (hi - lo)
        if dist(a) <= dist(b):
            hi = b
        else:
            lo = a
    return min(dist(ts[i]), dist((lo + hi) / 2))


def quarter_circle():
    return [(cos(pi / 2 * (k / 20) ** 2), sin(pi / 2 * (k / 20) ** 2)) for k in range(21)]


def nonincreasing(h):
    return all(b <= a for a, b in zip(h, h[1:]))


class TestWorkedExample(unittest.TestCase):
    def test_quarter_circle_from_chord_length(self):
        X = quarter_circle()
        P0 = lsq_fit(X, chord(X), CUBIC_U, 3)
        P, h, steps = squared_distance_minimization(X, P0, CUBIC_U, 3, mu=0.0, iterations=6, tol=0)
        self.assertAlmostEqual(h[0], 6.634e-7, delta=1e-10)
        self.assertLess(h[1], 5e-9)
        self.assertLess(h[-1], 1.6e-9)
        self.assertTrue(nonincreasing(h))
        self.assertEqual(steps, [1.0] * len(steps))
        # the energy agrees with an independent distance computation
        c = Curve(P, CUBIC_U, 3)
        oracle = sum(polyline_distance(c, x) ** 2 for x in X)
        self.assertAlmostEqual(oracle, h[-1], delta=1e-10)


class TestLocalModel(unittest.TestCase):
    def circle_case(self, r, theta, d):
        M = (0.3, -0.2)
        K = (M[0] + r * cos(theta), M[1] + r * sin(theta))
        T = (-sin(theta), cos(theta))
        N = (-cos(theta), -sin(theta))          # T turned left points to the center
        X = (K[0] + d * N[0], K[1] + d * N[1])
        return M, K, T, N, X

    def test_second_order_against_the_circle(self):
        rng = random.Random(1)
        for _ in range(40):
            r = rng.uniform(0.5, 3)
            theta = rng.uniform(0, 2 * pi)
            d = rng.uniform(-3 * r, 0.9 * r)
            M, K, T, N, X = self.circle_case(r, theta, d)
            v = (rng.gauss(0, 1), rng.gauss(0, 1))
            errs = []
            for eps in (1e-2, 5e-3, 2.5e-3):
                y = (X[0] + eps * v[0], X[1] + eps * v[1])
                true = (sqrt((y[0] - M[0]) ** 2 + (y[1] - M[1]) ** 2) - r) ** 2
                errs.append(abs(squared_distance_model(K, T, N, 1 / r, y) - true))
            # third-order error: halving eps divides the error by about 8
            for a, b in zip(errs, errs[1:]):
                self.assertLess(b, a / 5 + 1e-11)
            self.assertLess(errs[0], 1e-4)

    def test_model_is_exact_at_the_point_and_on_the_normal(self):
        M, K, T, N, X = self.circle_case(2.0, 0.7, -0.5)
        self.assertAlmostEqual(squared_distance_model(K, T, N, 0.5, X), 0.25, places=14)
        for s in (-0.3, 0.2, 1.0):
            y = (X[0] + s * N[0], X[1] + s * N[1])
            self.assertAlmostEqual(squared_distance_model(K, T, N, 0.5, y), (0.5 - s) ** 2, places=14)

    def test_weight_and_limits(self):
        self.assertEqual(sdm_weight(0.0, 5.0), 0.0)        # straight curve: tangent distance
        self.assertEqual(sdm_weight(3.0, 0.0), 0.0)        # point on the curve: tangent distance
        self.assertEqual(sdm_weight(1.0, 0.5), 0.0)        # between curve and center: clamped to 0
        self.assertAlmostEqual(sdm_weight(1.0, -1.0), 0.5, places=15)   # d / (d - rho) = -1 / (-1 - 1)
        self.assertGreater(sdm_weight(1.0, -1e9), 1 - 1e-8)            # far away: point distance
        rng = random.Random(2)
        for _ in range(100):
            w = sdm_weight(rng.uniform(-5, 5), rng.uniform(-5, 5))
            self.assertTrue(0.0 <= w < 1.0)

    def test_curvature_of_a_parabola(self):
        c = Curve([(-1, 1), (0, -1), (1, 1)], [0, 0, 0, 1, 1, 1], 2)   # (2t - 1, (2t - 1)^2), y = x^2
        T, N, kappa = frame(c, 0.5)
        self.assertAlmostEqual(kappa, 2.0, places=12)
        self.assertAlmostEqual(T[0], 1.0, places=12)
        self.assertAlmostEqual(N[1], 1.0, places=12)
        T, N, kappa = frame(c, 0.75)                                    # x = 1/2: kappa = 2 / (1 + 1)^(3/2)
        self.assertAlmostEqual(kappa, 2 / 2 ** 1.5, places=12)


class TestNoiseFree(unittest.TestCase):
    def test_the_true_curve_is_a_fixed_point(self):
        rng = random.Random(3)
        U = [0, 0, 0, 0, 1 / 3, 2 / 3, 1, 1, 1, 1]
        for _ in range(5):
            P = [(i + rng.uniform(-0.3, 0.3), rng.uniform(-1, 1)) for i in range(6)]
            c = Curve(P, U, 3)
            X = [c.point(k / 39) for k in range(40)]
            Q = sdm_step(X, P, U, 3, 0.0, 64)
            for a, b in zip(P, Q):
                self.assertAlmostEqual(a[0], b[0], places=8)
                self.assertAlmostEqual(a[1], b[1], places=8)
            self.assertLess(energy(X, P, U, 3), 1e-24)


class TestEdgeCases(unittest.TestCase):
    def test_degree_one_is_rejected(self):
        with self.assertRaises(ValueError):
            Curve([(0, 0), (1, 0)], [0, 0, 1, 1], 1)

    def test_straight_data_needs_damping(self):
        # on a straight curve every weight is 0, so sliding along the line costs nothing
        X = [(0.2 + 0.6 * k / 9, 0.01 * (-1) ** k) for k in range(10)]
        P = [(i / 4, 0.0) for i in range(5)]
        with self.assertRaises(ValueError):
            sdm_step(X, P, CUBIC_U, 3, 0.0, 64)
        with self.assertRaises(ValueError):
            sdm_step(X, P, CUBIC_U, 3, 1e-4, 64)       # second differences do not see the slide
        Q, h, _ = squared_distance_minimization(X, P, CUBIC_U, 3, mu=0.0, iterations=10)
        self.assertTrue(nonincreasing(h))
        self.assertAlmostEqual(h[0], 10 * 1e-4, delta=1e-12)
        self.assertLess(h[-1], h[0])


class TestRandomizedNoisy(unittest.TestCase):
    def test_energy_decreases_every_step(self):
        rng = random.Random(11)
        U = [0, 0, 0, 0, 0.2, 0.4, 0.6, 0.8, 1, 1, 1, 1]
        full = total = 0
        for _ in range(3):
            X = [(cos(1.5 * pi * k / 39) * (1 + 0.3 * cos(3 * pi * k / 39)) + rng.gauss(0, 0.005),
                  sin(1.5 * pi * k / 39) * (1 + 0.3 * cos(3 * pi * k / 39)) + rng.gauss(0, 0.005)) for k in range(40)]
            P0 = lsq_fit(X, [k / 39 for k in range(40)], U, 3)
            P, h, steps = squared_distance_minimization(X, P0, U, 3, mu=1e-6, iterations=8, tol=1e-10)
            self.assertTrue(nonincreasing(h))
            self.assertLess(h[-1], 0.2 * h[0])
            full += sum(1 for a in steps if a == 1.0)
            total += len(steps)
            # the reported energy is the independent squared distance plus the roughness term
            c = Curve(P, U, 3)
            oracle = sum(polyline_distance(c, x, 1500) ** 2 for x in X)
            self.assertAlmostEqual(oracle, energy(X, P, U, 3, 0.0), delta=1e-7)
        # measured: most steps are full steps
        self.assertGreaterEqual(full / total, 0.6)


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

History

In 2003 Pottmann and Hofer worked out the second-order approximation of the squared distance function to curves and surfaces from the curvature at the foot point. Pottmann, Leopoldseder and Hofer used such approximations for active curves and surfaces and for registration around the same time. In 2006 Wang, Pottmann and Liu turned the planar and space curve forms into the SDM fitting method, compared it with point distance and tangent distance minimization as optimization methods, and showed by experiments that it converges much faster than the older point distance method of Hoschek.

References

  1. Wenping Wang, Helmut Pottmann and Yang Liu, Fitting B-spline curves to point clouds by curvature-based squared distance minimization, ACM Transactions on Graphics 25(2), 2006, 214 to 238, the error terms of point distance, tangent distance and squared distance minimization, the curvature-based term with the case 0 <= d < rho, the regularization, and the analysis of the three methods as optimization methods
  2. Helmut Pottmann and Michael Hofer, Geometry of the squared distance function to curves and surfaces, in Visualization and Mathematics III, Springer, 2003, 221 to 242, the second-order Taylor approximation of the squared distance function to a planar curve, a space curve and a surface, in the Frenet frame or the principal frame at the foot point
  3. Jorge Nocedal and Stephen J. Wright, Numerical Optimization, second edition, Springer, 2006, Chapter 3, line search methods with backtracking, and Chapter 10, Gauss-Newton and Levenberg-Marquardt methods for nonlinear least squares

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