bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
extended_kalman_filter.h
Go to the documentation of this file.
1#ifndef BITSIM_ESTIMATION_EXTENDED_KALMAN_FILTER_H
2#define BITSIM_ESTIMATION_EXTENDED_KALMAN_FILTER_H
3
4#include "Eigen/Dense"
6
7#include <boost/noncopyable.hpp>
8
9#include <concepts>
10#include <limits>
11#include <map>
12#include <stdexcept>
13#include <string>
14#include <tuple>
15
16namespace bitsim
17{
18namespace estimation
19{
20
30
66template <typename MotionModelTp, typename ObservationModelTp = void>
67class ExtendedKalmanFilter : private boost::noncopyable
68{
69 public:
70 using motion_model_type = MotionModelTp;
71 using observation_model_type = ObservationModelTp;
72 using motion_model_input_type = typename motion_model_type::input_type;
73 using matrix_type = typename motion_model_type::matrix_type;
74 using state_type = typename motion_model_type::state_type;
75
79 explicit ExtendedKalmanFilter(motion_model_type &motion_model);
80
84 template <typename O = ObservationModelTp>
85 ExtendedKalmanFilter(motion_model_type &motion_model, const O &observation_model);
86
91 void predict(const motion_model_input_type &input);
92
97 void predict(const motion_model_input_type &input, const matrix_type &Q);
98
103 template <typename ObservationModel>
104 EKFUpdateResult update(const ObservationModel &model, const DynVec<real_t> &z,
105 const matrix_type &R,
106 real_t gate = std::numeric_limits<real_t>::infinity());
107
113
117 void estimate(const std::tuple<motion_model_input_type, DynVec<real_t>> &input);
118
123 void set_matrix(const std::string &name, const matrix_type &mat);
124 ExtendedKalmanFilter &with_matrix(const std::string &name, const matrix_type &mat);
125 bool has_matrix(const std::string &name) const;
126 const matrix_type &operator[](const std::string &name) const;
127 matrix_type &operator[](const std::string &name);
128
129 const state_type &get_state() const { return motion_model_ptr_->get_state(); }
130 state_type &get_state() { return motion_model_ptr_->get_state(); }
131
135 DynVec<real_t> state_vector() const { return motion_model_ptr_->get_state().as_vector(); }
136
137 real_t get(const std::string &name) const
138 {
139 return motion_model_ptr_->get_state_property(name);
140 }
141
142 protected:
144 const void *observation_model_ptr_{nullptr};
145 std::map<std::string, matrix_type> matrices_;
146};
147
148namespace ekf_detail
149{
150template <typename Model>
151concept CanSayIfItHasMatrices = requires(const Model &m)
152{
153 {
154 m.has_matrix("M")
155 } -> std::convertible_to<bool>;
156};
157
158template <typename Model>
159concept HasResidual = requires(const Model &m, const DynVec<real_t> &z)
160{
161 m.residual(z, z);
162};
163} // namespace ekf_detail
164
165template <typename MotionModelTp, typename ObservationModelTp>
171
172template <typename MotionModelTp, typename ObservationModelTp>
173template <typename O>
175 motion_model_type &motion_model, const O &observation_model)
176 : motion_model_ptr_(&motion_model), observation_model_ptr_(&observation_model)
177{
178}
179
180template <typename MotionModelTp, typename ObservationModelTp>
182 const matrix_type &mat)
183{
184 if (name != "Q" && name != "K" && name != "R" && name != "P")
185 {
186 throw std::logic_error("Invalid matrix name. Name: " + name + " not in [Q, K, R, P]");
187 }
188 matrices_.insert_or_assign(name, mat);
189}
190
191template <typename MotionModelTp, typename ObservationModelTp>
194 const matrix_type &mat)
195{
196 set_matrix(name, mat);
197 return *this;
198}
199
200template <typename MotionModelTp, typename ObservationModelTp>
202 const std::string &name) const
203{
204 return matrices_.find(name) != matrices_.end();
205}
206
207template <typename MotionModelTp, typename ObservationModelTp>
210{
211 auto itr = matrices_.find(name);
212 if (itr == matrices_.end())
213 {
214 throw std::invalid_argument("Matrix: " + name + " does not exist");
215 }
216 return itr->second;
217}
218
219template <typename MotionModelTp, typename ObservationModelTp>
222{
223 auto itr = matrices_.find(name);
224 if (itr == matrices_.end())
225 {
226 throw std::invalid_argument("Matrix: " + name + " does not exist");
227 }
228 return itr->second;
229}
230
231template <typename MotionModelTp, typename ObservationModelTp>
237
238template <typename MotionModelTp, typename ObservationModelTp>
240 const motion_model_input_type &u, const matrix_type &Q)
241{
242 // The motion model moves the state and works out F and L at the state before the move
243 motion_model_ptr_->evaluate(u);
244 auto &P = (*this)["P"];
245 const auto &L = motion_model_ptr_->get_matrix("L");
246 const auto &F = motion_model_ptr_->get_matrix("F");
247 P = F * P * F.transpose() + L * Q * L.transpose();
248}
249
250template <typename MotionModelTp, typename ObservationModelTp>
251template <typename ObservationModel>
253 const ObservationModel &model, const DynVec<real_t> &z, const matrix_type &R, real_t gate)
254{
255 auto &state = motion_model_ptr_->get_state();
256 auto &P = (*this)["P"];
257
258 const DynVec<real_t> zpred = model.evaluate(state.as_vector());
259 const matrix_type H = model.get_matrix("H");
260 if (z.size() != zpred.size() || H.rows() != z.size() || H.cols() != P.rows())
261 {
262 throw std::runtime_error("ExtendedKalmanFilter::update: the measurement has " +
263 std::to_string(z.size()) + " values, the model predicts " +
264 std::to_string(zpred.size()) + " and H is " +
265 std::to_string(H.rows()) + " x " + std::to_string(H.cols()));
266 }
267
268 matrix_type MRM = R;
270 {
271 if (model.has_matrix("M"))
272 {
273 const matrix_type M = model.get_matrix("M");
274 MRM = M * R * M.transpose();
275 }
276 }
277
278 EKFUpdateResult result;
280 {
281 result.innovation = model.residual(z, zpred);
282 }
283 else
284 {
285 result.innovation = z - zpred;
286 }
287
288 const matrix_type S = H * P * H.transpose() + MRM;
289 const auto S_ldlt = S.ldlt();
290 const ColVec<real_t> nu = result.innovation.transpose();
291 result.mahalanobis = nu.dot(S_ldlt.solve(nu));
292 if (!(result.mahalanobis <= gate))
293 {
294 return result;
295 }
296
297 // K = P H^T S^-1, worked out as (S^-1 H P)^T since S and P are symmetric
298 const matrix_type K = S_ldlt.solve(H * P).transpose();
299 const ColVec<real_t> dx = K * nu;
300 state += dx.transpose();
301
302 const auto n = P.rows();
303 P = (matrix_type::Identity(n, n) - K * H) * P;
304 // Keep P symmetric against round-off
305 P = 0.5 * (P + P.transpose()).eval();
306
307 if (has_matrix("K"))
308 {
309 (*this)["K"] = K;
310 }
311 else
312 {
313 set_matrix("K", K);
314 }
315 result.accepted = true;
316 return result;
317}
318
319template <typename MotionModelTp, typename ObservationModelTp>
322{
323 if constexpr (std::is_void_v<ObservationModelTp>)
324 {
325 throw std::logic_error("ExtendedKalmanFilter::update(z) needs a filter made with an "
326 "observation model; use update(model, z, R)");
327 }
328 else
329 {
330 if (observation_model_ptr_ == nullptr)
331 {
332 throw std::logic_error("ExtendedKalmanFilter::update(z): no observation model");
333 }
334 return update(*static_cast<const ObservationModelTp *>(observation_model_ptr_), z,
335 (*this)["R"]);
336 }
337}
338
339template <typename MotionModelTp, typename ObservationModelTp>
341 const std::tuple<motion_model_input_type, DynVec<real_t>> &input)
342{
343 predict(std::get<0>(input));
344 update(std::get<1>(input));
345}
346
347} // namespace estimation
348} // namespace bitsim
349
350#endif // BITSIM_ESTIMATION_EXTENDED_KALMAN_FILTER_H
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
The extended Kalman filter: it predicts the state with a non-linear motion model and corrects it with...
Definition extended_kalman_filter.h:68
ExtendedKalmanFilter(motion_model_type &motion_model)
A filter for the motion model, with the observation models given to update().
Definition extended_kalman_filter.h:166
std::map< std::string, matrix_type > matrices_
Definition extended_kalman_filter.h:145
const void * observation_model_ptr_
Definition extended_kalman_filter.h:144
typename motion_model_type::state_type state_type
Definition extended_kalman_filter.h:74
state_type & get_state()
Definition extended_kalman_filter.h:130
MotionModelTp motion_model_type
Definition extended_kalman_filter.h:70
typename motion_model_type::input_type motion_model_input_type
Definition extended_kalman_filter.h:72
bool has_matrix(const std::string &name) const
Definition extended_kalman_filter.h:201
ObservationModelTp observation_model_type
Definition extended_kalman_filter.h:71
typename motion_model_type::matrix_type matrix_type
Definition extended_kalman_filter.h:73
void predict(const motion_model_input_type &input)
Predict the state one step with the input, and its covariance with the Q set by set_matrix("Q").
Definition extended_kalman_filter.h:232
void set_matrix(const std::string &name, const matrix_type &mat)
Set P, the covariance of the state, Q, of the process noise, or R, of the own observation model's noi...
Definition extended_kalman_filter.h:181
real_t get(const std::string &name) const
Definition extended_kalman_filter.h:137
motion_model_type * motion_model_ptr_
Definition extended_kalman_filter.h:143
DynVec< real_t > state_vector() const
The state as a vector.
Definition extended_kalman_filter.h:135
const state_type & get_state() const
Definition extended_kalman_filter.h:129
const matrix_type & operator[](const std::string &name) const
Definition extended_kalman_filter.h:209
ExtendedKalmanFilter & with_matrix(const std::string &name, const matrix_type &mat)
Definition extended_kalman_filter.h:193
EKFUpdateResult update(const ObservationModel &model, const DynVec< real_t > &z, const matrix_type &R, real_t gate=std::numeric_limits< real_t >::infinity())
Correct the state with the measurement z of the observation model, of noise covariance R....
Definition extended_kalman_filter.h:252
void estimate(const std::tuple< motion_model_input_type, DynVec< real_t > > &input)
predict(), then update(z)
Definition extended_kalman_filter.h:340
ExtendedKalmanFilter(motion_model_type &motion_model)
A filter for the motion model, with the observation models given to update().
Definition extended_kalman_filter.h:166
void predict(const motion_model_input_type &input, const matrix_type &Q)
Predict with the process noise covariance Q of this step, for noise that depends on the input.
Definition extended_kalman_filter.h:239
ExtendedKalmanFilter(motion_model_type &motion_model, const O &observation_model)
A filter with an observation model of its own, for update(z).
Definition extended_kalman_filter.h:174
bitsim::estimation::DiffDriveGyroModel motion_model_type
Definition extended_kalman_filter.h:70
typename motion_model_type::input_type motion_model_input_type
Definition extended_kalman_filter.h:72
bool has_matrix(const std::string &name) const
Definition extended_kalman_filter.h:201
EKFUpdateResult update(const DynVec< real_t > &z)
Correct the state with the measurement z of the filter's own observation model and the R set by set_m...
Definition extended_kalman_filter.h:321
typename motion_model_type::matrix_type matrix_type
Definition extended_kalman_filter.h:73
matrix_type & operator[](const std::string &name)
Definition extended_kalman_filter.h:221
void predict(const motion_model_input_type &input)
Predict the state one step with the input, and its covariance with the Q set by set_matrix("Q").
Definition extended_kalman_filter.h:232
void set_matrix(const std::string &name, const matrix_type &mat)
Set P, the covariance of the state, Q, of the process noise, or R, of the own observation model's noi...
Definition extended_kalman_filter.h:181
const matrix_type & operator[](const std::string &name) const
Definition extended_kalman_filter.h:209
ExtendedKalmanFilter & with_matrix(const std::string &name, const matrix_type &mat)
Definition extended_kalman_filter.h:193
EKFUpdateResult update(const ObservationModel &model, const DynVec< real_t > &z, const matrix_type &R, real_t gate=std::numeric_limits< real_t >::infinity())
Correct the state with the measurement z of the observation model, of noise covariance R....
Definition extended_kalman_filter.h:252
void estimate(const std::tuple< motion_model_input_type, DynVec< real_t > > &input)
predict(), then update(z)
Definition extended_kalman_filter.h:340
Definition extended_kalman_filter.h:151
Definition extended_kalman_filter.h:159
Definition extended_kalman_filter.h:149
Definition diff_drive_ekf.cpp:12
Definition dc_motor_backend_base.h:9
double real_t
real_t
Definition bitsim_types.h:20
Eigen::RowVectorX< T > DynVec
Dynamically sized row vector.
Definition bitsim_types.h:101
Eigen::VectorX< T > ColVec
Column vector. Some maths operations are easier using column vectors rather than DynVec.
Definition bitsim_types.h:117
What an update of an ExtendedKalmanFilter did with a measurement.
Definition extended_kalman_filter.h:25
DynVec< real_t > innovation
z - h(x), or the model's residual of them
Definition extended_kalman_filter.h:28
bool accepted
false if the gate rejected the measurement
Definition extended_kalman_filter.h:26
real_t mahalanobis
the squared Mahalanobis distance of the innovation
Definition extended_kalman_filter.h:27