Skip to content

Commit ef5cfb0

Browse files
add em estimator as well as kf smoother
1 parent 51cfabc commit ef5cfb0

14 files changed

Lines changed: 1026 additions & 4 deletions
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
# Expectation-Maximization for Kalman Filter Parameters
2+
3+
## Overview & Motivation
4+
5+
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.
6+
7+
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.
8+
9+
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.
10+
11+
## Mathematical Theory
12+
13+
### State-Space Model
14+
15+
$$
16+
x_{t+1} = F x_t + w_t, \quad w_t \sim \mathcal{N}(0, Q)
17+
$$
18+
19+
$$
20+
z_t = H x_t + v_t, \quad v_t \sim \mathcal{N}(0, R)
21+
$$
22+
23+
with $x_0 \sim \mathcal{N}(\mu_0, P_0)$ and $T$ observations $z_0, \ldots, z_{T-1}$.
24+
25+
### EM Overview
26+
27+
EM alternates between:
28+
29+
- **E-step**: compute expected sufficient statistics of $x_{1:T}$ given current parameters and all observations, using the RTS smoother.
30+
- **M-step**: analytically maximize the expected complete-data log-likelihood over parameters.
31+
32+
### E-Step (RTS Smoother)
33+
34+
Run `KalmanSmoother::Smooth()` to obtain, for each $t$:
35+
36+
| Quantity | Notation | Description |
37+
|----------|----------|-------------|
38+
| $\hat{x}_{t\|T}$ | `smoothedMeans[t]` | Smoothed state mean |
39+
| $P_{t\|T}$ | `smoothedCovariances[t]` | Smoothed state covariance |
40+
| $P_{t,t-1\|T}$ | `lagCrossCovariances[t]` | Lag-1 cross-covariance (index 0 undefined) |
41+
42+
### Sufficient Statistics
43+
44+
From the smoother output, accumulate six matrices:
45+
46+
$$
47+
A = \sum_{t=1}^{T-1} P_{t,t-1|T}
48+
\qquad
49+
B = \sum_{t=0}^{T-2} \hat{x}_{t|T}\hat{x}_{t|T}^\top + P_{t|T}
50+
$$
51+
52+
$$
53+
C = \sum_{t=1}^{T-1} \hat{x}_{t|T}\hat{x}_{t|T}^\top + P_{t|T}
54+
\qquad
55+
D = \sum_{t=0}^{T-1} \hat{x}_{t|T}\hat{x}_{t|T}^\top + P_{t|T}
56+
$$
57+
58+
$$
59+
W = \sum_{t=0}^{T-1} z_t \hat{x}_{t|T}^\top
60+
\qquad
61+
\Sigma_{zz} = \sum_{t=0}^{T-1} z_t z_t^\top
62+
$$
63+
64+
### M-Step (Closed-Form Updates)
65+
66+
$$
67+
F \leftarrow A B^{-1}
68+
$$
69+
70+
$$
71+
Q \leftarrow \frac{C - F A^\top}{T - 1}, \quad Q \leftarrow \tfrac{1}{2}(Q + Q^\top) + \varepsilon I
72+
$$
73+
74+
$$
75+
H \leftarrow W D^{-1}
76+
$$
77+
78+
$$
79+
R \leftarrow \frac{\Sigma_{zz} - H W^\top}{T}, \quad R \leftarrow \tfrac{1}{2}(R + R^\top) + \varepsilon I
80+
$$
81+
82+
$$
83+
\mu_0 \leftarrow \hat{x}_{0|T}, \quad P_0 \leftarrow P_{0|T}
84+
$$
85+
86+
The symmetrisation and ridge term $\varepsilon I$ ($\varepsilon = 10^{-6}$) enforce that $Q$ and $R$ remain symmetric positive definite, preventing numerical collapse.
87+
88+
Matrix "division" — e.g. $A B^{-1}$ — is implemented as `SolveSystem(B, A^T)^T` (Gaussian elimination) to avoid explicit matrix inversion.
89+
90+
### Convergence
91+
92+
After each EM iteration, compute the log-likelihood $\ell(\theta)$ from the RTS smoother. Convergence is declared when
93+
94+
$$
95+
|\ell^{(k)} - \ell^{(k-1)}| < \delta
96+
$$
97+
98+
for a user-supplied tolerance $\delta$.
99+
100+
## Complexity Analysis
101+
102+
| Case | Time per iteration | Space (stack) | Notes |
103+
|-------|-----------------------|------------------------|-------|
104+
| All | $O(T \cdot N^3)$ | $O(T \cdot N^2)$ | Dominated by RTS smoother forward/backward |
105+
106+
All storage is stack-allocated inside `KalmanSmoother` (owned by `ExpectationMaximization`) and in local M-step temporaries.
107+
108+
## Step-by-Step Walkthrough
109+
110+
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$.
111+
112+
**Iteration 1:**
113+
114+
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.
115+
2. Accumulate scalars:
116+
- $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.)*
117+
- $B, C, D, W, \Sigma_{zz}$ as sums over the smoothed moments.
118+
3. M-step: $F \leftarrow A/B$, $Q \leftarrow (C - F\cdot A)/(T-1)$, etc.
119+
4. Evaluate new log-likelihood $\ell^{(1)}$.
120+
121+
Repeat until $|\ell^{(k)} - \ell^{(k-1)}| < \delta$ or maximum iterations reached.
122+
123+
## Pitfalls & Edge Cases
124+
125+
- **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.
126+
- **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$.
127+
- **$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.
128+
- **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.
129+
- **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.
130+
131+
## Variants & Generalizations
132+
133+
- **EM for EKF/UKF**: Replace the RTS smoother with an extended or unscented smoother for nonlinear models. The M-step remains identical.
134+
- **Constrained EM**: Fix some parameters (e.g., $H$ is known) by simply not updating them in the M-step.
135+
- **Online (incremental) EM**: Accumulate sufficient statistics incrementally to handle streaming data.
136+
- **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.
137+
138+
## Applications
139+
140+
- **System identification**: Learn the dynamics $F$ and noise statistics $Q$, $R$ of an unknown linear system from input-output data.
141+
- **Sensor calibration**: Identify measurement noise covariance $R$ from reference measurements.
142+
- **Hyperparameter tuning for KF**: Replace hand-tuned $Q$, $R$ with data-driven estimates before deploying a real-time Kalman filter.
143+
- **Time-series model selection**: Compare log-likelihoods of different state-space structures to select model order.
144+
145+
## Connections to Other Algorithms
146+
147+
- **`filters::KalmanSmoother`**: Provides the complete E-step. `ExpectationMaximization` owns a `KalmanSmoother` instance internally.
148+
- **`filters::KalmanFilter`**: After EM converges, pass the resulting `EmParameters` to `KalmanFilter::SetStateTransition()`, `SetProcessNoise()`, and `SetMeasurementNoise()` for real-time deployment.
149+
- **`solvers::GaussianElimination`**: Used internally (via `KalmanSmoother`) for numerically stable matrix solves in both the smoother and the M-step.
150+
151+
## References & Further Reading
152+
153+
- 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.
154+
- Shumway, R. H., & Stoffer, D. S. (2000). *Time Series Analysis and Its Applications*. Springer. (Section 6.3)
155+
- 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.
156+
- Ghahramani, Z., & Hinton, G. E. (1996). Parameter estimation for linear dynamical systems. Technical Report CRG-TR-96-2, University of Toronto.

‎doc/estimators/README.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@ Statistical estimation algorithms for fitting models to observed data and making
44

55
## Offline Estimators (Batch)
66

7-
| Algorithm | Description |
8-
|------------------------------------------|-------------------------------------------------------------------------|
9-
| [Linear Regression](LinearRegression.md) | Ordinary least-squares regression using the normal equation |
10-
| [Yule-Walker](YuleWalker.md) | Autoregressive model parameter estimation via the Yule-Walker equations |
7+
| Algorithm | Description |
8+
|-------------------------------------------------------------------|-------------------------------------------------------------------------|
9+
| [Linear Regression](LinearRegression.md) | Ordinary least-squares regression using the normal equation |
10+
| [Yule-Walker](YuleWalker.md) | Autoregressive model parameter estimation via the Yule-Walker equations |
11+
| [Expectation-Maximization](ExpectationMaximization.md) | EM algorithm for Kalman filter parameter identification (Shumway-Stoffer) |
1112

1213
## Online Estimators (Streaming)
1314

‎doc/filters/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Filters that incorporate feedback and a dynamic internal model of the system.
1313
| [Kalman Filter](active/KalmanFilter.md) | Optimal recursive state estimator for linear systems with Gaussian noise |
1414
| [Extended Kalman Filter](active/ExtendedKalmanFilter.md) | Nonlinear state estimator using first-order linearization (Jacobians) |
1515
| [Unscented Kalman Filter](active/UnscentedKalmanFilter.md) | Nonlinear state estimator using sigma points; no Jacobians required |
16+
| [Kalman Smoother](active/KalmanSmoother.md) | Offline RTS smoother providing MMSE estimates over the full observation sequence |
1617

1718
### Passive Filters
1819

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
# Kalman Smoother (RTS Smoother)
2+
3+
## Overview & Motivation
4+
5+
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}$.
6+
7+
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.
8+
9+
## Mathematical Theory
10+
11+
### State-Space Model
12+
13+
$$
14+
x_{t+1} = F x_t + w_t, \quad w_t \sim \mathcal{N}(0, Q)
15+
$$
16+
17+
$$
18+
z_t = H x_t + v_t, \quad v_t \sim \mathcal{N}(0, R)
19+
$$
20+
21+
with $x_0 \sim \mathcal{N}(\mu_0, P_0)$.
22+
23+
### Forward Pass (Kalman Filter)
24+
25+
For $t = 0, 1, \ldots, T-1$:
26+
27+
**Initialise** (t = 0 only):
28+
29+
$$\hat{x}_{0|-} = \mu_0, \quad P_{0|-} = P_0$$
30+
31+
**Update:**
32+
33+
$$
34+
S_t = H P_{t|-} H^\top + R
35+
$$
36+
37+
$$
38+
K_t = P_{t|-} H^\top S_t^{-1}
39+
$$
40+
41+
$$
42+
\hat{x}_{t|t} = \hat{x}_{t|-} + K_t (z_t - H \hat{x}_{t|-})
43+
$$
44+
45+
$$
46+
P_{t|t} = (I - K_t H) P_{t|-} (I - K_t H)^\top + K_t R K_t^\top \quad \text{(Joseph form)}
47+
$$
48+
49+
**Log-likelihood contribution:**
50+
51+
$$
52+
\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)
53+
$$
54+
55+
where $m$ = `MeasurementSize`. The total is $\ell = \sum_{t=0}^{T-1} \ell_t$.
56+
57+
**Predict** (for $t < T-1$):
58+
59+
$$
60+
\hat{x}_{t+1|-} = F \hat{x}_{t|t}, \quad P_{t+1|-} = F P_{t|t} F^\top + Q
61+
$$
62+
63+
### Backward Pass (RTS Smoother)
64+
65+
Initialise at $t = T-1$:
66+
67+
$$
68+
\hat{x}_{T-1|T} = \hat{x}_{T-1|T-1}, \quad P_{T-1|T} = P_{T-1|T-1}
69+
$$
70+
71+
For $t = T-2, T-3, \ldots, 0$:
72+
73+
**Smoother gain:**
74+
75+
$$
76+
G_t = P_{t|t} F^\top P_{t+1|t}^{-1}
77+
$$
78+
79+
**Smoothed mean and covariance:**
80+
81+
$$
82+
\hat{x}_{t|T} = \hat{x}_{t|t} + G_t (\hat{x}_{t+1|T} - \hat{x}_{t+1|t})
83+
$$
84+
85+
$$
86+
P_{t|T} = P_{t|t} + G_t (P_{t+1|T} - P_{t+1|t}) G_t^\top
87+
$$
88+
89+
### Lag-1 Cross-Covariance
90+
91+
The EM M-step requires $P_{t,t-1|T} = \mathrm{Cov}(x_t, x_{t-1} \mid z_{1:T})$.
92+
93+
**Initialisation** (Shumway & Stoffer, 1982):
94+
95+
$$
96+
P_{T-1, T-2|T} = (I - K_{T-1} H) F P_{T-2|T-2}
97+
$$
98+
99+
**Recursion** for $t = T-3, \ldots, 0$:
100+
101+
$$
102+
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
103+
$$
104+
105+
Note: $P_{0,-1|T}$ is undefined; index 0 of `lagCrossCovariances` is always zero.
106+
107+
## Complexity Analysis
108+
109+
| Case | Time | Space | Notes |
110+
|-------|----------------|--------------------------------|-------------------------------|
111+
| All | $O(T \cdot N^3)$ | $O(T \cdot N^2)$ stack | Dominant cost: $N\times N$ solves at each step |
112+
113+
All storage is stack-allocated via `std::array`. There is no heap usage.
114+
115+
## Step-by-Step Walkthrough
116+
117+
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]$.
118+
119+
**Forward pass:**
120+
121+
| $t$ | $P_{t\|-}$ | $S_t$ | $K_t$ | $\hat{x}_{t\|t}$ | $P_{t\|t}$ |
122+
|-----|-----------|-------|--------|------------------|-----------|
123+
| 0 | 1.0 | 2.0 | 0.500 | 0.250 | 0.500 |
124+
| 1 | 0.600 | 1.600 | 0.375 | 0.363 | 0.375 |
125+
| 2 | 0.475 | 1.475 | 0.322 | 0.620 | 0.322 |
126+
127+
**Backward pass ($t=1$ then $t=0$):**
128+
129+
$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$
130+
131+
$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$
132+
133+
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.
134+
135+
## Pitfalls & Edge Cases
136+
137+
- **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.
138+
- **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.
139+
- **`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}$).
140+
- **Unsigned loop guard**: The backward loop uses `std::size_t`; the break guard `if (t == 0) break` prevents unsigned wrap-around.
141+
- **Stack usage**: For large $N$ or $T$, the five internal `std::array` members dominate stack usage. Choose `MaxSteps` conservatively on resource-constrained targets.
142+
143+
## Variants & Generalizations
144+
145+
- **Square-root RTS smoother**: Propagates Cholesky factors instead of full covariance matrices for improved numerical conditioning.
146+
- **Information filter smoother**: Operates in the dual (information) domain; preferable when observations are dense relative to state transitions.
147+
- **Extended / Unscented smoother**: Replace the linear forward pass with EKF or UKF; the backward pass equations remain identical in form.
148+
149+
## Applications
150+
151+
- **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.
152+
- **Offline trajectory estimation**: Position/velocity smoothing in GNSS post-processing and inertial navigation.
153+
- **Batch signal denoising**: Any application where the full observation sequence is available before estimation begins.
154+
155+
## Connections to Other Algorithms
156+
157+
- **`filters::KalmanFilter`**: The forward pass of `KalmanSmoother` replicates the KF update equations. The smoother is applied *after* the filter, not *instead of* it.
158+
- **`estimators::ExpectationMaximization`**: The smoother is owned and invoked by `ExpectationMaximization` as its E-step. Users who only need EM should interact with `ExpectationMaximization` directly.
159+
- **`solvers::GaussianElimination`**: Used for all matrix "division" operations (smoother gain, Kalman gain) to avoid explicit matrix inversion.
160+
- **`solvers::CholeskyDecomposition`**: Used to compute $\log \det S_t$ for the log-likelihood.
161+
162+
## References & Further Reading
163+
164+
- Rauch, H. E., Tung, F., & Striebel, C. T. (1965). Maximum likelihood estimates of linear dynamic systems. *AIAA Journal*, 3(8), 1445–1450.
165+
- 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.
166+
- Shumway, R. H., & Stoffer, D. S. (2000). *Time Series Analysis and Its Applications*. Springer. (Chapter 6)
167+
- Särkkä, S. (2013). *Bayesian Filtering and Smoothing*. Cambridge University Press. (Chapter 8)

‎numerical/estimators/offline/CMakeLists.txt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,19 @@ target_include_directories(numerical.estimators.offline ${NUMERICAL_VISIBILITY}
77

88
target_link_libraries(numerical.estimators.offline ${NUMERICAL_VISIBILITY}
99
infra.util
10+
numerical.filters.active
1011
numerical.math
1112
numerical.solver
1213
)
1314

1415
target_sources(numerical.estimators.offline PRIVATE
16+
ExpectationMaximization.hpp
1517
LinearRegression.hpp
1618
YuleWalker.hpp
1719
)
1820

1921
numerical_add_coverage_sources(numerical.estimators.offline
22+
ExpectationMaximization.cpp
2023
LinearRegression.cpp
2124
YuleWalker.cpp
2225
)
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#include "numerical/estimators/offline/ExpectationMaximization.hpp"
2+
3+
namespace estimators
4+
{
5+
template class ExpectationMaximization<2, 1, 10>;
6+
template class ExpectationMaximization<4, 2, 20>;
7+
}

0 commit comments

Comments
 (0)