root/applications/bdmtoolbox/mex/controlloop.cpp @ 756

Revision 744, 6.6 kB (checked in by smidl, 15 years ago)

Working unitsteps and controlloop + corresponding fixes

  • Property svn:eol-style set to native
Line 
1/*!
2\file
3\brief Application Estimator
4
5The general task of estimation is defined on the following scheme:
6\dot
7digraph estimation{
8        node [shape=box];
9        subgraph cl0 {
10        "Data Source" -> "Controller" [label="observations"];
11        "Controller" -> "Data Source" [label="actions"];
12        }
13        {rank="same"; "Controller"; "Result Logger"}
14        "Controller" -> "Result Logger" [label="internals"];
15        "Data Source" -> "Result Logger" [label="Simulated\n data"];
16}
17\enddot
18
19Here,
20\li Data Source is an object (class DS) providing sequential data, \f$ [d_1, d_2, \ldots d_t] \f$.
21\li Bayesian Model is an object (class BM) performing Bayesian filtering,
22\li Result Logger is an object (class logger) dedicated to storing important data from the experiment.
23
24\section  cmd Command-line usage
25Execute command:
26\code
27$> estimator config_file.cfg
28\endcode
29
30Full description of the experiment is in the file config_file.cfg which is expected to have the following structure:
31\code
32system = {type = "DS_offspring", ...};      // definition of a data source
33estimator = {type = "BM_offspring", ...};   // definition of an estimator
34logger = {type = "logger_type",...};        // definition of a logger
35experiment = {ndat = 11000; };              // definition of number of data records
36\endcode
37
38The above description must be specialized to specific classes. See, \subpage arx_ui how to do it for estimation of an ARX model.
39
40\section ex Matlab usage
41Execute command:
42\code
43>> estimator('config_file.cfg');
44\endcode
45when using loggers storing results on hard drives, and
46\code
47>> Res=estimator('config_file.cfg');
48\endcode
49when using logger of the type \c "mex_logger". The results will be stored in structure \c M.
50
51 */
52
53#include <estim/arx.h>
54#include <stat/emix.h>
55#include <base/datasources.h>
56#include <base/loggers.h>
57#include <design/arx_ctrl.h>
58
59//#include "mex_datasource.h"
60
61using namespace bdm;
62
63#ifdef MEX
64#include <itpp/itmex.h>
65#include <mex/mex_BM.h>
66#include <mex/mex_logger.h>
67#include <mex/mex_datasource.h>
68
69void mexFunction ( int n_output, mxArray *output[], int n_input, const mxArray *input[] ) {
70        // Check the number of inputs and output arguments
71        if ( n_input<2 ) mexErrMsgTxt ( "Usage:\n"
72                                                "result=estimator(system, estimators, experiment, logger)\n"
73                                                "  system     = struct('class','datasource',...);  % Estimated system\n"
74                                                "  estimators = {struct('class','estimator',...),  % Estimators\n"
75                                                "                struct('class','estimator',...),...} \n"
76                                                "  === optional ==="
77                                                "  experiment = struct('ndat',10);                 % number of data in experiment, full length of finite datasources, 10 otherwise \n"
78                                                "  logger     = struct('class','mexlogger');       % How to store results, default=mexlog, i.e. matlab structure\n\n"
79                                                "see documentation of classes datasource, BM, and mexlogger and their offsprings in BDM." );
80
81        RV::clear_all();
82        //CONFIG
83        UImxArray Cfg;
84        try {
85                Cfg.addGroup ( input[0],"system" );
86                Cfg.addList ( input[1],"controllers" );
87                if ( n_input>2 ) {
88                        Cfg.addGroup ( input[2],"experiment" );
89                }
90                if ( n_input>3 ) {
91                        Cfg.addGroup ( input[3],"logger" );
92                }
93        } catch ( SettingException e ) {
94                it_error ( "error: "+string ( e.getPath() ) );
95        }
96
97        //DBG
98        Cfg.writeFile ( "controlloop.cfg" );
99
100#else
101int main ( int argc, char* argv[] ) {
102        const char *fname;
103        if ( argc>1 ) {
104                fname = argv[1];
105        } else {
106                fname="controlloop.cfg";
107        }
108        UIFile Cfg ( fname );
109#endif
110
111        RNG_randomize();
112       
113        shared_ptr<DS> Ds = UI::build<DS> ( Cfg, "system" );
114        Array<shared_ptr<Controller> > Cs;
115        UI::get ( Cs,Cfg, "controllers" );
116        int Ndat=100;
117        int burnin=10;
118        if ( Cfg.exists ( "experiment" ) ) {
119                if ( Cfg.getRoot().lookupValue ( "experiment.ndat",Ndat ) ) {
120                        bdm_assert ( Ndat<=Ds->max_length(), "Data source has less data then required" );
121                };
122        } else {
123                if ( Ds->max_length() < std::numeric_limits< int >::max() ) {
124                        Ndat=Ds->max_length();
125                }
126                ;// else Ndat=10;
127        }
128        shared_ptr<logger> L = UI::build<logger> ( Cfg, "logger",UI::optional );
129        if ( !L ) {
130#ifdef MEX
131                //mex logger has only from_setting constructor - we  have to fill it...
132                L=new mexlog ( Ndat );
133#else
134                L=new stdlog();
135#endif
136        }
137
138        Ds->log_register ( *L, "DS" );
139        bdm_assert((Ds->_urv()._dsize() > 0), "Given DataSource is not controllable");
140        string Cname;
141        Setting &S=Cfg;
142        for ( int i=0; i<Cs.length(); i++ ) {
143                if (!UI::get ( Cname, S["controllers"][i], "name" ,UI::optional)){
144                        Cname="Ctrl"+num2str ( i );
145                }
146               
147                Cs ( i )->log_register ( *L,Cname ); // estimate
148        }
149        L->init();
150
151        vec dt=zeros ( Ds->_drv()._dsize() );   //data variable
152        Array<datalink_part*> Dlsu ( Cs.length() );
153        Array<datalink*> Dlsc ( Cs.length() );
154        Array<datalink_buffered*> Dls_buf (0);
155        for ( int i=0; i<Cs.length(); i++ ) {
156                //connect actual data
157                Dlsu ( i ) = new datalink_part;
158                Dlsu(i)->set_connection( Ds->_urv(), Cs ( i )->_rv()); //datalink controller -> datasource
159                //connect data in condition: datasource -> controller
160                if (Cs ( i )->_rvc().mint()<0){ 
161                        //delayed values are required
162                       
163                        //create delayed dl
164                        int ith_buf=Dls_buf.size();
165                        Dls_buf.set_size( ith_buf + 1, true);
166                        Dls_buf(ith_buf) = new datalink_buffered(); 
167                        //add dl to list of buffered DS
168                        Dlsc(i) = Dls_buf(ith_buf);
169                        Dlsc(i)->set_connection ( Cs ( i )->_rvc(),Ds->_drv() ); //datalink between a datasource and estimator
170                       
171                } else {
172                        Dlsc ( i ) = new datalink ( Cs ( i )->_rvc(),Ds->_drv() ); //datalink between a datasource and estimator
173                }
174        }
175
176        vec ut(Ds->_urv()._dsize());
177        for ( int tK=0;tK<Ndat;tK++ ) {
178                Ds->getdata ( dt );                                     // read data
179                Ds->log_write ( );
180
181                for ( int i=0; i<Cs.length(); i++ ) {
182                        if (tK + Cs ( i )->_rvc().mint() > 0 ) {
183                                Cs(i) -> redesign();
184                                Cs(i) -> adapt( Dlsc(i) ->pushdown(dt));
185                        }
186                        if (tK > burnin){
187                                vec uti=Cs ( i )->ctrlaction ( Dlsc(i) ->pushdown(dt) );                // update estimates
188                                Dlsu(i)->filldown(uti, ut);
189                        } else {
190                                ut = 0.1*randn(Ds->_urv()._dsize());
191                        }
192                       
193                        Cs ( i )->log_write ();
194                }
195                Ds->write(ut);
196               
197                L->step();
198                Ds->step();                                                     // simulator step
199                //update buffered fdat links
200                for (int i=0; i<Dls_buf.length(); i++){
201                        Dls_buf(i)->store_data(dt);
202                }
203                       
204        }
205
206        L->finalize();
207        // ------------------ End of routine -----------------------------
208
209#ifdef MEX
210        mexlog* mL=dynamic_cast<mexlog*> ( L.get() );
211
212        if ( mL ) { // user wants output!!
213                if ( n_output<1 ) mexErrMsgTxt ( "Wrong number of output variables!" );
214                output[0] = mL->toCell();
215        }
216#endif
217        for (int i=0;i<Dlsu.length(); i++){delete Dlsu(i); delete Dlsc(i);}
218}
Note: See TracBrowser for help on using the browser.