Changeset 723

Show
Ignore:
Timestamp:
11/15/09 23:02:02 (14 years ago)
Author:
smidl
Message:

Big commit of LQG stuff

Files:
3 added
19 modified

Legend:

Unmodified
Added
Removed
  • applications/bdmtoolbox/mex/controlloop.cpp

    r706 r723  
    103103 
    104104        //DBG 
    105         Cfg.writeFile ( "closedloop.cfg" ); 
     105        Cfg.writeFile ( "controlloop.cfg" ); 
    106106 
    107107#else 
     
    111111                fname = argv[1]; 
    112112        } else { 
    113                 fname="closedloop.cfg"; 
     113                fname="controlloop.cfg"; 
    114114        } 
    115115        UIFile Cfg ( fname ); 
     
    119119        Array<shared_ptr<Controller> > Cs; 
    120120        UI::get ( Cs,Cfg, "controllers" ); 
    121         int Ndat=10; 
     121        int Ndat=100; 
    122122        if ( Cfg.exists ( "experiment" ) ) { 
    123123                if ( Cfg.getRoot().lookupValue ( "experiment.ndat",Ndat ) ) { 
     
    187187                                Cs(i) -> adapt( Dlsc(i) ->pushdown(dt)); 
    188188                                vec ut=Cs ( i )->ctrlaction ( Dlsc(i) ->pushdown(dt) );         // update estimates 
    189                                 Ds->write(ut, vec_1(1)); 
     189                                Ds->write(ut, vec_1(0)); 
     190                        } else { 
     191                                Ds->write(0.001*randn(Ds->_urv()._dsize())); 
    190192                        } 
     193                         
    191194                        Cs ( i )->log_write (); 
    192195                } 
     
    196199                //update buffered fdat links 
    197200                for (int i=0; i<Dls_buf.length(); i++){ 
    198                         Dls_buf(i)->step(dt); 
     201                        Dls_buf(i)->store_data(dt); 
    199202                } 
    200203                         
  • applications/bdmtoolbox/mex/estimator.cpp

    r706 r723  
    195195                //update buffered fdat links 
    196196                for (int i=0; i<Dls_buf.length(); i++){ 
    197                         Dls_buf(i)->step(dt); 
     197                        Dls_buf(i)->store_data(dt); 
    198198                } 
    199199                         
  • applications/dual/experiment/itermc.m

    r706 r723  
    2525    c.controller = C1; 
    2626    Mmc=iterativemc(c); 
    27     losses(i) = sum((Mmc.y-yr*ones(size(Mmc.y))).^2); 
     27    losses(i) = sum((Mmc.S_y-yr*ones(size(Mmc.S_y))).^2); 
    2828     
    2929    c.controller = C2; 
    3030    Mmc=iterativemc(c); 
    31     losses2(i) = sum((Mmc.y-yr*ones(size(Mmc.y))).^2); 
     31    looo= sum((Mmc.S_y-yr*ones(size(Mmc.S_y))).^2) 
     32%     keyboard 
     33    losses2(i) = looo; 
    3234end 
    3335[min(losses) median(losses) max(losses)] 
  • applications/dual/src/arx1_ctrl.h

    r706 r723  
    2121                void set_b (const double b0){b=b0;} 
    2222                //! data in ctrlaction are only past outputs yt 
    23                 vec ctrlaction(const vec &yt){ 
     23                vec ctrlaction(const vec &yt)const{ 
    2424                        vec ut(1); 
    2525                        if (abs(b)<1e-2) { 
     
    6363        public: 
    6464                //! expected input is yt 
    65                 virtual void adapt(const vec &yt){ 
     65                virtual void adapt(const vec &dt){ 
    6666                        //prepare data for ARX 
    67                         Psi(0) = yt(0)-ytm; 
    68                         Psi(1) = utm; 
    6967                        // do estimation 
    70                         est.bayes(Psi); 
     68                        est.bayes(vec_1(dt(0)-ytm),vec_1(dt(1))); 
     69                        ytm = dt(0); 
    7170                        // save estimate b = E(b); 
    7271                        b = est.posterior().mean()(0); // first 
    7372                } 
    7473                //! same as exact control, but stores ut as utm 
    75                 vec ctrlaction(const vec &yt){ 
    76                         vec ut=exact_ctrl::ctrlaction(yt); 
     74                vec ctrlaction(const vec &dt)const{ 
     75                        vec ut(1); 
     76                        mat P = est.posterior().variance(); 
     77                        ut(0) =(yr - dt(0))/(b + (b<0 ? P(0,0) : -P(0,0)));; 
    7778                        // remember last ut for estimation 
    78                         utm=ut(0); 
    79                         ytm=yt(0); 
    8079                        return ut; 
    8180                } 
     
    9291                        V0(1,0) = b0; 
    9392                        V0(0,1) = b0; 
    94                         V0(1,1) = P0; 
     93                        V0(1,1) = P0/6; 
    9594                         
    96                         est.set_statistics(1,V0); 
     95                        est.set_statistics(1,V0,6); 
    9796                        est.set_constant(false); 
     97                        est.validate(); 
    9898                        validate(); 
    9999                } 
    100100                void validate(){ 
    101101                        Psi = zeros(2); 
    102                         LIDs = zeros_i(1); 
    103102                } 
    104                 virtual void log_add ( logger &L, const string &name = "" ) { 
    105                         LIDs ( 0 ) = L.add ( RV("bhat",1) ); 
     103                void log_register( logger& L, const string& prefix ){ 
     104                        est.set_log_level(1); 
     105                        est.log_register(L,""); 
     106                }; 
     107                void log_write() const{ 
     108                        est.log_write(); 
    106109                } 
    107                 virtual void logit ( logger &L ) { 
    108                         L.logit ( LIDs ( 0 ), b ); 
    109                 } 
    110                  
    111110}; 
    112111UIREGISTER(ce_ctrl); 
  • applications/dual/src/iterativemc.cpp

    r706 r723  
    4747        double b; 
    4848        double sigma; 
    49         double ytm; 
     49        double ytm=0.0; 
    5050        double yr; 
    5151        int Ndat; 
     
    9191        RV y("y",1); // name random variable 
    9292        RV u("u",1); // name random variable 
    93         int L_yt=L->add(y); 
    94         int L_ut=L->add(u); 
    95         C->log_add(*L); 
     93        int L_yt=L->add(y,"S"); 
     94        int L_ut=L->add(u,"S"); 
     95        C->log_register(*L,"C"); 
    9696        L->init(); 
    9797         
    9898        vec psi(2);       // regressor 
    99         double ut;        // input 
     99        double ut=0.0;        // input 
    100100        vec yt; 
    101101         
     
    103103                //yt has now meaning of yt-1 
    104104                //design controller 
    105                 C->adapt(vec_1(ytm)); 
    106                 ut = C->ctrlaction(vec_1(ytm))(0);   // the best controller there is 
     105                C->adapt(vec_2(ytm,ut)); 
     106                ut = C->ctrlaction(vec_2(ytm,ut))(0);   // the best controller there is 
    107107                 
    108108                //prepare regressor 
     
    116116                L->logit(L_yt, yt); 
    117117                L->logit(L_ut, vec_1(ut)); 
    118                 C->logit(*L); 
     118                C->log_write(); 
    119119                L->step(); 
    120120        } 
  • library/bdm/base/bdmbase.h

    r713 r723  
    796796        datalink_buffered() : datalink_part(), history ( 0 ), h2v_down ( 0 ), h2v_hist ( 0 ) {}; 
    797797        //! push current data to history 
    798         void step ( const vec &val_up ) { 
     798        void store_data ( const vec &val_up ) { 
    799799                if ( v2h_up.length() > 0 ) { 
    800800                        history.shift_right ( 0, v2h_up.length() ); 
     
    818818        void set_connection ( const RV &rv, const RV &rv_up ) { 
    819819                // create link between up and down 
    820                 datalink_part::set_connection ( rv, rv_up ); 
     820                datalink_part::set_connection ( rv, rv_up.remove_time() ); // only non-delayed version 
    821821 
    822822                // create rvs of history 
     
    871871        //! update buffer 
    872872        void step ( const vec &dt, const vec &ut ) { 
    873                 dl1.step ( dt ); 
    874                 dl2.step ( ut ); 
     873                dl1.store_data ( dt ); 
     874                dl2.store_data ( ut ); 
    875875        } 
    876876}; 
  • library/bdm/base/datasources.h

    r700 r723  
    163163        public: 
    164164                void step() { 
    165                         yt2rgr.step(yt); // y is now history 
     165                        yt2rgr.store_data(yt); // y is now history 
    166166                        ut2rgr.filldown ( ut,rgr ); 
    167167                        yt2rgr.filldown ( yt,rgr ); 
    168168                        yt=ipdf->samplecond ( rgr ); 
    169                         ut2rgr.step(ut); //u is now history 
     169                        ut2rgr.store_data(ut); //u is now history 
    170170                } 
    171171                void getdata ( vec &dt_out ) const { 
     
    175175                } 
    176176                void write(const vec &ut0){ut=ut0;} 
    177  
     177                void write(const vec &ut0, const ivec &ind){set_subvector(ut,ind,ut0);} 
     178                 
    178179                /*! 
    179180                \code 
  • library/bdm/design/ctrlbase.cpp

    r706 r723  
    33namespace bdm{ 
    44 
    5 void LQG::set_system(shared_ptr<StateSpace<fsqmat> > S0){ 
     5void LQG::set_system(shared_ptr<StateSpace<chmat> > S0){ 
    66        S = S0; 
    7         dimx= S->_A().rows(); 
    8         dimy= S->_C().rows(); 
    9         dimu= S->_B().cols(); 
    10         pr=zeros(dimx+dimu+dimy,  dimu+dimx+dimu+dimy); 
    11         pr.set_submatrix(dimx, dimu+dimx, eye(dimu+dimy)); 
    127} 
    138 
     
    1712        y_req=y_req0; 
    1813        horizon = horizon0; 
    19         validate(); 
    20         initialize(); 
    2114} 
    2215 
    2316void LQG::validate() { 
     17        // set properties from S 
     18        dimx= S->_A().rows(); 
     19        dimy= S->_C().rows(); 
     20        dimu= S->_B().cols(); 
     21        pr=zeros(dimx+dimu+dimy,  dimu+dimx+dimu+dimy); 
     22        pr.set_submatrix(dimx, dimu+dimx, eye(dimu+dimy)); 
     23         
     24        //penalization 
    2425        bdm_assert ( Qy.cols() == dimy, "LQG: wrong dimensions of Qy " ); 
    2526        bdm_assert ( Qu.cols() == dimu, "LQG: wrong dimensions of Qu " ); 
    2627        bdm_assert ( y_req.length() == dimy, "LQG: wrong dimensions of y_req " ); 
     28         
     29        qux=zeros(dimu,dimx+2*dimu+dimy);      
     30        qyx=zeros(dimy, dimx+dimy+dimu); 
     31         
     32        // 
     33        initial_belmann(); 
     34        // parts of QR 
     35        post_qr = zeros(pre_qr.rows(), pre_qr.cols()); 
     36         
     37        update_system(); 
    2738} 
    2839 
    29 void LQG::initialize(){ 
    30         // set parameter matrix 
    31         pr.set_submatrix(0,0,S->_B()); 
    32         pr.set_submatrix(0,dimu, S->_A()); 
    33          
    34         //penalization 
    35         qux=zeros(dimu,dimx+2*dimu+dimy);      
    36         qux.set_submatrix(0,0,Qu); 
    37         qux.set_submatrix(0,dimx+dimu+dimy,Qu); 
    38  
    39         qyx=zeros(dimy, dimx+dimy+dimu); 
    40         qyx.set_submatrix(0,0,S->_C()); 
    41         qyx.set_submatrix(0,dimx,-eye(dimy)); 
    42          
    43         // 
    44         s=1e-5*eye(dimx+dimu+dimy); 
    45         // parts of QR 
    46         hqy=Qy*qyx*pr; 
    47          
    48         // pre_qr 
    49         pre_qr = concat_vertical(s*pr, concat_vertical(hqy, qux)); 
    50         post_qr = zeros(pre_qr.rows(), pre_qr.cols()); 
    51 } 
    5240 
    5341} 
  • library/bdm/design/ctrlbase.h

    r706 r723  
    1414#include "../estim/kalman.h" 
    1515 
    16 namespace bdm{ 
     16namespace bdm { 
    1717 
    18         //! Base class for adaptive controllers  
    19         //! The base class is, however, non-adaptive, method \c adapt() is empty. 
    20         //! \note advanced Controllers will probably include estimator as their internal attribute (e.g. dual controllers) 
    21         class Controller : public root { 
    22                 protected: 
    23                         //! identifier of the designed action; 
    24                         RV rv; 
    25                         //! identifier of the conditioning variables; 
    26                         RV rvc; 
    27                 public: 
    28                         //! function processing new observations and adapting control strategy accordingly 
    29                         virtual void adapt(const vec &data){}; 
    30                         //! function redesigning the control strategy  
    31                         virtual void redesign(){}; 
    32                         //! returns designed control action 
    33                         virtual vec ctrlaction(const vec &cond){return vec(0);} 
    34                          
    35                         void from_setting(const Setting &set){ 
    36                                 UI::get(rv,set,"rv",UI::optional); 
    37                                 UI::get(rvc,set,"rvc",UI::optional); 
    38                         } 
    39                         //! access function 
    40                         const RV& _rv() {return rv;} 
    41                         //! access function 
    42                         const RV& _rvc() {return rvc;} 
    43                         //! register this controller with given datasource under name "name" 
    44                         virtual void log_register (logger &L, const string &prefix ) { } 
    45                         //! write requested values into the logger 
    46                         virtual void log_write ( ) const { } 
    47                          
    48         }; 
    49          
     18//! Base class for adaptive controllers 
     19//! The base class is, however, non-adaptive, method \c adapt() is empty. 
     20//! \note advanced Controllers will probably include estimator as their internal attribute (e.g. dual controllers) 
     21class Controller : public root { 
     22protected: 
     23        //! identifier of the designed action; 
     24        RV rv; 
     25        //! identifier of the conditioning variables - data needed ; 
     26        RV rvc; 
     27public: 
     28        //! function processing new observations and adapting control strategy accordingly 
     29        virtual void adapt ( const vec &data ) {}; 
     30        //! function redesigning the control strategy 
     31        virtual void redesign() {}; 
     32        //! returns designed control action 
     33        virtual vec ctrlaction ( const vec &cond ) const {return vec ( 0 );} 
     34 
     35        void from_setting ( const Setting &set ) { 
     36                UI::get ( rv,set,"rv",UI::optional ); 
     37                UI::get ( rvc,set,"rvc",UI::optional ); 
     38        } 
     39        //! access function 
     40        const RV& _rv() {return rv;} 
     41        //! access function 
     42        const RV& _rvc() {return rvc;} 
     43        //! register this controller with given datasource under name "name" 
     44        virtual void log_register ( logger &L, const string &prefix ) { } 
     45        //! write requested values into the logger 
     46        virtual void log_write ( ) const { } 
     47 
     48}; 
     49 
    5050//! Linear Quadratic Gaussian designer for constant penalizations and constant target 
    5151//! Its internals are very close to Kalman estimator 
    5252class LQG : public Controller { 
    53         protected: 
    54                 //! StateSpace model from which we read data 
    55                 shared_ptr<StateSpace<fsqmat> > S; 
    56                 //! required value of the output y at time t (assumed constant) 
    57                 vec y_req; 
    58                 //! required value of the output y at time t (assumed constant) 
    59                 vec u_req; 
    60                  
    61                 //! Control horizon, set to maxint for infinite horizons 
    62                 int horizon; 
    63                 //! penalization matrix Qy 
    64                 mat Qy; 
    65                 //! penalization matrix Qu 
    66                 mat Qu; 
    67                 //! time of the design step - from horizon->0 
    68                 int td; 
    69                 //! controller parameters 
    70                 mat L; 
    71                  
    72                 //!@{ \name temporary storage for ricatti - use initialize 
    73                 //! convenience parameters 
    74                 int dimx; 
    75                 //! convenience parameters 
    76                 int dimy; 
    77                 //! convenience parameters 
    78                 int dimu; 
    79                  
    80                 //!  parameters 
    81                 mat pr; 
    82                 //! penalization  
    83                 mat qux; 
    84                 //! penalization 
    85                 mat qyx; 
    86                 //! internal quadratic form  
    87                 mat s; 
    88                 //! penalization 
    89                 mat qy; 
    90                 //! pre_qr part 
    91                 mat hqy; 
    92                 //! pre qr matrix 
    93                 mat pre_qr; 
    94                 //! post qr matrix 
    95                 mat post_qr; 
    96                 //!@} 
    97                  
    98         public: 
    99                 //! set system parameters from given matrices 
    100                 void set_system(shared_ptr<StateSpace<fsqmat> > S0); 
    101                 //! set penalization matrices and control horizon 
    102                 void set_control_parameters(const mat &Qy0, const mat &Qu0, const vec &y_req0, int horizon0); 
    103                 //! set system parameters from Kalman filter 
    104 //              void set_system_parameters(const Kalman &K); 
    105                 //! refresh temporary storage - inefficient can be improved 
    106                 void initialize(); 
    107                 //! validation procedure 
    108                 void validate(); 
    109                 //! function for future use which is called at each time td; Should call initialize()! 
    110                 virtual void update_state(){}; 
    111                 //! redesign one step of the  
    112                 void ricatti_step(){ 
    113                         pre_qr.set_submatrix(0,0,s*pr); 
    114                         pre_qr.set_submatrix(dimx+dimu+dimy, dimu+dimx, -Qy*y_req); 
    115                         if (!qr(pre_qr,post_qr)){ bdm_warning("QR in LQG unstable");} 
    116                         triu(post_qr); 
    117         // hn(m+1:2*m+n+r,m+1:2*m+n+r); 
    118                         s=post_qr.get(dimu, 2*dimu+dimx+dimy-1, dimu, 2*dimu+dimx+dimy-1); 
    119                 }; 
    120                 void redesign(){ 
    121                         for(td=horizon; td>0; td--){ 
    122                                 update_state(); 
    123                                 ricatti_step(); 
    124                         } 
    125 /*                      ws=hn(1:m,m+1:2*m+n+r); 
    126                         wsd=hn(1:m,1:m); 
    127                         Lklq=-inv(wsd)*ws;*/ 
    128                         L = -inv(post_qr.get(0,dimu-1, 0,dimu-1)) * post_qr.get(0,dimu-1, dimu, 2*dimu+dimx+dimy-1); 
     53protected: 
     54        //! StateSpace model from which we read data 
     55        shared_ptr<StateSpace<chmat> > S; 
     56        //! required value of the output y at time t (assumed constant) 
     57        vec y_req; 
     58        //! required value of the output y at time t (assumed constant) 
     59        vec u_req; 
     60 
     61        //! Control horizon, set to maxint for infinite horizons 
     62        int horizon; 
     63        //! penalization matrix Qy 
     64        chmat Qy; 
     65        //! penalization matrix Qu 
     66        chmat Qu; 
     67        //! time of the design step - from horizon->0 
     68        int td; 
     69        //! controller parameters 
     70        mat L; 
     71 
     72        //!@{ \name temporary storage for ricatti - use initialize 
     73        //! convenience parameters 
     74        int dimx; 
     75        //! convenience parameters 
     76        int dimy; 
     77        //! convenience parameters 
     78        int dimu; 
     79 
     80        //!  parameters 
     81        mat pr; 
     82        //! penalization 
     83        mat qux; 
     84        //! penalization 
     85        mat qyx; 
     86        //! internal quadratic form 
     87        mat s; 
     88        //! penalization 
     89        mat qy; 
     90        //! pre_qr part 
     91        mat hqy; 
     92        //! pre qr matrix 
     93        mat pre_qr; 
     94        //! post qr matrix 
     95        mat post_qr; 
     96        //!@} 
     97 
     98public: 
     99        //! set system parameters from given matrices 
     100        void set_system ( shared_ptr<StateSpace<chmat> > S0 ); 
     101        //! update internal whan system has changed 
     102        void update_system() { 
     103                pr.set_submatrix ( 0,0,S->_B() ); 
     104                pr.set_submatrix ( 0,dimu, S->_A() ); 
     105 
     106                //penalization 
     107                qux.set_submatrix ( 0,0, Qu._Ch() ); 
     108                qux.set_submatrix ( 0,dimx+dimu+dimy,Qu._Ch() ); 
     109 
     110                qyx.set_submatrix ( 0,0,S->_C() ); 
     111                qyx.set_submatrix ( 0,dimx,-eye ( dimy ) ); 
     112 
     113                // parts of QR 
     114                hqy=Qy.to_mat()*qyx*pr; 
     115 
     116                // pre_qr 
     117                pre_qr = concat_vertical ( s*pr, concat_vertical ( hqy, qux ) ); 
     118        } 
     119        //! set penalization matrices and control horizon 
     120        void set_control_parameters ( const mat &Qy0, const mat &Qu0, const vec &y_req0, int horizon0 ); 
     121        //! set penalization matrices and control horizon 
     122        void set_control_Qy ( const mat &Qy0 ) {Qy=Qy0;} 
     123        //! refresh temporary storage - inefficient can be improved 
     124        void initial_belmann() {s=1e-5*eye ( dimx+dimu+dimy );}; 
     125        //! validation procedure 
     126        void validate(); 
     127        //! function for future use which is called at each time td; Should call initialize()! 
     128        //! redesign one step of the 
     129        void ricatti_step() { 
     130                pre_qr.set_submatrix ( 0,0,s*pr ); 
     131                pre_qr.set_submatrix ( dimx+dimu+dimy, dimu+dimx, -Qy.to_mat()*y_req ); 
     132                if ( !qr ( pre_qr,post_qr ) ) { bdm_warning ( "QR in LQG unstable" );} 
     133                triu ( post_qr ); 
     134                // hn(m+1:2*m+n+r,m+1:2*m+n+r); 
     135                s=post_qr.get ( dimu, 2*dimu+dimx+dimy-1, dimu, 2*dimu+dimx+dimy-1 ); 
     136        }; 
     137        void redesign() { 
     138                for ( td=horizon; td>0; td-- ) { 
     139                        update_system(); 
     140                        ricatti_step(); 
    129141                } 
    130                 //! compute control action 
    131                 vec ctrlaction(const vec &state, const vec &ukm){vec pom=concat(state, ones(dimy), ukm); return L*pom;} 
    132         } ; 
     142                /*                      ws=hn(1:m,m+1:2*m+n+r); 
     143                                        wsd=hn(1:m,1:m); 
     144                                        Lklq=-inv(wsd)*ws;*/ 
     145                L = -inv ( post_qr.get ( 0,dimu-1, 0,dimu-1 ) ) * post_qr.get ( 0,dimu-1, dimu, 2*dimu+dimx+dimy-1 ); 
     146        } 
     147        //! compute control action 
     148        vec ctrlaction ( const vec &state, const vec &ukm ) const { 
     149                vec pom=concat ( state, ones ( dimy ), ukm ); 
     150                return L*pom; 
     151        } 
     152} ; 
    133153 
    134                          
     154 
    135155} // namespace 
  • library/bdm/estim/arx.cpp

    r700 r723  
    9898} 
    9999 
    100 mlnorm<ldmat>* ARX::predictor ( ) const { 
    101         mat mu ( dimy, posterior()._V().rows() - dimy ); 
    102         mat R ( dimy, dimy ); 
    103         mlnorm<ldmat>* tmp; 
    104         tmp = new mlnorm<ldmat> ( ); 
    105  
    106         est.mean_mat ( mu, R ); //mu = 
    107         mu = mu.T(); 
    108         //correction for student-t  -- TODO check if correct!! 
    109  
    110         if ( have_constant) { // constant term 
    111                 //Assume the constant term is the last one: 
    112                 tmp->set_parameters ( mu.get_cols ( 0, mu.cols() - 2 ), mu.get_col ( mu.cols() - 1 ), ldmat ( R ) ); 
    113         } else { 
    114                 tmp->set_parameters ( mu, zeros ( dimy ), ldmat ( R ) ); 
    115         } 
    116         return tmp; 
    117 } 
    118100 
    119101mlstudent* ARX::predictor_student ( ) const { 
  • library/bdm/estim/arx.h

    r700 r723  
    9898        } 
    9999        //! conditional version of the predictor 
    100         mlnorm<ldmat>* predictor() const; 
     100        template<class sq_T> 
     101        shared_ptr<mlnorm<sq_T> > ml_predictor() const; 
     102        //! fast version of predicto  
     103        template<class sq_T> 
     104        void ml_predictor_update(mlnorm<sq_T> &pred) const; 
    101105        mlstudent* predictor_student() const; 
    102106        //! Brute force structure estimation.\return indeces of accepted regressors. 
     
    188192}; 
    189193UIREGISTER(ARXfrg); 
     194 
     195 
     196//////////////////// 
     197template<class sq_T> 
     198shared_ptr< mlnorm<sq_T> > ARX::ml_predictor ( ) const { 
     199        shared_ptr< mlnorm<sq_T> > tmp = new mlnorm<sq_T> ( ); 
     200        tmp->set_rv(yrv); 
     201        tmp->set_rvc(_rvc()); 
     202         
     203        ml_predictor_update(*tmp); 
     204        tmp->validate(); 
     205        return tmp; 
     206} 
     207 
     208template<class sq_T> 
     209void ARX::ml_predictor_update(mlnorm<sq_T> &pred) const { 
     210        mat mu ( dimy, posterior()._V().rows() - dimy ); 
     211        mat R ( dimy, dimy ); 
     212         
     213        est.mean_mat ( mu, R ); //mu = 
     214        mu = mu.T(); 
     215        //correction for student-t  -- TODO check if correct!! 
     216         
     217        if ( have_constant) { // constant term 
     218                //Assume the constant term is the last one: 
     219                pred.set_parameters ( mu.get_cols ( 0, mu.cols() - 2 ), mu.get_col ( mu.cols() - 1 ), sq_T ( R ) ); 
     220        } else { 
     221                pred.set_parameters ( mu, zeros ( dimy ), sq_T( R ) ); 
     222        } 
     223} 
     224 
    190225}; 
    191226#endif // AR_H 
  • library/bdm/estim/kalman.h

    r703 r723  
    2727 * \brief Basic elements of linear state-space model 
    2828 
    29 Parameter evolution model:\f[ x_t = A x_{t-1} + B u_t + Q^{1/2} e_t \f] 
    30 Observation model: \f[ y_t = C x_{t-1} + C u_t + Q^{1/2} w_t. \f] 
    31 Where $e_t$ and $w_t$ are independent vectors Normal(0,1)-distributed disturbances. 
     29Parameter evolution model:\f[ x_{t+1} = A x_{t} + B u_t + Q^{1/2} e_t \f] 
     30Observation model: \f[ y_t = C x_{t} + C u_t + R^{1/2} w_t. \f] 
     31Where $e_t$ and $w_t$ are mutually independent vectors of Normal(0,1)-distributed disturbances. 
    3232 */ 
    3333template<class sq_T> 
     
    6161                        UI::get (C, set, "C", UI::compulsory); 
    6262                        UI::get (D, set, "D", UI::compulsory); 
    63                         mat Qtm, Rtm; 
     63                        mat Qtm, Rtm; // full matrices 
    6464                        if(!UI::get(Qtm, set, "Q", UI::optional)){ 
    6565                                vec dq; 
     
    7272                                Rtm=diag(dr); 
    7373                        } 
    74                         R=Rtm; // automatic conversion 
     74                        R=Rtm; // automatic conversion to square-root form 
    7575                        Q=Qtm;  
    7676                         
     
    519519 
    520520*/ 
    521 class StateFromARX: public StateSpace<fsqmat>{ 
     521class StateFromARX: public StateSpace<chmat>{ 
    522522        protected: 
    523523                //! remember connection from theta ->A 
    524524                datalink_part th2A; 
    525                 //! xrv 
    526                 RV xrv; 
     525                //! remember connection from theta ->B 
     526                datalink_part th2B; 
    527527                //!function adds n diagonal elements from given starting point r,c 
    528528                void diagonal_part(mat &A, int r, int c, int n){ 
    529529                        for(int i=0; i<n; i++){A(r,c)=1.0; r++;c++;} 
    530530                }; 
     531                //! similar to ARX.have_constant 
     532                bool have_constant; 
    531533        public: 
    532534                //! set up this object to match given mlnorm 
    533                 void connect_mlnorm(const mlnorm<fsqmat> &ml){ 
     535                //! Note that state-space and common mpdf use different meaning of \f$ _t \f$ in \f$ u_t \f$.  
     536                //!While mlnorm typically assumes that \f$ u_t \rightarrow y_t \f$ in state space it is \f$ u_{t-1} \rightarrow y_t \f$ 
     537                //! For consequences in notation of internal variable xt see arx2statespace_notes.lyx. 
     538                void connect_mlnorm(const mlnorm<chmat> &ml, RV &xrv, RV &urv){ 
     539 
    534540                        //get ids of yrv                                 
    535541                        const RV &yrv = ml._rv(); 
     
    537543                        const RV &rgr = ml._rvc(); 
    538544                        RV rgr0 = rgr.remove_time(); 
    539                         RV urv = rgr0.subt(yrv);  
     545                        urv = rgr0.subt(yrv);  
    540546                                                 
    541547                        // create names for state variables 
    542548                        xrv=yrv;  
    543549                         
    544                         int y_multiplicity = rgr.mint(yrv); 
    545                         int y_block_size = yrv.length()*(y_multiplicity+1); // current yt + all delayed yts 
    546                         for (int m=0;m<y_multiplicity;m++){  
     550                        int y_multiplicity = -rgr.mint(yrv); 
     551                        int y_block_size = yrv.length()*(y_multiplicity); // current yt + all delayed yts 
     552                        for (int m=0;m<y_multiplicity - 1;m++){ // ========= -1 is important see arx2statespace_notes 
    547553                                xrv.add(yrv.copy_t(-m-1)); //add delayed yt 
    548554                        } 
     555                        //! temporary RV for connection to ml.rvc, since notation of xrv and ml.rvc does not match 
     556                        RV xrv_ml = xrv.copy_t(-1); 
     557                         
    549558                        // add regressors 
    550559                        ivec u_block_sizes(urv.length()); // no_blocks = yt + unique rgr 
     
    552561                                RV R=urv.subselect(vec_1(r)); //non-delayed element of rgr 
    553562                                int r_size=urv.size(r); 
    554                                 int r_multiplicity=rgr.mint(R); 
     563                                int r_multiplicity=-rgr.mint(R); 
    555564                                u_block_sizes(r)= r_size*r_multiplicity ; 
    556565                                for(int m=0;m<r_multiplicity;m++){  
    557566                                        xrv.add(R.copy_t(-m-1)); //add delayed yt 
     567                                        xrv_ml.add(R.copy_t(-m-1)); //add delayed yt 
    558568                                } 
    559569                        } 
    560                          
     570                        // add constant 
     571                        if (any(ml._mu_const()!=0.0)){ 
     572                                have_constant=true; 
     573                                xrv.add(RV("bdm_reserved_constant_one",1)); 
     574                        } else {have_constant=false;} 
     575                                 
     576                 
    561577                        // get mapp 
    562                         th2A.set_connection(xrv, ml._rvc()); 
     578                        th2A.set_connection(xrv_ml, ml._rvc()); 
     579                        th2B.set_connection(urv, ml._rvc()); 
    563580                         
    564581                        //set matrix sizes 
     
    577594                        this->C=zeros(yrv._dsize(), xrv._dsize()); 
    578595                        this->C.set_submatrix(0,0,eye(yrv._dsize())); 
    579                                 this->D=zeros(yrv._dsize(),urv._dsize()); 
    580                                 this->R = zeros(yrv._dsize(),yrv._dsize()); 
    581                                 this->Q = zeros(xrv._dsize(),xrv._dsize()); 
    582                                 // Q is set by update 
    583                                                                  
    584                                 update_from(ml); 
    585                                 validate(); 
     596                        this->D=zeros(yrv._dsize(),urv._dsize()); 
     597                        this->R.setCh(zeros(yrv._dsize(),yrv._dsize())); 
     598                        this->Q.setCh(zeros(xrv._dsize(),xrv._dsize())); 
     599                        // Q is set by update 
     600                                                         
     601                        update_from(ml); 
     602                        validate(); 
    586603                }; 
    587604                //! fast function to update parameters from ml - not checked for compatibility!! 
    588                 void update_from(const mlnorm<fsqmat> &ml){ 
    589                          
    590                         vec theta = ml._A().get_row(0); // this  
    591                         this->Q._M().set_submatrix(0,0,ml._R()); 
    592                          
    593                 } 
     605                void update_from(const mlnorm<chmat> &ml){ 
     606 
     607                        vec Arow=zeros(A.cols()); 
     608                        vec Brow=zeros(B.cols()); 
     609                        //  ROW- WISE EVALUATION ===== 
     610                        for(int i=0;i<ml._rv()._dsize(); i++){  
     611                                 
     612                                vec theta = ml._A().get_row(i);  
     613                                 
     614                                th2A.filldown(theta,Arow); 
     615                                if (have_constant){ 
     616                                        // constant is always at the end no need for datalink 
     617                                        Arow(A.cols()-1) = ml._mu_const()(i); 
     618                                } 
     619                                this->A.set_row(i,Arow); 
     620                                 
     621                                th2B.filldown(theta,Brow); 
     622                                this->B.set_row(i,Brow); 
     623                        } 
     624                        this->Q._Ch().set_submatrix(0,0,ml.__R()._Ch()); 
     625                         
     626                }; 
     627                //! access function 
     628                bool _have_constant() const {return have_constant;} 
    594629}; 
    595630 
  • library/bdm/itpp_ext.cpp

    r712 r723  
    108108bvec operator| (const bvec &a, const bvec &b) 
    109109{ 
    110         it_assert_debug (b.size() != a.size(), "operator&(): Vectors of different lengths"); 
     110        it_assert_debug (b.size() == a.size(), "operator|(): Vectors of different lengths"); 
    111111 
    112112        bvec temp (a.size()); 
  • library/bdm/itpp_ext.h

    r712 r723  
    4545} 
    4646 
    47 const double inf = std::numeric_limits<double>::infinity(); 
     47static const double inf = std::numeric_limits<double>::infinity(); 
    4848 
    4949//#if 0 
  • library/bdm/math/chmat.h

    r660 r723  
    106106                copy_vector ( dim*dim, chQ._data(), Ch._data() ); 
    107107        } 
    108  
     108        //! access function 
     109        void setCh ( const chmat &Ch0 ) { 
     110                Ch = Ch0._Ch(); 
     111                dim=Ch0.rows(); 
     112        } 
     113        //! access function 
     114        void setCh ( const mat &Ch0 ) { 
     115                //TODO check if Ch0 is OK!!! 
     116                Ch = Ch0; 
     117                dim=Ch0.rows(); 
     118        } 
     119         
    109120        //! Access functions 
    110121        void setD ( const vec &nD, int i ) { 
  • library/bdm/stat/exp_family.h

    r713 r723  
    708708                //!access function 
    709709                mat _R() const { return this->iepdf._R().to_mat(); } 
    710  
     710                //!access function 
     711                sq_T __R() const { return this->iepdf._R(); } 
     712                 
    711713                //! Debug stream 
    712714                template<typename sq_M> 
  • library/tests/testsuite/LQG_test.cpp

    r722 r723  
    55using namespace bdm; 
    66 
    7 TEST ( LQG_test ) { 
     7TEST(LQG_test) { 
    88        LQG reg; 
    9         shared_ptr<StateSpace<fsqmat> > stsp = new StateSpace<fsqmat>; 
     9        shared_ptr<StateSpace<chmat> > stsp=new StateSpace<chmat>; 
    1010        // 2 x 1 x 1 
    11         stsp-> set_parameters ( eye ( 2 ), ones ( 2, 1 ), ones ( 1, 2 ), ones ( 1, 1 ), /* Q,R */ eye ( 2 ), eye ( 1 ) ); 
    12         reg.set_system ( stsp ); // A, B, C 
    13         reg.set_control_parameters ( eye ( 1 ), eye ( 1 ),  vec_1 ( 1.0 ), 6 ); //Qy, Qu, horizon 
     11        stsp-> set_parameters(eye(2), ones(2,1), ones(1,2), ones(1,1), /* Q,R */ eye(2), eye(1)); 
     12        reg.set_system(stsp); // A, B, C 
     13        reg.set_control_parameters(eye(1), eye(1),  vec_1(1.0), 6); //Qy, Qu, horizon 
     14        reg.validate(); 
    1415 
    1516        reg.redesign(); 
    16         double reg_apply = reg.ctrlaction ( "0.5, 1.1", "0.0" ) ( 0 ); /*convert vec to double*/ 
    17         CHECK_CLOSE ( reg_apply, -0.248528137234392, 0.0001 ); 
     17        double reg_apply=reg.ctrlaction("0.5, 1.1","0.0")(0); /*convert vec to double*/ 
     18        CHECK_CLOSE(reg_apply, -0.248528137234392, 0.0001); 
    1819} 
    1920 
    20 TEST ( to_state_test ) { 
     21TEST(to_state_test) { 
    2122        mlnorm<fsqmat> ml; 
    22         mat A = "1.1, 2.3"; 
    23         ml.set_parameters ( A, vec_1 ( 1.3 ), eye ( 1 ) ); 
    24         RV yr = RV ( "y", 1 ); 
    25         RV ur = RV ( "u", 1 ); 
    26         ml.set_rv ( yr ); 
    27         yr.t_plus ( -1 ); 
    28         ml.set_rvc ( concat ( yr, ur ) ); 
    29  
    30         shared_ptr<StateCanonical > Stsp = new StateCanonical; 
    31         Stsp->connect_mlnorm ( ml ); 
    32  
    33         /* results from 
     23        mat A="1.1, 2.3"; 
     24        ml.set_parameters(A, vec_1(1.3), eye(1)); 
     25        RV yr=RV("y",1); 
     26        RV ur=RV("u",1); 
     27        ml.set_rv(yr); 
     28        yr.t_plus(-1); 
     29        ml.set_rvc(concat(yr, ur)); 
     30         
     31        shared_ptr<StateCanonical > Stsp=new StateCanonical; 
     32        Stsp->connect_mlnorm(ml); 
     33         
     34        /* results from  
    3435        [A,B,C,D]=tf2ss([2.3 0],[1 -1.1]) 
    3536        */ 
    36         CHECK_CLOSE_EX ( Stsp->_A().get_row ( 0 ), vec ( "1.1" ), 0.0001 ); 
    37         CHECK_CLOSE_EX ( Stsp->_C().get_row ( 0 ), vec ( "2.53" ), 0.0001 ); 
    38         CHECK_CLOSE_EX ( Stsp->_D().get_row ( 0 ), vec ( "2.30" ), 0.0001 ); 
     37        CHECK_CLOSE_EX(Stsp->_A().get_row(0), vec("1.1"), 0.0001); 
     38        CHECK_CLOSE_EX(Stsp->_C().get_row(0), vec("2.53"), 0.0001); 
     39        CHECK_CLOSE_EX(Stsp->_D().get_row(0), vec("2.30"), 0.0001); 
    3940} 
    4041 
    41 TEST ( to_state_arx_test ) { 
    42         mlnorm<fsqmat> ml; 
    43         mat A = "1.1, 2.3"; 
    44         ml.set_parameters ( A, vec_1 ( 1.3 ), eye ( 1 ) ); 
    45         RV yr = RV ( "y", 1 ); 
    46         RV ur = RV ( "u", 1 ); 
    47         ml.set_rv ( yr ); 
    48         yr.t_plus ( -1 ); 
    49         ml.set_rvc ( concat ( yr, ur ) ); 
    50  
    51         shared_ptr<StateFromARX> Stsp = new StateFromARX; 
    52         Stsp->connect_mlnorm ( ml ); 
    53  
    54         /* results from 
     42TEST(to_state_arx_test) { 
     43        mlnorm<chmat> ml; 
     44        mat A="1.1, 2.3, 3.4"; 
     45        ml.set_parameters(A, vec_1(1.3), eye(1)); 
     46        RV yr=RV("y",1); 
     47        RV ur=RV("u",1); 
     48        ml.set_rv(yr); 
     49        ml.set_rvc(concat(yr.copy_t(-1), concat(ur, ur.copy_t(-1)))); 
     50         
     51        shared_ptr<StateFromARX> Stsp=new StateFromARX; 
     52        RV xrv; RV urv; 
     53        Stsp->connect_mlnorm(ml,xrv,urv); 
     54         
     55        /* results from  
    5556        [A,B,C,D]=tf2ss([2.3 0],[1 -1.1]) 
    5657        */ 
    57         cout << "---" << endl; 
     58        CHECK_CLOSE_EX(Stsp->_A().get_row(0), vec("1.1, 3.4, 1.3"), 0.0001); 
     59        CHECK_CLOSE_EX(Stsp->_B().get_row(0), vec("2.3"), 0.0001); 
     60        CHECK_CLOSE_EX(Stsp->_C().get_row(0), vec("1, 0, 0"), 0.0001); 
    5861} 
    5962 
    60 TEST ( arx_LQG_test ) { 
    61         mlnorm<fsqmat> ml; 
    62         mat A = "1.81, -.8189, .00468, .00438"; 
    63         ml.set_parameters ( A, vec_1 ( 0.0 ), 0.00001*eye ( 1 ) ); 
    64         RV yr = RV ( "y", 1 ); 
    65         RV ur = RV ( "u", 1 ); 
    66         RV rgr = yr.copy_t ( -1 ); 
    67         rgr.add ( yr.copy_t ( -2 ) ); 
    68         rgr.add ( yr.copy_t ( -2 ) ); 
    69         rgr.add ( ur.copy_t ( -2 ) ); 
    70         rgr.add ( ur.copy_t ( -1 ) ); 
    71  
    72         ml.set_rv ( yr ); 
    73         ml.set_rvc ( rgr ); 
     63TEST(arx_LQG_test){ 
     64        mlnorm<chmat> ml; 
     65        mat A="1.81, -.81, .00468, .00438"; 
     66        ml.set_parameters(A, vec_1(0.0), 0.00001*eye(1)); 
     67        RV yr=RV("y",1); 
     68        RV ur=RV("u",1); 
     69        RV rgr = yr.copy_t(-1); 
     70        rgr.add(yr.copy_t(-2)); 
     71        rgr.add(yr.copy_t(-2)); 
     72        rgr.add(ur.copy_t(-1)); 
     73        rgr.add(ur); 
     74         
     75        ml.set_rv(yr); 
     76        ml.set_rvc(rgr); 
    7477        ml.validate(); 
    75  
    76         shared_ptr<StateCanonical > Stsp = new StateCanonical; 
    77         Stsp->connect_mlnorm ( ml ); 
    78  
     78         
     79        shared_ptr<StateFromARX> Stsp=new StateFromARX; 
     80        RV xrv; RV urv; 
     81        Stsp->connect_mlnorm(ml,xrv,urv); 
     82         
    7983        LQG L; 
    80         L.set_system ( Stsp ); 
    81         L.set_control_parameters ( eye ( 1 ), eye ( 1 ), vec_1 ( 0.0 ), 100 ); 
     84        L.set_system(Stsp); 
     85        L.set_control_parameters(eye(1), sqrt(1.0/1000)*eye(1), vec_1(0.0), 100); 
    8286        L.validate(); 
    83  
     87         
    8488        L.redesign(); 
    85         cout << L.to_string() << endl; 
     89        cout << L.to_string()<<endl; 
    8690} 
  • library/tests/testsuite/datalink_test.cpp

    r722 r723  
    101101 
    102102        vec val_up ( "1 2" ); 
    103         dl.step ( val_up ); 
     103        dl.store_data(val_up); 
    104104        val_up = "3 4"; 
    105105 
  • library/tests/testsuite/logger_test.cpp

    r722 r723  
    6464        remove_all ( ls.c_str() ); 
    6565        makedir ( ls, false ); 
    66         remove_all ( "exp/dirfile" ); 
     66        remove_all ( "dirfilelog_files" ); 
    6767 
    68         dirfilelog L ( "exp/dirfile", 10 ); 
     68        dirfilelog L ( "dirfilelog_files", 10 ); 
    6969 
    7070        int rid = L.add ( r, "" ); 
     
    8282 
    8383        std::string expected ( load_test_file ( "logger_test_dirfile_format.matrix" ) ); 
    84         std::string actual ( load_test_file ( "exp/dirfile/format" ) ); 
     84        std::string actual ( load_test_file ( "dirfilelog_files/format" ) ); 
    8585        CHECK_EQUAL ( expected, actual ); 
    8686}