strawlab / adskalman-rs

Kalman filter implementation in Rust
Apache License 2.0
60 stars 8 forks source link

Explicit lifetime on KalmanFilterNoControl #13

Closed elaye closed 2 years ago

elaye commented 2 years ago

Hello,

First of all thank you for this crate, I was very glad to find a rust implementation of a Kalman filter!

I'm using it in one of my projects and I have an issue with the explicit lifetime required on KalmanFilterNoControl. I need to keep the filter in a nested long lived struct and that forces me to annotate all its parents with the explicit lifetime which is not convenient or even possible in some cases.

Maybe the API could change so that KalmanFilterNoControl takes ownership of the transition model and the observation matrix and we'd have getters if we need to access them later on?

I'm not sure what's the right solution, if you have a better idea I'm willing to fork the repo and experiment with it.

astraw commented 2 years ago

I'm glad it's useful.

Yes, I agree that the annotation of parents with explicit lifetimes can be annoying. But in this case, as far as I recall (it's been a while), KalmanFilterNoControl::new does not take ownership of its inputs because the matrices may be allocated statically (e.g. on a microcontroller with no dynamic allocation possible) and I would like to keep the core library compatible with no_std.

As one potential solution with the existing API, you could call KalmanFilterNoControl::new only when the methods on KalmanFilterNoControl are needed and the drop it shortly afterward? The constructor is very lightweight (it merely takes pointers to the matrices and stores them), so this may not be such a bad solution. (I see that new is not marked as inline but this seems reasonable to do.) Anyhow, calling KalmanFilterNoControl::new in a tight loop is indeed what I do in some code of mine in a similar case. (For an EKF in which the observation model is re-linearized every time step and a new KalmanFilterNoControl created with the new linearized observation model.)

Otherwise, if you find a solution you like more while maintaining no_std compatibility, please let me know.

elaye commented 2 years ago

That makes a lot of sense. I have a superficial understanding of Kalman filters and naively thought that KalmanFilterNoControl kept an internal state that was changed after every update, requiring it to be kept around in my case. But since it's stateless, I can indeed keep only the observation / transition models and recreate the filter every time. Thank you for your prompt answer!

astraw commented 2 years ago

I updated the docs to suggest this to future users d0eb0c5fb59f97bfee15eb0bd2b9761b502375f6 as I imagine it could come up again. Thanks for the feedback.