root/bdm/estim/libKF.h @ 67

Revision 67, 10.5 kB (checked in by smidl, 16 years ago)

opavy

  • Property svn:eol-style set to native
Line 
1/*!
2  \file
3  \brief Bayesian Filtering for linear Gaussian models (Kalman Filter) and extensions
4  \author Vaclav Smidl.
5
6  -----------------------------------
7  BDM++ - C++ library for Bayesian Decision Making under Uncertainty
8
9  Using IT++ for numerical operations
10  -----------------------------------
11*/
12
13#ifndef KF_H
14#define KF_H
15
16#include <itpp/itbase.h>
17#include "../stat/libFN.h"
18#include "../stat/libEF.h"
19#include "../math/chmat.h"
20
21using namespace itpp;
22
23/*!
24* \brief Basic Kalman filter with full matrices (education purpose only)! Will be deleted soon!
25*/
26
27class KalmanFull {
28protected:
29        int dimx, dimy, dimu;
30        mat A, B, C, D, R, Q;
31
32        //cache
33        mat _Pp, _Ry, _iRy, _K;
34public:
35        //posterior
36        //! Mean value of the posterior density
37        vec mu;
38        //! Variance of the posterior density
39        mat P;
40
41        bool evalll;
42        double ll;
43public:
44        //! Full constructor
45        KalmanFull ( mat A, mat B, mat C, mat D, mat R, mat Q, mat P0, vec mu0 );
46        //! Here dt = [yt;ut] of appropriate dimensions
47        void bayes ( const vec &dt );
48        //! print elements of KF
49        friend std::ostream &operator<< ( std::ostream &os, const KalmanFull &kf );
50        //! For EKFfull;
51        KalmanFull(){};
52};
53
54
55/*!
56* \brief Kalman filter with covariance matrices in square root form.
57
58Parameter evolution model:\f[ x_t = A x_{t-1} + B u_t + Q^{1/2} e_t \f]
59Observation model: \f[ y_t = C x_{t-1} + C u_t + Q^{1/2} w_t. \f]
60Where $e_t$ and $w_t$ are independent vectors Normal(0,1)-distributed disturbances.
61*/
62template<class sq_T>
63
64class Kalman : public BM {
65protected:
66        //! Indetifier of output rv
67        RV rvy;
68        //! Indetifier of exogeneous rv
69        RV rvu;
70        //! cache of rv.count()
71        int dimx;
72        //! cache of rvy.count()
73        int dimy;
74        //! cache of rvu.count()
75        int dimu;
76        //! Matrix A
77        mat A;
78        //! Matrix B
79        mat B; 
80        //! Matrix C
81        mat C;
82        //! Matrix D
83        mat D;
84        //! Matrix Q in square-root form
85        sq_T Q;
86        //! Matrix R in square-root form
87        sq_T R;
88
89        //!posterior density on $x_t$
90        enorm<sq_T> est;
91        //!preditive density on $y_t$
92        enorm<sq_T> fy;
93
94        //! placeholder for Kalman gain
95        mat _K;
96        //! cache of fy.mu
97        vec* _yp;
98        //! cache of fy.R
99        sq_T* _Ry;
100        //! cache of fy.iR
101        sq_T* _iRy;
102        //!cache of est.mu
103        vec* _mu;
104        //!cache of est.R
105        sq_T* _P;
106        //!cache of est.iR
107        sq_T* _iP;
108
109public:
110        //! Default constructor
111        Kalman ( RV rvx0, RV rvy0, RV rvu0 );
112        //! Copy constructor
113        Kalman ( const Kalman<sq_T> &K0 );
114        //! Set parameters with check of relevance
115        void set_parameters ( const mat &A0,const mat &B0,const mat &C0,const mat &D0,const sq_T &R0,const sq_T &Q0 );
116        //! Set estimate values, used e.g. in initialization.
117        void set_est ( const vec &mu0, const sq_T &P0 ) {
118                sq_T pom(dimy);
119                est.set_parameters ( mu0,P0 );
120                P0.mult_sym(C,pom);
121                fy.set_parameters ( C*mu0, pom );
122        };
123
124        //! Here dt = [yt;ut] of appropriate dimensions
125        void bayes ( const vec &dt );
126        //!access function
127        epdf& _epdf() {return est;}
128        //!access function
129        mat& __K() {return _K;}
130        //!access function
131        vec _dP() {return _P->getD();}
132};
133
134/*! \brief Kalman filter in square root form
135*/
136class KalmanCh : public Kalman<chmat>{
137protected:
138//! pre array (triangular matrix)
139mat preA;
140//! post array (triangular matrix)
141mat postA;
142
143public:
144        //! Default constructor
145        KalmanCh ( RV rvx0, RV rvy0, RV rvu0 ):Kalman<chmat>(rvx0,rvy0,rvu0),preA(dimy+dimx+dimx,dimy+dimx),postA(dimy+dimx,dimy+dimx){};
146        //! Set parameters with check of relevance
147        void set_parameters ( const mat &A0,const mat &B0,const mat &C0,const mat &D0,const chmat &R0,const chmat &Q0 );
148        void set_est ( const vec &mu0, const chmat &P0 ) {
149                est.set_parameters ( mu0,P0 );
150        };
151       
152       
153        /*!\brief  Here dt = [yt;ut] of appropriate dimensions
154       
155        The following equality hold::\f[
156\left[\begin{array}{cc}
157R^{0.5}\\
158P_{t|t-1}^{0.5}C' & P_{t|t-1}^{0.5}CA'\\
159 & Q^{0.5}\end{array}\right]<\mathrm{orth.oper.}>=\left[\begin{array}{cc}
160R_{y}^{0.5} & KA'\\
161 & P_{t+1|t}^{0.5}\\
162\\\end{array}\right]\f]
163
164Thus this objevt evaluates only predictors! Not filtering densities.
165        */
166        void bayes ( const vec &dt );
167};
168
169/*!
170\brief Extended Kalman Filter in full matrices
171
172An approximation of the exact Bayesian filter with Gaussian noices and non-linear evolutions of their mean.
173*/
174class EKFfull : public KalmanFull, public BM {
175
176        //! Internal Model f(x,u)
177        diffbifn* pfxu;
178        //! Observation Model h(x,u)
179        diffbifn* phxu;
180       
181        enorm<fsqmat> E; 
182public:
183        //! Default constructor
184        EKFfull ( RV rvx, RV rvy, RV rvu );
185        //! Set nonlinear functions for mean values and covariance matrices.
186        void set_parameters ( diffbifn* pfxu, diffbifn* phxu, const mat Q0, const mat R0 );
187        //! Here dt = [yt;ut] of appropriate dimensions
188        void bayes ( const vec &dt );
189        //! set estimates
190        void set_est (vec mu0, mat P0){mu=mu0;P=P0;};
191        //!dummy!
192        epdf& _epdf(){return E;};
193};
194
195/*!
196\brief Extended Kalman Filter
197
198An approximation of the exact Bayesian filter with Gaussian noices and non-linear evolutions of their mean.
199*/
200template<class sq_T>
201class EKF : public Kalman<fsqmat> {
202        //! Internal Model f(x,u)
203        diffbifn* pfxu;
204        //! Observation Model h(x,u)
205        diffbifn* phxu;
206public:
207        //! Default constructor
208        EKF ( RV rvx, RV rvy, RV rvu );
209        //! Set nonlinear functions for mean values and covariance matrices.
210        void set_parameters ( diffbifn* pfxu, diffbifn* phxu, const sq_T Q0, const sq_T R0 );
211        //! Here dt = [yt;ut] of appropriate dimensions
212        void bayes ( const vec &dt );
213};
214
215/*!
216\brief Extended Kalman Filter in Square root
217
218An approximation of the exact Bayesian filter with Gaussian noices and non-linear evolutions of their mean.
219*/
220
221class EKFCh : public KalmanCh {
222        //! Internal Model f(x,u)
223        diffbifn* pfxu;
224        //! Observation Model h(x,u)
225        diffbifn* phxu;
226public:
227        //! Default constructor
228        EKFCh ( RV rvx, RV rvy, RV rvu );
229        //! Set nonlinear functions for mean values and covariance matrices.
230        void set_parameters ( diffbifn* pfxu, diffbifn* phxu, const chmat Q0, const chmat R0 );
231        //! Here dt = [yt;ut] of appropriate dimensions
232        void bayes ( const vec &dt );
233};
234
235/*!
236\brief Kalman Filter with conditional diagonal matrices R and Q.
237*/
238
239class KFcondQR : public Kalman<ldmat>, public BMcond {
240//protected:
241public:
242        //!Default constructor
243        KFcondQR ( RV rvx, RV rvy, RV rvu, RV rvRQ ) : Kalman<ldmat> ( rvx, rvy,rvu ),BMcond ( rvRQ ) {};
244
245        void condition ( const vec &RQ );
246};
247
248/*!
249\brief Kalman Filter with conditional diagonal matrices R and Q.
250*/
251
252class KFcondR : public Kalman<ldmat>, public BMcond {
253//protected:
254public:
255        //!Default constructor
256        KFcondR ( RV rvx, RV rvy, RV rvu, RV rvR ) : Kalman<ldmat> ( rvx, rvy,rvu ),BMcond ( rvR ) {};
257
258        void condition ( const vec &R );
259};
260
261//////// INstance
262
263template<class sq_T>
264Kalman<sq_T>::Kalman ( const Kalman<sq_T> &K0 ) : BM ( K0.rv ),rvy ( K0.rvy ),rvu ( K0.rvu ),
265                dimx ( rv.count() ), dimy ( rvy.count() ),dimu ( rvu.count() ),
266                A ( dimx,dimx ), B ( dimx,dimu ), C ( dimy,dimx ), D ( dimy,dimu ),
267                Q(dimx), R(dimy),
268                est ( rv ), fy ( rvy ) {
269
270        this->set_parameters ( K0.A, K0.B, K0.C, K0.D, K0.R, K0.Q );
271
272//establish pointers
273        _mu = est._mu();
274        est._R ( _P,_iP );
275
276//fy
277        _yp = fy._mu();
278        fy._R ( _Ry,_iRy );
279
280// copy values in pointers
281        *_mu = *K0._mu;
282        *_P = *K0._P;
283        *_iP = *K0._iP;
284        *_yp = *K0._yp;
285        *_iRy = *K0._iRy;
286        *_Ry = *K0._Ry;
287
288}
289
290template<class sq_T>
291Kalman<sq_T>::Kalman ( RV rvx, RV rvy0, RV rvu0 ) : BM ( rvx ),rvy ( rvy0 ),rvu ( rvu0 ),
292                dimx ( rvx.count() ), dimy ( rvy.count() ),dimu ( rvu.count() ),
293                A ( dimx,dimx ), B ( dimx,dimu ), C ( dimy,dimx ), D ( dimy,dimu ),
294                Q(dimx), R (dimy),
295                est ( rvx ), fy ( rvy ) {
296//assign cache
297//est
298        _mu = est._mu();
299        est._R ( _P,_iP );
300
301//fy
302        _yp = fy._mu();
303        fy._R ( _Ry,_iRy );
304};
305
306template<class sq_T>
307void Kalman<sq_T>::set_parameters ( const mat &A0,const  mat &B0, const mat &C0, const mat &D0, const sq_T &R0, const sq_T &Q0 ) {
308        it_assert_debug ( A0.cols() ==dimx, "Kalman: A is not square" );
309        it_assert_debug ( B0.rows() ==dimx, "Kalman: B is not compatible" );
310        it_assert_debug ( C0.cols() ==dimx, "Kalman: C is not square" );
311        it_assert_debug ( ( D0.rows() ==dimy ) || ( D0.cols() ==dimu ), "Kalman: D is not compatible" );
312        it_assert_debug ( ( R0.cols() ==dimy ) || ( R0.rows() ==dimy ), "Kalman: R is not compatible" );
313        it_assert_debug ( ( Q0.cols() ==dimx ) || ( Q0.rows() ==dimx ), "Kalman: Q is not compatible" );
314
315        A = A0;
316        B = B0;
317        C = C0;
318        D = D0;
319        R = R0;
320        Q = Q0;
321}
322
323template<class sq_T>
324void Kalman<sq_T>::bayes ( const vec &dt ) {
325        it_assert_debug ( dt.length() == ( dimy+dimu ),"KalmanFull::bayes wrong size of dt" );
326
327        vec u = dt.get ( dimy,dimy+dimu-1 );
328        vec y = dt.get ( 0,dimy-1 );
329        //Time update
330        *_mu = A* ( *_mu ) + B*u;
331        //P  = A*P*A.transpose() + Q; in sq_T
332        _P->mult_sym ( A );
333        ( *_P ) +=Q;
334
335        //Data update
336        //_Ry = C*P*C.transpose() + R; in sq_T
337        _P->mult_sym ( C, *_Ry );
338        ( *_Ry ) +=R;
339
340        mat Pfull = _P->to_mat();
341
342        _Ry->inv ( *_iRy ); // result is in _iRy;
343        fy._cached ( true );
344        _K = Pfull*C.transpose() * ( _iRy->to_mat() );
345
346        sq_T pom ( ( int ) Pfull.rows() );
347        _iRy->mult_sym_t ( C*Pfull,pom );
348        ( *_P ) -= pom; // P = P -PC'iRy*CP;
349        ( *_yp ) = C* ( *_mu ) +D*u; //y prediction
350        ( *_mu ) += _K* ( y- ( *_yp ) );
351
352
353        if ( evalll==true ) { //likelihood of observation y
354                ll=fy.evalpdflog ( y );
355        }
356
357//cout << "y: " << y-(*_yp) <<" R: " << _Ry->to_mat() << " iR: " << _iRy->to_mat() << " ll: " << ll <<endl;
358
359};
360 
361
362
363//TODO why not const pointer??
364
365template<class sq_T>
366EKF<sq_T>::EKF ( RV rvx0, RV rvy0, RV rvu0 ) : Kalman<sq_T> ( rvx0,rvy0,rvu0 ) {}
367
368template<class sq_T>
369void EKF<sq_T>::set_parameters ( diffbifn* pfxu0,  diffbifn* phxu0,const sq_T Q0,const sq_T R0 ) {
370        pfxu = pfxu0;
371        phxu = phxu0;
372
373        //initialize matrices A C, later, these will be only updated!
374        pfxu->dfdx_cond ( *_mu,zeros ( dimu ),A,true );
375//      pfxu->dfdu_cond ( *_mu,zeros ( dimu ),B,true );
376        B.clear();
377        phxu->dfdx_cond ( *_mu,zeros ( dimu ),C,true );
378//      phxu->dfdu_cond ( *_mu,zeros ( dimu ),D,true );
379        D.clear();
380
381        R = R0;
382        Q = Q0;
383}
384
385template<class sq_T>
386void EKF<sq_T>::bayes ( const vec &dt ) {
387        it_assert_debug ( dt.length() == ( dimy+dimu ),"KalmanFull::bayes wrong size of dt" );
388
389        vec u = dt.get ( dimy,dimy+dimu-1 );
390        vec y = dt.get ( 0,dimy-1 );
391        //Time update
392        *_mu = pfxu->eval ( *_mu, u );
393        pfxu->dfdx_cond ( *_mu,u,A,false ); //update A by a derivative of fx
394
395        //P  = A*P*A.transpose() + Q; in sq_T
396        _P->mult_sym ( A );
397        ( *_P ) +=Q;
398
399        //Data update
400        phxu->dfdx_cond ( *_mu,u,C,false ); //update C by a derivative hx
401        //_Ry = C*P*C.transpose() + R; in sq_T
402        _P->mult_sym ( C, *_Ry );
403        ( *_Ry ) +=R;
404
405        mat Pfull = _P->to_mat();
406
407        _Ry->inv ( *_iRy ); // result is in _iRy;
408        fy._cached ( true );
409        _K = Pfull*C.transpose() * ( _iRy->to_mat() );
410
411        sq_T pom ( ( int ) Pfull.rows() );
412        _iRy->mult_sym_t ( C*Pfull,pom );
413        ( *_P ) -= pom; // P = P -PC'iRy*CP;
414        *_yp = phxu->eval ( *_mu,u ); //y prediction
415        ( *_mu ) += _K* ( y-*_yp );
416
417        if ( evalll==true ) {ll+=fy.evalpdflog ( y );}
418};
419
420
421#endif // KF_H
422
Note: See TracBrowser for help on using the browser.