1use crate::{Error, Result, linalg::solve_dynamic, matrix::Matrix};
13
14pub 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 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 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 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 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 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 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 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 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 pub fn state_pre(&self) -> Result<Matrix> {
177 vector_matrix(&self.state_pre)
178 }
179
180 pub fn state_post(&self) -> Result<Matrix> {
186 vector_matrix(&self.state_post)
187 }
188
189 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 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 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
273fn 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 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}