root/bdm/estim/libKF.h @ 283

Revision 283, 10.5 kB (checked in by smidl, 15 years ago)

get rid of BMcond + adaptation in doprava/

  • 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
17#include "../stat/libFN.h"
18#include "../stat/libEF.h"
19#include "../math/chmat.h"
20
21namespace bdm {
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 est.mu
101        vec& _mu;
102        //!cache of est.R
103        sq_T& _P;
104
105public:
106        //! Default constructor
107        Kalman ( );
108        //! Copy constructor
109        Kalman ( const Kalman<sq_T> &K0 );
110        //! Set parameters with check of relevance
111        void set_parameters ( const mat &A0,const mat &B0,const mat &C0,const mat &D0,const sq_T &Q0,const sq_T &R0 );
112        //! Set estimate values, used e.g. in initialization.
113        void set_est ( const vec &mu0, const sq_T &P0 ) {
114                sq_T pom ( dimy );
115                est.set_parameters ( mu0,P0 );
116                P0.mult_sym ( C,pom );
117                fy.set_parameters ( C*mu0, pom );
118        };
119
120        //! Here dt = [yt;ut] of appropriate dimensions
121        void bayes ( const vec &dt );
122        //!access function
123        const epdf& posterior() const {return est;}
124        const enorm<sq_T>* _e() const {return &est;}
125        //!access function
126        mat& __K() {return _K;}
127        //!access function
128        vec _dP() {return _P->getD();}
129};
130
131/*! \brief Kalman filter in square root form
132
133Trivial example:
134\include kalman_simple.cpp
135
136*/
137class KalmanCh : public Kalman<chmat> {
138protected:
139//! pre array (triangular matrix)
140        mat preA;
141//! post array (triangular matrix)
142        mat postA;
143
144public:
145        //! copy constructor
146        BM* _copy_() const {
147                KalmanCh* K=new KalmanCh;
148                K->set_parameters ( A,B,C,D,Q,R );
149                K->set_statistics ( _mu,_P );
150                return K;
151        }
152        //! Set parameters with check of relevance
153        void set_parameters ( const mat &A0,const mat &B0,const mat &C0,const mat &D0,const chmat &Q0,const chmat &R0 );
154        void set_statistics ( const vec &mu0, const chmat &P0 ) {
155                est.set_parameters ( mu0,P0 );
156        };
157
158
159        /*!\brief  Here dt = [yt;ut] of appropriate dimensions
160
161        The following equality hold::\f[
162        \left[\begin{array}{cc}
163        R^{0.5}\\
164        P_{t|t-1}^{0.5}C' & P_{t|t-1}^{0.5}CA'\\
165        & Q^{0.5}\end{array}\right]<\mathrm{orth.oper.}>=\left[\begin{array}{cc}
166        R_{y}^{0.5} & KA'\\
167        & P_{t+1|t}^{0.5}\\
168        \\\end{array}\right]\f]
169
170        Thus this object evaluates only predictors! Not filtering densities.
171        */
172        void bayes ( const vec &dt );
173};
174
175/*!
176\brief Extended Kalman Filter in full matrices
177
178An approximation of the exact Bayesian filter with Gaussian noices and non-linear evolutions of their mean.
179*/
180class EKFfull : public KalmanFull, public BM {
181
182        //! Internal Model f(x,u)
183        diffbifn* pfxu;
184        //! Observation Model h(x,u)
185        diffbifn* phxu;
186
187        enorm<fsqmat> E;
188public:
189        //! Default constructor
190        EKFfull ( );
191        //! Set nonlinear functions for mean values and covariance matrices.
192        void set_parameters ( diffbifn* pfxu, diffbifn* phxu, const mat Q0, const mat R0 );
193        //! Here dt = [yt;ut] of appropriate dimensions
194        void bayes ( const vec &dt );
195        //! set estimates
196        void set_est ( vec mu0, mat P0 ) {mu=mu0;P=P0;};
197        //!dummy!
198        const epdf& posterior() const{return E;};
199        const enorm<fsqmat>* _e() const{return &E;};
200        const mat _R() {return P;}
201};
202
203/*!
204\brief Extended Kalman Filter
205
206An approximation of the exact Bayesian filter with Gaussian noices and non-linear evolutions of their mean.
207*/
208template<class sq_T>
209class EKF : public Kalman<fsqmat> {
210        //! Internal Model f(x,u)
211        diffbifn* pfxu;
212        //! Observation Model h(x,u)
213        diffbifn* phxu;
214public:
215        //! Default constructor
216        EKF ( RV rvx, RV rvy, RV rvu );
217        //! copy constructor
218        EKF<sq_T>* _copy_() const { return new EKF<sq_T>(this); }
219        //! Set nonlinear functions for mean values and covariance matrices.
220        void set_parameters ( diffbifn* pfxu, diffbifn* phxu, const sq_T Q0, const sq_T R0 );
221        //! Here dt = [yt;ut] of appropriate dimensions
222        void bayes ( const vec &dt );
223};
224
225/*!
226\brief Extended Kalman Filter in Square root
227
228An approximation of the exact Bayesian filter with Gaussian noices and non-linear evolutions of their mean.
229*/
230
231class EKFCh : public KalmanCh {
232protected:
233        //! Internal Model f(x,u)
234        diffbifn* pfxu;
235        //! Observation Model h(x,u)
236        diffbifn* phxu;
237public:
238        //! copy constructor duplicated - calls different set_parameters
239        BM* _copy_() const {
240                EKFCh* E=new EKFCh;
241                E->set_parameters ( pfxu,phxu,Q,R );
242                E->set_statistics ( _mu,_P );
243                return E;
244        }
245        //! Set nonlinear functions for mean values and covariance matrices.
246        void set_parameters ( diffbifn* pfxu, diffbifn* phxu, const chmat Q0, const chmat R0 );
247        //! Here dt = [yt;ut] of appropriate dimensions
248        void bayes ( const vec &dt );
249};
250
251/*!
252\brief Kalman Filter with conditional diagonal matrices R and Q.
253*/
254
255class KFcondQR : public Kalman<ldmat> {
256//protected:
257public:
258        void condition ( const vec &QR ) {
259                it_assert_debug ( QR.length() == ( dimx+dimy ),"KFcondRQ: conditioning by incompatible vector" );
260
261                Q.setD ( QR ( 0, dimx-1 ) );
262                R.setD ( QR ( dimx, -1 ) );
263        };
264};
265
266/*!
267\brief Kalman Filter with conditional diagonal matrices R and Q.
268*/
269
270class KFcondR : public Kalman<ldmat> {
271//protected:
272public:
273        //!Default constructor
274        KFcondR ( ) : Kalman<ldmat> ( ) {};
275
276        void condition ( const vec &R0 ) {
277                it_assert_debug ( R0.length() == ( dimy ),"KFcondR: conditioning by incompatible vector" );
278
279                R.setD ( R0 );
280        };
281
282};
283
284//////// INstance
285
286template<class sq_T>
287Kalman<sq_T>::Kalman ( const Kalman<sq_T> &K0 ) : BM ( ),rvy ( K0.rvy ),rvu ( K0.rvu ),
288                dimx ( K0.dimx ), dimy ( K0.dimy ),dimu ( K0.dimu ),
289                A ( K0.A ), B ( K0.B ), C ( K0.C ), D ( K0.D ),
290                Q ( K0.Q ), R ( K0.R ),
291                est ( K0.est ), fy ( K0.fy ), _yp ( fy._mu() ),_Ry ( fy._R() ), _mu ( est._mu() ), _P ( est._R() ) {
292
293// copy values in pointers
294//      _mu = K0._mu;
295//      _P = K0._P;
296//      _yp = K0._yp;
297//      _Ry = K0._Ry;
298
299}
300
301template<class sq_T>
302Kalman<sq_T>::Kalman ( ) : BM (), est ( ), fy (),  _yp ( fy._mu() ), _Ry ( fy._R() ), _mu ( est._mu() ), _P ( est._R() ) {
303};
304
305template<class sq_T>
306void Kalman<sq_T>::set_parameters ( const mat &A0,const  mat &B0, const mat &C0, const mat &D0, const sq_T &Q0, const sq_T &R0 ) {
307        dimx = A0.rows();
308        dimy = C0.rows();
309        dimu = B0.cols();
310
311        it_assert_debug ( A0.cols() ==dimx, "Kalman: A is not square" );
312        it_assert_debug ( B0.rows() ==dimx, "Kalman: B is not compatible" );
313        it_assert_debug ( C0.cols() ==dimx, "Kalman: C is not square" );
314        it_assert_debug ( ( D0.rows() ==dimy ) || ( D0.cols() ==dimu ), "Kalman: D is not compatible" );
315        it_assert_debug ( ( R0.cols() ==dimy ) || ( R0.rows() ==dimy ), "Kalman: R is not compatible" );
316        it_assert_debug ( ( Q0.cols() ==dimx ) || ( Q0.rows() ==dimx ), "Kalman: Q is not compatible" );
317
318        A = A0;
319        B = B0;
320        C = C0;
321        D = D0;
322        R = R0;
323        Q = Q0;
324}
325
326template<class sq_T>
327void Kalman<sq_T>::bayes ( const vec &dt ) {
328        it_assert_debug ( dt.length() == ( dimy+dimu ),"KalmanFull::bayes wrong size of dt" );
329
330        sq_T iRy ( dimy );
331        vec u = dt.get ( dimy,dimy+dimu-1 );
332        vec y = dt.get ( 0,dimy-1 );
333        //Time update
334        _mu = A* _mu + B*u;
335        //P  = A*P*A.transpose() + Q; in sq_T
336        _P.mult_sym ( A );
337        _P  +=Q;
338
339        //Data update
340        //_Ry = C*P*C.transpose() + R; in sq_T
341        _P.mult_sym ( C, _Ry );
342        _Ry  +=R;
343
344        mat Pfull = _P.to_mat();
345
346        _Ry.inv ( iRy ); // result is in _iRy;
347        _K = Pfull*C.transpose() * ( iRy.to_mat() );
348
349        sq_T pom ( ( int ) Pfull.rows() );
350        iRy.mult_sym_t ( C*Pfull,pom );
351        ( _P ) -= pom; // P = P -PC'iRy*CP;
352        ( _yp ) = C* _mu  +D*u; //y prediction
353        ( _mu ) += _K* ( y- _yp );
354
355
356        if ( evalll==true ) { //likelihood of observation y
357                ll=fy.evallog ( y );
358        }
359
360//cout << "y: " << y-(*_yp) <<" R: " << _Ry->to_mat() << " iR: " << _iRy->to_mat() << " ll: " << ll <<endl;
361
362};
363
364
365
366//TODO why not const pointer??
367
368template<class sq_T>
369EKF<sq_T>::EKF ( RV rvx0, RV rvy0, RV rvu0 ) : Kalman<sq_T> ( rvx0,rvy0,rvu0 ) {}
370
371template<class sq_T>
372void EKF<sq_T>::set_parameters ( diffbifn* pfxu0,  diffbifn* phxu0,const sq_T Q0,const sq_T R0 ) {
373        pfxu = pfxu0;
374        phxu = phxu0;
375
376        //initialize matrices A C, later, these will be only updated!
377        pfxu->dfdx_cond ( _mu,zeros ( dimu ),A,true );
378//      pfxu->dfdu_cond ( *_mu,zeros ( dimu ),B,true );
379        B.clear();
380        phxu->dfdx_cond ( _mu,zeros ( dimu ),C,true );
381//      phxu->dfdu_cond ( *_mu,zeros ( dimu ),D,true );
382        D.clear();
383
384        R = R0;
385        Q = Q0;
386}
387
388template<class sq_T>
389void EKF<sq_T>::bayes ( const vec &dt ) {
390        it_assert_debug ( dt.length() == ( dimy+dimu ),"KalmanFull::bayes wrong size of dt" );
391
392        sq_T iRy ( dimy,dimy );
393        vec u = dt.get ( dimy,dimy+dimu-1 );
394        vec y = dt.get ( 0,dimy-1 );
395        //Time update
396        _mu = pfxu->eval ( _mu, u );
397        pfxu->dfdx_cond ( _mu,u,A,false ); //update A by a derivative of fx
398
399        //P  = A*P*A.transpose() + Q; in sq_T
400        _P.mult_sym ( A );
401        _P +=Q;
402
403        //Data update
404        phxu->dfdx_cond ( _mu,u,C,false ); //update C by a derivative hx
405        //_Ry = C*P*C.transpose() + R; in sq_T
406        _P.mult_sym ( C, _Ry );
407        ( _Ry ) +=R;
408
409        mat Pfull = _P.to_mat();
410
411        _Ry.inv ( iRy ); // result is in _iRy;
412        _K = Pfull*C.transpose() * ( iRy.to_mat() );
413
414        sq_T pom ( ( int ) Pfull.rows() );
415        iRy.mult_sym_t ( C*Pfull,pom );
416        ( _P ) -= pom; // P = P -PC'iRy*CP;
417        _yp = phxu->eval ( _mu,u ); //y prediction
418        ( _mu ) += _K* ( y-_yp );
419
420        if ( evalll==true ) {ll+=fy.evallog ( y );}
421};
422
423
424}
425#endif // KF_H
426
Note: See TracBrowser for help on using the browser.