Skip to content

Commit a246fc2

Browse files
committed
feat(math): add vector-valued cubic spline interpolation
Deploy roadmap item 61: C² cubic spline through up to MaxKnots knots with clamped or natural ends. All channels share the abscissa and one TridiagonalSolver factorization. Evaluate clamps x to the knot range, finds the interval by binary search and returns value, slope and curvature per channel. Checked on 2000 random fits beyond the unit tests: knots reproduced, one-sided first and second derivatives agree at interior knots (≈1e-13 in double), and end conditions hold. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q53m7MZDmHwocmKbhhd2o5
1 parent d8bce74 commit a246fc2

13 files changed

Lines changed: 521 additions & 269 deletions

File tree

‎README.md‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,14 @@ Refer to the documentation to quickly integrate and utilize the library's signal
2121
| [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, Deadbeat Control, PID, LQR, LQI (Integral/Servo State Feedback), MPC, Saturation, Rate Limiter, Slew-Limited Saturation, Feedforward/2-DOF, Gain-Scheduled Controller, Lead-Lag Compensator, Luenberger Observer, Friction Compensation (Coulomb + Viscous + Stribeck) |
2222
| [Estimators](doc/estimators/README.md) | Linear Regression, Polynomial Fitting, Total Least Squares, Yule-Walker (offline), Recursive Least Squares, Recursive Instrumental Variables, LMS / NLMS Adaptive Filter (online), Consistency Metrics / NEES / NIS |
2323
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, Square-Root Kalman, Alpha-Beta/Alpha-Beta-Gamma, FIR, IIR, Exponential Moving Average, Moving Average, Complementary, Median Filter, CIC (Cascaded Integrator-Comb), Notch/Comb Filter, Savitzky-Golay Filter, Biquad/Second-Order-Section Cascade, IIR Filter Design (Butterworth/Chebyshev-I + Bilinear Transform), Madgwick/Mahony AHRS |
24-
| [Optimization](doc/optimization/README.md) | Gradient Descent, SGD / Adam Step Optimisers |
25-
| [Regularization](doc/regularization/README.md) | L1 (Lasso), L2 (Ridge) |
26-
| [Math](doc/math/README.md) | CORDIC, Quaternion, MatrixNorms, Step Response Metrics, MatrixExponential, Angle Utilities, Tridiagonal (Thomas) Solver |
27-
| [Motion Profiles](doc/motion_profiles/README.md) | Polynomial (Cubic/Quintic) Point-to-Point Profile, Trapezoidal (LSPB) Profile, S-Curve (Jerk-Limited) Profile |
28-
| [Solvers](doc/solvers/README.md) | Gaussian Elimination, Levinson-Durbin, Durand-Kerner, Cholesky, DARE, Runge-Kutta ODE Integrators (RK4 + Dormand-Prince), Spectral Radius & Discrete Stability Margin, QR Decomposition (Householder / Givens), LU Decomposition with Partial Pivoting, Singular Value Decomposition (Golub-Kahan), Symplectic Integrators (Semi-Implicit Euler, Velocity Verlet) |
29-
| [Nonlinear Control](doc/nonlinear_control/README.md) | Feedback Linearization, Backstepping Control, Model Reference Adaptive Control (MRAC) |
30-
| [Robust Control](doc/robust_control/README.md) | Active Disturbance Rejection Control (ADRC + ESO), Sliding Mode Control (SMC), Disturbance Observer (DOB), H∞ State-Feedback Control |
31-
| [Performance Optimization](doc/performance-optimization/README.md) | Compiler optimizations |
24+
| [Optimization](doc/optimization/README.md) | Gradient Descent, SGD / Adam Step Optimisers |
25+
| [Regularization](doc/regularization/README.md) | L1 (Lasso), L2 (Ridge) |
26+
| [Math](doc/math/README.md) | CORDIC, Quaternion, MatrixNorms, Step Response Metrics, MatrixExponential, Angle Utilities, Tridiagonal (Thomas) Solver, Cubic Spline Interpolation |
27+
| [Motion Profiles](doc/motion_profiles/README.md) | Polynomial (Cubic/Quintic) Point-to-Point Profile, Trapezoidal (LSPB) Profile, S-Curve (Jerk-Limited) Profile |
28+
| [Solvers](doc/solvers/README.md) | Gaussian Elimination, Levinson-Durbin, Durand-Kerner, Cholesky, DARE, Runge-Kutta ODE Integrators (RK4 + Dormand-Prince), Spectral Radius & Discrete Stability Margin, QR Decomposition (Householder / Givens), LU Decomposition with Partial Pivoting, Singular Value Decomposition (Golub-Kahan), Symplectic Integrators (Semi-Implicit Euler, Velocity Verlet) |
29+
| [Nonlinear Control](doc/nonlinear_control/README.md) | Feedback Linearization, Backstepping Control, Model Reference Adaptive Control (MRAC) |
30+
| [Robust Control](doc/robust_control/README.md) | Active Disturbance Rejection Control (ADRC + ESO), Sliding Mode Control (SMC), Disturbance Observer (DOB), H∞ State-Feedback Control |
31+
| [Performance Optimization](doc/performance-optimization/README.md) | Compiler optimizations |
3232

3333
Each category page lists its algorithms with a brief description and links to the detailed documentation.
3434

‎ROADMAP.md‎

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,13 @@ Difficulty legend:
2424

2525
## Master list (by priority)
2626

27-
| # | Component | Target module | Difficulty |
28-
|----|-----------------------------------------------------|----------------------|------------|
29-
| 53 | SE(3) transform, twists, wrenches, adjoint, exp/log | `math` | ★★☆☆☆ |
30-
| 61 | Cubic spline interpolation (vector-valued) | `math` | ★★☆☆☆ |
31-
| 62 | Damped pseudo-inverse + null-space projector | `solvers` | ★★☆☆☆ |
32-
| 63 | Incremental QR least squares (rank-revealing) | `estimators/offline` | ★★★☆☆ |
33-
| 64 | Levenberg–Marquardt (retraction, pluggable damping) | `optimization` | ★★★☆☆ |
34-
| 65 | Dense convex QP (Goldfarb–Idnani dual active set) | `solvers` | ★★★★☆ |
27+
| # | Component | Target module | Difficulty |
28+
|----|------------------------------------------------------|-------------------------|------------|
29+
| 53 | SE(3) transform, twists, wrenches, adjoint, exp/log | `math` | ★★☆☆☆ |
30+
| 62 | Damped pseudo-inverse + null-space projector | `solvers` | ★★☆☆☆ |
31+
| 63 | Incremental QR least squares (rank-revealing) | `estimators/offline` | ★★★☆☆ |
32+
| 64 | Levenberg–Marquardt (retraction, pluggable damping) | `optimization` | ★★★☆☆ |
33+
| 65 | Dense convex QP (Goldfarb–Idnani dual active set) | `solvers` | ★★★★☆ |
3534

3635
Items 53–65 are the generic building blocks of robotics-toolbox-cpp's roadmap (referenced there as
3736
NT53–NT65); each also serves non-robotics consumers (motor control, navigation, calibration). All are
@@ -56,15 +55,6 @@ the library does not yet expose. Detailed below under
5655
- **Reuses:** `Geometry3D` (`RotationAboutAxis`, `SkewSymmetric`), `Quaternion`.
5756
- **Spec:** [roadmap/math/SE3Transform](roadmap/math/SE3Transform/implementation.md).
5857

59-
### 61. Cubic spline interpolation
60-
- **What:** C² vector-valued spline through `K` knots, clamped or natural ends, shared factorization across
61-
channels.
62-
- **Embedded value:** Smooth interpolation of waypoint lists and calibration tables in linear time on fixed
63-
storage.
64-
- **Algorithm / paper:** C. de Boor, *A Practical Guide to Splines* (2001), Ch. IV.
65-
- **Reuses:** Item 59.
66-
- **Spec:** [roadmap/math/CubicSpline](roadmap/math/CubicSpline/implementation.md).
67-
6858
### 62. Damped pseudo-inverse and null-space projector
6959
- **What:** `A⁺_λ·b` and the exact projector `I − A⁺A` for any `Rows × Cols` matrix from one SVD.
7060
- **Embedded value:** Singularity-robust inversion for redundant robots, over-actuated control allocation

‎doc/math/CubicSpline.md‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# Cubic Spline Interpolation (Vector-Valued, Clamped / Natural)
2+
3+
## Overview & Motivation
4+
5+
Waypoint lists (robot teach-in programs, CNC paths, planner output), calibration tables and resampled signals all need a smooth curve through given samples. A single high-order polynomial through many points rings between them; a piecewise-linear curve has corners that excite mechanics. A **cubic spline** joins one cubic per interval so that value, slope **and** curvature are continuous ($C^2$), and it stays well behaved however many knots are used.
6+
7+
Several channels (the joints of a robot, the axes of a path, the columns of a table) share the same abscissae. They are fitted together: the linear system depends only on the knot spacing, so it is factored once and every channel reuses the factors. Fitting is a single linear-time pass on fixed storage; evaluation is a binary search plus a cubic, cheap and deterministic.
8+
9+
## Mathematical Theory
10+
11+
### Unknowns and per-interval form
12+
13+
Knots $x_0 < x_1 < \dots < x_{K-1}$ with spans $h_k = x_{k+1} - x_k$ and values $y_k$ (one component per channel; channels are independent). The unknowns are the knot second derivatives $M_k = y''(x_k)$. On interval $k$, with $\tau = x - x_k \in [0, h_k]$,
14+
15+
$$y(\tau) = y_k + \beta_k\,\tau + \tfrac{M_k}{2}\,\tau^2 + d_k\,\tau^3, \qquad d_k = \frac{M_{k+1} - M_k}{6\,h_k}, \qquad \beta_k = \frac{y_{k+1} - y_k}{h_k} - \frac{h_k\,(2M_k + M_{k+1})}{6}$$
16+
17+
The cubic hits both knot values and both knot curvatures, so value is $C^0$ and curvature is $C^2$ by construction. Only slope continuity remains to be imposed.
18+
19+
### Interior rows
20+
21+
Equating the slope at the end of interval $k-1$, $\beta_{k-1} + h_{k-1}(M_{k-1} + M_k)/2$, with $\beta_k$ and writing $s_k = (y_{k+1} - y_k)/h_k$ gives, for $k = 1, \dots, K-2$,
22+
23+
$$h_{k-1} M_{k-1} + 2(h_{k-1} + h_k)\,M_k + h_k M_{k+1} = 6\,(s_k - s_{k-1})$$
24+
25+
Each row couples a knot to its two neighbours only, so the system is tridiagonal with $K-2$ rows. Two end conditions supply the missing two.
26+
27+
### End conditions
28+
29+
| Condition | First row | Last row |
30+
|-----------|-----------|----------|
31+
| **Clamped** (end slopes $\sigma_0$, $\sigma_1$) | $2h_0 M_0 + h_0 M_1 = 6\,(s_0 - \sigma_0)$ | $h_{K-2} M_{K-2} + 2h_{K-2} M_{K-1} = 6\,(\sigma_1 - s_{K-2})$ |
32+
| **Natural** | $M_0 = 0$ | $M_{K-1} = 0$ |
33+
34+
Clamping fixes the end slopes and leaves the end second derivatives free; natural ends do the reverse. Default slopes are zero.
35+
36+
### Solvability
37+
38+
Every interior row has diagonal $2(h_{k-1} + h_k)$ against off-diagonal sum $h_{k-1} + h_k$; clamped end rows have $2h$ against $h$; natural rows have $1$ against $0$. All rows are strictly diagonally dominant, so the matrix is nonsingular and the [Thomas algorithm](TridiagonalSolver.md) is stable without pivoting. The matrix contains only spans and the end-condition kind, never values or slopes: one factorization serves all channels, and only the right-hand sides differ.
39+
40+
### Evaluation
41+
42+
Clamp $x$ to $[x_0, x_{K-1}]$, find the interval by binary search, then use Horner's scheme per channel:
43+
44+
$$y = y_k + \tau\,\bigl(\beta_k + \tau\,(\tfrac{M_k}{2} + \tau\,d_k)\bigr), \quad y' = \beta_k + \tau\,(M_k + 3 d_k \tau), \quad y'' = M_k + 6 d_k \tau$$
45+
46+
An abscissa exactly on an interior knot selects the interval starting there; the last knot selects the final interval. Both choices give the same result because the spline is $C^2$.
47+
48+
## Complexity Analysis
49+
50+
| Operation | Time | Space | Notes |
51+
|-----------|------|-------|-------|
52+
| Factorization | $O(K)$ | three bands | Once per fit, shared by all channels |
53+
| Fit | $O(D\,K)$ | $K_{\max}(2 + 2D)$ scalars | $D$ channels, each one right-hand side build and one solve of $O(K)$; no iteration |
54+
| Evaluate | $O(\log K + D)$ | $O(1)$ | Binary search, then three Horner polynomials per channel |
55+
56+
Storage holds the knots, their reciprocal spans, the values and the second derivatives: $K_{\max}(2 + 2D)$ scalars, where $K_{\max}$ is the compile-time capacity, plus the three bands of the solver. All of it is bounded and on the stack or inside the object; no heap.
57+
58+
## Step-by-Step Walkthrough
59+
60+
Knots $(0, 1, 2)$, values $(0, 1, 0)$, so $h_0 = h_1 = 1$ and $s_0 = 1$, $s_1 = -1$.
61+
62+
**Clamped, zero end slopes.** The system is
63+
$$\begin{pmatrix} 2 & 1 & 0 \\ 1 & 4 & 1 \\ 0 & 1 & 2 \end{pmatrix} M = \begin{pmatrix} 6 \\ -12 \\ 6 \end{pmatrix}$$
64+
65+
| $k$ | Pivot $p_k$ | $c'_k$ | Forward $y_k$ | Back $M_k$ |
66+
|-----|-------------|--------|---------------|------------|
67+
| 0 | $2$ | $1/2$ | $3$ | $3 + 3 = 6$ |
68+
| 1 | $4 - 1/2 = 7/2$ | $2/7$ | $-30/7$ | $-30/7 - 12/7 = -6$ |
69+
| 2 | $2 - 2/7 = 12/7$ | unused | $6$ | $6$ |
70+
71+
So $M = (6, -6, 6)$. Interval 0 has $\beta_0 = 1 - (12 - 6)/6 = 0$ and $d_0 = -2$, giving $y(\tau) = 3\tau^2 - 2\tau^3$. Hence $y(0.5) = 0.75 - 0.25 = 0.5$, $y'(0.5) = 3 - 1.5 = 1.5$ and $y''(0.5) = 0$. The curve leaves and enters every knot flat, like a smooth step.
72+
73+
**Natural.** The end rows reduce to $M_0 = M_2 = 0$, so the middle row is $4M_1 = -12$ and $M = (0, -3, 0)$. Interval 0 has $\beta_0 = 1 + 3/6 = 1.5$ and $d_0 = -0.5$, giving $y(\tau) = 1.5\tau - 0.5\tau^3$. Hence $y(0.5) = 0.75 - 0.0625 = 0.6875$ and $y'(0.5) = 1.125$. The end slope $y'(0) = 1.5$ is free, and the curvature is zero there.
74+
75+
### Verification
76+
77+
Random fits are checked for interpolation of every knot, for continuity of first and second derivative across each interior knot, and for the end conditions (prescribed slopes when clamped, zero curvature when natural). Continuity holds to about $10^{-13}$ in double precision and to the single-precision rounding level in float.
78+
79+
## Pitfalls & Edge Cases
80+
81+
- **Invalid knots.** Fewer than 2 knots, more than the capacity, or spacing $x_{k+1} - x_k \le \varepsilon \max(1, |x_k|)$ is rejected, where $\varepsilon$ is the machine epsilon of the scalar type. Near-coincident knots would make slope quotients and the second derivatives huge.
82+
- **Failure leaves no fit.** A rejected or unfactorable fit discards any earlier fit; evaluating before a successful fit is a precondition violation.
83+
- **Tolerance is a floor, not a guarantee.** Spacing only a few $\varepsilon$ wide passes the test yet produces enormous slopes; keep sample spacing meaningful relative to the data.
84+
- **Overshoot.** A cubic spline interpolates; it does not bound the curve between knots, so limits (velocity, position) must be checked on the evaluated curve.
85+
- **Outside the domain.** The abscissa is clamped, so the output is the end-knot sample, including its slope and curvature, which need not be zero. Position holds while the reported velocity does not drop to zero.
86+
- **Pick the end condition per application.** Clamped when end velocities matter (start and stop at rest); natural when they do not, accepting free end slopes.
87+
- **Degenerate cases.** Two clamped knots give exactly the cubic Hermite polynomial. Two natural knots give the straight line. Collinear data with a matching clamped slope give a zero right-hand side and so $M \equiv 0$: the line is reproduced exactly.
88+
- **Floating-point only.** The reciprocal spans and the epsilon test have no meaning for integer types.
89+
90+
## Variants & Generalizations
91+
92+
- **Not-a-knot / periodic ends.** Other end rows keep the tridiagonal shape (not-a-knot) or add corner entries solved by Sherman–Morrison (periodic).
93+
- **Shape-preserving cubics.** Monotone Hermite interpolation chooses slopes locally; it removes overshoot but gives up $C^2$ for $C^1$.
94+
- **B-spline form.** Same curve family with local basis functions; suited to non-interpolating fits and variable degree.
95+
- **Smoothing and least-squares splines.** Trade exact interpolation for noise rejection; see polynomial fitting for the non-interpolating alternative.
96+
97+
## Applications
98+
99+
- **Joint-space and Cartesian trajectories** through waypoints, with continuous velocity and acceleration.
100+
- **CNC and planner paths** parameterized by time or arc length.
101+
- **Calibration tables and resampling** of sensor signals onto a new grid.
102+
103+
## Connections to Other Algorithms
104+
105+
| Algorithm | Relationship |
106+
|-----------|--------------|
107+
| [Tridiagonal Solver](TridiagonalSolver.md) | Solves the second-derivative system; its factorization is reused across channels |
108+
| [Polynomial Profile](../motion_profiles/PolynomialProfile.md) | The two-knot clamped case is the same cubic Hermite polynomial; the spline generalizes it to many knots with $C^2$ joins |
109+
| Polynomial fitting | Least-squares fit instead of interpolation |
110+
111+
## References & Further Reading
112+
113+
- de Boor, C., *A Practical Guide to Splines*, Springer, 1978 (rev. ed. 2001).
114+
- Burden, R. L. & Faires, J. D., *Numerical Analysis*, §3.5 (cubic spline interpolation).

0 commit comments

Comments
 (0)