Skip to main content

oa/vision/
kalman.rs

1//! Constant-model Kalman predictor/corrector, following `cv::KalmanFilter`.
2//!
3//! The filter carries `dynam`-dimensional state, `measure`-dimensional
4//! measurements, and an optional `control`-dimensional input. All state and
5//! covariance math runs in `f64` on the host; callers pass and receive F32
6//! [`Matrix`] values exactly as the other host estimators in this module.
7//!
8//! `predict` advances `state_post` through the transition (plus optional
9//! control) into `state_pre`; `correct` fuses a measurement into
10//! `state_post` via the Kalman gain `P_pre * H' * (H * P_pre * H' + R)^-1`.
11
12use crate::{Error, Result, linalg::solve_dynamic, matrix::Matrix};
13
14/// Discrete linear Kalman filter over fixed-size state, measurement, and
15/// control vectors.
16///
17/// Construct with [`KalmanFilter::new`], assign the model matrices with the
18/// `set_*` methods, seed [`KalmanFilter::set_state_post`] and
19/// [`KalmanFilter::set_error_cov_post`], then alternate `predict`/`correct`
20/// calls.
21pub struct KalmanFilter {
22	dynam_params: usize,
23	measure_params: usize,
24	control_params: usize,
25	state_pre: Vec<f64>,
26	state_post: Vec<f64>,
27	transition_matrix: Vec<f64>,
28	control_matrix: Vec<f64>,
29	measurement_matrix: Vec<f64>,
30	process_noise_cov: Vec<f64>,
31	measurement_noise_cov: Vec<f64>,
32	error_cov_pre: Vec<f64>,
33	error_cov_post: Vec<f64>,
34}
35
36impl KalmanFilter {
37	/// Creates a filter with zero-filled model matrices and covariances,
38	/// matching `cv::KalmanFilter::KalmanFilter`.
39	///
40	/// # Errors
41	///
42	/// Returns an error unless `dynam_params` and `measure_params` are
43	/// nonzero; `control_params` may be zero to disable the control input.
44	pub fn new(dynam_params: usize, measure_params: usize, control_params: usize) -> Result<Self> {
45		if dynam_params == 0 || measure_params == 0 {
46			return Err(Error::invalid_argument(
47				"vision::KalmanFilter requires nonzero state and measurement dimensions",
48			));
49		}
50		Ok(Self {
51			dynam_params,
52			measure_params,
53			control_params,
54			state_pre: vec![0.0; dynam_params],
55			state_post: vec![0.0; dynam_params],
56			transition_matrix: vec![0.0; dynam_params * dynam_params],
57			control_matrix: vec![0.0; dynam_params * control_params],
58			measurement_matrix: vec![0.0; measure_params * dynam_params],
59			process_noise_cov: vec![0.0; dynam_params * dynam_params],
60			measurement_noise_cov: vec![0.0; measure_params * measure_params],
61			error_cov_pre: vec![0.0; dynam_params * dynam_params],
62			error_cov_post: vec![0.0; dynam_params * dynam_params],
63		})
64	}
65
66	/// Assigns the `dynam x dynam` state-transition matrix `A`.
67	///
68	/// # Errors
69	///
70	/// Returns an error unless `matrix` is `[dynam, dynam]` F32.
71	pub fn set_transition_matrix(&mut self, matrix: &Matrix) -> Result<()> {
72		self.transition_matrix = read_rect(
73			matrix,
74			self.dynam_params,
75			self.dynam_params,
76			"vision::KalmanFilter::set_transition_matrix",
77		)?;
78		Ok(())
79	}
80
81	/// Assigns the `dynam x control` control-input matrix `B`.
82	///
83	/// # Errors
84	///
85	/// Returns an error unless `matrix` is `[dynam, control]` F32.
86	pub fn set_control_matrix(&mut self, matrix: &Matrix) -> Result<()> {
87		self.control_matrix = read_rect(
88			matrix,
89			self.dynam_params,
90			self.control_params,
91			"vision::KalmanFilter::set_control_matrix",
92		)?;
93		Ok(())
94	}
95
96	/// Assigns the `measure x dynam` measurement matrix `H`.
97	///
98	/// # Errors
99	///
100	/// Returns an error unless `matrix` is `[measure, dynam]` F32.
101	pub fn set_measurement_matrix(&mut self, matrix: &Matrix) -> Result<()> {
102		self.measurement_matrix = read_rect(
103			matrix,
104			self.measure_params,
105			self.dynam_params,
106			"vision::KalmanFilter::set_measurement_matrix",
107		)?;
108		Ok(())
109	}
110
111	/// Assigns the `dynam x dynam` process-noise covariance `Q`.
112	///
113	/// # Errors
114	///
115	/// Returns an error unless `matrix` is `[dynam, dynam]` F32.
116	pub fn set_process_noise_cov(&mut self, matrix: &Matrix) -> Result<()> {
117		self.process_noise_cov = read_rect(
118			matrix,
119			self.dynam_params,
120			self.dynam_params,
121			"vision::KalmanFilter::set_process_noise_cov",
122		)?;
123		Ok(())
124	}
125
126	/// Assigns the `measure x measure` measurement-noise covariance `R`.
127	///
128	/// # Errors
129	///
130	/// Returns an error unless `matrix` is `[measure, measure]` F32.
131	pub fn set_measurement_noise_cov(&mut self, matrix: &Matrix) -> Result<()> {
132		self.measurement_noise_cov = read_rect(
133			matrix,
134			self.measure_params,
135			self.measure_params,
136			"vision::KalmanFilter::set_measurement_noise_cov",
137		)?;
138		Ok(())
139	}
140
141	/// Seeds the corrected state estimate consumed by the next `predict`
142	/// call.
143	///
144	/// # Errors
145	///
146	/// Returns an error unless `state` holds exactly `dynam` F32 values.
147	pub fn set_state_post(&mut self, state: &Matrix) -> Result<()> {
148		self.state_post = read_vector(
149			state,
150			self.dynam_params,
151			"vision::KalmanFilter::set_state_post",
152		)?;
153		Ok(())
154	}
155
156	/// Seeds the corrected `dynam x dynam` error covariance `P`.
157	///
158	/// # Errors
159	///
160	/// Returns an error unless `matrix` is `[dynam, dynam]` F32.
161	pub fn set_error_cov_post(&mut self, matrix: &Matrix) -> Result<()> {
162		self.error_cov_post = read_rect(
163			matrix,
164			self.dynam_params,
165			self.dynam_params,
166			"vision::KalmanFilter::set_error_cov_post",
167		)?;
168		Ok(())
169	}
170
171	/// Current predicted state `[dynam, 1]` (`state_pre`).
172	///
173	/// # Errors
174	///
175	/// Returns an error when the F32 output cannot be materialized.
176	pub fn state_pre(&self) -> Result<Matrix> {
177		vector_matrix(&self.state_pre)
178	}
179
180	/// Current corrected state `[dynam, 1]` (`state_post`).
181	///
182	/// # Errors
183	///
184	/// Returns an error when the F32 output cannot be materialized.
185	pub fn state_post(&self) -> Result<Matrix> {
186		vector_matrix(&self.state_post)
187	}
188
189	/// Advances the model one step: `state_pre = A * state_post + B * u`,
190	/// `error_cov_pre = A * P * A' + Q`. `control` must be `[control, 1]`
191	/// when the filter was built with a nonzero control dimension. Like
192	/// `cv::KalmanFilter::predict`, only the `*_pre` fields advance.
193	///
194	/// Returns `state_pre` as `[dynam, 1]`.
195	///
196	/// # Errors
197	///
198	/// Returns an error for a wrongly sized or missing control input.
199	pub fn predict(&mut self, control: Option<&Matrix>) -> Result<Matrix> {
200		let n = self.dynam_params;
201		let control_vec = match control {
202			Some(matrix) => Some(read_vector(
203				matrix,
204				self.control_params,
205				"vision::KalmanFilter::predict",
206			)?),
207			None if self.control_params == 0 => None,
208			None => {
209				return Err(Error::invalid_argument(
210					"vision::KalmanFilter::predict requires a control input",
211				));
212			}
213		};
214		let mut next = mat_vec(&self.transition_matrix, &self.state_post, n, n);
215		if let Some(u) = &control_vec {
216			let driven = mat_vec(&self.control_matrix, u, n, self.control_params);
217			for (value, add) in next.iter_mut().zip(driven) {
218				*value += add;
219			}
220		}
221		let ap = mat_mul(&self.transition_matrix, &self.error_cov_post, n, n, n);
222		let at = transpose(&self.transition_matrix, n, n);
223		let mut cov = mat_mul(&ap, &at, n, n, n);
224		for (value, noise) in cov.iter_mut().zip(&self.process_noise_cov) {
225			*value += noise;
226		}
227		self.state_pre = next;
228		self.error_cov_pre = cov;
229		self.state_pre()
230	}
231
232	/// Fuses a `measure`-dimensional measurement: gain
233	/// `K = P_pre * H' * (H * P_pre * H' + R)^-1`, then
234	/// `state_post = state_pre + K * (z - H * state_pre)` and
235	/// `error_cov_post = (I - K * H) * P_pre`.
236	///
237	/// Returns `state_post` as `[dynam, 1]`.
238	///
239	/// # Errors
240	///
241	/// Returns an error for a wrongly sized measurement or a singular
242	/// innovation covariance `H * P_pre * H' + R`.
243	pub fn correct(&mut self, measurement: &Matrix) -> Result<Matrix> {
244		let n = self.dynam_params;
245		let m = self.measure_params;
246		let z = read_vector(measurement, m, "vision::KalmanFilter::correct")?;
247		let hp = mat_mul(&self.measurement_matrix, &self.error_cov_pre, m, n, n);
248		let ht = transpose(&self.measurement_matrix, m, n);
249		let mut innovation = mat_mul(&hp, &ht, m, n, m);
250		for (value, noise) in innovation.iter_mut().zip(&self.measurement_noise_cov) {
251			*value += noise;
252		}
253		let inv = invert(&innovation, m).ok_or_else(|| {
254			Error::invalid_argument("vision::KalmanFilter::correct innovation covariance is singular")
255		})?;
256		// gain = P_pre * H' * S^-1 = (H * P_pre)' * S^-1
257		let gain = mat_mul(&transpose(&hp, m, n), &inv, n, m, m);
258		let hx = mat_vec(&self.measurement_matrix, &self.state_pre, m, n);
259		let residual: Vec<f64> = z.iter().zip(hx).map(|(a, b)| a - b).collect();
260		let update = mat_vec(&gain, &residual, n, m);
261		let mut post = self.state_pre.clone();
262		for (value, add) in post.iter_mut().zip(update) {
263			*value += add;
264		}
265		self.state_post = post;
266		let kh = mat_mul(&gain, &self.measurement_matrix, n, m, n);
267		let factor: Vec<f64> = identity(n).iter().zip(&kh).map(|(a, b)| a - b).collect();
268		self.error_cov_post = mat_mul(&factor, &self.error_cov_pre, n, n, n);
269		self.state_post()
270	}
271}
272
273// ---- dynamic dense helpers -------------------------------------------------
274
275fn mat_vec(a: &[f64], v: &[f64], rows: usize, cols: usize) -> Vec<f64> {
276	let mut out = vec![0.0f64; rows];
277	for (row, value) in out.iter_mut().enumerate() {
278		for col in 0..cols {
279			*value += a[row * cols + col] * v[col];
280		}
281	}
282	out
283}
284
285fn mat_mul(a: &[f64], b: &[f64], rows: usize, inner: usize, cols: usize) -> Vec<f64> {
286	let mut out = vec![0.0f64; rows * cols];
287	for row in 0..rows {
288		for col in 0..cols {
289			let mut sum = 0.0f64;
290			for k in 0..inner {
291				sum += a[row * inner + k] * b[k * cols + col];
292			}
293			out[row * cols + col] = sum;
294		}
295	}
296	out
297}
298
299fn transpose(a: &[f64], rows: usize, cols: usize) -> Vec<f64> {
300	let mut out = vec![0.0f64; rows * cols];
301	for row in 0..rows {
302		for col in 0..cols {
303			out[col * rows + row] = a[row * cols + col];
304		}
305	}
306	out
307}
308
309fn identity(n: usize) -> Vec<f64> {
310	let mut out = vec![0.0f64; n * n];
311	for i in 0..n {
312		out[i * n + i] = 1.0;
313	}
314	out
315}
316
317fn invert(a: &[f64], n: usize) -> Option<Vec<f64>> {
318	let rows: Vec<Vec<f64>> = a.chunks(n).map(Vec::from).collect();
319	let mut inverse = Vec::with_capacity(n * n);
320	for column in 0..n {
321		let mut unit = vec![0.0f64; n];
322		unit[column] = 1.0;
323		inverse.extend(solve_dynamic(&mut rows.clone(), &mut unit, n)?);
324	}
325	// columns solved independently; transpose back to row-major
326	Some(transpose(&inverse, n, n))
327}
328
329fn vector_matrix(v: &[f64]) -> Result<Matrix> {
330	Matrix::new_from_f32(
331		[v.len(), 1],
332		&v.iter().map(|value| *value as f32).collect::<Vec<_>>(),
333	)
334}
335
336fn read_vector(matrix: &Matrix, expected: usize, operation: &str) -> Result<Vec<f64>> {
337	let values = matrix.read_f32()?;
338	if values.len() != expected {
339		return Err(Error::invalid_argument(format!(
340			"{operation} requires {expected} values"
341		)));
342	}
343	Ok(values.iter().map(|value| f64::from(*value)).collect())
344}
345
346fn read_rect(matrix: &Matrix, rows: usize, cols: usize, operation: &str) -> Result<Vec<f64>> {
347	if matrix.shape() != [rows, cols] {
348		return Err(Error::invalid_argument(format!(
349			"{operation} requires a [{rows}, {cols}] matrix"
350		)));
351	}
352	read_vector(matrix, rows * cols, operation)
353}