Skip to main content

lib_jsl_dsp/discrete/controls/
kalman.rs

1//! A discrete-time Kalman filter with complex-valued matrices.
2//!
3//! See the book entry [Control: state-space models, PID controllers and the Kalman filter](https://jwkunz.github.io/lib_jsl/book/comms/controls.html#the-kalman-filter).
4
5use ndarray::{Array1, Array2};
6use lib_jsl_linalg::Solve;
7use num_complex::Complex;
8
9use crate::{
10    dsp::discrete::stream_operator::{StreamOperator, StreamOperatorManagement},
11    prelude::{C1D, C2D, ErrorsJSL},
12};
13
14/// The output of one predict-update cycle of a [`KalmanFilter`].
15#[derive(Clone, Debug, PartialEq)]
16#[non_exhaustive]
17pub struct KalmanResult {
18    /// The updated a-posteriori state estimate after incorporating the current
19    /// measurement.
20    pub next_state: C1D,
21    /// The innovation or residual vector `z[k] - H x_pred[k]` formed from the
22    /// incoming measurement and the predicted observation.
23    pub residual_error: C1D,
24}
25
26/// Streaming discrete-time Kalman filter with complex-valued matrices.
27///
28/// This type implements the classic linear Kalman filter for a discrete-time,
29/// possibly complex-valued state-space system. It is intended for streaming
30/// estimation workloads where each call to [`process`](StreamOperator::process)
31/// consumes one or more measurement vectors and returns the updated state
32/// estimate after each observation.
33///
34/// The filter operates on the standard state-space model:
35/// `x[k] = F x[k-1] + B u[k] + w[k]`
36/// `z[k] = H x[k] + v[k]`
37///
38/// where:
39/// - `x[k]` is the hidden state vector
40/// - `z[k]` is the measurement vector
41/// - `F` is the state-transition matrix
42/// - `H` is the observation matrix
43/// - `B` is the optional control-input matrix
44/// - `u[k]` is the optional control vector
45/// - `w[k]` and `v[k]` are the process and measurement noise terms
46///
47/// All internal matrices use [`C2D`] and all state/measurement vectors use
48/// [`C1D`]. The covariance update uses conjugate-transpose operations so the
49/// filter works naturally with complex-valued systems.
50///
51/// Dimension conventions:
52/// - `F` is `n x n`
53/// - `H` is `m x n`
54/// - `Q` is `n x n`
55/// - `R` is `m x m`
56/// - `P` is `n x n`
57/// - `x` is length `n`
58/// - `B`, when present, is `n x p`
59/// - `u`, when present, is length `p`
60///
61/// Each streamed measurement triggers one full predict/update cycle:
62/// 1. Predict the next state and covariance.
63/// 2. Form the innovation from the new measurement.
64/// 3. Compute the Kalman gain.
65/// 4. Update the state estimate and covariance.
66///
67/// This filter is stateful. Reusing the same instance across multiple calls to
68/// [`process`](StreamOperator::process) continues estimation from the previous
69/// internal state until [`reset`](StreamOperatorManagement::reset) is called.
70pub struct KalmanFilter {
71    state_transition: C2D,
72    observation_model: C2D,
73    observation_model_h: C2D,
74    process_noise: C2D,
75    measurement_noise: C2D,
76    estimate_covariance: C2D,
77    control_model: Option<C2D>,
78    control_input: Option<C1D>,
79    state_estimate: C1D,
80    initial_state_estimate: C1D,
81    initial_estimate_covariance: C2D,
82}
83
84impl KalmanFilter {
85    /// Creates a new streaming Kalman filter.
86    ///
87    /// The constructor validates the dimensional compatibility of all provided
88    /// matrices and vectors before any processing begins.
89    ///
90    /// Arguments:
91    /// - `state_transition`: State-transition matrix `F`
92    /// - `observation_model`: Observation matrix `H`
93    /// - `process_noise`: Process-noise covariance `Q`
94    /// - `measurement_noise`: Measurement-noise covariance `R`
95    /// - `estimate_covariance`: Initial estimate covariance `P`
96    /// - `initial_state_estimate`: Initial state estimate `x`
97    /// - `control_model`: Optional control matrix `B`
98    /// - `control_input`: Optional control vector `u`
99    ///
100    /// Returns an error when any dimensions are incompatible, when the state
101    /// matrix is not square, or when a control input is supplied without a
102    /// matching control model.
103    #[allow(clippy::too_many_arguments)]
104    pub fn new(
105        state_transition: C2D,
106        observation_model: C2D,
107        process_noise: C2D,
108        measurement_noise: C2D,
109        estimate_covariance: C2D,
110        initial_state_estimate: C1D,
111        control_model: Option<C2D>,
112        control_input: Option<C1D>,
113    ) -> Result<Self, ErrorsJSL> {
114        let state_dim = state_transition.nrows();
115        if state_dim == 0 || state_transition.ncols() != state_dim {
116            return Err(ErrorsJSL::InvalidInputRange(
117                "state_transition must be a non-empty square matrix",
118            ));
119        }
120        if observation_model.ncols() != state_dim {
121            return Err(ErrorsJSL::IncompatibleArraySizes((
122                observation_model.ncols(),
123                state_dim,
124            )));
125        }
126        if process_noise.dim() != (state_dim, state_dim) {
127            return Err(ErrorsJSL::IncompatibleArraySizes((
128                process_noise.len(),
129                state_dim * state_dim,
130            )));
131        }
132        if estimate_covariance.dim() != (state_dim, state_dim) {
133            return Err(ErrorsJSL::IncompatibleArraySizes((
134                estimate_covariance.len(),
135                state_dim * state_dim,
136            )));
137        }
138        if initial_state_estimate.len() != state_dim {
139            return Err(ErrorsJSL::IncompatibleArraySizes((
140                initial_state_estimate.len(),
141                state_dim,
142            )));
143        }
144
145        let measurement_dim = observation_model.nrows();
146        if measurement_noise.dim() != (measurement_dim, measurement_dim) {
147            return Err(ErrorsJSL::IncompatibleArraySizes((
148                measurement_noise.len(),
149                measurement_dim * measurement_dim,
150            )));
151        }
152
153        if let Some(b) = &control_model
154            && b.nrows() != state_dim
155        {
156            return Err(ErrorsJSL::IncompatibleArraySizes((b.nrows(), state_dim)));
157        }
158
159        if let (Some(b), Some(u)) = (&control_model, &control_input)
160            && b.ncols() != u.len()
161        {
162            return Err(ErrorsJSL::IncompatibleArraySizes((b.ncols(), u.len())));
163        }
164
165        if control_model.is_none() && control_input.is_some() {
166            return Err(ErrorsJSL::Misconfiguration(
167                "control_input requires control_model",
168            ));
169        }
170
171        let observation_model_h = Self::conjugate_transpose(&observation_model);
172
173        Ok(Self {
174            state_transition,
175            observation_model,
176            observation_model_h,
177            process_noise,
178            measurement_noise,
179            estimate_covariance: estimate_covariance.clone(),
180            control_model,
181            control_input,
182            state_estimate: initial_state_estimate.clone(),
183            initial_state_estimate,
184            initial_estimate_covariance: estimate_covariance,
185        })
186    }
187
188    /// Returns the current a-posteriori state estimate.
189    ///
190    /// This is the most recent state after the last successful measurement
191    /// update. Before any measurements are processed, this is equal to the
192    /// `initial_state_estimate` provided at construction time.
193    pub fn state_estimate(&self) -> &C1D {
194        &self.state_estimate
195    }
196
197    /// Returns the current estimate covariance matrix.
198    ///
199    /// This matrix represents the filter's current uncertainty about the state
200    /// estimate. Smaller diagonal values generally indicate greater confidence
201    /// in the corresponding state components.
202    pub fn estimate_covariance(&self) -> &C2D {
203        &self.estimate_covariance
204    }
205
206    /// Updates the observation matrix `H` used during the measurement update.
207    ///
208    /// The matrix must preserve the existing state dimension and measurement
209    /// dimension. The cached conjugate-transpose `H^H` is refreshed whenever
210    /// this matrix is changed.
211    pub fn set_observation_model(&mut self, observation_model: C2D) -> Result<(), ErrorsJSL> {
212        let expected_state_dim = self.state_estimate.len();
213        let expected_measurement_dim = self.measurement_noise.nrows();
214
215        if observation_model.ncols() != expected_state_dim {
216            return Err(ErrorsJSL::IncompatibleArraySizes((
217                observation_model.ncols(),
218                expected_state_dim,
219            )));
220        }
221        if observation_model.nrows() != expected_measurement_dim {
222            return Err(ErrorsJSL::IncompatibleArraySizes((
223                observation_model.nrows(),
224                expected_measurement_dim,
225            )));
226        }
227
228        self.observation_model_h = Self::conjugate_transpose(&observation_model);
229        self.observation_model = observation_model;
230        Ok(())
231    }
232
233    /// Updates the control-input vector used during the prediction step.
234    ///
235    /// When both a control model `B` and a control vector `u` are present, the
236    /// predictor applies the term `B u` before the measurement update.
237    ///
238    /// Passing `None` disables the control input while leaving the control
239    /// matrix configured.
240    pub fn set_control_input(&mut self, control_input: Option<C1D>) -> Result<(), ErrorsJSL> {
241        if let (Some(b), Some(u)) = (&self.control_model, &control_input)
242            && b.ncols() != u.len()
243        {
244            return Err(ErrorsJSL::IncompatibleArraySizes((b.ncols(), u.len())));
245        }
246        if self.control_model.is_none() && control_input.is_some() {
247            return Err(ErrorsJSL::Misconfiguration(
248                "control_input requires control_model",
249            ));
250        }
251        self.control_input = control_input;
252        Ok(())
253    }
254
255    /// Updates the optional control matrix used during prediction.
256    ///
257    /// The control matrix must have one row per state component. If a control
258    /// vector is already configured, its length must match the new matrix's
259    /// column count.
260    ///
261    /// Passing `None` removes the control model, but only when no control input
262    /// is currently configured.
263    pub fn set_control_model(&mut self, control_model: Option<C2D>) -> Result<(), ErrorsJSL> {
264        if let Some(b) = &control_model {
265            if b.nrows() != self.state_estimate.len() {
266                return Err(ErrorsJSL::IncompatibleArraySizes((
267                    b.nrows(),
268                    self.state_estimate.len(),
269                )));
270            }
271            if let Some(u) = &self.control_input
272                && b.ncols() != u.len()
273            {
274                return Err(ErrorsJSL::IncompatibleArraySizes((b.ncols(), u.len())));
275            }
276        } else if self.control_input.is_some() {
277            return Err(ErrorsJSL::Misconfiguration(
278                "control_model cannot be removed while control_input is set",
279            ));
280        }
281
282        self.control_model = control_model;
283        Ok(())
284    }
285
286    fn conjugate_transpose(matrix: &C2D) -> C2D {
287        matrix.t().mapv(|x| x.conj()).to_owned()
288    }
289
290    fn identity(size: usize) -> C2D {
291        Array2::from_diag(&Array1::from_elem(size, Complex::new(1.0, 0.0)))
292    }
293
294    // ANCHOR: kalman
295    fn predict(&mut self) {
296        self.state_estimate = self.state_transition.dot(&self.state_estimate);
297
298        if let (Some(b), Some(u)) = (&self.control_model, &self.control_input) {
299            self.state_estimate += &b.dot(u);
300        }
301
302        let f_h = Self::conjugate_transpose(&self.state_transition);
303        self.estimate_covariance = self
304            .state_transition
305            .dot(&self.estimate_covariance)
306            .dot(&f_h)
307            + &self.process_noise;
308    }
309
310    fn update(&mut self, measurement: &C1D) -> Result<KalmanResult, ErrorsJSL> {
311        let measurement_dim = self.observation_model.nrows();
312        if measurement.len() != measurement_dim {
313            return Err(ErrorsJSL::IncompatibleArraySizes((
314                measurement.len(),
315                measurement_dim,
316            )));
317        }
318
319        let innovation = measurement - &self.observation_model.dot(&self.state_estimate);
320        let innovation_covariance = self
321            .observation_model
322            .dot(&self.estimate_covariance)
323            .dot(&self.observation_model_h)
324            + &self.measurement_noise;
325        let gain_rhs = self.estimate_covariance.dot(&self.observation_model_h);
326        let gain_rhs_t = gain_rhs.t().to_owned();
327        let mut kalman_gain_t = C2D::zeros(gain_rhs_t.raw_dim());
328        for (column_idx, rhs_column) in gain_rhs_t.columns().into_iter().enumerate() {
329            let solved_column = innovation_covariance
330                .solve_t_into(rhs_column.to_owned())
331                .map_err(|_| ErrorsJSL::RuntimeError("failed to solve innovation covariance"))?;
332            kalman_gain_t.column_mut(column_idx).assign(&solved_column);
333        }
334        let kalman_gain = kalman_gain_t.t().to_owned();
335
336        self.state_estimate = &self.state_estimate + &kalman_gain.dot(&innovation);
337
338        let identity = Self::identity(self.state_estimate.len());
339        self.estimate_covariance =
340            (identity - kalman_gain.dot(&self.observation_model)).dot(&self.estimate_covariance);
341
342        Ok(KalmanResult {
343            next_state: self.state_estimate.clone(),
344            residual_error: innovation,
345        })
346    }
347    // ANCHOR_END: kalman
348
349    fn step(&mut self, measurement: &C1D) -> Result<KalmanResult, ErrorsJSL> {
350        self.predict();
351        self.update(measurement)
352    }
353}
354
355impl StreamOperatorManagement for KalmanFilter {
356    /// Restores the filter to its initial state estimate and covariance.
357    ///
358    /// This is useful when starting a fresh estimation run over a new signal or
359    /// simulation without reallocating the filter object.
360    fn reset(&mut self) -> Result<(), ErrorsJSL> {
361        self.state_estimate = self.initial_state_estimate.clone();
362        self.estimate_covariance = self.initial_estimate_covariance.clone();
363        Ok(())
364    }
365
366    /// Finalizes the filter.
367    ///
368    /// The Kalman filter does not buffer delayed output, so finalization is a
369    /// no-op and simply returns `Ok(())`.
370    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
371        Ok(())
372    }
373}
374
375impl StreamOperator<C1D, KalmanResult> for KalmanFilter {
376    /// Processes a slice of measurement vectors and returns the updated state
377    /// estimate and residual after each measurement.
378    ///
379    /// Input:
380    /// - Each element of `data_in` is one measurement vector `z[k]`
381    ///
382    /// Output:
383    /// - The returned vector contains one [`KalmanResult`] per input
384    ///   measurement, in the same order as the measurements were processed
385    ///
386    /// For an empty input slice, this method returns `Ok(None)` to match the
387    /// stream-operator conventions used elsewhere in the crate.
388    fn process(&mut self, data_in: &[C1D]) -> Result<Option<Vec<KalmanResult>>, ErrorsJSL> {
389        if data_in.is_empty() {
390            return Ok(None);
391        }
392
393        let mut out = Vec::with_capacity(data_in.len());
394        for measurement in data_in {
395            out.push(self.step(measurement)?);
396        }
397        Ok(Some(out))
398    }
399
400    /// Flushes any buffered output from the filter.
401    ///
402    /// The Kalman filter has no delayed-output buffering, so flushing produces
403    /// no additional samples and returns `Ok(None)`.
404    fn flush(&mut self) -> Result<Option<Vec<KalmanResult>>, ErrorsJSL> {
405        Ok(None)
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412    use crate::discrete::stream_operator::{StreamOperator, StreamOperatorManagement};
413
414    fn c(re: f64) -> Complex<f64> {
415        Complex::new(re, 0.0)
416    }
417
418    #[test]
419    fn test_kalman_filter_tracks_constant_scalar_signal() {
420        let f = Array2::from_elem((1, 1), c(1.0));
421        let h = Array2::from_elem((1, 1), c(1.0));
422        let q = Array2::from_elem((1, 1), c(1e-3));
423        let r = Array2::from_elem((1, 1), c(1e-2));
424        let p0 = Array2::from_elem((1, 1), c(1.0));
425        let x0 = Array1::from_vec(vec![c(0.0)]);
426
427        let mut dut = KalmanFilter::new(f, h, q, r, p0, x0, None, None).unwrap();
428        let measurements = vec![
429            Array1::from_vec(vec![c(1.2)]),
430            Array1::from_vec(vec![c(0.8)]),
431            Array1::from_vec(vec![c(1.1)]),
432            Array1::from_vec(vec![c(0.9)]),
433            Array1::from_vec(vec![c(1.0)]),
434        ];
435
436        let estimates = dut.process(&measurements).unwrap().unwrap();
437        let final_estimate = estimates.last().unwrap().next_state[0].re;
438        let final_residual = estimates.last().unwrap().residual_error[0].re;
439
440        assert!((final_estimate - 1.0).abs() < 0.08);
441        assert!(final_residual.abs() < 0.15);
442        assert!(dut.estimate_covariance()[[0, 0]].re < 0.05);
443    }
444
445    #[test]
446    fn test_kalman_filter_reset_restores_initial_conditions() {
447        let f = Array2::from_elem((1, 1), c(1.0));
448        let h = Array2::from_elem((1, 1), c(1.0));
449        let q = Array2::from_elem((1, 1), c(1e-3));
450        let r = Array2::from_elem((1, 1), c(1e-2));
451        let p0 = Array2::from_elem((1, 1), c(1.0));
452        let x0 = Array1::from_vec(vec![c(0.25)]);
453
454        let mut dut = KalmanFilter::new(f, h, q, r, p0.clone(), x0.clone(), None, None).unwrap();
455        let measurement = Array1::from_vec(vec![c(1.0)]);
456        let _ = dut.process(&[measurement]).unwrap().unwrap();
457
458        dut.reset().unwrap();
459
460        assert_eq!(dut.state_estimate(), &x0);
461        assert_eq!(dut.estimate_covariance(), &p0);
462    }
463
464    #[test]
465    fn test_kalman_filter_rejects_bad_measurement_dimension() {
466        let f = Array2::from_elem((2, 2), c(1.0));
467        let h = Array2::from_shape_vec((1, 2), vec![c(1.0), c(0.0)]).unwrap();
468        let q = Array2::from_diag(&Array1::from_vec(vec![c(1e-3), c(1e-3)]));
469        let r = Array2::from_elem((1, 1), c(1e-2));
470        let p0 = Array2::from_diag(&Array1::from_vec(vec![c(1.0), c(1.0)]));
471        let x0 = Array1::from_vec(vec![c(0.0), c(0.0)]);
472
473        let mut dut = KalmanFilter::new(f, h, q, r, p0, x0, None, None).unwrap();
474        let bad_measurement = Array1::from_vec(vec![c(1.0), c(2.0)]);
475
476        let err = dut.process(&[bad_measurement]).unwrap_err();
477        assert!(matches!(err, ErrorsJSL::IncompatibleArraySizes((2, 1))));
478    }
479}