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.
- Solves
- Curve fitting
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 for each data point ; with the parameters fixed, the control points follow from one linear least squares problem. But that problem measures , 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 to the foot point of 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 , a degree and a clamped knot vector that define B-spline basis functions on , and optionally starting parameters.
Output. Control points of the curve that make the orthogonal error
small. is the geometric error of curve fitting; it is not a quadratic function of . The algorithm works with the extended error
which is quadratic in for fixed , and satisfies . So minimizing over is the same as minimizing over and together. The same holds for a tensor-product surface with parameter pairs .
The algorithm
PARAMETER-CORRECTION(Q_0..Q_m, U, p, t)- 1
if no parameters are given then t ← chord-length parameters of Q, from a to b - 2
P ← least-squares control points for the parameters t - 3
repeat - 4
for 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 - 5
P ← least-squares control points for the new parameters t - 6
E ← Σ_k |Q_k − C_P(t_k)|² - 7
until E falls by at most tol · E, or after the iteration limit - 8
return P and t
Line L1. Chord-length parameters put in proportion to the length of the polygon . 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 , is with the collocation matrix , and the minimizer solves the normal equations . It is unique when has full column rank, which by the Schoenberg-Whitney theorem means that some 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 is a parameter that minimizes . Inside it satisfies : the error vector is normal to the curve. The code samples the curve at equal steps, starts from the best of the samples and the old , and runs Newton steps with , clamped to . The new 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 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 and . 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 points with , which are dense near and sparse near . The curve is a cubic B-spline with the knots , so control points. is the error of line L6, the true orthogonal error, and "max" the largest distance from a data point to the curve.
| start | corrections | max | ||
|---|---|---|---|---|
| uniform | 0 | |||
| uniform | 1 | |||
| uniform | 10 | |||
| uniform | 200 | |||
| chord length | 0 | |||
| chord length | 10 | |||
| chord length | 200 |
Three things show. With the uniform start, the fixed parameters overstate the error four times ( against ), and the first correction removes most of the gap. After that, progress is slow: more corrections lower only by a factor of . And the start matters more than the corrections: chord length with no correction is about times better than uniform with 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 corrections the error had dropped by factors from to , and the largest distance from the true curve to the fitted curve had dropped from between and to between and . 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 over for fixed , and line L4 does not raise any term of for fixed . So the values of after each fit never increase, and they converge.
- The orthogonal error. for every . If every parameter is moved to a global foot point, the orthogonal errors of the successive curves never increase either.
- Fixed points are stationary. At a fixed point whose parameters are interior foot points, the gradient of in and in vanishes, and every error vector is normal to the curve: the parameterization is intrinsic in Hoschek's sense. If the foot points are unique and nondegenerate, is then a stationary point of .
- Noise-free data. If for a curve of the spline space and the collocation matrix at has full rank, the fit at returns exactly, and every later iteration keeps it.
Not proved: that the iteration reaches the global minimum of , 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. are the B-spline basis functions of degree on a clamped knot vector with parameter interval . For control points in the curve is . The data are , and for parameters ,
The minimum in exists because is continuous on the compact interval. is the collocation matrix with entries . One iteration of the algorithm maps to : line L4 gives with
and line L5 gives , a minimizer of . Line L2 gives , a minimizer of . Write .
Termination. Each iteration does a fixed amount of work: curve samples, at most 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 , , where and have the points as rows. Its minimizers are the solutions of , and the minimizer is unique exactly when has full column rank.
Proof. is row of , so the formula for holds. The Frobenius norm splits into the columns, and each column is a linear least squares problem . Its gradient is , 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 , so the minimizer is unique exactly when has full column rank.
Theorem 1 (monotone error). for every . So the sequence converges to a limit .
Proof. By (1), summed over , . By Lemma 1, minimizes , so . Together . A nonincreasing sequence bounded below by converges.
The code keeps the end parameters fixed and keeps any new only when it is not farther than the old one, so (1) holds for every in the code, whether or not Newton's method converges.
Theorem 2 (the orthogonal error). (a) for every and , so . (b) If in every iteration each is a global foot point, for all , then .
Proof. (a) Each term of is a minimum over , which is at most the value at . (b) With global foot points, . Then by (a) and Lemma 1, .
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 satisfy: minimizes , and each with is a local minimizer of , at which is differentiable. Then for each such
and and for each such . If, in addition, every is interior, the unique global minimizer of its term, and nondegenerate (the second derivative of the term is positive there), then is differentiable at and .
Proof. , which is zero at an interior local minimizer of the -th term because only that term depends on . This is (2). is zero by Lemma 1. For the last part, let , which is smooth in and, on each knot span, in . At the nondegenerate minimizer, and , so by the implicit function theorem there is a smooth near with ; since the global minimizer is unique and the minimum depends continuously on , is the global minimizer for near . Then and, by the chain rule, .
Equation (2) says that every error vector at an interior parameter is normal to the curve, which is Hoschek's intrinsic parameterization. When is a knot where has only continuity with , the curve may have a corner there and (2) need not hold.
Theorem 4 (noise-free data). Let for some control points and parameters with , , and let have full column rank. Started at , the algorithm returns and for every , provided the collocation matrices of the later parameters have full rank. In the code, for every .
Proof. , which is the least possible value, so minimizes ; by Lemma 1 it is the only minimizer, so and . Suppose and . By (1), every new parameter satisfies , so and . Again is a minimizer of , the only one when has full rank, so and . In the code, the search starts at the old parameter with squared distance ; a sample replaces it only when strictly closer, which is impossible, and the first Newton step has , so it does not move. Hence , the rank condition holds by assumption, and the induction goes through.
Complexity
One iteration samples the curve at parameters in (each point costs by the Cox-de Boor scheme, plus to combine control points), compares each of the data points with the samples in and runs Newton steps in , then refits in with the banded solver of B-spline fitting. With 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 and solves the normal equations densely, which costs per iteration; that is enough for small .
Properties
- Monotone. The error 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 equals the geometric error .
- General. The same two steps work for surfaces, with foot points , and for any family of curves that is linear in its coefficients.
Variants and improvements
- Hoschek's first-order correction. Move by proportional to , 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 . Treat the parameters as unknowns together with the control points and apply Gauss-Newton to . 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 and . 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 and are corrected too, the curve can extend past the data. In tests on noise-free spline data, correcting all parameters made fall while the largest distance from the true curve to the fitted curve rose from to in 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag RY3SVA Edit this page History Report an error Markdown