root/bdm/estim/libKF.h @ 262

Revision 262, 10.4 kB (checked in by smidl, 15 years ago)

cleanup of include files

  • 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 ( RV rvx0, RV rvy0, RV rvu0 );
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 &R0,const sq_T &Q0 );
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& _epdf() 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*/
133class KalmanCh : public Kalman<chmat>{
134protected:
135//! pre array (triangular matrix)
136mat preA;
137//! post array (triangular matrix)
138mat postA;
139
140public:
141        //! Default constructor
142        KalmanCh ( RV rvx0, RV rvy0, RV rvu0 ):Kalman<chmat>(rvx0,rvy0,rvu0),preA(dimy+dimx+dimx,dimy+dimx),postA(dimy+dimx,dimy+dimx){};
143        //! Set parameters with check of relevance
144        void set_parameters ( const mat &A0,const mat &B0,const mat &C0,const mat &D0,const chmat &R0,const chmat &Q0 );
145        void set_est ( const vec &mu0, const chmat &P0 ) {
146                est.set_parameters ( mu0,P0 );
147        };
148       
149       
150        /*!\brief  Here dt = [yt;ut] of appropriate dimensions
151       
152        The following equality hold::\f[
153\left[\begin{array}{cc}
154R^{0.5}\\
155P_{t|t-1}^{0.5}C' & P_{t|t-1}^{0.5}CA'\\
156 & Q^{0.5}\end{array}\right]<\mathrm{orth.oper.}>=\left[\begin{array}{cc}
157R_{y}^{0.5} & KA'\\
158 & P_{t+1|t}^{0.5}\\
159\\\end{array}\right]\f]
160
161Thus this object evaluates only predictors! Not filtering densities.
162        */
163        void bayes ( const vec &dt );
164};
165
166/*!
167\brief Extended Kalman Filter in full matrices
168
169An approximation of the exact Bayesian filter with Gaussian noices and non-linear evolutions of their mean.
170*/
171class EKFfull : public KalmanFull, public BM {
172
173        //! Internal Model f(x,u)
174        diffbifn* pfxu;
175        //! Observation Model h(x,u)
176        diffbifn* phxu;
177       
178        enorm<fsqmat> E; 
179public:
180        //! Default constructor
181        EKFfull ( RV rvx, RV rvy, RV rvu );
182        //! Set nonlinear functions for mean values and covariance matrices.
183        void set_parameters ( diffbifn* pfxu, diffbifn* phxu, const mat Q0, const mat R0 );
184        //! Here dt = [yt;ut] of appropriate dimensions
185        void bayes ( const vec &dt );
186        //! set estimates
187        void set_est (vec mu0, mat P0){mu=mu0;P=P0;};
188        //!dummy!
189        const epdf& _epdf()const{return E;};
190        const enorm<fsqmat>* _e()const{return &E;};
191        const mat _R(){return P;}
192};
193
194/*!
195\brief Extended Kalman Filter
196
197An approximation of the exact Bayesian filter with Gaussian noices and non-linear evolutions of their mean.
198*/
199template<class sq_T>
200class EKF : public Kalman<fsqmat> {
201        //! Internal Model f(x,u)
202        diffbifn* pfxu;
203        //! Observation Model h(x,u)
204        diffbifn* phxu;
205public:
206        //! Default constructor
207        EKF ( RV rvx, RV rvy, RV rvu );
208        //! Set nonlinear functions for mean values and covariance matrices.
209        void set_parameters ( diffbifn* pfxu, diffbifn* phxu, const sq_T Q0, const sq_T R0 );
210        //! Here dt = [yt;ut] of appropriate dimensions
211        void bayes ( const vec &dt );
212};
213
214/*!
215\brief Extended Kalman Filter in Square root
216
217An approximation of the exact Bayesian filter with Gaussian noices and non-linear evolutions of their mean.
218*/
219
220class EKFCh : public KalmanCh {
221        protected:
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 ), _yp(fy._mu()),_Ry(fy._R()), _mu(est._mu()), _P(est._R()) {
269
270        this->set_parameters ( K0.A, K0.B, K0.C, K0.D, K0.R, K0.Q );
271
272// copy values in pointers
273        _mu = K0._mu;
274        _P = K0._P;
275        _yp = K0._yp;
276        _Ry = K0._Ry;
277
278}
279
280template<class sq_T>
281Kalman<sq_T>::Kalman ( RV rvx, RV rvy0, RV rvu0 ) : BM ( rvx ),rvy ( rvy0 ),rvu ( rvu0 ),
282                dimx ( rvx.count() ), dimy ( rvy.count() ),dimu ( rvu.count() ),
283                A ( dimx,dimx ), B ( dimx,dimu ), C ( dimy,dimx ), D ( dimy,dimu ),
284                Q(dimx), R (dimy),
285                est ( rvx ), fy ( rvy ),  _yp(fy._mu()),_Ry(fy._R()),_mu(est._mu()), _P(est._R()) {
286};
287
288template<class sq_T>
289void 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 ) {
290        it_assert_debug ( A0.cols() ==dimx, "Kalman: A is not square" );
291        it_assert_debug ( B0.rows() ==dimx, "Kalman: B is not compatible" );
292        it_assert_debug ( C0.cols() ==dimx, "Kalman: C is not square" );
293        it_assert_debug ( ( D0.rows() ==dimy ) || ( D0.cols() ==dimu ), "Kalman: D is not compatible" );
294        it_assert_debug ( ( R0.cols() ==dimy ) || ( R0.rows() ==dimy ), "Kalman: R is not compatible" );
295        it_assert_debug ( ( Q0.cols() ==dimx ) || ( Q0.rows() ==dimx ), "Kalman: Q is not compatible" );
296
297        A = A0;
298        B = B0;
299        C = C0;
300        D = D0;
301        R = R0;
302        Q = Q0;
303}
304
305template<class sq_T>
306void Kalman<sq_T>::bayes ( const vec &dt ) {
307        it_assert_debug ( dt.length() == ( dimy+dimu ),"KalmanFull::bayes wrong size of dt" );
308
309        sq_T iRy(dimy);
310        vec u = dt.get ( dimy,dimy+dimu-1 );
311        vec y = dt.get ( 0,dimy-1 );
312        //Time update
313        _mu = A* _mu + B*u;
314        //P  = A*P*A.transpose() + Q; in sq_T
315        _P.mult_sym ( A );
316        _P  +=Q;
317
318        //Data update
319        //_Ry = C*P*C.transpose() + R; in sq_T
320        _P.mult_sym ( C, _Ry );
321        _Ry  +=R;
322
323        mat Pfull = _P.to_mat();
324
325        _Ry.inv ( iRy ); // result is in _iRy;
326        _K = Pfull*C.transpose() * ( iRy.to_mat() );
327
328        sq_T pom ( ( int ) Pfull.rows() );
329        iRy.mult_sym_t ( C*Pfull,pom );
330        (_P ) -= pom; // P = P -PC'iRy*CP;
331        (_yp ) = C* _mu  +D*u; //y prediction
332        (_mu ) += _K* ( y- _yp  );
333
334
335        if ( evalll==true ) { //likelihood of observation y
336                ll=fy.evallog ( y );
337        }
338
339//cout << "y: " << y-(*_yp) <<" R: " << _Ry->to_mat() << " iR: " << _iRy->to_mat() << " ll: " << ll <<endl;
340
341};
342 
343
344
345//TODO why not const pointer??
346
347template<class sq_T>
348EKF<sq_T>::EKF ( RV rvx0, RV rvy0, RV rvu0 ) : Kalman<sq_T> ( rvx0,rvy0,rvu0 ) {}
349
350template<class sq_T>
351void EKF<sq_T>::set_parameters ( diffbifn* pfxu0,  diffbifn* phxu0,const sq_T Q0,const sq_T R0 ) {
352        pfxu = pfxu0;
353        phxu = phxu0;
354
355        //initialize matrices A C, later, these will be only updated!
356        pfxu->dfdx_cond ( _mu,zeros ( dimu ),A,true );
357//      pfxu->dfdu_cond ( *_mu,zeros ( dimu ),B,true );
358        B.clear();
359        phxu->dfdx_cond ( _mu,zeros ( dimu ),C,true );
360//      phxu->dfdu_cond ( *_mu,zeros ( dimu ),D,true );
361        D.clear();
362
363        R = R0;
364        Q = Q0;
365}
366
367template<class sq_T>
368void EKF<sq_T>::bayes ( const vec &dt ) {
369        it_assert_debug ( dt.length() == ( dimy+dimu ),"KalmanFull::bayes wrong size of dt" );
370
371        sq_T iRy(dimy,dimy);
372        vec u = dt.get ( dimy,dimy+dimu-1 );
373        vec y = dt.get ( 0,dimy-1 );
374        //Time update
375        _mu = pfxu->eval ( _mu, u );
376        pfxu->dfdx_cond ( _mu,u,A,false ); //update A by a derivative of fx
377
378        //P  = A*P*A.transpose() + Q; in sq_T
379        _P.mult_sym ( A );
380        _P +=Q;
381
382        //Data update
383        phxu->dfdx_cond ( _mu,u,C,false ); //update C by a derivative hx
384        //_Ry = C*P*C.transpose() + R; in sq_T
385        _P.mult_sym ( C, _Ry );
386        ( _Ry ) +=R;
387
388        mat Pfull = _P.to_mat();
389
390        _Ry.inv ( iRy ); // result is in _iRy;
391        _K = Pfull*C.transpose() * ( iRy.to_mat() );
392
393        sq_T pom ( ( int ) Pfull.rows() );
394        iRy.mult_sym_t ( C*Pfull,pom );
395        (_P ) -= pom; // P = P -PC'iRy*CP;
396        _yp = phxu->eval ( _mu,u ); //y prediction
397        ( _mu ) += _K* ( y-_yp );
398
399        if ( evalll==true ) {ll+=fy.evallog ( y );}
400};
401
402
403}
404#endif // KF_H
405
Note: See TracBrowser for help on using the browser.