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.
- Solves
- Curve fitting
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 to the moving curve by the squared distance to its current foot point , a model that is correct only far from the curve. Tangent distance minimization (TDM) uses the squared distance to the tangent line at , 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 and the normal at the foot point, with signed distance and radius of curvature ,
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 in the plane, a degree , a clamped knot vector with basis functions on , a starting control polygon , and a smoothing weight .
Output. Control points of the curve that make
small, where is the orthogonal distance to the curve and 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 with , let be the unit tangent, the unit normal ( turned left by degrees), the signed curvature, so that the center of curvature is and , and the signed distance. The SDM weight is
set to when , and to when the foot point is an end of the curve.
SDM(X_1..X_m, U, p, P, μ)- 1
P ← the starting control points - 2
repeat - 3
for each k: t_k ← foot point of X_k on C_P; K_k, T_k, N_k, κ_k, d_k at t_k - 4
w_k ← κ_k d_k / (κ_k d_k − 1), or 0 if 0 ≤ κ_k d_k < 1, or 1 at an end of the curve - 5
Q ← 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) - 6
α ← 1; while f(P + α(Q − P)) > f(P) do α ← α / 2 - 7
P ← P + α (Q − P) - 8
until the decrease of f is below a tolerance - 9
return 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 . , and come from the first two derivatives of the B-spline, as in the Frenet frame.
Line L4, the weight. At a true foot point , because the second derivative of there is . For a point on the outer side of the bend, and lies in . For a point on the inner side, between the curve and its center of curvature, and the formula gives a negative : the true squared distance is not convex there. SDM then uses , 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 makes the term the squared distance to the end point.
Line L5. The term of point is a quadratic function of the new control points , because is linear in . So the minimum solves a linear system with unknowns. Unlike in PDM, the two coordinates are coupled through and . Points with do not constrain a slide along the curve; when all weights are , as on straight data, the system is singular, and the code adds a tiny damping term , 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 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 points with are fitted by a cubic B-spline with the knots and , 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 | ||
| 1 | ||
| 2 | ||
| 3 | ||
| 10 | ||
| 200 |
SDM took full steps every time and reached in one step an error times smaller than parameter correction reached in . The largest distance from a data point to the final SDM curve is .
A poor start. From the fit with uniform parameters, whose error is , SDM needed step halving in some iterations and stopped at , 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 after iterations.
Noisy data. Forty points with noise on three quarters of a wavy loop, for , cubic with control points, , five noise samples: in iterations each, of the steps were full steps, and the energy fell from between and to between and .
All numbers are measured with the code of this page.
Correctness
The correctness file proves:
- The second-order model. If has the unique foot point on a curve, with , then the squared distance function satisfies , the formula of the lead.
- The limits. As or , the weight tends to and the model to the squared distance to the tangent line (TDM). As on the outer side, the weight tends to and the model to the squared distance to the foot point (PDM). With the clamp, at every interior foot point.
- The step. The model of line L5 is a sum of squares of linear functions of , so its minimizers solve a linear system; with damping the solution is unique.
- Monotone energy. With the step control of line L6, 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. is a curve with . At a parameter let , let be turned left by degrees, and let be the signed curvature, so that
For a point , is the squared distance to the curve. A foot point of is a parameter where the minimum is attained; write and . The SDM weight is ; when and , this is .
Lemma 1 (foot point conditions). If is a foot point of inside , then and .
Proof. Let . Since is an interior minimum, , so is normal to the curve and equals . Also . Now , and by (1), . So , and .
Theorem 1 (the second-order model). Let be the only foot point of , inside , with . Then is near , and for small
Proof. Let . Then and, by the computation of Lemma 1, at . By the implicit function theorem there is a function near with and , and it is the only zero of near .
It is also the foot point of . Take and foot points of . Every limit point of satisfies , because is continuous (it is a minimum of functions that are -Lipschitz in the distance). So is a foot point of , and . Hence , so is an interior minimum of , a zero of near , and equal to for large . So near .
Differentiate: , since the factor in parentheses is . This is , so is , with . Differentiating gives , so at
using and . Taylor's theorem with and gives
which is (2). With , and , so (2) is the model of the page.
Theorem 2 (the weight and its limits). Let .
- If , then . If , then . If , then .
- as , that is, as or , and then the model tends to , the squared distance to the tangent line (TDM).
- as , that is, as the point moves far away on the outer side, and then the model tends to , the squared distance to the foot point (PDM).
- With the clamp of line L4 ( when ), every interior foot point gets a weight in , and the end feet get .
Proof. For , . For , the numerator is positive and the denominator negative. The limits follow from the continuity of at and from . The two limit models follow by putting or in the model, with . By Lemma 1, at an interior foot point; makes the formula undefined and is clamped to , so the weight lies in .
Item 1 shows why line L4 clamps: for , the true squared distance is not convex in the direction , and an unclamped model would have no minimum.
Theorem 3 (the step). Fix the foot parameters , the frames and the weights of lines L3 and L4. The function
with is a convex quadratic function of the control points . Its minimizers are the solutions of a linear system with symmetric positive semidefinite, and for the minimizer is unique.
Proof. is linear in , so each term in brackets, each second difference in , and each coordinate of is an affine function . So with weights . Then with positive semidefinite, so is convex, and characterizes its minimizers. For the coordinates of add to , so is positive definite and the solution is unique.
When and all , a move of each along costs nothing in the data terms; on straight data this move can be a slide of the whole curve along the line, which does not see either, so is singular. This is why the code adds a small .
Theorem 4 (monotone energy and termination). Let be the energy that the code computes, the sum over the data points of the squared distance to the computed foot point plus . The accepted energies satisfy , and the algorithm stops.
Proof. Line L6 tries and accepts a trial only when its energy is at most the current ; the code stops the halving when falls below a fixed minimum step, and if no trial was accepted the algorithm returns the current without a change. So every accepted energy is at most the one before it. Each iteration does at most energy evaluations, each with a fixed amount of work, and the outer loop runs at most the iteration limit.
When the computed foot points are global nearest points, is the true , and the theorem holds for the true energy.
Theorem 5 (exact data give a fixed point). Let , let every data point lie on the regular curve , and let the foot points be computed exactly. Then minimizes , it is the only minimizer when or when is nonsingular, and SDM returns unchanged with energy .
Proof. Each has distance , so its foot point is a parameter with . At every data term vanishes, and so does , so for every . When the minimizer is unique (Theorem 3), it is , the step is , and the energy stays .
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.
Complexity
Each iteration computes foot points: one sampling of the curve costs , comparing each point with the samples and Newton steps . Each term of line L5 touches unknowns, so the system has band width in a suitable order, costs to build and to solve. Each energy evaluation of line L6 costs another foot point pass. With energy evaluations per iteration and iterations this gives the bound in the front matter on the real RAM. The code of this page uses a dense solver, per iteration, which is fine for small .
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 , and the weights jump at the boundary of the clamped region .
Variants and improvements
- Tangent distance minimization. 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. 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 , with the principal radii of curvature , and the normal coordinate ; 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 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 is close to , 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.
# 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
- 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
- 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
- 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.
| 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 YVZM72 Edit this page History Report an error Markdown