From ef5cfb0f5d4628849a50a206d1135ae3849ca830 Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Sat, 4 Apr 2026 10:07:54 +0000 Subject: [PATCH] add em estimator as well as kf smoother --- doc/estimators/ExpectationMaximization.md | 156 +++++++++++++ doc/estimators/README.md | 9 +- doc/filters/README.md | 1 + doc/filters/active/KalmanSmoother.md | 167 ++++++++++++++ numerical/estimators/offline/CMakeLists.txt | 3 + .../offline/ExpectationMaximization.cpp | 7 + .../offline/ExpectationMaximization.hpp | 205 +++++++++++++++++ .../estimators/offline/test/CMakeLists.txt | 1 + .../test/TestExpectationMaximization.cpp | 147 ++++++++++++ numerical/filters/active/CMakeLists.txt | 2 + numerical/filters/active/KalmanSmoother.cpp | 7 + numerical/filters/active/KalmanSmoother.hpp | 214 ++++++++++++++++++ numerical/filters/active/test/CMakeLists.txt | 1 + .../active/test/TestKalmanSmoother.cpp | 110 +++++++++ 14 files changed, 1026 insertions(+), 4 deletions(-) create mode 100644 doc/estimators/ExpectationMaximization.md create mode 100644 doc/filters/active/KalmanSmoother.md create mode 100644 numerical/estimators/offline/ExpectationMaximization.cpp create mode 100644 numerical/estimators/offline/ExpectationMaximization.hpp create mode 100644 numerical/estimators/offline/test/TestExpectationMaximization.cpp create mode 100644 numerical/filters/active/KalmanSmoother.cpp create mode 100644 numerical/filters/active/KalmanSmoother.hpp create mode 100644 numerical/filters/active/test/TestKalmanSmoother.cpp diff --git a/doc/estimators/ExpectationMaximization.md b/doc/estimators/ExpectationMaximization.md new file mode 100644 index 00000000..d37f431b --- /dev/null +++ b/doc/estimators/ExpectationMaximization.md @@ -0,0 +1,156 @@ +# Expectation-Maximization for Kalman Filter Parameters + +## Overview & Motivation + +A Kalman filter requires four parameter matrices — the state-transition matrix $F$, measurement matrix $H$, process-noise covariance $Q$, and measurement-noise covariance $R$ — to be known *a priori*. In many real systems these parameters are unknown or only approximately known. + +The **Expectation-Maximization (EM) algorithm** for linear Gaussian state-space models (Shumway & Stoffer, 1982; 2000) treats the latent state sequence $x_{1:T}$ as missing data and iteratively finds the maximum-likelihood parameter estimate from a batch of observations $z_{1:T}$. Each iteration of EM is guaranteed to be non-decreasing in log-likelihood, providing a principled convergence criterion. + +This implementation follows the Shumway-Stoffer formulation and operates exclusively in `float` because typical dynamics (forces, velocities, torques) exceed the $[-1, 1]$ range of Q15/Q31 fixed-point formats. + +## Mathematical Theory + +### State-Space Model + +$$ +x_{t+1} = F x_t + w_t, \quad w_t \sim \mathcal{N}(0, Q) +$$ + +$$ +z_t = H x_t + v_t, \quad v_t \sim \mathcal{N}(0, R) +$$ + +with $x_0 \sim \mathcal{N}(\mu_0, P_0)$ and $T$ observations $z_0, \ldots, z_{T-1}$. + +### EM Overview + +EM alternates between: + +- **E-step**: compute expected sufficient statistics of $x_{1:T}$ given current parameters and all observations, using the RTS smoother. +- **M-step**: analytically maximize the expected complete-data log-likelihood over parameters. + +### E-Step (RTS Smoother) + +Run `KalmanSmoother::Smooth()` to obtain, for each $t$: + +| Quantity | Notation | Description | +|----------|----------|-------------| +| $\hat{x}_{t\|T}$ | `smoothedMeans[t]` | Smoothed state mean | +| $P_{t\|T}$ | `smoothedCovariances[t]` | Smoothed state covariance | +| $P_{t,t-1\|T}$ | `lagCrossCovariances[t]` | Lag-1 cross-covariance (index 0 undefined) | + +### Sufficient Statistics + +From the smoother output, accumulate six matrices: + +$$ +A = \sum_{t=1}^{T-1} P_{t,t-1|T} +\qquad +B = \sum_{t=0}^{T-2} \hat{x}_{t|T}\hat{x}_{t|T}^\top + P_{t|T} +$$ + +$$ +C = \sum_{t=1}^{T-1} \hat{x}_{t|T}\hat{x}_{t|T}^\top + P_{t|T} +\qquad +D = \sum_{t=0}^{T-1} \hat{x}_{t|T}\hat{x}_{t|T}^\top + P_{t|T} +$$ + +$$ +W = \sum_{t=0}^{T-1} z_t \hat{x}_{t|T}^\top +\qquad +\Sigma_{zz} = \sum_{t=0}^{T-1} z_t z_t^\top +$$ + +### M-Step (Closed-Form Updates) + +$$ +F \leftarrow A B^{-1} +$$ + +$$ +Q \leftarrow \frac{C - F A^\top}{T - 1}, \quad Q \leftarrow \tfrac{1}{2}(Q + Q^\top) + \varepsilon I +$$ + +$$ +H \leftarrow W D^{-1} +$$ + +$$ +R \leftarrow \frac{\Sigma_{zz} - H W^\top}{T}, \quad R \leftarrow \tfrac{1}{2}(R + R^\top) + \varepsilon I +$$ + +$$ +\mu_0 \leftarrow \hat{x}_{0|T}, \quad P_0 \leftarrow P_{0|T} +$$ + +The symmetrisation and ridge term $\varepsilon I$ ($\varepsilon = 10^{-6}$) enforce that $Q$ and $R$ remain symmetric positive definite, preventing numerical collapse. + +Matrix "division" — e.g. $A B^{-1}$ — is implemented as `SolveSystem(B, A^T)^T` (Gaussian elimination) to avoid explicit matrix inversion. + +### Convergence + +After each EM iteration, compute the log-likelihood $\ell(\theta)$ from the RTS smoother. Convergence is declared when + +$$ +|\ell^{(k)} - \ell^{(k-1)}| < \delta +$$ + +for a user-supplied tolerance $\delta$. + +## Complexity Analysis + +| Case | Time per iteration | Space (stack) | Notes | +|-------|-----------------------|------------------------|-------| +| All | $O(T \cdot N^3)$ | $O(T \cdot N^2)$ | Dominated by RTS smoother forward/backward | + +All storage is stack-allocated inside `KalmanSmoother` (owned by `ExpectationMaximization`) and in local M-step temporaries. + +## Step-by-Step Walkthrough + +Consider $N=1$, $M=1$, $T=3$, observations $z=[0.5, 0.3, 0.8]$, initial guess $F=1, H=1, Q=0.5, R=1, \mu_0=0, P_0=1$. + +**Iteration 1:** + +1. E-step via RTS smoother: obtain $\hat{x}_{0|3}, \hat{x}_{1|3}, \hat{x}_{2|3}$ and corresponding covariances and lag cross-covariances. +2. Accumulate scalars: + - $A = P_{2,1|3} + P_{3,2|3}$ (indices 2 and 3 in the 1-indexed convention). *(In the implementation indices 1..T-1 are used.)* + - $B, C, D, W, \Sigma_{zz}$ as sums over the smoothed moments. +3. M-step: $F \leftarrow A/B$, $Q \leftarrow (C - F\cdot A)/(T-1)$, etc. +4. Evaluate new log-likelihood $\ell^{(1)}$. + +Repeat until $|\ell^{(k)} - \ell^{(k-1)}| < \delta$ or maximum iterations reached. + +## Pitfalls & Edge Cases + +- **Local optima**: EM converges to a local maximum of the likelihood, not necessarily the global maximum. The quality of the solution depends heavily on the initial parameter guess. +- **Short sequences ($T \ll N$)**: With fewer observations than state dimensions, some sufficient-statistic matrices become rank-deficient and `SolveSystem` may produce inaccurate results. Prefer $T \gg N$. +- **$Q$ or $R$ collapse**: Without the $\varepsilon I$ regularisation, a maximally tight model (zero-noise) can collapse $Q$ or $R$ to zero, making the likelihood degenerate. If this happens, increase the regularisation or constrain the parameters. +- **Float only**: `ExpectationMaximization` has no template type parameter. Dynamics values typically exceed the $[-1, 1]$ range of Q15/Q31. Scale your state variables into $[-1, 1]$ and use a float wrapper if fixed-point EM is required. +- **Re-entrant smoother**: `ExpectationMaximization` owns a `KalmanSmoother` instance. The smoother state is overwritten on every call to `Run()`. Do not share an `ExpectationMaximization` instance across threads. + +## Variants & Generalizations + +- **EM for EKF/UKF**: Replace the RTS smoother with an extended or unscented smoother for nonlinear models. The M-step remains identical. +- **Constrained EM**: Fix some parameters (e.g., $H$ is known) by simply not updating them in the M-step. +- **Online (incremental) EM**: Accumulate sufficient statistics incrementally to handle streaming data. +- **Structural constraints on $F$**: If $F$ has a known parametric form (e.g., a companion matrix), the M-step can be modified to enforce the structure. + +## Applications + +- **System identification**: Learn the dynamics $F$ and noise statistics $Q$, $R$ of an unknown linear system from input-output data. +- **Sensor calibration**: Identify measurement noise covariance $R$ from reference measurements. +- **Hyperparameter tuning for KF**: Replace hand-tuned $Q$, $R$ with data-driven estimates before deploying a real-time Kalman filter. +- **Time-series model selection**: Compare log-likelihoods of different state-space structures to select model order. + +## Connections to Other Algorithms + +- **`filters::KalmanSmoother`**: Provides the complete E-step. `ExpectationMaximization` owns a `KalmanSmoother` instance internally. +- **`filters::KalmanFilter`**: After EM converges, pass the resulting `EmParameters` to `KalmanFilter::SetStateTransition()`, `SetProcessNoise()`, and `SetMeasurementNoise()` for real-time deployment. +- **`solvers::GaussianElimination`**: Used internally (via `KalmanSmoother`) for numerically stable matrix solves in both the smoother and the M-step. + +## References & Further Reading + +- Shumway, R. H., & Stoffer, D. S. (1982). An approach to time series smoothing and forecasting using the EM algorithm. *Journal of Time Series Analysis*, 3(4), 253–264. +- Shumway, R. H., & Stoffer, D. S. (2000). *Time Series Analysis and Its Applications*. Springer. (Section 6.3) +- Dempster, A. P., Laird, N. M., & Rubin, D. B. (1977). Maximum likelihood from incomplete data via the EM algorithm. *Journal of the Royal Statistical Society, Series B*, 39(1), 1–38. +- Ghahramani, Z., & Hinton, G. E. (1996). Parameter estimation for linear dynamical systems. Technical Report CRG-TR-96-2, University of Toronto. diff --git a/doc/estimators/README.md b/doc/estimators/README.md index 7204399f..aac4cf7a 100644 --- a/doc/estimators/README.md +++ b/doc/estimators/README.md @@ -4,10 +4,11 @@ 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 | -| [Yule-Walker](YuleWalker.md) | Autoregressive model parameter estimation via the Yule-Walker equations | +| Algorithm | Description | +|-------------------------------------------------------------------|-------------------------------------------------------------------------| +| [Linear Regression](LinearRegression.md) | Ordinary least-squares regression using the normal equation | +| [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/doc/filters/README.md b/doc/filters/README.md index 4e51db7f..eb6bdeba 100644 --- a/doc/filters/README.md +++ b/doc/filters/README.md @@ -13,6 +13,7 @@ Filters that incorporate feedback and a dynamic internal model of the system. | [Kalman Filter](active/KalmanFilter.md) | Optimal recursive state estimator for linear systems with Gaussian noise | | [Extended Kalman Filter](active/ExtendedKalmanFilter.md) | Nonlinear state estimator using first-order linearization (Jacobians) | | [Unscented Kalman Filter](active/UnscentedKalmanFilter.md) | Nonlinear state estimator using sigma points; no Jacobians required | +| [Kalman Smoother](active/KalmanSmoother.md) | Offline RTS smoother providing MMSE estimates over the full observation sequence | ### Passive Filters diff --git a/doc/filters/active/KalmanSmoother.md b/doc/filters/active/KalmanSmoother.md new file mode 100644 index 00000000..05f962ab --- /dev/null +++ b/doc/filters/active/KalmanSmoother.md @@ -0,0 +1,167 @@ +# Kalman Smoother (RTS Smoother) + +## Overview & Motivation + +The Kalman filter is a **causal** estimator: its state estimate at time $t$ uses only observations up to and including time $t$. When the full observation sequence is available (offline/batch setting), the **Rauch-Tung-Striebel (RTS) smoother** refines every filtered estimate by incorporating future measurements. The result is the minimum-mean-square-error (MMSE) state estimate given the *entire* sequence $z_{1:T}$. + +The RTS smoother is the prerequisite for the Expectation-Maximization (EM) algorithm for Kalman Filter parameter identification: the E-step requires smoothed means, smoothed covariances, and the **lag-1 cross-covariance** $P_{t,t-1|T}$ in order to form the sufficient statistics used by the M-step. + +## Mathematical Theory + +### State-Space Model + +$$ +x_{t+1} = F x_t + w_t, \quad w_t \sim \mathcal{N}(0, Q) +$$ + +$$ +z_t = H x_t + v_t, \quad v_t \sim \mathcal{N}(0, R) +$$ + +with $x_0 \sim \mathcal{N}(\mu_0, P_0)$. + +### Forward Pass (Kalman Filter) + +For $t = 0, 1, \ldots, T-1$: + +**Initialise** (t = 0 only): + +$$\hat{x}_{0|-} = \mu_0, \quad P_{0|-} = P_0$$ + +**Update:** + +$$ +S_t = H P_{t|-} H^\top + R +$$ + +$$ +K_t = P_{t|-} H^\top S_t^{-1} +$$ + +$$ +\hat{x}_{t|t} = \hat{x}_{t|-} + K_t (z_t - H \hat{x}_{t|-}) +$$ + +$$ +P_{t|t} = (I - K_t H) P_{t|-} (I - K_t H)^\top + K_t R K_t^\top \quad \text{(Joseph form)} +$$ + +**Log-likelihood contribution:** + +$$ +\ell_t = -\tfrac{1}{2}\bigl(\log\det S_t + (z_t - H\hat{x}_{t|-})^\top S_t^{-1} (z_t - H\hat{x}_{t|-}) + m\log 2\pi\bigr) +$$ + +where $m$ = `MeasurementSize`. The total is $\ell = \sum_{t=0}^{T-1} \ell_t$. + +**Predict** (for $t < T-1$): + +$$ +\hat{x}_{t+1|-} = F \hat{x}_{t|t}, \quad P_{t+1|-} = F P_{t|t} F^\top + Q +$$ + +### Backward Pass (RTS Smoother) + +Initialise at $t = T-1$: + +$$ +\hat{x}_{T-1|T} = \hat{x}_{T-1|T-1}, \quad P_{T-1|T} = P_{T-1|T-1} +$$ + +For $t = T-2, T-3, \ldots, 0$: + +**Smoother gain:** + +$$ +G_t = P_{t|t} F^\top P_{t+1|t}^{-1} +$$ + +**Smoothed mean and covariance:** + +$$ +\hat{x}_{t|T} = \hat{x}_{t|t} + G_t (\hat{x}_{t+1|T} - \hat{x}_{t+1|t}) +$$ + +$$ +P_{t|T} = P_{t|t} + G_t (P_{t+1|T} - P_{t+1|t}) G_t^\top +$$ + +### Lag-1 Cross-Covariance + +The EM M-step requires $P_{t,t-1|T} = \mathrm{Cov}(x_t, x_{t-1} \mid z_{1:T})$. + +**Initialisation** (Shumway & Stoffer, 1982): + +$$ +P_{T-1, T-2|T} = (I - K_{T-1} H) F P_{T-2|T-2} +$$ + +**Recursion** for $t = T-3, \ldots, 0$: + +$$ +P_{t+1, t|T} = P_{t+1|t+1} G_t^\top + G_{t+1} (P_{t+2, t+1|T} - F P_{t+1|t+1}) G_t^\top +$$ + +Note: $P_{0,-1|T}$ is undefined; index 0 of `lagCrossCovariances` is always zero. + +## Complexity Analysis + +| Case | Time | Space | Notes | +|-------|----------------|--------------------------------|-------------------------------| +| All | $O(T \cdot N^3)$ | $O(T \cdot N^2)$ stack | Dominant cost: $N\times N$ solves at each step | + +All storage is stack-allocated via `std::array`. There is no heap usage. + +## Step-by-Step Walkthrough + +Consider a 1-D constant-position model ($N=1$, $M=1$, $T=3$) with $F=1$, $H=1$, $Q=0.1$, $R=1$, $\mu_0=0$, $P_0=1$, and observations $z = [0.5, 0.3, 0.8]$. + +**Forward pass:** + +| $t$ | $P_{t\|-}$ | $S_t$ | $K_t$ | $\hat{x}_{t\|t}$ | $P_{t\|t}$ | +|-----|-----------|-------|--------|------------------|-----------| +| 0 | 1.0 | 2.0 | 0.500 | 0.250 | 0.500 | +| 1 | 0.600 | 1.600 | 0.375 | 0.363 | 0.375 | +| 2 | 0.475 | 1.475 | 0.322 | 0.620 | 0.322 | + +**Backward pass ($t=1$ then $t=0$):** + +$t=1$: $G_1 = 0.500/0.600 = 0.833$; $\hat{x}_{1|3} = 0.363 + 0.833(0.620 - 0.363) \approx 0.577$ + +$t=0$: $G_0 = 0.375/0.375 = 1.000$; $\hat{x}_{0|3} = 0.250 + 1.000(0.577 - 0.363) \approx 0.464$ + +Notice how the smoothed $\hat{x}_{0|3}=0.464$ incorporates all three observations, whereas the filtered $\hat{x}_{0|0}=0.250$ only used the first. + +## Pitfalls & Edge Cases + +- **Near-singular $P_{t+1|t}$**: The smoother gain is computed via `SolveSystem` (Gaussian elimination with partial pivoting) rather than explicit matrix inversion. If the predicted covariance becomes near-singular (possible when $Q \approx 0$), numerical accuracy degrades. Ensure $Q$ has positive diagonal entries. +- **Joseph-form update**: The standard update $P = (I-KH)P$ is numerically unstable for finite-precision arithmetic. This implementation uses the Joseph form to maintain positive semi-definiteness. +- **`lagCrossCovariances[0]` is always zero**: The lag-1 cross-covariance for index 0 ($P_{0,-1|T}$) is undefined. The first valid entry is index 1 ($P_{1,0|T}$). +- **Unsigned loop guard**: The backward loop uses `std::size_t`; the break guard `if (t == 0) break` prevents unsigned wrap-around. +- **Stack usage**: For large $N$ or $T$, the five internal `std::array` members dominate stack usage. Choose `MaxSteps` conservatively on resource-constrained targets. + +## Variants & Generalizations + +- **Square-root RTS smoother**: Propagates Cholesky factors instead of full covariance matrices for improved numerical conditioning. +- **Information filter smoother**: Operates in the dual (information) domain; preferable when observations are dense relative to state transitions. +- **Extended / Unscented smoother**: Replace the linear forward pass with EKF or UKF; the backward pass equations remain identical in form. + +## Applications + +- **EM parameter identification**: Used as the E-step by `ExpectationMaximization` to compute the sufficient statistics $\{A, B, C, D, W, \Sigma_{zz}\}$ for the M-step. +- **Offline trajectory estimation**: Position/velocity smoothing in GNSS post-processing and inertial navigation. +- **Batch signal denoising**: Any application where the full observation sequence is available before estimation begins. + +## Connections to Other Algorithms + +- **`filters::KalmanFilter`**: The forward pass of `KalmanSmoother` replicates the KF update equations. The smoother is applied *after* the filter, not *instead of* it. +- **`estimators::ExpectationMaximization`**: The smoother is owned and invoked by `ExpectationMaximization` as its E-step. Users who only need EM should interact with `ExpectationMaximization` directly. +- **`solvers::GaussianElimination`**: Used for all matrix "division" operations (smoother gain, Kalman gain) to avoid explicit matrix inversion. +- **`solvers::CholeskyDecomposition`**: Used to compute $\log \det S_t$ for the log-likelihood. + +## References & Further Reading + +- Rauch, H. E., Tung, F., & Striebel, C. T. (1965). Maximum likelihood estimates of linear dynamic systems. *AIAA Journal*, 3(8), 1445–1450. +- Shumway, R. H., & Stoffer, D. S. (1982). An approach to time series smoothing and forecasting using the EM algorithm. *Journal of Time Series Analysis*, 3(4), 253–264. +- Shumway, R. H., & Stoffer, D. S. (2000). *Time Series Analysis and Its Applications*. Springer. (Chapter 6) +- Särkkä, S. (2013). *Bayesian Filtering and Smoothing*. Cambridge University Press. (Chapter 8) diff --git a/numerical/estimators/offline/CMakeLists.txt b/numerical/estimators/offline/CMakeLists.txt index ed632abb..8ab3e7c6 100644 --- a/numerical/estimators/offline/CMakeLists.txt +++ b/numerical/estimators/offline/CMakeLists.txt @@ -7,16 +7,19 @@ target_include_directories(numerical.estimators.offline ${NUMERICAL_VISIBILITY} target_link_libraries(numerical.estimators.offline ${NUMERICAL_VISIBILITY} infra.util + numerical.filters.active numerical.math numerical.solver ) target_sources(numerical.estimators.offline PRIVATE + ExpectationMaximization.hpp LinearRegression.hpp YuleWalker.hpp ) numerical_add_coverage_sources(numerical.estimators.offline + ExpectationMaximization.cpp LinearRegression.cpp YuleWalker.cpp ) diff --git a/numerical/estimators/offline/ExpectationMaximization.cpp b/numerical/estimators/offline/ExpectationMaximization.cpp new file mode 100644 index 00000000..708586d2 --- /dev/null +++ b/numerical/estimators/offline/ExpectationMaximization.cpp @@ -0,0 +1,7 @@ +#include "numerical/estimators/offline/ExpectationMaximization.hpp" + +namespace estimators +{ + template class ExpectationMaximization<2, 1, 10>; + template class ExpectationMaximization<4, 2, 20>; +} diff --git a/numerical/estimators/offline/ExpectationMaximization.hpp b/numerical/estimators/offline/ExpectationMaximization.hpp new file mode 100644 index 00000000..e8c1452a --- /dev/null +++ b/numerical/estimators/offline/ExpectationMaximization.hpp @@ -0,0 +1,205 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/filters/active/KalmanSmoother.hpp" +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/Matrix.hpp" +#include "numerical/solvers/GaussianElimination.hpp" +#include +#include +#include + +namespace estimators +{ + template + class ExpectationMaximization + { + static_assert(StateSize > 0, "StateSize must be positive"); + static_assert(MeasurementSize > 0, "MeasurementSize must be positive"); + static_assert(MaxSteps >= 2, "MaxSteps must be at least 2 for EM"); + + public: + using StateVector = math::Vector; + using StateMatrix = math::SquareMatrix; + using MeasurementMatrix = math::Matrix; + using MeasurementVector = math::Vector; + using MeasurementCovariance = math::SquareMatrix; + + struct EmParameters + { + StateMatrix F; + MeasurementMatrix H; + StateMatrix Q; + MeasurementCovariance R; + StateVector initialState; + StateMatrix initialCovariance; + }; + + struct EmResult + { + EmParameters parameters; + std::size_t iterations; + float logLikelihood; + bool converged; + }; + + ExpectationMaximization() = default; + + OPTIMIZE_FOR_SPEED EmResult Run( + const std::array& observations, + std::size_t numSteps, + const EmParameters& initialParameters, + std::size_t maxIterations, + float convergenceTolerance); + + private: + using SmootherType = filters::KalmanSmoother; + using SmootherOutput = typename SmootherType::SmootherOutput; + + SmootherType smoother_; + + OPTIMIZE_FOR_SPEED EmParameters MStep( + const SmootherOutput& smootherOutput, + const std::array& observations, + std::size_t numSteps); + + static StateMatrix SymmetrizeState(const StateMatrix& M); + static MeasurementCovariance SymmetrizeMeasurement(const MeasurementCovariance& M); + }; + + // Implementation // + + template + OPTIMIZE_FOR_SPEED + typename ExpectationMaximization::EmResult + ExpectationMaximization::Run( + const std::array& observations, + std::size_t numSteps, + const EmParameters& initialParameters, + std::size_t maxIterations, + float convergenceTolerance) + { + really_assert(numSteps >= 2 && numSteps <= MaxSteps); + really_assert(maxIterations > 0); + + EmParameters currentParams = initialParameters; + float prevLogLikelihood = std::numeric_limits::lowest(); + float logLikelihood = std::numeric_limits::lowest(); + std::size_t iter = 0; + bool converged = false; + + while (iter < maxIterations) + { + const auto smootherOutput = smoother_.Smooth( + currentParams.F, currentParams.H, + currentParams.Q, currentParams.R, + observations, numSteps, + currentParams.initialState, currentParams.initialCovariance); + + logLikelihood = smootherOutput.logLikelihood; + ++iter; + + if (std::abs(logLikelihood - prevLogLikelihood) < convergenceTolerance) + { + converged = true; + break; + } + prevLogLikelihood = logLikelihood; + + currentParams = MStep(smootherOutput, observations, numSteps); + } + + return EmResult{ currentParams, iter, logLikelihood, converged }; + } + + template + OPTIMIZE_FOR_SPEED + typename ExpectationMaximization::EmParameters + ExpectationMaximization::MStep( + const SmootherOutput& smootherOutput, + const std::array& observations, + std::size_t numSteps) + { + StateMatrix A{}; + StateMatrix B{}; + StateMatrix C{}; + StateMatrix D{}; + math::Matrix W{}; + MeasurementCovariance sumZZT{}; + + for (std::size_t t = 0; t < numSteps; ++t) + { + const auto& xS = smootherOutput.smoothedMeans[t]; + const auto& PS = smootherOutput.smoothedCovariances[t]; + const auto xxT = xS * xS.Transpose(); + const auto PxxT = PS + xxT; + + // S2 / B: t = 0 .. T-2 + if (t < numSteps - 1) + B += PxxT; + + // S3_F / C and S1 / A: t = 1 .. T-1 + if (t >= 1) + { + C += PxxT; + A += smootherOutput.lagCrossCovariances[t] + xS * smootherOutput.smoothedMeans[t - 1].Transpose(); + } + + // S3_H / D, W, sumZZT: t = 0 .. T-1 + D += PxxT; + W += observations[t] * xS.Transpose(); + sumZZT += observations[t] * observations[t].Transpose(); + } + + // F_new = A * B^{-1} → SolveSystem(B, A^T)^T + const auto F_new = solvers::SolveSystem( + B, A.Transpose()) + .Transpose(); + + // Q_new = (C - F_new * A^T) / (T-1), symmetrized + PD-regularized + const float invTm1 = 1.0f / static_cast(numSteps - 1); + auto Q_new = SymmetrizeState((C - F_new * A.Transpose()) * invTm1); + Q_new += StateMatrix::Identity() * 1e-6f; + + // H_new = W * D^{-1} → SolveSystem(D, W^T)^T + const auto H_new = solvers::SolveSystem( + D, W.Transpose()) + .Transpose(); + + // R_new = (sumZZT - H_new * W^T) / T, symmetrized + PD-regularized + const float invT = 1.0f / static_cast(numSteps); + auto R_new = SymmetrizeMeasurement((sumZZT - H_new * W.Transpose()) * invT); + R_new += MeasurementCovariance::Identity() * 1e-6f; + + return EmParameters{ + F_new, + H_new, + Q_new, + R_new, + smootherOutput.smoothedMeans[0], + smootherOutput.smoothedCovariances[0] + }; + } + + template + typename ExpectationMaximization::StateMatrix + ExpectationMaximization::SymmetrizeState(const StateMatrix& M) + { + return (M + M.Transpose()) * 0.5f; + } + + template + typename ExpectationMaximization::MeasurementCovariance + ExpectationMaximization::SymmetrizeMeasurement(const MeasurementCovariance& M) + { + return (M + M.Transpose()) * 0.5f; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class ExpectationMaximization<2, 1, 10>; + extern template class ExpectationMaximization<4, 2, 20>; +#endif +} diff --git a/numerical/estimators/offline/test/CMakeLists.txt b/numerical/estimators/offline/test/CMakeLists.txt index e275fb67..9011dc99 100644 --- a/numerical/estimators/offline/test/CMakeLists.txt +++ b/numerical/estimators/offline/test/CMakeLists.txt @@ -8,6 +8,7 @@ target_link_libraries(numerical.estimators.offline_test PUBLIC ) target_sources(numerical.estimators.offline_test PRIVATE + TestExpectationMaximization.cpp TestLinearRegression.cpp TestYuleWalker.cpp ) diff --git a/numerical/estimators/offline/test/TestExpectationMaximization.cpp b/numerical/estimators/offline/test/TestExpectationMaximization.cpp new file mode 100644 index 00000000..774fdb85 --- /dev/null +++ b/numerical/estimators/offline/test/TestExpectationMaximization.cpp @@ -0,0 +1,147 @@ +#include "numerical/estimators/offline/ExpectationMaximization.hpp" +#include +#include +#include + +namespace +{ + class TestExpectationMaximization : public ::testing::Test + { + protected: + static constexpr std::size_t N = 2; + static constexpr std::size_t M = 1; + static constexpr std::size_t T = 10; + + using Em = estimators::ExpectationMaximization; + using EmParameters = Em::EmParameters; + using EmResult = Em::EmResult; + using StateMatrix = Em::StateMatrix; + using StateVector = Em::StateVector; + using MeasurementMatrix = Em::MeasurementMatrix; + using MeasurementVector = Em::MeasurementVector; + using MeasurementCovariance = Em::MeasurementCovariance; + + Em em; + + // Deliberately wrong initial guess — F = I, H known, Q/R inflated + EmParameters initialGuess{ + StateMatrix::Identity(), + MeasurementMatrix{ { 1.0f, 0.0f } }, + StateMatrix::Identity() * 0.1f, + MeasurementCovariance::Identity() * 0.5f, + StateVector{}, + StateMatrix::Identity() + }; + + // Hardcoded synthetic observations from true model (noisy position) + std::array observations{ { MeasurementVector{ { 0.07f } }, + MeasurementVector{ { 0.15f } }, + MeasurementVector{ { 0.22f } }, + MeasurementVector{ { 0.28f } }, + MeasurementVector{ { 0.36f } }, + MeasurementVector{ { 0.43f } }, + MeasurementVector{ { 0.52f } }, + MeasurementVector{ { 0.59f } }, + MeasurementVector{ { 0.64f } }, + MeasurementVector{ { 0.73f } } } }; + }; +} + +TEST_F(TestExpectationMaximization, log_likelihood_improves_over_iterations) +{ + // One iteration versus ten: the log-likelihood should increase meaningfully. + const float noConverge = std::numeric_limits::lowest(); + const auto result1 = em.Run(observations, T, initialGuess, 1, noConverge); + Em em10; + const auto result10 = em10.Run(observations, T, initialGuess, 10, noConverge); + + EXPECT_GT(result10.logLikelihood, result1.logLikelihood + 0.1f); +} + +TEST_F(TestExpectationMaximization, iteration_count_is_plausible) +{ + const auto result = em.Run(observations, T, initialGuess, 50, 1e-3f); + + EXPECT_GE(result.iterations, std::size_t{ 2 }); + EXPECT_LE(result.iterations, std::size_t{ 50 }); +} + +TEST_F(TestExpectationMaximization, log_likelihood_is_finite) +{ + // The Kalman log-likelihood may be positive for a tight model (small R); + // it is not bounded above. Only finiteness is guaranteed. + const auto result = em.Run(observations, T, initialGuess, 50, 1e-3f); + + EXPECT_TRUE(std::isfinite(result.logLikelihood)); +} + +TEST_F(TestExpectationMaximization, process_noise_is_symmetric) +{ + const auto result = em.Run(observations, T, initialGuess, 50, 1e-3f); + + for (std::size_t i = 0; i < N; ++i) + for (std::size_t j = 0; j < N; ++j) + EXPECT_NEAR(result.parameters.Q.at(i, j), result.parameters.Q.at(j, i), 1e-5f); +} + +TEST_F(TestExpectationMaximization, measurement_noise_is_symmetric) +{ + const auto result = em.Run(observations, T, initialGuess, 50, 1e-3f); + + for (std::size_t i = 0; i < M; ++i) + for (std::size_t j = 0; j < M; ++j) + EXPECT_NEAR(result.parameters.R.at(i, j), result.parameters.R.at(j, i), 1e-5f); +} + +TEST_F(TestExpectationMaximization, process_noise_diagonal_is_positive) +{ + const auto result = em.Run(observations, T, initialGuess, 50, 1e-3f); + + for (std::size_t i = 0; i < N; ++i) + EXPECT_GT(result.parameters.Q.at(i, i), 0.0f); +} + +TEST_F(TestExpectationMaximization, measurement_noise_diagonal_is_positive) +{ + const auto result = em.Run(observations, T, initialGuess, 50, 1e-3f); + + for (std::size_t i = 0; i < M; ++i) + EXPECT_GT(result.parameters.R.at(i, i), 0.0f); +} + +TEST_F(TestExpectationMaximization, initial_state_is_plausible) +{ + const auto result = em.Run(observations, T, initialGuess, 50, 1e-3f); + + EXPECT_GT(result.parameters.initialState.at(0, 0), -2.0f); + EXPECT_LT(result.parameters.initialState.at(0, 0), 2.0f); +} + +TEST_F(TestExpectationMaximization, recovered_parameters_produce_finite_predictions) +{ + // With any converged parameters, running the smoother again must not produce NaN/Inf. + const float noConverge = std::numeric_limits::lowest(); + const auto result = em.Run(observations, T, initialGuess, 20, noConverge); + + Em em2; + const auto result2 = em2.Run(observations, T, result.parameters, 1, noConverge); + + EXPECT_TRUE(std::isfinite(result2.logLikelihood)); +} + +TEST_F(TestExpectationMaximization, log_likelihood_increases_monotonically) +{ + // Run EM one step at a time, feeding output as next input; verify non-decreasing log-likelihood + const float neverConverge = std::numeric_limits::lowest(); + EmParameters params = initialGuess; + float prevLl = neverConverge; + + for (std::size_t step = 0; step < 5; ++step) + { + const auto result = em.Run(observations, T, params, 1, neverConverge); + if (prevLl != neverConverge) + EXPECT_GE(result.logLikelihood, prevLl - 1e-3f); + prevLl = result.logLikelihood; + params = result.parameters; + } +} diff --git a/numerical/filters/active/CMakeLists.txt b/numerical/filters/active/CMakeLists.txt index 05480571..323787f2 100644 --- a/numerical/filters/active/CMakeLists.txt +++ b/numerical/filters/active/CMakeLists.txt @@ -15,6 +15,7 @@ target_sources(numerical.filters.active PRIVATE ExtendedKalmanFilter.hpp KalmanFilter.hpp KalmanFilterBase.hpp + KalmanSmoother.hpp UnscentedKalmanFilter.hpp ) @@ -22,6 +23,7 @@ numerical_add_coverage_sources(numerical.filters.active ExtendedKalmanFilter.cpp KalmanFilter.cpp KalmanFilterBase.cpp + KalmanSmoother.cpp UnscentedKalmanFilter.cpp ) diff --git a/numerical/filters/active/KalmanSmoother.cpp b/numerical/filters/active/KalmanSmoother.cpp new file mode 100644 index 00000000..5e280d4d --- /dev/null +++ b/numerical/filters/active/KalmanSmoother.cpp @@ -0,0 +1,7 @@ +#include "numerical/filters/active/KalmanSmoother.hpp" + +namespace filters +{ + template class KalmanSmoother<2, 1, 10>; + template class KalmanSmoother<4, 2, 20>; +} diff --git a/numerical/filters/active/KalmanSmoother.hpp b/numerical/filters/active/KalmanSmoother.hpp new file mode 100644 index 00000000..fb72c1fc --- /dev/null +++ b/numerical/filters/active/KalmanSmoother.hpp @@ -0,0 +1,214 @@ +#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/CholeskyDecomposition.hpp" +#include "numerical/solvers/GaussianElimination.hpp" +#include +#include +#include + +namespace filters +{ + template + class KalmanSmoother + { + static_assert(StateSize > 0, "StateSize must be positive"); + static_assert(MeasurementSize > 0, "MeasurementSize must be positive"); + static_assert(MaxSteps >= 2, "MaxSteps must be at least 2"); + + public: + using StateVector = math::Vector; + using StateMatrix = math::SquareMatrix; + using MeasurementMatrix = math::Matrix; + using MeasurementVector = math::Vector; + using MeasurementCovariance = math::SquareMatrix; + using KalmanGainMatrix = math::Matrix; + + struct SmootherOutput + { + std::array smoothedMeans{}; + std::array smoothedCovariances{}; + // lagCrossCovariances[t] = P_{t, t-1 | T} + // Index 0 is always zero (undefined); indices 1..numSteps-1 are valid + std::array lagCrossCovariances{}; + float logLikelihood{}; + }; + + KalmanSmoother() = default; + + OPTIMIZE_FOR_SPEED SmootherOutput Smooth( + const StateMatrix& F, + const MeasurementMatrix& H, + const StateMatrix& Q, + const MeasurementCovariance& R, + const std::array& observations, + std::size_t numSteps, + const StateVector& initialState, + const StateMatrix& initialCovariance); + + private: + std::array filteredMeans_{}; + std::array filteredCovariances_{}; + std::array predictedMeans_{}; + std::array predictedCovariances_{}; + std::array kalmanGains_{}; + + OPTIMIZE_FOR_SPEED float RunForwardPass( + const StateMatrix& F, + const MeasurementMatrix& H, + const StateMatrix& Q, + const MeasurementCovariance& R, + const std::array& observations, + std::size_t numSteps, + const StateVector& initialState, + const StateMatrix& initialCovariance); + + OPTIMIZE_FOR_SPEED void RunBackwardPass( + const StateMatrix& F, + const MeasurementMatrix& H, + std::size_t numSteps, + SmootherOutput& output); + }; + + // Implementation // + + template + OPTIMIZE_FOR_SPEED + typename KalmanSmoother::SmootherOutput + KalmanSmoother::Smooth( + const StateMatrix& F, + const MeasurementMatrix& H, + const StateMatrix& Q, + const MeasurementCovariance& R, + const std::array& observations, + std::size_t numSteps, + const StateVector& initialState, + const StateMatrix& initialCovariance) + { + really_assert(numSteps >= 2 && numSteps <= MaxSteps); + + SmootherOutput output; + output.logLikelihood = RunForwardPass(F, H, Q, R, observations, numSteps, initialState, initialCovariance); + RunBackwardPass(F, H, numSteps, output); + return output; + } + + template + OPTIMIZE_FOR_SPEED float + KalmanSmoother::RunForwardPass( + const StateMatrix& F, + const MeasurementMatrix& H, + const StateMatrix& Q, + const MeasurementCovariance& R, + const std::array& observations, + std::size_t numSteps, + const StateVector& initialState, + const StateMatrix& initialCovariance) + { + predictedMeans_[0] = initialState; + predictedCovariances_[0] = initialCovariance; + + float logLikelihood = 0.0f; + const float logTwoPi = std::log(2.0f * std::numbers::pi_v); + + for (std::size_t t = 0; t < numSteps; ++t) + { + const auto nu = observations[t] - H * predictedMeans_[t]; + const auto S = H * predictedCovariances_[t] * H.Transpose() + R; + + // Kalman gain: K = P H^T S^{-1} via SolveSystem(S, H*P)^T + const auto K = solvers::SolveSystem( + S, H * predictedCovariances_[t]) + .Transpose(); + + filteredMeans_[t] = predictedMeans_[t] + K * nu; + + // Joseph-form covariance update for numerical PD-preservation + const auto IminusKH = StateMatrix::Identity() - K * H; + filteredCovariances_[t] = + IminusKH * predictedCovariances_[t] * IminusKH.Transpose() + K * R * K.Transpose(); + + kalmanGains_[t] = K; + + // Log-likelihood contribution: -0.5 * (log det S + nu^T S^{-1} nu + M*log(2pi)) + const auto L = solvers::CholeskyDecomposition(S); + const auto S_inv_nu = solvers::SolveSystem(S, nu); + float logDetS = 0.0f; + float quadForm = 0.0f; + for (std::size_t i = 0; i < MeasurementSize; ++i) + { + logDetS += std::log(L.at(i, i)); + quadForm += nu.at(i, 0) * S_inv_nu.at(i, 0); + } + logDetS *= 2.0f; + logLikelihood += -0.5f * (logDetS + quadForm + static_cast(MeasurementSize) * logTwoPi); + + if (t < numSteps - 1) + { + predictedMeans_[t + 1] = F * filteredMeans_[t]; + predictedCovariances_[t + 1] = F * filteredCovariances_[t] * F.Transpose() + Q; + } + } + + return logLikelihood; + } + + template + OPTIMIZE_FOR_SPEED void + KalmanSmoother::RunBackwardPass( + const StateMatrix& F, + const MeasurementMatrix& H, + std::size_t numSteps, + SmootherOutput& output) + { + output.smoothedMeans[numSteps - 1] = filteredMeans_[numSteps - 1]; + output.smoothedCovariances[numSteps - 1] = filteredCovariances_[numSteps - 1]; + + StateMatrix G_prev{}; + + for (std::size_t t = numSteps - 2;; --t) + { + // RTS smoother gain: G_t = P_{t|t} F^T (P_{t+1|t})^{-1} + // Solve P_{t+1|t} * G_t^T = F * P_{t|t} then transpose + const auto G_t = solvers::SolveSystem( + predictedCovariances_[t + 1], + F * filteredCovariances_[t]) + .Transpose(); + + const auto deltaP = output.smoothedCovariances[t + 1] - predictedCovariances_[t + 1]; + output.smoothedMeans[t] = filteredMeans_[t] + G_t * (output.smoothedMeans[t + 1] - predictedMeans_[t + 1]); + output.smoothedCovariances[t] = filteredCovariances_[t] + G_t * deltaP * G_t.Transpose(); + + // Lag-1 cross-covariance: P_{t+1, t | T} + if (t == numSteps - 2) + { + // Initialization: P_{T-1, T-2 | T} = (I - K_{T-1} H) F P_{T-2 | T-2} + const auto IminusKH = StateMatrix::Identity() - kalmanGains_[numSteps - 1] * H; + output.lagCrossCovariances[numSteps - 1] = + IminusKH * F * filteredCovariances_[numSteps - 2]; + } + else + { + // Recursion: P_{t+2, t+1 | T} = P_{t+1|t+1} G_t^T + G_{t+1} (P_{t+2,t+1|T} - F P_{t+1|t+1}) G_t^T + const auto crossDiff = output.lagCrossCovariances[t + 2] - F * filteredCovariances_[t + 1]; + output.lagCrossCovariances[t + 1] = + filteredCovariances_[t + 1] * G_t.Transpose() + G_prev * crossDiff * G_t.Transpose(); + } + + G_prev = G_t; + + if (t == 0) + break; + } + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class KalmanSmoother<2, 1, 10>; + extern template class KalmanSmoother<4, 2, 20>; +#endif +} diff --git a/numerical/filters/active/test/CMakeLists.txt b/numerical/filters/active/test/CMakeLists.txt index a7d67b56..133f8e2d 100644 --- a/numerical/filters/active/test/CMakeLists.txt +++ b/numerical/filters/active/test/CMakeLists.txt @@ -10,5 +10,6 @@ target_link_libraries(numerical.filters.active_test PUBLIC target_sources(numerical.filters.active_test PRIVATE TestExtendedKalmanFilter.cpp TestKalmanFilter.cpp + TestKalmanSmoother.cpp TestUnscentedKalmanFilter.cpp ) diff --git a/numerical/filters/active/test/TestKalmanSmoother.cpp b/numerical/filters/active/test/TestKalmanSmoother.cpp new file mode 100644 index 00000000..ed2f6b7c --- /dev/null +++ b/numerical/filters/active/test/TestKalmanSmoother.cpp @@ -0,0 +1,110 @@ +#include "numerical/filters/active/KalmanFilter.hpp" +#include "numerical/filters/active/KalmanSmoother.hpp" +#include +#include + +namespace +{ + class TestKalmanSmoother : public ::testing::Test + { + protected: + static constexpr std::size_t N = 2; + static constexpr std::size_t M = 1; + static constexpr std::size_t T = 10; + + using Smoother = filters::KalmanSmoother; + using StateVector = Smoother::StateVector; + using StateMatrix = Smoother::StateMatrix; + using MeasurementMatrix = Smoother::MeasurementMatrix; + using MeasurementVector = Smoother::MeasurementVector; + using MeasurementCovariance = Smoother::MeasurementCovariance; + + Smoother smoother; + + // Constant-velocity model: x = [position, velocity], z = position, dt = 0.1 s + StateMatrix F{ { 1.0f, 0.1f }, { 0.0f, 1.0f } }; + MeasurementMatrix H{ { 1.0f, 0.0f } }; + StateMatrix Q{ { 0.01f, 0.0f }, { 0.0f, 0.01f } }; + MeasurementCovariance R{ { 0.5f } }; + StateVector x0{ { 0.0f }, { 0.0f } }; + StateMatrix P0{ { 1.0f, 0.0f }, { 0.0f, 1.0f } }; + + // Noisy position observations from a constant-velocity trajectory (v = 0.5 m/s) + std::array observations{ { MeasurementVector{ { 0.07f } }, + MeasurementVector{ { 0.15f } }, + MeasurementVector{ { 0.22f } }, + MeasurementVector{ { 0.28f } }, + MeasurementVector{ { 0.36f } }, + MeasurementVector{ { 0.43f } }, + MeasurementVector{ { 0.52f } }, + MeasurementVector{ { 0.59f } }, + MeasurementVector{ { 0.64f } }, + MeasurementVector{ { 0.73f } } } }; + }; +} + +TEST_F(TestKalmanSmoother, log_likelihood_is_finite_and_negative) +{ + const auto output = smoother.Smooth(F, H, Q, R, observations, T, x0, P0); + + EXPECT_TRUE(std::isfinite(output.logLikelihood)); + EXPECT_LT(output.logLikelihood, 0.0f); +} + +TEST_F(TestKalmanSmoother, lag_cross_covariance_index_zero_is_zero) +{ + const auto output = smoother.Smooth(F, H, Q, R, observations, T, x0, P0); + + for (std::size_t i = 0; i < N; ++i) + for (std::size_t j = 0; j < N; ++j) + EXPECT_FLOAT_EQ(output.lagCrossCovariances[0].at(i, j), 0.0f); +} + +TEST_F(TestKalmanSmoother, lag_cross_covariance_last_index_is_nonzero) +{ + const auto output = smoother.Smooth(F, H, Q, R, observations, T, x0, P0); + + float norm = 0.0f; + for (std::size_t i = 0; i < N; ++i) + for (std::size_t j = 0; j < N; ++j) + norm += output.lagCrossCovariances[T - 1].at(i, j) * output.lagCrossCovariances[T - 1].at(i, j); + + EXPECT_GT(norm, 0.0f); +} + +TEST_F(TestKalmanSmoother, smoothed_covariances_are_no_larger_than_filtered) +{ + // Run a KF matching the smoother's forward pass: + // t=0: use P0 directly as prediction cov (no prior Predict), then Update + // t=1..T-1: Predict then Update + filters::KalmanFilter kf(x0, P0); + kf.SetStateTransition(F); + kf.SetMeasurementMatrix(H); + kf.SetProcessNoise(Q); + kf.SetMeasurementNoise(R); + + std::array filteredVar{}; + kf.Update(observations[0]); + filteredVar[0] = kf.GetCovariance().at(0, 0); + for (std::size_t t = 1; t < T; ++t) + { + kf.Predict(); + kf.Update(observations[t]); + filteredVar[t] = kf.GetCovariance().at(0, 0); + } + + const auto output = smoother.Smooth(F, H, Q, R, observations, T, x0, P0); + + for (std::size_t t = 0; t < T; ++t) + EXPECT_LE(output.smoothedCovariances[t].at(0, 0), filteredVar[t] + 1e-5f); +} + +TEST_F(TestKalmanSmoother, smoothed_covariance_at_first_step_less_than_prior) +{ + // After observing T steps backward, uncertainty at t=0 must be less than prior P0. + // P_{0|T} <= P_{0|0} <= P0 is guaranteed by the Kalman update and RTS smoother. + const auto output = smoother.Smooth(F, H, Q, R, observations, T, x0, P0); + + EXPECT_LT(output.smoothedCovariances[0].at(0, 0), P0.at(0, 0)); + EXPECT_LT(output.smoothedCovariances[0].at(1, 1), P0.at(1, 1)); +}