snark
kalman_filter.h
1 // This file is part of snark, a generic and flexible library
2 // for robotics research.
3 //
4 // Copyright (C) 2011 The University of Sydney
5 //
6 // snark is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 3 of the License, or (at your option) any later version.
10 //
11 // snark is distributed in the hope that it will be useful, but WITHOUT ANY
12 // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
14 // for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with snark. If not, see <http://www.gnu.org/licenses/>.
18 
19 #ifndef SNARK_FILTER_KALMAN_FILTER_H
20 #define SNARK_FILTER_KALMAN_FILTER_H
21 
22 #include <Eigen/Core>
23 #include <Eigen/Cholesky>
24 
25 namespace snark{
26 
28 template< class State, class Model >
30 {
31 public:
35  kalman_filter( const State& initialstate, Model& model ) : m_state( initialstate ), m_model( model ) {}
36 
39  void predict( double deltaT )
40  {
41  const Eigen::Matrix< double, State::dimension, State::dimension >& A = m_model.jacobian( m_state, deltaT );
42  m_state.covariance = A * m_state.covariance * A.transpose() + m_model.noise_covariance( deltaT );
43  m_model.update_state( m_state, deltaT );
44  }
45 
48  template< class Measurement >
49  void update( const Measurement& m )
50  {
51  const Eigen::Matrix<double,Measurement::dimension,State::dimension>& H = m.measurement_jacobian( m_state );
52  const Eigen::Matrix<double,Measurement::dimension,Measurement::dimension>& R = m.measurement_covariance( m_state );
53  const Eigen::Matrix<double,Measurement::dimension,1>& innovation = m.innovation( m_state );
54 
55  const Eigen::Matrix<double,State::dimension, Measurement::dimension> PHt = m_state.covariance * H.transpose();
56  const Eigen::LDLT< Eigen::Matrix<double,Measurement::dimension,Measurement::dimension> > S = ( H * PHt + R ).ldlt();
57 
58  m_state.covariance -= PHt * S.solve( PHt.transpose() );
59  m_state.set_innovation( PHt * S.solve( innovation ) );
60  }
61 
63  const State& state() const { return m_state; }
64 
65 private:
66  State m_state;
67  Model& m_model;
68 };
69 
70 }
71 
72 #endif // SNARK_FILTER_KALMAN_FILTER_H