root/bdm/estim/libKF.h @ 51

Revision 51, 9.8 kB (checked in by smidl, 16 years ago)

oprava EKF + debug vypisove fce

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