From 89503ee485eb03165c3a052d728098d0aae19e2f Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Sun, 26 Jul 2026 19:46:43 +0000 Subject: [PATCH 1/2] Add Polynomial Least-Squares Fitting --- README.md | 2 +- ROADMAP.md | 2 - doc/estimators/PolynomialFitting.md | 158 +++++++++++++++++ doc/estimators/README.md | 1 + numerical/estimators/offline/CMakeLists.txt | 2 + .../estimators/offline/PolynomialFitting.cpp | 6 + .../estimators/offline/PolynomialFitting.hpp | 72 ++++++++ .../estimators/offline/test/CMakeLists.txt | 1 + .../offline/test/TestPolynomialFitting.cpp | 162 ++++++++++++++++++ .../offline/PolynomialFitting/explanation.md | 31 ---- .../PolynomialFitting/implementation.md | 71 -------- .../offline/PolynomialFitting/tests.md | 55 ------ 12 files changed, 403 insertions(+), 160 deletions(-) create mode 100644 doc/estimators/PolynomialFitting.md create mode 100644 numerical/estimators/offline/PolynomialFitting.cpp create mode 100644 numerical/estimators/offline/PolynomialFitting.hpp create mode 100644 numerical/estimators/offline/test/TestPolynomialFitting.cpp delete mode 100644 roadmap/estimators/offline/PolynomialFitting/explanation.md delete mode 100644 roadmap/estimators/offline/PolynomialFitting/implementation.md delete mode 100644 roadmap/estimators/offline/PolynomialFitting/tests.md diff --git a/README.md b/README.md index a7818f47..3c5ee842 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal | [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus | | [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation, Feedforward/2-DOF, Gain-Scheduled Controller | | [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA | -| [Estimators](doc/estimators/README.md) | Linear Regression, Yule-Walker (offline), Recursive Least Squares (online) | +| [Estimators](doc/estimators/README.md) | Linear Regression, Polynomial Fitting, Yule-Walker (offline), Recursive Least Squares (online) | | [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, Alpha-Beta/Alpha-Beta-Gamma, FIR, IIR, Exponential Moving Average, Moving Average, Complementary, Median Filter | | [Kinematics](doc/kinematics/README.md) | Forward Kinematics | | [Neural Network](doc/neural_network/README.md) | Layers, activations, losses, model | diff --git a/ROADMAP.md b/ROADMAP.md index 1030ec76..048a53ed 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -27,9 +27,7 @@ Difficulty legend: | # | Component | Target module | Difficulty | |----|------------------------------------------------------|---------------------------|------------| -| 10 | Gain-scheduled controller | `controllers` | ★★☆☆☆ | | 11 | Convolution & correlation utilities | `analysis` | ★★☆☆☆ | -| 12 | Polynomial least-squares curve fitting | `estimators/offline` | ★★☆☆☆ | | 13 | Goertzel algorithm | `analysis` | ★★☆☆☆ | | 14 | CIC (Cascaded Integrator-Comb) filter | `filters/passive` | ★★☆☆☆ | | 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ | diff --git a/doc/estimators/PolynomialFitting.md b/doc/estimators/PolynomialFitting.md new file mode 100644 index 00000000..8c6e2fe7 --- /dev/null +++ b/doc/estimators/PolynomialFitting.md @@ -0,0 +1,158 @@ +# Polynomial Least-Squares Fitting + +## Overview & Motivation + +Sensor calibration curves, ADC linearization, thermistor transfer functions, and drift trends +all require fitting a smooth curve to a discrete set of measured points. A degree-$d$ polynomial +captures these behaviors with only $d+1$ coefficients, making evaluation at runtime a handful of +multiply-adds rather than a table lookup or expensive transcendental. + +The least-squares formulation finds the polynomial that minimizes the sum of squared residuals +across all measurement samples. Unlike exact interpolation, it is robust to measurement noise: +extra samples average out errors rather than being forced to pass through noisy points. + +## Mathematical Theory + +### The Model + +Given $n$ scalar observations $\{(x_i, y_i)\}_{i=0}^{n-1}$, the degree-$d$ polynomial model is + +$$p(x) = c_0 + c_1 x + c_2 x^2 + \cdots + c_d x^d$$ + +The goal is to find the coefficient vector $\mathbf{c} \in \mathbb{R}^{d+1}$ that minimizes + +$$\min_{\mathbf{c}} \sum_{i=0}^{n-1} \bigl(y_i - p(x_i)\bigr)^2$$ + +### Vandermonde Design Matrix + +Stacking the model evaluations at all sample abscissae gives the Vandermonde matrix + +$$\mathbf{V} \in \mathbb{R}^{n \times (d+1)}, \quad V_{i,j} = x_i^j$$ + +The least-squares problem then becomes $\min_{\mathbf{c}} \|\mathbf{V}\mathbf{c} - \mathbf{y}\|^2$. + +### Normal Equations + +Setting the gradient of the squared residual with respect to $\mathbf{c}$ to zero yields + +$$(\mathbf{V}^\top \mathbf{V})\,\mathbf{c} = \mathbf{V}^\top \mathbf{y}$$ + +The $(d+1)\times(d+1)$ matrix $\mathbf{V}^\top\mathbf{V}$ is symmetric and, when the abscissae are +distinct and $n \geq d+1$, positive-definite. Its small size allows direct solution by Gaussian +elimination or Cholesky factorization in bounded time on embedded hardware. + +### Horner Evaluation + +Once $\mathbf{c}$ is known, evaluating $p(x)$ at a new point uses Horner's method + +$$p(x) = c_0 + x\bigl(c_1 + x\bigl(c_2 + \cdots + x\,c_d\bigr)\cdots\bigr)$$ + +This requires exactly $d$ multiplications and $d$ additions — optimal for a degree-$d$ polynomial. + +## Complexity Analysis + +| Phase | Time | Space | Notes | +|---------------------------------------|--------------------|-------------|------------------------------------| +| Build $\mathbf{V}$ | $O(n\,d)$ | $O(n\,d)$ | Incremental powers, no `pow()` | +| Form $\mathbf{V}^\top\mathbf{V}$ | $O(n\,d^2)$ | $O(d^2)$ | Symmetric, only upper half needed | +| Form $\mathbf{V}^\top\mathbf{y}$ | $O(n\,d)$ | $O(d)$ | Matrix-vector product | +| Solve $(d+1)\times(d+1)$ system | $O(d^3)$ | $O(d^2)$ | Gaussian elimination | +| Predict (Horner) | $O(d)$ | $O(1)$ | One MAC per coefficient | + +All dimensions are compile-time constants; no heap allocation is required. + +## Step-by-Step Walkthrough + +**Data:** $n = 4$ samples, $d = 2$ (quadratic fit). + +| $x_i$ | $y_i$ | +|--------|--------| +| 0 | 1 | +| 1 | 0.75 | +| 2 | 1 | +| 3 | 1.75 | + +**Step 1 — Build $\mathbf{V}$:** + +$$\mathbf{V} = \begin{bmatrix} 1 & 0 & 0 \\ 1 & 1 & 1 \\ 1 & 2 & 4 \\ 1 & 3 & 9 \end{bmatrix}$$ + +**Step 2 — Normal equations:** + +$$\mathbf{V}^\top\mathbf{V} = \begin{bmatrix} 4 & 6 & 14 \\ 6 & 14 & 36 \\ 14 & 36 & 98 \end{bmatrix}, \qquad \mathbf{V}^\top\mathbf{y} = \begin{bmatrix} 4.5 \\ 7.25 \\ 19.75 \end{bmatrix}$$ + +**Step 3 — Solve:** Gaussian elimination → $\mathbf{c} \approx [1,\,-0.5,\,0.25]^\top$. + +**Result:** $p(x) = 1 - 0.5\,x + 0.25\,x^2$. + +**Prediction at $x = 1.5$:** + +$$p(1.5) = 0.25\cdot1.5^2 - 0.5\cdot1.5 + 1 = 0.5625 - 0.75 + 1 = 0.8125$$ + +## Pitfalls & Edge Cases + +- **Ill-conditioning of the Vandermonde system.** The condition number of $\mathbf{V}^\top\mathbf{V}$ + grows exponentially with $d$ and with the spread of abscissae. Center and scale the abscissa + $x \leftarrow (x - \bar{x})/\sigma_x$ before fitting to reduce condition numbers by orders of + magnitude. Recommended for $d \geq 3$ or when abscissae are far from the origin. + +- **Degree selection.** Over-fitting occurs when $d$ is too large relative to $n$ or to the + signal-to-noise ratio. Keep $d \leq 4$ for typical embedded calibration tasks. + +- **Exactly $n = d+1$ points.** The normal equation system has a unique solution equal to the + interpolating polynomial; the residual is zero. The system is well-posed only if all abscissae + are distinct. + +- **Repeated or nearly-coincident abscissae.** $\mathbf{V}^\top\mathbf{V}$ becomes singular or + nearly so. Partial-pivoting in the Gaussian solver will flag this via `really_assert`; avoid + duplicate $x$ values in practice. + +- **Large degree with `float` arithmetic.** Powers $x^d$ for $|x| \gg 1$ can exceed the `float` + dynamic range. Centering/scaling eliminates this risk. + +## Variants & Generalizations + +| Variant | Key Difference | +|-----------------------------------|-------------------------------------------------------------------------------| +| Orthogonal polynomial basis | Uses Legendre/Chebyshev basis instead of monomials; much better conditioning | +| Weighted least squares | Each sample weighted differently (e.g., by measurement precision) | +| Regularized (Ridge) fitting | Adds $\lambda\|\mathbf{c}\|^2$ to damp large coefficients | +| Constrained fitting | Enforces derivative constraints at endpoints | +| Savitzky-Golay smoothing | Sliding-window polynomial fit for real-time derivative estimation | + +## Applications + +- **Sensor linearization** — converting thermistor resistance or pressure-sensor ADC counts to + engineering units via a quadratic or cubic polynomial. +- **Drift and aging compensation** — fitting a polynomial to sampled drift data and subtracting + the trend from future measurements. +- **Compact lookup-table replacement** — replacing a 256-entry table with a degree-3 polynomial + evaluated in four MACs. +- **Calibration curve storage** — a handful of coefficients in flash replace a bulky lookup table. + +## Connections to Other Algorithms + +```mermaid +graph LR + PF["Polynomial Fitting"] + GE["Gaussian Elimination"] + LR["Linear Regression"] + SG["Savitzky-Golay (planned)"] + RLS["Recursive Least Squares"] + + PF --> GE + PF -.->|"polynomial features = special case"| LR + SG -.->|"local polynomial fit per window"| PF + RLS -.->|"online counterpart"| PF +``` + +| Algorithm | Relationship | +|-------------------------------------------------------------------|-----------------------------------------------------------------| +| [Gaussian Elimination](../solvers/GaussianElimination.md) | Solves the normal equations | +| [Linear Regression](LinearRegression.md) | Polynomial fitting is linear regression with polynomial features | +| [Recursive Least Squares](RecursiveLeastSquares.md) | Online / streaming counterpart for time-varying models | + +## References & Further Reading + +- Press, W. H., Teukolsky, S. A., Vetterling, W. T. and Flannery, B. P., *Numerical Recipes in C*, 3rd ed., Cambridge University Press, 2007 — Chapter 15 (Modeling of Data). +- Golub, G. H. and Van Loan, C. F., *Matrix Computations*, 4th ed., Johns Hopkins University Press, 2013 — Chapter 5 (orthogonal factorizations and least squares). +- Hildebrand, F. B., *Introduction to Numerical Analysis*, 2nd ed., Dover, 1987 — Chapter 7 (least-squares approximation). diff --git a/doc/estimators/README.md b/doc/estimators/README.md index aac4cf7a..68c4ad8a 100644 --- a/doc/estimators/README.md +++ b/doc/estimators/README.md @@ -7,6 +7,7 @@ Statistical estimation algorithms for fitting models to observed data and making | Algorithm | Description | |-------------------------------------------------------------------|-------------------------------------------------------------------------| | [Linear Regression](LinearRegression.md) | Ordinary least-squares regression using the normal equation | +| [Polynomial Fitting](PolynomialFitting.md) | Degree-d polynomial fit via Vandermonde normal equations | | [Yule-Walker](YuleWalker.md) | Autoregressive model parameter estimation via the Yule-Walker equations | | [Expectation-Maximization](ExpectationMaximization.md) | EM algorithm for Kalman filter parameter identification (Shumway-Stoffer) | diff --git a/numerical/estimators/offline/CMakeLists.txt b/numerical/estimators/offline/CMakeLists.txt index 8ab3e7c6..4672b5d8 100644 --- a/numerical/estimators/offline/CMakeLists.txt +++ b/numerical/estimators/offline/CMakeLists.txt @@ -15,12 +15,14 @@ target_link_libraries(numerical.estimators.offline ${NUMERICAL_VISIBILITY} target_sources(numerical.estimators.offline PRIVATE ExpectationMaximization.hpp LinearRegression.hpp + PolynomialFitting.hpp YuleWalker.hpp ) numerical_add_coverage_sources(numerical.estimators.offline ExpectationMaximization.cpp LinearRegression.cpp + PolynomialFitting.cpp YuleWalker.cpp ) diff --git a/numerical/estimators/offline/PolynomialFitting.cpp b/numerical/estimators/offline/PolynomialFitting.cpp new file mode 100644 index 00000000..39128db8 --- /dev/null +++ b/numerical/estimators/offline/PolynomialFitting.cpp @@ -0,0 +1,6 @@ +#include "numerical/estimators/offline/PolynomialFitting.hpp" + +namespace estimators +{ + template class PolynomialFitting; +} diff --git a/numerical/estimators/offline/PolynomialFitting.hpp b/numerical/estimators/offline/PolynomialFitting.hpp new file mode 100644 index 00000000..052a60e7 --- /dev/null +++ b/numerical/estimators/offline/PolynomialFitting.hpp @@ -0,0 +1,72 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/Matrix.hpp" +#include "numerical/solvers/GaussianElimination.hpp" +#include + +namespace estimators +{ + template + class PolynomialFitting + { + static_assert(std::is_floating_point_v, "PolynomialFitting supports floating-point types"); + static_assert(Samples >= Degree + 1, "Samples must be >= Degree + 1"); + + public: + using CoefficientsVector = math::Matrix; + using SamplesVector = math::Matrix; + + PolynomialFitting() = default; + + OPTIMIZE_FOR_SPEED void Fit(const SamplesVector& x, const SamplesVector& y); + T Predict(T xVal) const; + const CoefficientsVector& Coefficients() const; + + private: + CoefficientsVector coefficients; + }; + + template + OPTIMIZE_FOR_SPEED void PolynomialFitting::Fit(const SamplesVector& x, const SamplesVector& y) + { + math::Matrix v; + + for (std::size_t i = 0; i < Samples; ++i) + { + v.at(i, 0) = T{ 1 }; + for (std::size_t j = 1; j <= Degree; ++j) + v.at(i, j) = v.at(i, j - 1) * x.at(i, 0); + } + + auto vt = v.Transpose(); + auto normalMatrix = vt * v; + auto rhs = vt * y; + + coefficients = solvers::SolveSystem(normalMatrix, rhs); + } + + template + T PolynomialFitting::Predict(T xVal) const + { + T acc = coefficients.at(Degree, 0); + for (std::size_t j = Degree; j > 0; --j) + acc = acc * xVal + coefficients.at(j - 1, 0); + return acc; + } + + template + const typename PolynomialFitting::CoefficientsVector& + PolynomialFitting::Coefficients() const + { + return coefficients; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class PolynomialFitting; +#endif +} diff --git a/numerical/estimators/offline/test/CMakeLists.txt b/numerical/estimators/offline/test/CMakeLists.txt index 9011dc99..249c26fb 100644 --- a/numerical/estimators/offline/test/CMakeLists.txt +++ b/numerical/estimators/offline/test/CMakeLists.txt @@ -10,5 +10,6 @@ target_link_libraries(numerical.estimators.offline_test PUBLIC target_sources(numerical.estimators.offline_test PRIVATE TestExpectationMaximization.cpp TestLinearRegression.cpp + TestPolynomialFitting.cpp TestYuleWalker.cpp ) diff --git a/numerical/estimators/offline/test/TestPolynomialFitting.cpp b/numerical/estimators/offline/test/TestPolynomialFitting.cpp new file mode 100644 index 00000000..13543543 --- /dev/null +++ b/numerical/estimators/offline/test/TestPolynomialFitting.cpp @@ -0,0 +1,162 @@ +#include "numerical/estimators/offline/PolynomialFitting.hpp" +#include "numerical/math/Tolerance.hpp" +#include +#include + +namespace +{ + class TestPolynomialFitting : public ::testing::Test + { + protected: + estimators::PolynomialFitting fitter; + }; +} + +TEST_F(TestPolynomialFitting, recovers_exact_line) +{ + estimators::PolynomialFitting linFitter; + math::Matrix x; + math::Matrix y; + + for (std::size_t i = 0; i < 8; ++i) + { + float xi = static_cast(i); + x.at(i, 0) = xi; + y.at(i, 0) = 2.0f + 3.0f * xi; + } + + linFitter.Fit(x, y); + const auto& c = linFitter.Coefficients(); + + EXPECT_NEAR(c.at(0, 0), 2.0f, math::Tolerance()); + EXPECT_NEAR(c.at(1, 0), 3.0f, math::Tolerance()); +} + +TEST_F(TestPolynomialFitting, recovers_exact_quadratic) +{ + math::Matrix x; + math::Matrix y; + + for (std::size_t i = 0; i < 8; ++i) + { + float xi = -1.0f + static_cast(i) * (2.0f / 7.0f); + x.at(i, 0) = xi; + y.at(i, 0) = 1.0f - 0.5f * xi + 0.25f * xi * xi; + } + + fitter.Fit(x, y); + + for (std::size_t i = 0; i < 8; ++i) + { + float xi = x.at(i, 0); + float expected = 1.0f - 0.5f * xi + 0.25f * xi * xi; + EXPECT_NEAR(fitter.Predict(xi), expected, math::Tolerance()); + } +} + +TEST_F(TestPolynomialFitting, fits_noisy_data_least_squares) +{ + math::Matrix x; + math::Matrix y; + + static constexpr float noise[] = { 0.01f, -0.01f, 0.005f, -0.005f, 0.008f, -0.008f, 0.003f, -0.003f }; + + for (std::size_t i = 0; i < 8; ++i) + { + float xi = static_cast(i) * 0.25f; + x.at(i, 0) = xi; + y.at(i, 0) = 1.0f - 0.5f * xi + 0.25f * xi * xi + noise[i]; + } + + fitter.Fit(x, y); + const auto& c = fitter.Coefficients(); + + EXPECT_NEAR(c.at(0, 0), 1.0f, 0.05f); + EXPECT_NEAR(c.at(1, 0), -0.5f, 0.05f); + EXPECT_NEAR(c.at(2, 0), 0.25f, 0.05f); +} + +TEST_F(TestPolynomialFitting, predict_uses_horner) +{ + math::Matrix x; + math::Matrix y; + + for (std::size_t i = 0; i < 8; ++i) + { + float xi = static_cast(i) * 0.5f; + x.at(i, 0) = xi; + y.at(i, 0) = 1.0f + 2.0f * xi + 3.0f * xi * xi; + } + + fitter.Fit(x, y); + const auto& c = fitter.Coefficients(); + + float xVal = 1.5f; + float horner = c.at(2, 0) * xVal * xVal + c.at(1, 0) * xVal + c.at(0, 0); + + EXPECT_NEAR(fitter.Predict(xVal), horner, math::Tolerance()); +} + +TEST_F(TestPolynomialFitting, constant_data_gives_constant_term) +{ + math::Matrix x; + math::Matrix y; + + for (std::size_t i = 0; i < 8; ++i) + { + x.at(i, 0) = static_cast(i); + y.at(i, 0) = 7.0f; + } + + fitter.Fit(x, y); + const auto& c = fitter.Coefficients(); + + EXPECT_NEAR(c.at(0, 0), 7.0f, math::Tolerance()); + EXPECT_NEAR(c.at(1, 0), 0.0f, math::Tolerance()); + EXPECT_NEAR(c.at(2, 0), 0.0f, math::Tolerance()); +} + +TEST_F(TestPolynomialFitting, centering_improves_conditioning) +{ + math::Matrix x; + math::Matrix y; + + float xMean = 104.0f; + for (std::size_t i = 0; i < 8; ++i) + { + float xi = 100.0f + static_cast(i); + float xc = xi - xMean; + x.at(i, 0) = xc; + y.at(i, 0) = 1.0f - 0.5f * xc + 0.25f * xc * xc; + } + + fitter.Fit(x, y); + const auto& c = fitter.Coefficients(); + + EXPECT_TRUE(std::isfinite(c.at(0, 0))); + EXPECT_TRUE(std::isfinite(c.at(1, 0))); + EXPECT_TRUE(std::isfinite(c.at(2, 0))); + EXPECT_NEAR(c.at(1, 0), -0.5f, math::Tolerance()); + EXPECT_NEAR(c.at(2, 0), 0.25f, math::Tolerance()); +} + +TEST_F(TestPolynomialFitting, degree_zero_is_mean) +{ + estimators::PolynomialFitting constFitter; + math::Matrix x; + math::Matrix y; + + float sum = 0.0f; + for (std::size_t i = 0; i < 8; ++i) + { + x.at(i, 0) = static_cast(i); + float yi = static_cast(i) * 1.5f + 2.0f; + y.at(i, 0) = yi; + sum += yi; + } + + constFitter.Fit(x, y); + const auto& c = constFitter.Coefficients(); + + EXPECT_NEAR(c.at(0, 0), sum / 8.0f, math::Tolerance()); +} diff --git a/roadmap/estimators/offline/PolynomialFitting/explanation.md b/roadmap/estimators/offline/PolynomialFitting/explanation.md deleted file mode 100644 index c55356be..00000000 --- a/roadmap/estimators/offline/PolynomialFitting/explanation.md +++ /dev/null @@ -1,31 +0,0 @@ -# Polynomial Least-Squares Fitting — Overview - -## What it is -A batch estimator that fits a degree-`d` polynomial `p(x) = c₀ + c₁x + … + c_d xᵈ` to a set of -`(x, y)` samples by minimizing the sum of squared residuals. It is the classic *linear* -least-squares problem: linear in the coefficients even though the model curve is not a line. - -## Why it matters (embedded) -Sensor-calibration curves, thermistor/ADC linearization, drift and trend modeling, and compact -lookup-table replacement all reduce to fitting a low-order polynomial. It runs offline (at -commissioning or on a captured buffer) and produces a handful of coefficients that evaluate in a -few multiply-adds at runtime. - -## How it works (intuition) -Stack the samples into a **Vandermonde** matrix `V` whose columns are successive powers of `x`. -The best-fit coefficients solve the **normal equations** `(VᵀV) c = Vᵀy`. Because `VᵀV` is small -(`(d+1)×(d+1)`) and symmetric positive-definite, a Cholesky or Gaussian solve returns the -coefficients directly — no iteration. - -## Key parameters -- **Degree `d`** — model order; higher fits more wiggles but conditions worse and can overfit. -- **Sample count** — must be `≥ d+1`; more samples average out measurement noise. -- **Centering/scaling** — normalizing `x` is essential for numerical health at higher degree. - -## Reference -W. H. Press, S. A. Teukolsky, W. T. Vetterling, B. P. Flannery, *Numerical Recipes*, Ch. 15 -(Modeling of Data — general linear least squares). - -## See also -`LinearRegression` (multivariate linear fit), `solvers::CholeskyDecomposition`, -`SavitzkyGolayFilter` (local polynomial smoothing), `TotalLeastSquares` (errors-in-variables). diff --git a/roadmap/estimators/offline/PolynomialFitting/implementation.md b/roadmap/estimators/offline/PolynomialFitting/implementation.md deleted file mode 100644 index 6cb6ac0a..00000000 --- a/roadmap/estimators/offline/PolynomialFitting/implementation.md +++ /dev/null @@ -1,71 +0,0 @@ -# Polynomial Least-Squares Fitting — Implementation Pseudocode - -> Roadmap ref: #12 (Tier 2) · Target: `numerical/estimators/offline` · Namespace `estimators` · Type: `float` (templated on `T`, instantiated for `float` only) - -## Data structures - -``` -template # static_assert(std::is_floating_point_v); instantiated for float -class PolynomialFitting: # degree d ⇒ d+1 coefficients - Matrix coefficients # [c0, c1, ..., cd] - static_assert Samples >= Degree + 1 # enough points to fit -``` - -## Interface - -``` -PolynomialFitting() -void Fit(Matrix x, Matrix y) # hot path -T Predict(T x) # Horner evaluation -const Matrix& Coefficients() -``` - -## Algorithm (pseudocode) - -``` -function Fit(x, y): # OPTIMIZE_FOR_SPEED - # Build Vandermonde design matrix V (Samples x Degree+1) - for i in 0 .. Samples-1: - V[i,0] = 1 - for j in 1 .. Degree: - V[i,j] = V[i,j-1] * x[i] # incremental power, no pow() - # Normal equations: (Vᵀ V) c = Vᵀ y - A = Vᵀ * V # (Degree+1) x (Degree+1), symmetric PD - b = Vᵀ * y - coefficients = solvers::SolveSystem(A, b) # Gaussian elimination - # (or) L = CholeskyDecomposition(A); solve L Lᵀ c = b - -function Predict(x): # Horner - acc = coefficients[Degree] - for j in Degree-1 .. 0: - acc = acc * x + coefficients[j] - return acc -``` - -## Complexity & memory - -- Fit: `O(Samples·Degree²)` to form `VᵀV`, `O(Degree³)` to solve — both bounded at compile time. -- Predict: `O(Degree)` via Horner (one MAC per term). -- Memory: `O(Degree²)` for the normal-equation matrix on the stack; no heap. - -## Numerical / embedded notes - -- `VᵀV` is symmetric positive-definite ⇒ `CholeskyDecomposition` is ~2× cheaper than Gaussian - elimination and preserves symmetry; fall back to pivoted elimination if conditioning is poor. -- The Vandermonde system is **ill-conditioned** for high `Degree`; keep `Degree ≤ 4–5` and - **center/scale** the abscissa (`x ← (x − x̄)/σ`) before fitting to tame the condition number. -- Build powers incrementally (`V[i,j] = V[i,j-1]·x[i]`) to avoid `pow()` and reduce round-off. -- Float-only: `static_assert(std::is_floating_point_v)`; the generic `T` signature keeps a - `Q15`/`Q31` specialisation cheap to add later. - -## Deployment - -- Header: `numerical/estimators/offline/PolynomialFitting.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `Fit`, and - `extern template class PolynomialFitting;` under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/estimators/offline/PolynomialFitting.cpp` → `template class PolynomialFitting;` -- Test: `numerical/estimators/offline/test/TestPolynomialFitting.cpp` -- Doc: `doc/estimators/PolynomialFitting.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestPolynomialFitting.cpp` → the `_test` target. -- Generic pattern: see `roadmap/DEPLOYMENT.md`. diff --git a/roadmap/estimators/offline/PolynomialFitting/tests.md b/roadmap/estimators/offline/PolynomialFitting/tests.md deleted file mode 100644 index 90dc6fc7..00000000 --- a/roadmap/estimators/offline/PolynomialFitting/tests.md +++ /dev/null @@ -1,55 +0,0 @@ -# Polynomial Least-Squares Fitting — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestPolynomialFitting : public ::testing::Test: - PolynomialFitting fitter # 8 samples, quadratic -# each case below is a TEST_F(TestPolynomialFitting, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -recovers_exact_line: - Arrange: y = 2 + 3x sampled at 8 points (Degree 1 fitter) - Act: Fit(x, y) - Assert: coefficients ≈ [2, 3] (within tol for T) - -recovers_exact_quadratic: - Arrange: y = 1 − 0.5x + 0.25x² on [-1,1] - Act: Fit; Predict at held-out points - Assert: predictions ≈ true polynomial - -fits_noisy_data_least_squares: - Arrange: quadratic + small zero-mean noise - Assert: coefficients close to truth; residual norm small - -predict_uses_horner: - Arrange: known coefficients via Fit - Assert: Predict(x) matches manual Horner evaluation - -constant_data_gives_constant_term: - Arrange: y = c constant - Assert: c0 ≈ c, higher terms ≈ 0 - -centering_improves_conditioning: - Arrange: abscissa far from origin (x in [100,108]) - Assert: centered fit matches; coefficients finite (no blow-up) - -degree_zero_is_mean: - Arrange: Degree 0 fitter - Assert: c0 ≈ mean(y) -``` - -## Reference vectors - -- `y = 2 + 3x` ⇒ exact coefficients `[2, 3]`, zero residual. -- `y = x²` on a symmetric grid ⇒ `[0, 0, 1]` (odd terms vanish by symmetry). - -## Edge cases - -- `Samples == Degree + 1` (exact interpolation, zero residual). -- Near-collinear abscissa (repeated `x`) ⇒ singular `VᵀV`; assert graceful/pivoted handling. From edfacd40abbac998354ed6bb49ca6936a8bf2946 Mon Sep 17 00:00:00 2001 From: gfs Date: Sun, 26 Jul 2026 21:52:13 +0200 Subject: [PATCH 2/2] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/estimators/PolynomialFitting.md | 48 +++++++++---------- doc/estimators/README.md | 12 ++--- .../offline/test/TestPolynomialFitting.cpp | 2 +- 3 files changed, 31 insertions(+), 31 deletions(-) diff --git a/doc/estimators/PolynomialFitting.md b/doc/estimators/PolynomialFitting.md index 8c6e2fe7..92a6a3e1 100644 --- a/doc/estimators/PolynomialFitting.md +++ b/doc/estimators/PolynomialFitting.md @@ -51,13 +51,13 @@ This requires exactly $d$ multiplications and $d$ additions — optimal for a de ## Complexity Analysis -| Phase | Time | Space | Notes | -|---------------------------------------|--------------------|-------------|------------------------------------| -| Build $\mathbf{V}$ | $O(n\,d)$ | $O(n\,d)$ | Incremental powers, no `pow()` | -| Form $\mathbf{V}^\top\mathbf{V}$ | $O(n\,d^2)$ | $O(d^2)$ | Symmetric, only upper half needed | -| Form $\mathbf{V}^\top\mathbf{y}$ | $O(n\,d)$ | $O(d)$ | Matrix-vector product | -| Solve $(d+1)\times(d+1)$ system | $O(d^3)$ | $O(d^2)$ | Gaussian elimination | -| Predict (Horner) | $O(d)$ | $O(1)$ | One MAC per coefficient | +| Phase | Time | Space | Notes | +|----------------------------------|-------------|-----------|-----------------------------------| +| Build $\mathbf{V}$ | $O(n\,d)$ | $O(n\,d)$ | Incremental powers, no `pow()` | +| Form $\mathbf{V}^\top\mathbf{V}$ | $O(n\,d^2)$ | $O(d^2)$ | Symmetric, only upper half needed | +| Form $\mathbf{V}^\top\mathbf{y}$ | $O(n\,d)$ | $O(d)$ | Matrix-vector product | +| Solve $(d+1)\times(d+1)$ system | $O(d^3)$ | $O(d^2)$ | Gaussian elimination | +| Predict (Horner) | $O(d)$ | $O(1)$ | One MAC per coefficient | All dimensions are compile-time constants; no heap allocation is required. @@ -66,11 +66,11 @@ All dimensions are compile-time constants; no heap allocation is required. **Data:** $n = 4$ samples, $d = 2$ (quadratic fit). | $x_i$ | $y_i$ | -|--------|--------| -| 0 | 1 | -| 1 | 0.75 | -| 2 | 1 | -| 3 | 1.75 | +|-------|-------| +| 0 | 1 | +| 1 | 0.75 | +| 2 | 1 | +| 3 | 1.75 | **Step 1 — Build $\mathbf{V}$:** @@ -111,13 +111,13 @@ $$p(1.5) = 0.25\cdot1.5^2 - 0.5\cdot1.5 + 1 = 0.5625 - 0.75 + 1 = 0.8125$$ ## Variants & Generalizations -| Variant | Key Difference | -|-----------------------------------|-------------------------------------------------------------------------------| -| Orthogonal polynomial basis | Uses Legendre/Chebyshev basis instead of monomials; much better conditioning | -| Weighted least squares | Each sample weighted differently (e.g., by measurement precision) | -| Regularized (Ridge) fitting | Adds $\lambda\|\mathbf{c}\|^2$ to damp large coefficients | -| Constrained fitting | Enforces derivative constraints at endpoints | -| Savitzky-Golay smoothing | Sliding-window polynomial fit for real-time derivative estimation | +| Variant | Key Difference | +|-----------------------------|------------------------------------------------------------------------------| +| Orthogonal polynomial basis | Uses Legendre/Chebyshev basis instead of monomials; much better conditioning | +| Weighted least squares | Each sample weighted differently (e.g., by measurement precision) | +| Regularized (Ridge) fitting | Adds $\lambda\|\mathbf{c}\|^2$ to damp large coefficients | +| Constrained fitting | Enforces derivative constraints at endpoints | +| Savitzky-Golay smoothing | Sliding-window polynomial fit for real-time derivative estimation | ## Applications @@ -145,11 +145,11 @@ graph LR RLS -.->|"online counterpart"| PF ``` -| Algorithm | Relationship | -|-------------------------------------------------------------------|-----------------------------------------------------------------| -| [Gaussian Elimination](../solvers/GaussianElimination.md) | Solves the normal equations | -| [Linear Regression](LinearRegression.md) | Polynomial fitting is linear regression with polynomial features | -| [Recursive Least Squares](RecursiveLeastSquares.md) | Online / streaming counterpart for time-varying models | +| Algorithm | Relationship | +|-----------------------------------------------------------|------------------------------------------------------------------| +| [Gaussian Elimination](../solvers/GaussianElimination.md) | Solves the normal equations | +| [Linear Regression](LinearRegression.md) | Polynomial fitting is linear regression with polynomial features | +| [Recursive Least Squares](RecursiveLeastSquares.md) | Online / streaming counterpart for time-varying models | ## References & Further Reading diff --git a/doc/estimators/README.md b/doc/estimators/README.md index 68c4ad8a..390d0980 100644 --- a/doc/estimators/README.md +++ b/doc/estimators/README.md @@ -4,12 +4,12 @@ Statistical estimation algorithms for fitting models to observed data and making ## Offline Estimators (Batch) -| Algorithm | Description | -|-------------------------------------------------------------------|-------------------------------------------------------------------------| -| [Linear Regression](LinearRegression.md) | Ordinary least-squares regression using the normal equation | -| [Polynomial Fitting](PolynomialFitting.md) | Degree-d polynomial fit via Vandermonde normal equations | -| [Yule-Walker](YuleWalker.md) | Autoregressive model parameter estimation via the Yule-Walker equations | -| [Expectation-Maximization](ExpectationMaximization.md) | EM algorithm for Kalman filter parameter identification (Shumway-Stoffer) | +| Algorithm | Description | +|--------------------------------------------------------|---------------------------------------------------------------------------| +| [Linear Regression](LinearRegression.md) | Ordinary least-squares regression using the normal equation | +| [Polynomial Fitting](PolynomialFitting.md) | Degree-d polynomial fit via Vandermonde normal equations | +| [Yule-Walker](YuleWalker.md) | Autoregressive model parameter estimation via the Yule-Walker equations | +| [Expectation-Maximization](ExpectationMaximization.md) | EM algorithm for Kalman filter parameter identification (Shumway-Stoffer) | ## Online Estimators (Streaming) diff --git a/numerical/estimators/offline/test/TestPolynomialFitting.cpp b/numerical/estimators/offline/test/TestPolynomialFitting.cpp index 13543543..413a9079 100644 --- a/numerical/estimators/offline/test/TestPolynomialFitting.cpp +++ b/numerical/estimators/offline/test/TestPolynomialFitting.cpp @@ -1,7 +1,7 @@ #include "numerical/estimators/offline/PolynomialFitting.hpp" #include "numerical/math/Tolerance.hpp" -#include #include +#include namespace {