Algorithm Search⌘K

Algorithmadvanced

Parameter correction

Also called Hoschek parameter correction, intrinsic parameterization.

Hoschek's step of B-spline fitting that moves each data parameter to the foot point on the current curve or surface and refits, so the error is measured orthogonally.

Time
Θ(s (S p² + m (S d + k p²) + (m + n) p (p + d))) worst
Space
Θ(m + n p + S d) extra
Where
S = the number of curve samples per iteration; d = the dimension of the points; k = the number of Newton steps per foot point; m = the number of data points, minus one; n = the number of control points; p = the degree; s = the number of iterations
Properties
deterministicnot exactiterative
Origin
Josef Hoschek, 1988

Parameter correction is an algorithm that fits a B-spline curve or surface to measured points so that the error is the orthogonal distance from each point to the curve, not the distance to some arbitrary point of the curve. B-spline fitting needs a parameter value tkt_k for each data point QkQ_k; with the parameters fixed, the control points follow from one linear least squares problem. But that problem measures ∣Qk−C(tk)∣\lvert Q_k - C(t_k) \rvert, the distance to the curve point at a guessed parameter, which is larger than the distance to the curve whenever the error vector is not normal to the curve. Parameter correction alternates two steps: move each tkt_k to the foot point of QkQ_k on the current curve, which is a point projection problem, and refit the control points for the new parameters. Neither step can raise the total error, so the error decreases monotonically. Hoschek (1988) introduced the idea under the name intrinsic parameterization: parameters for which every error vector is normal to the curve. The method is simple and robust, but it converges only linearly, and slowly when the curve is far from the data; squared distance minimization was designed to remove that weakness.

In plain words

To fit a smooth curve to many points, the usual method first gives each point a "time" along the curve, then finds the curve that passes close to each point at its own time. The trouble is that the times are a guess. A point may be matched to a place on the curve that is not the nearest one, and the fit then pulls the curve in the wrong direction.

Parameter correction repairs the guess. After a fit, it looks along the curve for the place nearest to each point and gives the point that new time. Then it fits again with the new times. It repeats this until the curve stops getting better. Each round can only make the total error smaller, but the rounds help less and less, so many rounds may be needed.

The problem

Input. Data points Q0,…,Qm∈RdQ_0, \dots, Q_m \in \mathbb{R}^d, a degree pp and a clamped knot vector UU that define nn B-spline basis functions N1,p,…,Nn,pN_{1,p}, \dots, N_{n,p} on [a,b][a, b], and optionally starting parameters.

Output. Control points P1,…,PnP_1, \dots, P_n of the curve CP(t)=∑iNi,p(t)PiC_P(t) = \sum_i N_{i,p}(t) P_i that make the orthogonal error

D(P)=∑k=0mdist⁡(Qk,CP)2,dist⁡(Q,CP)=min⁡t∈[a,b]∣Q−CP(t)∣,D(P) = \sum_{k=0}^{m} \operatorname{dist}(Q_k, C_P)^2 , \qquad \operatorname{dist}(Q, C_P) = \min_{t \in [a, b]} \lvert Q - C_P(t) \rvert ,

small. DD is the geometric error of curve fitting; it is not a quadratic function of PP. The algorithm works with the extended error

E(P,t)=∑k=0m∣Qk−CP(tk)∣2,E(P, t) = \sum_{k=0}^{m} \lvert Q_k - C_P(t_k) \rvert^2 ,

which is quadratic in PP for fixed tt, and satisfies D(P)=min⁡tE(P,t)D(P) = \min_t E(P, t). So minimizing DD over PP is the same as minimizing EE over PP and tt together. The same holds for a tensor-product surface with parameter pairs (uk,vk)(u_k, v_k).

The algorithm

  1. PARAMETER-CORRECTION(Q_0..Q_m, U, p, t)
  2. 1if no parameters are given then t ← chord-length parameters of Q, from a to b
  3. 2P ← least-squares control points for the parameters t
  4. 3repeat
  5. 4for each k (t_0 and t_m stay at a and b) do t_k ← foot point of Q_k on C_P, kept only if |Q_k − C_P(t_k)| does not grow
  6. 5P ← least-squares control points for the new parameters t
  7. 6E ← Σ_k |Q_k − C_P(t_k)|²
  8. 7until E falls by at most tol · E, or after the iteration limit
  9. 8return P and t

Line L1. Chord-length parameters put tkt_k in proportion to the length of the polygon Q0Q1…QkQ_0 Q_1 \dots Q_k. They are a good start for points spread evenly along a smooth curve. Uniform parameters are a poor start when the points are spaced unevenly, as the example shows.

Lines L2 and L5. For fixed tt, EE is ∥Q−NP∥F2\lVert \mathbf{Q} - N \mathbf{P} \rVert_F^2 with the collocation matrix Nki=Ni,p(tk)N_{ki} = N_{i,p}(t_k), and the minimizer solves the normal equations NTNP=NTQN^{\mathsf T} N \mathbf{P} = N^{\mathsf T} \mathbf{Q}. It is unique when NN has full column rank, which by the Schoenberg-Whitney theorem means that some nn of the parameters can be matched to the basis functions so that each basis function is nonzero at its parameter. The B-spline fitting page solves this banded system in linear time; the code here uses a dense solver.

Line L4. The foot point of QkQ_k is a parameter tt that minimizes ∣Qk−C(t)∣\lvert Q_k - C(t) \rvert. Inside (a,b)(a, b) it satisfies g(t)=(C(t)−Qk)⋅C′(t)=0g(t) = (C(t) - Q_k) \cdot C'(t) = 0: the error vector is normal to the curve. The code samples the curve at S+1S + 1 equal steps, starts from the best of the samples and the old tkt_k, and runs Newton steps t←t−g(t)/g′(t)t \leftarrow t - g(t)/g'(t) with g′=∣C′∣2+(C−Qk)⋅C′′g' = \lvert C' \rvert^2 + (C - Q_k) \cdot C'', clamped to [a,b][a, b]. The new tkt_k is kept only if it is not farther than the old one, which is what makes the error monotone even when Newton fails. Hoschek's original step is cheaper: it moves tkt_k by the tangential part of the error vector, scaled from length to parameter, which is one first-order step toward the foot point.

The end parameters. The code keeps t0=at_0 = a and tm=bt_m = b. If they move too, the curve can grow past the first and the last data point, where no data hold it, and the part beyond the data has no meaning. That growth was seen in tests; see the pitfalls.

Example

A quarter circle with unevenly spaced points. The data are 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, which are dense near (1,0)(1, 0) and sparse near (0,1)(0, 1). The curve is 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), so 55 control points. EE is the error of line L6, DD the true orthogonal error, and "max" the largest distance from a data point to the curve.

start corrections EE DD max
uniform 0 2.087×10−42.087 \times 10^{-4} 5.231×10−55.231 \times 10^{-5} 0.003040.00304
uniform 1 6.267×10−56.267 \times 10^{-5} 4.074×10−54.074 \times 10^{-5} 0.002420.00242
uniform 10 3.920×10−53.920 \times 10^{-5} 3.498×10−53.498 \times 10^{-5} 0.001990.00199
uniform 200 2.832×10−52.832 \times 10^{-5} 2.786×10−52.786 \times 10^{-5} 0.001940.00194
chord length 0 7.392×10−77.392 \times 10^{-7} 6.634×10−76.634 \times 10^{-7} 0.0003090.000309
chord length 10 6.163×10−76.163 \times 10^{-7} 6.105×10−76.105 \times 10^{-7} 0.0003220.000322
chord length 200 3.083×10−73.083 \times 10^{-7} 3.064×10−73.064 \times 10^{-7} 0.0002450.000245

Three things show. With the uniform start, the fixed parameters overstate the error four times (EE against DD), and the first correction removes most of the gap. After that, progress is slow: 199199 more corrections lower EE only by a factor of 2.22.2. And the start matters more than the corrections: chord length with no correction is about 4040 times better than uniform with 200200 corrections, because the corrections only find a nearby local minimum.

Noise-free data from a spline. Thirty points sampled at random parameters on random cubic curves of the same spline space, eight curves, chord-length start. After 100100 corrections the error EE had dropped by factors from 22 to 4040, and the largest distance from the true curve to the fitted curve had dropped from between 0.0140.014 and 0.0470.047 to between 0.0040.004 and 0.0190.019. The fit moves toward the true curve, but slowly. From the true parameters, the first fit is already the true curve and the corrections leave it there; that case is proved.

These numbers are measured with the code of this page.

Correctness

The correctness file proves:

  • Monotone error. Line L5 minimizes EE over PP for fixed tt, and line L4 does not raise any term of EE for fixed PP. So the values of EE after each fit never increase, and they converge.
  • The orthogonal error. D(P)≤E(P,t)D(P) \le E(P, t) for every tt. If every parameter is moved to a global foot point, the orthogonal errors DD of the successive curves never increase either.
  • Fixed points are stationary. At a fixed point whose parameters are interior foot points, the gradient of EE in PP and in tt vanishes, and every error vector Qk−C(tk)Q_k - C(t_k) is normal to the curve: the parameterization is intrinsic in Hoschek's sense. If the foot points are unique and nondegenerate, PP is then a stationary point of DD.
  • Noise-free data. If Qk=C∗(τk)Q_k = C^*(\tau_k) for a curve C∗C^* of the spline space and the collocation matrix at τ\tau has full rank, the fit at t=τt = \tau returns C∗C^* exactly, and every later iteration keeps it.

Not proved: that the iteration reaches the global minimum of DD, or even that the parameters converge, and how fast. Wang, Pottmann and Liu analyze the alternation as an optimization method, which they call point distance minimization, and find linear convergence, slow when the curve is far from the data; the example agrees with that.

Proof: Parameter correction never increases the error, bounds the orthogonal error, stops at points where the error vectors are normal to the curve, and keeps the true curve on noise-free datafull

Setup. N1,p,…,Nn,pN_{1,p}, \dots, N_{n,p} are the B-spline basis functions of degree pp on a clamped knot vector with parameter interval [a,b][a, b]. For control points P=(P1,…,Pn)P = (P_1, \dots, P_n) in Rd\mathbb{R}^d the curve is CP(t)=∑iNi,p(t)PiC_P(t) = \sum_i N_{i,p}(t) P_i. The data are Q0,…,QmQ_0, \dots, Q_m, and for parameters t=(t0,…,tm)∈[a,b]m+1t = (t_0, \dots, t_m) \in [a, b]^{m+1},

E(P,t)=∑k=0m∣Qk−CP(tk)∣2,D(P)=∑k=0mmin⁡s∈[a,b]∣Qk−CP(s)∣2.E(P, t) = \sum_{k=0}^{m} \lvert Q_k - C_P(t_k) \rvert^2, \qquad D(P) = \sum_{k=0}^{m} \min_{s \in [a, b]} \lvert Q_k - C_P(s) \rvert^2 .

The minimum in DD exists because CPC_P is continuous on the compact interval. N(t)N(t) is the (m+1)×n(m + 1) \times n collocation matrix with entries Ni,p(tk)N_{i,p}(t_k). One iteration of the algorithm maps (Pj,tj)(P^j, t^j) to (Pj+1,tj+1)(P^{j+1}, t^{j+1}): line L4 gives tj+1t^{j+1} with

∣Qk−CPj(tkj+1)∣≤∣Qk−CPj(tkj)∣for every k,(1)\lvert Q_k - C_{P^j}(t^{j+1}_k) \rvert \le \lvert Q_k - C_{P^j}(t^j_k) \rvert \quad \text{for every } k, \tag{1}

and line L5 gives Pj+1P^{j+1}, a minimizer of E(⋅,tj+1)E(\cdot, t^{j+1}). Line L2 gives P0P^0, a minimizer of E(⋅,t0)E(\cdot, t^0). Write Ej=E(Pj,tj)E_j = E(P^j, t^j).

Termination. Each iteration does a fixed amount of work: S+1S + 1 curve samples, at most kk Newton steps per data point, and one linear solve. The loop runs at most the iteration limit. So the algorithm stops.

Lemma 1 (the fit step). For fixed tt, E(P,t)=∥Q−N(t)P∥F2E(P, t) = \lVert \mathbf{Q} - N(t) \mathbf{P} \rVert_F^2, where Q\mathbf{Q} and P\mathbf{P} have the points as rows. Its minimizers are the solutions of NTNP=NTQN^{\mathsf T} N \mathbf{P} = N^{\mathsf T} \mathbf{Q}, and the minimizer is unique exactly when N(t)N(t) has full column rank.

Proof. CP(tk)=∑iNi,p(tk)PiC_P(t_k) = \sum_i N_{i,p}(t_k) P_i is row kk of NPN \mathbf{P}, so the formula for EE holds. The Frobenius norm splits into the dd columns, and each column is a linear least squares problem ∥q−Nx∥2\lVert q - N x \rVert^2. Its gradient is 2NT(Nx−q)2 N^{\mathsf T}(N x - q), and it is convex, so the minimizers are exactly the solutions of the normal equations. They form an affine set of dimension equal to the nullity of NN, so the minimizer is unique exactly when NN has full column rank. □\square

Theorem 1 (monotone error). Ej+1≤EjE_{j+1} \le E_j for every jj. So the sequence EjE_j converges to a limit E∞≥0E_\infty \ge 0.

Proof. By (1), summed over kk, E(Pj,tj+1)≤E(Pj,tj)=EjE(P^j, t^{j+1}) \le E(P^j, t^j) = E_j. By Lemma 1, Pj+1P^{j+1} minimizes E(⋅,tj+1)E(\cdot, t^{j+1}), so Ej+1=E(Pj+1,tj+1)≤E(Pj,tj+1)E_{j+1} = E(P^{j+1}, t^{j+1}) \le E(P^j, t^{j+1}). Together Ej+1≤EjE_{j+1} \le E_j. A nonincreasing sequence bounded below by 00 converges. □\square

The code keeps the end parameters fixed and keeps any new tkt_k only when it is not farther than the old one, so (1) holds for every kk in the code, whether or not Newton's method converges.

Theorem 2 (the orthogonal error). (a) D(P)≤E(P,t)D(P) \le E(P, t) for every PP and tt, so D(Pj)≤EjD(P^j) \le E_j. (b) If in every iteration each tkj+1t^{j+1}_k is a global foot point, ∣Qk−CPj(tkj+1)∣=min⁡s∣Qk−CPj(s)∣\lvert Q_k - C_{P^j}(t^{j+1}_k) \rvert = \min_s \lvert Q_k - C_{P^j}(s) \rvert for all kk, then D(Pj+1)≤D(Pj)D(P^{j+1}) \le D(P^j).

Proof. (a) Each term of DD is a minimum over ss, which is at most the value at s=tks = t_k. (b) With global foot points, E(Pj,tj+1)=D(Pj)E(P^j, t^{j+1}) = D(P^j). Then by (a) and Lemma 1, D(Pj+1)≤E(Pj+1,tj+1)≤E(Pj,tj+1)=D(Pj)D(P^{j+1}) \le E(P^{j+1}, t^{j+1}) \le E(P^j, t^{j+1}) = D(P^j). □\square

In the code the foot points come from samples and Newton steps and are global foot points in practice, not by proof; and the end parameters stay fixed, so (b) applies only when the end points are not moved. Part (a) holds always.

Theorem 3 (fixed points are stationary). Let (P,t)(P, t) satisfy: PP minimizes E(⋅,t)E(\cdot, t), and each tkt_k with a<tk<ba < t_k < b is a local minimizer of s↦∣Qk−CP(s)∣2s \mapsto \lvert Q_k - C_P(s) \rvert^2, at which CPC_P is differentiable. Then for each such kk

(Qk−CP(tk))⋅CP′(tk)=0,(2)\bigl( Q_k - C_P(t_k) \bigr) \cdot C_P'(t_k) = 0 , \tag{2}

and ∂E/∂P=0\partial E / \partial P = 0 and ∂E/∂tk=0\partial E / \partial t_k = 0 for each such kk. If, in addition, every tkt_k is interior, the unique global minimizer of its term, and nondegenerate (the second derivative of the term is positive there), then DD is differentiable at PP and ∇D(P)=0\nabla D(P) = 0.

Proof. ∂E/∂tk=−2(Qk−CP(tk))⋅CP′(tk)\partial E / \partial t_k = -2 (Q_k - C_P(t_k)) \cdot C_P'(t_k), which is zero at an interior local minimizer of the kk-th term because only that term depends on tkt_k. This is (2). ∂E/∂P=−2NT(Q−NP)\partial E / \partial P = -2 N^{\mathsf T}(\mathbf{Q} - N \mathbf{P}) is zero by Lemma 1. For the last part, let hk(P,s)=∣Qk−CP(s)∣2h_k(P, s) = \lvert Q_k - C_P(s) \rvert^2, which is smooth in PP and, on each knot span, in ss. At the nondegenerate minimizer, ∂hk/∂s=0\partial h_k / \partial s = 0 and ∂2hk/∂s2>0\partial^2 h_k / \partial s^2 > 0, so by the implicit function theorem there is a smooth sk(P′)s_k(P') near PP with ∂hk/∂s(P′,sk(P′))=0\partial h_k / \partial s (P', s_k(P')) = 0; since the global minimizer is unique and the minimum depends continuously on P′P', sk(P′)s_k(P') is the global minimizer for P′P' near PP. Then D(P′)=∑khk(P′,sk(P′))D(P') = \sum_k h_k(P', s_k(P')) and, by the chain rule, ∇D(P)=∑k(∂hk/∂P+∂hk/∂s⋅∇sk)=∑k∂hk/∂P=∂E/∂P(P,t)=0\nabla D(P) = \sum_k \bigl( \partial h_k / \partial P + \partial h_k / \partial s \cdot \nabla s_k \bigr) = \sum_k \partial h_k / \partial P = \partial E / \partial P (P, t) = 0. □\square

Equation (2) says that every error vector at an interior parameter is normal to the curve, which is Hoschek's intrinsic parameterization. When tkt_k is a knot where CPC_P has only Cp−1C^{p-1} continuity with p=1p = 1, the curve may have a corner there and (2) need not hold.

Theorem 4 (noise-free data). Let Qk=CP∗(τk)Q_k = C_{P^*}(\tau_k) for some control points P∗P^* and parameters τ∈[a,b]m+1\tau \in [a, b]^{m+1} with τ0=a\tau_0 = a, τm=b\tau_m = b, and let N(τ)N(\tau) have full column rank. Started at t0=τt^0 = \tau, the algorithm returns Pj=P∗P^j = P^* and Ej=0E_j = 0 for every jj, provided the collocation matrices of the later parameters have full rank. In the code, tj=τt^j = \tau for every jj.

Proof. E(P∗,τ)=0E(P^*, \tau) = 0, which is the least possible value, so P∗P^* minimizes E(⋅,τ)E(\cdot, \tau); by Lemma 1 it is the only minimizer, so P0=P∗P^0 = P^* and E0=0E_0 = 0. Suppose Pj=P∗P^j = P^* and Ej=0E_j = 0. By (1), every new parameter satisfies ∣Qk−CP∗(tkj+1)∣≤0\lvert Q_k - C_{P^*}(t^{j+1}_k) \rvert \le 0, so CP∗(tkj+1)=QkC_{P^*}(t^{j+1}_k) = Q_k and E(P∗,tj+1)=0E(P^*, t^{j+1}) = 0. Again P∗P^* is a minimizer of E(⋅,tj+1)E(\cdot, t^{j+1}), the only one when N(tj+1)N(t^{j+1}) has full rank, so Pj+1=P∗P^{j+1} = P^* and Ej+1=0E_{j+1} = 0. In the code, the search starts at the old parameter with squared distance 00; a sample replaces it only when strictly closer, which is impossible, and the first Newton step has g=(C(t)−Qk)⋅C′(t)=0g = (C(t) - Q_k) \cdot C'(t) = 0, so it does not move. Hence tj+1=τt^{j+1} = \tau, the rank condition holds by assumption, and the induction goes through. ■\blacksquare

Complexity

One iteration samples the curve at S+1S + 1 parameters in Θ(Sp2)\Theta(S p^2) (each point costs Θ(p2)\Theta(p^2) by the Cox-de Boor scheme, plus Θ(pd)\Theta(p d) to combine control points), compares each of the m+1m + 1 data points with the samples in Θ(Sd)\Theta(S d) and runs kk Newton steps in Θ(kp2)\Theta(k p^2), then refits in Θ((m+n)p(p+d))\Theta((m + n) p (p + d)) with the banded solver of B-spline fitting. With ss iterations this is the bound in the front matter, on the real RAM. The sample search dominates; with a good start it can be replaced by Newton steps from the old parameter alone. The code of this page stores dense rows of length nn and solves the normal equations densely, which costs Θ(m(pn+Sd+kpn)+n3)\Theta(m (p n + S d + k p n) + n^3) per iteration; that is enough for small nn.

Properties

  • Monotone. The error EE never increases, so the method cannot diverge.
  • Local. It finds a local minimum near the start. The start, the knots and the degree decide most of the result.
  • Linear convergence. The steps shrink as the curve settles, because moving the parameters and moving the control points are coupled and the alternation sees the coupling only one side at a time; this is the behavior of block coordinate descent.
  • Orthogonal at the end. At a fixed point the error vectors are normal to the curve, so EE equals the geometric error DD.
  • General. The same two steps work for surfaces, with foot points (uk,vk)(u_k, v_k), and for any family of curves that is linear in its coefficients.

Variants and improvements

  • Hoschek's first-order correction. Move tkt_k by Δtk\Delta t_k proportional to (Qk−C(tk))⋅C′(tk)/∣C′(tk)∣(Q_k - C(t_k)) \cdot C'(t_k) / \lvert C'(t_k) \rvert, without a full foot point search. Cheaper per step, and enough when the curve is already close.
  • Global foot points by sampling, as in the code. Safer on curves that bend back, where a Newton step from the old parameter can lock onto the wrong branch.
  • Joint Gauss-Newton on (P,t)(P, t). Treat the parameters as unknowns together with the control points and apply Gauss-Newton to EE. The normal equations have a sparse structure, and convergence is faster than alternation.
  • Tangent and squared distance minimization. Eliminate the parameters by using, at each foot point, a quadratic model of the squared distance: the distance to the tangent line, or the curvature-based model of squared distance minimization. These converge much faster near the solution.
  • Smoothing. Add a fairness term, as in a smoothing spline, so the curve does not wiggle when it has many control points.
  • Knot updates. Insert knots where the error stays large, and correct the parameters again.

When to use it

Use parameter correction after a B-spline fit with fixed parameters when the result is judged by the orthogonal distance, as in reverse engineering and inspection, and a few rounds are enough to remove most of the gap between EE and DD. It is simple to add to any least-squares fit and never makes the fit worse. When high accuracy is needed or the start is poor, use squared distance minimization or a joint Gauss-Newton fit instead, and keep parameter correction as the cheap first step. When the parameters are known from the measuring process, for example time stamps of a tracked tool, correction is not needed.

Pitfalls

  • Moving the end parameters. If t0t_0 and tmt_m are corrected too, the curve can extend past the data. In tests on noise-free spline data, correcting all parameters made EE fall while the largest distance from the true curve to the fitted curve rose from 0.0180.018 to 0.180.18 in 100100 iterations. Keep the end parameters fixed, or trim the curve to the feet of the end points.
  • Rank loss. Corrected parameters can crowd into a few knot spans and leave a basis function with no parameter in its support; the normal equations then become singular. Check the Schoenberg-Whitney condition, or add a small smoothing term.
  • Wrong foot points. A Newton step from the old parameter finds a local foot point; on curves that bend back, it can be the wrong one. Sample, as the code does, or keep the step small.
  • Stopping too early. The first corrections give large gains and later ones small gains, but small gains do not mean that the minimum is reached. Stop on a target error, not only on a small change.
  • Expecting the true curve. On noisy data, or data not from the spline space, the result is a local minimum of the geometric error, not a recovery of a true curve.

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.

parameter_correction.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parameter-correction/. The authors are listed in prov/RY3SVA.jsonl.

"""Parameter correction for least-squares B-spline curve fitting.

The fit alternates two steps on the error E(P, t) = sum_k |Q_k - C_P(t_k)|^2:
for fixed parameters t it solves the linear least-squares problem for the
control points P, and for fixed control points it moves every parameter t_k
to the foot point of Q_k on the current curve, the point where the error
vector Q_k - C(t_k) is normal to the curve. Neither step can raise E.

The curve is a clamped B-spline of degree p on the knot vector U, with
control points in any dimension. The foot point search takes the best of the
current parameter and a set of samples of the curve, refines it by Newton
steps on (C(t) - q) . C'(t) = 0, and keeps the new parameter only when the
distance does not grow.
"""

from typing import List, Optional, Sequence, Tuple

from re1lin import dot, solve, sub

Point = Tuple[float, ...]


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


def find_span(U: Sequence[float], p: int, t: float) -> int:
    """The index s with U[s] <= t < U[s + 1], and the last span at the right end."""
    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 n + 1 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_curve(P: Sequence[Point], U: Sequence[float], p: int) -> Tuple[List[Point], List[float], int]:
    """Control points, knots and degree of C'(t)."""
    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: Sequence[Point], U: Sequence[float], p: int, t: float) -> Point:
    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 B-spline curve with its first and second derivative curves."""

    def __init__(self, P: Sequence[Point], U: Sequence[float], p: int):
        self.P, self.U, self.p = [tuple(map(float, x)) for x in P], list(map(float, U)), p
        self.d1 = derivative_curve(self.P, self.U, p) if p >= 1 else None
        self.d2 = derivative_curve(*self.d1) if p >= 2 else None
        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:
        if self.d1 is None:
            return tuple(0.0 for _ in self.P[0])
        return evaluate(*self.d1, t)

    def second(self, t: float) -> Point:
        if self.d2 is None or self.d2[2] < 0:
            return tuple(0.0 for _ in self.P[0])
        return evaluate(*self.d2, t)


# ---- the two steps ----


def fit_control_points(Q: Sequence[Point], t: Sequence[float], U: Sequence[float], p: int) -> List[Point]:
    """Least-squares control points for fixed parameters, by the normal equations N^T N P = N^T Q.

    Precondition: N^T N is nonsingular (Schoenberg-Whitney), else ValueError.
    Cost: Theta(m p n + n^3) with the dense solver used here.
    """
    rows = [basis_row(U, p, tk) for tk in t]
    n1 = len(rows[0])
    A = [[0.0] * n1 for _ in range(n1)]
    for row in rows:
        nz = [i for i in range(n1) if row[i] != 0.0]
        for i in nz:
            for j in nz:
                A[i][j] += row[i] * row[j]
    big = max(A[i][i] for i in range(n1))
    cols = []
    for c in range(len(Q[0])):
        rhs = [sum(row[i] * q[c] for row, q in zip(rows, Q)) for i in range(n1)]
        x = solve(A, rhs, 1e-13 * big)
        if x is None:
            raise ValueError("the collocation matrix does not have full rank")
        cols.append(x)
    return [tuple(cols[c][i] for c in range(len(Q[0]))) for i in range(n1)]


def sample_table(curve: Curve, samples: int) -> List[Tuple[float, Point]]:
    """The pairs (s, C(s)) for samples + 1 equally spaced parameters s of [a, b]."""
    grid = [curve.a + (curve.b - curve.a) * i / samples for i in range(samples + 1)]
    return [(s, curve.point(s)) for s in grid]


def foot_point(curve: Curve, q: Point, t0: float, table: Sequence[Tuple[float, Point]],
               newton_steps: int = 30) -> float:
    """A parameter t whose distance |q - C(t)| is at most that of t0, refined to a foot point.

    Starts from the best of t0 and the sampled curve points of the table, and
    runs Newton steps on g(t) = (C(t) - q) . C'(t), clamped to [a, b].
    Cost: Theta(S d + k p^2) for S samples and k Newton steps.
    """
    def dist2(t):
        e = sub(curve.point(t), q)
        return dot(e, e)

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


def chord_length_parameters(Q: Sequence[Point], a: float = 0.0, b: float = 1.0) -> List[float]:
    """Parameters proportional to the cumulative chord length, from a to b."""
    acc = [0.0]
    for x, y in zip(Q, Q[1:]):
        acc.append(acc[-1] + sum((u - v) ** 2 for u, v in zip(x, y)) ** 0.5)
    total = acc[-1] or 1.0
    return [a + (b - a) * s / total for s in acc]


def error(Q: Sequence[Point], curve: Curve, t: Sequence[float]) -> float:
    return sum(dot(sub(q, curve.point(tk)), sub(q, curve.point(tk))) for q, tk in zip(Q, t))


def parameter_correction(Q: Sequence[Point], U: Sequence[float], p: int, t: Optional[Sequence[float]] = None,
                         iterations: int = 100, tol: float = 0.0, samples: int = 64, fix_ends: bool = True
                         ) -> Tuple[List[Point], List[float], List[float]]:
    """Fit a B-spline curve to the points Q with parameter correction.

    With fix_ends the first and the last parameter stay at a and b, so the
    curve does not grow past the end points of the data.

    Precondition: the collocation matrix has full rank at every parameter set
    reached (for example, the parameters stay spread over all spans).
    Returns (control points, parameters, history of E after each fit); the
    history never increases, up to rounding. Cost: Theta(S p n + m (S d + k p n)
    + m p n + n^3) per iteration with S samples and k Newton steps per foot
    point (the dense rows of length n + 1 used here cost Theta(n) each).
    """
    Q = [tuple(map(float, q)) for q in Q]
    U = [float(u) for u in U]
    a, b = U[p], U[len(U) - p - 1]
    t = list(map(float, t)) if t is not None else chord_length_parameters(Q, a, b)    # @line L1
    P = fit_control_points(Q, t, U, p)                                                 # @line L2
    curve = Curve(P, U, p)
    history = [error(Q, curve, t)]
    for _ in range(iterations):                                                        # @line L3
        table = sample_table(curve, samples)
        t = [tk if fix_ends and k in (0, len(Q) - 1) else foot_point(curve, q, tk, table)
             for k, (q, tk) in enumerate(zip(Q, t))]                                   # @line L4
        P = fit_control_points(Q, t, U, p)                                             # @line L5
        curve = Curve(P, U, p)
        e = error(Q, curve, t)                                                         # @line L6
        history.append(e)
        if history[-2] - history[-1] <= tol * history[-2] or e < 1e-30:                # @line L7
            break
    return P, t, history                                                               # @line L8
re1lin.py 221 lines
# SPDX-License-Identifier: MIT
# Shared helper of the re1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra for the re1 fitting pages.

Vectors are tuples or lists of numbers, matrices are lists of rows. The
elimination routines work with int, Fraction or float entries: with Fraction
they are exact. The Jacobi routine is float only. The helper holds no
fitting algorithm of any page.
"""

from fractions import Fraction
from math import atan2, cos, sin, sqrt
from typing import List, Optional, Sequence, Tuple

Vec = Sequence
Mat = List[List]


# ---- vectors ----


def dot(a: Vec, b: Vec):
    return sum(x * y for x, y in zip(a, b))


def add(a: Vec, b: Vec) -> tuple:
    return tuple(x + y for x, y in zip(a, b))


def sub(a: Vec, b: Vec) -> tuple:
    return tuple(x - y for x, y in zip(a, b))


def scale(s, a: Vec) -> tuple:
    return tuple(s * x for x in a)


def norm(a: Vec) -> float:
    return sqrt(float(dot(a, a)))


def cross(a: Vec, b: Vec) -> tuple:
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


# ---- matrices ----


def zeros(n: int, m: int, z=0) -> Mat:
    return [[z] * m for _ in range(n)]


def transpose(a: Mat) -> Mat:
    return [list(r) for r in zip(*a)]


def mat_vec(a: Mat, x: Vec) -> list:
    return [dot(r, x) for r in a]


def mat_mul(a: Mat, b: Mat) -> Mat:
    bt = transpose(b)
    return [[dot(r, c) for c in bt] for r in a]


def gram(rows: Sequence[Vec]) -> Mat:
    """The matrix sum over the rows u of u u^T."""
    n = len(rows[0])
    g = zeros(n, n)
    for u in rows:
        for i in range(n):
            if u[i] == 0:
                continue
            for j in range(n):
                g[i][j] += u[i] * u[j]
    return g


# ---- elimination (exact with Fraction) ----


def solve(a: Mat, b: Vec, tol: float = 0.0) -> Optional[list]:
    """Solve a x = b for a square a by Gaussian elimination with partial pivoting.

    Returns None when a pivot has absolute value at most tol (singular
    matrix). With Fraction entries and tol = 0 the answer is exact.
    """
    n = len(a)
    m = [list(a[i]) + [b[i]] for i in range(n)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[p][c]) <= tol:
            return None
        m[c], m[p] = m[p], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0:
                for k in range(c, n + 1):
                    m[r][k] -= f * m[c][k]
    x = [0] * n
    for r in range(n - 1, -1, -1):
        s = m[r][n] - sum(m[r][k] * x[k] for k in range(r + 1, n))
        x[r] = s / m[r][r]
    return x


def lstsq(a: Mat, b: Vec, tol: float = 0.0) -> Optional[list]:
    """Least squares solution of a x = b by the normal equations (a^T a) x = a^T b."""
    at = transpose(a)
    return solve(mat_mul(at, a), mat_vec(at, b), tol)


def nullspace(a: Mat) -> List[list]:
    """A basis of the null space of a, by reduced row echelon form. Exact for Fraction entries."""
    m = [[Fraction(x) for x in r] for r in a]
    rows, cols = len(m), len(m[0])
    piv = []
    r = 0
    for c in range(cols):
        p = next((i for i in range(r, rows) if m[i][c] != 0), None)
        if p is None:
            continue
        m[r], m[p] = m[p], m[r]
        inv = 1 / m[r][c]
        m[r] = [x * inv for x in m[r]]
        for i in range(rows):
            if i != r and m[i][c] != 0:
                f = m[i][c]
                m[i] = [x - f * y for x, y in zip(m[i], m[r])]
        piv.append(c)
        r += 1
        if r == rows:
            break
    free = [c for c in range(cols) if c not in piv]
    basis = []
    for f in free:
        v = [Fraction(0)] * cols
        v[f] = Fraction(1)
        for i, c in enumerate(piv):
            v[c] = -m[i][f]
        basis.append(v)
    return basis


def rank(a: Mat) -> int:
    return len(a[0]) - len(nullspace(a))


# ---- symmetric matrices (float) ----


def cholesky(a: Mat, rtol: float = 0.0) -> Mat:
    """Lower triangular l with l l^T = a, for a symmetric positive definite a.

    Raises ValueError when a pivot is at most rtol times the largest diagonal entry.
    """
    n = len(a)
    l = zeros(n, n, 0.0)
    big = max(abs(float(a[i][i])) for i in range(n))
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(l[i][k] * l[j][k] for k in range(j))
            if i == j:
                if s <= rtol * big:
                    raise ValueError("matrix is not positive definite")
                l[i][i] = sqrt(s)
            else:
                l[i][j] = s / l[j][j]
    return l


def lower_solve(l: Mat, b: Vec) -> list:
    x = []
    for i in range(len(l)):
        x.append((b[i] - sum(l[i][k] * x[k] for k in range(i))) / l[i][i])
    return x


def upper_solve_t(l: Mat, b: Vec) -> list:
    """Solve l^T x = b for a lower triangular l."""
    n = len(l)
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (b[i] - sum(l[k][i] * x[k] for k in range(i + 1, n))) / l[i][i]
    return x


def jacobi_eigen(a: Mat, sweeps: int = 100, eps: float = 1e-15) -> Tuple[list, Mat]:
    """Eigenvalues and eigenvectors of a symmetric matrix by cyclic Jacobi rotations.

    Returns (values, vectors) with the values in ascending order and
    vectors[k] the unit eigenvector of values[k].
    """
    n = len(a)
    s = [[float(x) for x in r] for r in a]
    v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        off = sum(s[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        if off <= eps * eps * max(1.0, sum(s[i][i] ** 2 for i in range(n))):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if s[p][q] == 0.0:
                    continue
                th = 0.5 * atan2(2 * s[p][q], s[q][q] - s[p][p])
                c, sn = cos(th), sin(th)
                for k in range(n):
                    skp, skq = s[k][p], s[k][q]
                    s[k][p] = c * skp - sn * skq
                    s[k][q] = sn * skp + c * skq
                for k in range(n):
                    spk, sqk = s[p][k], s[q][k]
                    s[p][k] = c * spk - sn * sqk
                    s[q][k] = sn * spk + c * sqk
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
    order = sorted(range(n), key=lambda i: s[i][i])
    return [s[i][i] for i in order], [[v[k][i] for k in range(n)] for i in order]
test_parameter_correction.py 190 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parameter-correction/. The authors are listed in prov/RY3SVA.jsonl.

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

from parameter_correction import (Curve, basis_row, chord_length_parameters, error, fit_control_points, foot_point,
                                  parameter_correction, sample_table)

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


def cox_de_boor(i, p, U, t):
    """Independent recursive B-spline value, with the right end in the last nonempty span."""
    if p == 0:
        last = max(j for j in range(len(U) - 1) if U[j] < U[j + 1])
        if U[i] <= t < U[i + 1] or (i == last and t == U[i + 1]):
            return 1.0
        return 0.0
    s = 0.0
    if U[i + p] > U[i]:
        s += (t - U[i]) / (U[i + p] - U[i]) * cox_de_boor(i, p - 1, U, t)
    if U[i + p + 1] > U[i + 1]:
        s += (U[i + p + 1] - t) / (U[i + p + 1] - U[i + 1]) * cox_de_boor(i + 1, p - 1, U, t)
    return s


def polyline_distance(curve, q, n=2000):
    """Oracle: the distance from q to a dense polyline through the curve."""
    pts = [curve.point(curve.a + (curve.b - curve.a) * i / n) for i in range(n + 1)]
    best = float("inf")
    for a, b in zip(pts, pts[1:]):
        ab = [y - x for x, y in zip(a, b)]
        aq = [y - x for x, y in zip(a, q)]
        L = sum(v * v for v in ab)
        s = 0.0 if L == 0 else min(1.0, max(0.0, sum(u * v for u, v in zip(ab, aq)) / L))
        best = min(best, sqrt(sum((x + s * u - y) ** 2 for x, u, y in zip(a, ab, q))))
    return best


def orthogonal_error(Q, P, U, p):
    c = Curve(P, U, p)
    return sum(polyline_distance(c, q, 600) ** 2 for q in Q)


def nonincreasing(h, rel=1e-12):
    return all(b <= a + rel * a for a, b in zip(h, h[1:]))


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


class TestWorkedExample(unittest.TestCase):
    def test_quarter_circle_uniform_start(self):
        Q = quarter_circle()
        t0 = [k / 20 for k in range(21)]
        P, t, h = parameter_correction(Q, CUBIC_U, 3, t0, iterations=10, tol=-1)
        self.assertAlmostEqual(h[0], 2.087e-4, delta=1e-7)
        self.assertAlmostEqual(h[1], 6.267e-5, delta=1e-7)
        self.assertTrue(nonincreasing(h))
        self.assertLess(h[-1], 0.2 * h[0])
        # the orthogonal error of the final curve is at most its parametric error
        self.assertLessEqual(orthogonal_error(Q, P, CUBIC_U, 3), h[-1] * (1 + 1e-9))
        self.assertEqual(t[0], 0.0)
        self.assertEqual(t[-1], 1.0)


class TestBSplineParts(unittest.TestCase):
    def test_basis_against_recursion(self):
        rng = random.Random(1)
        for U, p in ((CUBIC_U, 3), ([0, 0, 0, 0.2, 0.7, 1, 1, 1], 2), ([0, 0, 0.3, 0.6, 1, 1], 1)):
            n = len(U) - p - 2
            for t in [rng.random() for _ in range(20)] + [0.0, 1.0, 0.5]:
                row = basis_row(U, p, t)
                for i in range(n + 1):
                    self.assertAlmostEqual(row[i], cox_de_boor(i, p, U, t), places=12)
                self.assertAlmostEqual(sum(row), 1.0, places=12)

    def test_derivative_against_differences(self):
        rng = random.Random(2)
        P = [(rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(5)]
        c = Curve(P, CUBIC_U, 3)
        for t in (0.1, 0.3, 0.7, 0.9):
            h = 1e-6
            fd = [(a - b) / (2 * h) for a, b in zip(c.point(t + h), c.point(t - h))]
            sd = [(a - b) / (2 * h) for a, b in zip(c.first(t + h), c.first(t - h))]
            for x, y in zip(fd, c.first(t)):
                self.assertAlmostEqual(x, y, places=6)
            for x, y in zip(sd, c.second(t)):
                self.assertAlmostEqual(x, y, places=5)

    def test_foot_point_is_normal_and_nearest(self):
        rng = random.Random(3)
        for _ in range(20):
            P = [(i + rng.uniform(-0.3, 0.3), rng.uniform(-1, 1)) for i in range(5)]
            c = Curve(P, CUBIC_U, 3)
            q = (rng.uniform(0.5, 3.5), rng.uniform(-1.5, 1.5))
            t = foot_point(c, q, 0.0, sample_table(c, 64))
            e = [a - b for a, b in zip(q, c.point(t))]
            d = sqrt(sum(v * v for v in e))
            self.assertAlmostEqual(d, polyline_distance(c, q), delta=1e-5)
            if 1e-9 < t < 1 - 1e-9:
                tang = c.first(t)
                cosang = sum(a * b for a, b in zip(e, tang)) / (d * sqrt(sum(v * v for v in tang)))
                self.assertLess(abs(cosang), 1e-8)


class TestNoiseFree(unittest.TestCase):
    def test_true_parameters_give_the_true_curve_and_stay(self):
        rng = random.Random(4)
        for _ in range(10):
            P0 = [(i + rng.uniform(-0.3, 0.3), rng.uniform(-1, 1), rng.uniform(-1, 1)) for i in range(5)]
            c0 = Curve(P0, CUBIC_U, 3)
            tau = sorted([0.0, 1.0] + [rng.random() for _ in range(18)])
            Q = [c0.point(x) for x in tau]
            P, t, h = parameter_correction(Q, CUBIC_U, 3, tau, iterations=5, tol=-1)
            for a, b in zip(P, P0):
                for x, y in zip(a, b):
                    self.assertAlmostEqual(x, y, places=9)
            self.assertLess(max(h), 1e-20)
            for x, y in zip(t, tau):
                self.assertAlmostEqual(x, y, places=9)

    def test_chord_start_moves_towards_the_true_curve(self):
        # measured, not proved: from chord-length parameters the error and the
        # distance to the true curve both fall in every trial
        rng = random.Random(5)
        better = 0
        trials = 3
        for _ in range(trials):
            P0 = [(i + rng.uniform(-0.2, 0.2), rng.uniform(-0.5, 0.5)) for i in range(5)]
            c0 = Curve(P0, CUBIC_U, 3)
            tau = sorted([0.0, 1.0] + [rng.random() for _ in range(18)])
            Q = [c0.point(x) for x in tau]
            far = [c0.point(i / 100) for i in range(101)]
            _, _, h0 = parameter_correction(Q, CUBIC_U, 3, None, iterations=0)
            P0fit = fit_control_points(Q, chord_length_parameters(Q), CUBIC_U, 3)
            P, _, h = parameter_correction(Q, CUBIC_U, 3, None, iterations=25, tol=-1)
            self.assertTrue(nonincreasing(h))
            d_start = max(polyline_distance(Curve(P0fit, CUBIC_U, 3), x, 300) for x in far)
            d_end = max(polyline_distance(Curve(P, CUBIC_U, 3), x, 300) for x in far)
            better += h[-1] < h0[0] and d_end < d_start
        self.assertEqual(better, trials)


class TestEdgeCases(unittest.TestCase):
    def test_too_few_points(self):
        with self.assertRaises(ValueError):
            parameter_correction([(0, 0), (1, 1), (2, 0), (3, 1)], CUBIC_U, 3)

    def test_points_in_one_span_only(self):
        with self.assertRaises(ValueError):
            fit_control_points([(k, k * k) for k in range(10)], [k / 30 for k in range(10)], CUBIC_U, 3)

    def test_degree_one_and_exact_data(self):
        U = [0, 0, 0.5, 1, 1]
        Q = [(0, 0), (1, 2), (2, 2), (3, 1), (4, 0)]
        P, t, h = parameter_correction(Q, U, 1, [0, 0.25, 0.5, 0.75, 1], iterations=20)
        self.assertTrue(nonincreasing(h))
        self.assertLessEqual(h[-1], 24 / 35 + 1e-12)
        self.assertAlmostEqual(h[0], 24 / 35, places=12)


class TestRandomizedNoisy(unittest.TestCase):
    def test_error_never_increases_and_bounds_the_orthogonal_error(self):
        rng = random.Random(2026)
        ok_mono = ok_bound = ok_ortho = 0
        trials = 6
        for trial in range(trials):
            m = 25
            Q = []
            for k in range(m):
                s = k / (m - 1)
                Q.append((3 * s + rng.gauss(0, 0.01), sin(3 * s) + 0.3 * s * s + rng.gauss(0, 0.01),
                          0.5 * cos(2 * s) + rng.gauss(0, 0.01)))
            P, t, h = parameter_correction(Q, CUBIC_U, 3, None, iterations=8, tol=-1,
                                           fix_ends=(trial % 2 == 0))
            ok_mono += nonincreasing(h)
            D = orthogonal_error(Q, P, CUBIC_U, 3)
            ok_bound += D <= h[-1] * (1 + 1e-9)
            ok_ortho += error(Q, Curve(P, CUBIC_U, 3), t) == h[-1]
        self.assertEqual(ok_mono, trials)
        self.assertEqual(ok_bound, trials)
        self.assertEqual(ok_ortho, trials)


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

History

Least-squares fitting of splines with fixed parameters was standard by the 1970s, with uniform and chord-length parameters as the usual guesses. In 1988 Josef Hoschek observed that the error should be measured normal to the curve, called a parameterization with that property intrinsic, and reached it by correcting the parameters between fits. The same alternation appears in many fields, from principal curves in statistics to iterative closest point registration, where the closest points play the role of the foot points. Wang, Pottmann and Liu (2006) analyzed it as point distance minimization and introduced squared distance minimization to speed it up.

References

  1. Josef Hoschek, Intrinsic parametrization for approximation, Computer Aided Geometric Design 5(1), 1988, 27 to 31, the condition that the error vectors be orthogonal to the approximating curve, and the iterative correction of the parameter values between least-squares fits
  2. 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 analysis of point distance minimization (the alternation of foot point computation and least-squares fit) as an optimization method with linear convergence, compared with tangent and squared distance minimization
  3. Les Piegl and Wayne Tiller, The NURBS Book, second edition, Springer, 1997, Chapter 6, point inversion and projection by Newton iteration, and Chapter 9, least-squares curve and surface approximation with chord-length parameters

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example