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

Revision 764, 7.3 kB (checked in by smidl, 14 years ago)

burnin in controlloop is configurable

  • 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=controlloop(system, controllers, experiment, logger)\n"
73                                                "  system     = struct('class','datasource',...);  % Estimated system\n"
74                                                "  controllers= {struct('class','controller',...),  % Controllers\n"
75                                                "                struct('class','controller',...),...} \n"
76                                                "  === optional ==="
77                                                "  experiment = struct('ndat',100,...               % number of data in experiment, full length of finite datasources, 100 otherwise \n"
78                                                "               'burnin',10,...                    % initial time with different control\n"
79                                                "               'burn_pdf', struct('class','epdf_offspring') );\n"
80                                                "                                                  % sampler of the initial control\n"
81                                                "  logger     = struct('class','mexlogger');       % How to store results, default=mexlog, i.e. matlab structure\n\n"
82                                                "see documentation of classes datasource, BM, and mexlogger and their offsprings in BDM." );
83
84        RV::clear_all();
85        //CONFIG
86        UImxArray Cfg;
87        try {
88                Cfg.addGroup ( input[0],"system" );
89                Cfg.addList ( input[1],"controllers" );
90                if ( n_input>2 ) {
91                        Cfg.addGroup ( input[2],"experiment" );
92                }
93                if ( n_input>3 ) {
94                        Cfg.addGroup ( input[3],"logger" );
95                }
96        } catch ( SettingException e ) {
97                it_error ( "error: "+string ( e.getPath() ) );
98        }
99
100        //DBG
101        Cfg.writeFile ( "controlloop.cfg" );
102
103#else
104int main ( int argc, char* argv[] ) {
105        const char *fname;
106        if ( argc>1 ) {
107                fname = argv[1];
108        } else {
109                fname="controlloop.cfg";
110        }
111        UIFile Cfg ( fname );
112#endif
113
114        RNG_randomize();
115       
116        shared_ptr<DS> Ds = UI::build<DS> ( Cfg, "system" );
117        Array<shared_ptr<Controller> > Cs;
118        UI::get ( Cs,Cfg, "controllers" );
119        int Ndat=100;
120        int burnin=0;
121        shared_ptr<epdf> burn_pdf; 
122       
123        if ( Cfg.exists ( "experiment" ) ) {
124                Setting &exper=Cfg.getRoot()["experiment"];
125                if (UI::get(Ndat, exper, "Ndat", UI::optional ) ) {
126                        bdm_assert ( Ndat<=Ds->max_length(), "Data source has less data then required" );
127                };
128                if (UI::get(burnin, exper, "burnin",UI::optional )){
129                        burn_pdf = UI::build<epdf>(exper,"burn_pdf", UI::compulsory);
130                        if (burn_pdf){
131                                bdm_assert(burn_pdf->dimension()==Ds->_urv()._dsize(),"Given burn_pdf does not match the DataSource");
132                        } else {
133                                bdm_error("burn_pdf not specified!");
134                        }
135                       
136                }
137        } else {
138                if ( Ds->max_length() < std::numeric_limits< int >::max() ) {
139                        Ndat=Ds->max_length();
140                }
141                ;// else Ndat=10;
142        }
143        shared_ptr<logger> L = UI::build<logger> ( Cfg, "logger",UI::optional );
144        if ( !L ) {
145#ifdef MEX
146                //mex logger has only from_setting constructor - we  have to fill it...
147                L=new mexlog ( Ndat );
148#else
149                L=new stdlog();
150#endif
151        }
152
153        Ds->log_register ( *L, "DS" );
154        bdm_assert((Ds->_urv()._dsize() > 0), "Given DataSource is not controllable");
155        string Cname;
156        Setting &S=Cfg;
157        for ( int i=0; i<Cs.length(); i++ ) {
158                if (!UI::get ( Cname, S["controllers"][i], "name" ,UI::optional)){
159                        Cname="Ctrl"+num2str ( i );
160                }
161               
162                Cs ( i )->log_register ( *L,Cname ); // estimate
163        }
164        L->init();
165
166        vec dt=zeros ( Ds->_drv()._dsize() );   //data variable
167        Array<datalink_part*> Dlsu ( Cs.length() );
168        Array<datalink*> Dlsc ( Cs.length() );
169        Array<datalink_buffered*> Dls_buf (0);
170        for ( int i=0; i<Cs.length(); i++ ) {
171                //connect actual data
172                Dlsu ( i ) = new datalink_part;
173                Dlsu(i)->set_connection( Ds->_urv(), Cs ( i )->_rv()); //datalink controller -> datasource
174                //connect data in condition: datasource -> controller
175                if (Cs ( i )->_rvc().mint()<0){ 
176                        //delayed values are required
177                       
178                        //create delayed dl
179                        int ith_buf=Dls_buf.size();
180                        Dls_buf.set_size( ith_buf + 1, true);
181                        Dls_buf(ith_buf) = new datalink_buffered(); 
182                        //add dl to list of buffered DS
183                        Dlsc(i) = Dls_buf(ith_buf);
184                        Dlsc(i)->set_connection ( Cs ( i )->_rvc(),Ds->_drv() ); //datalink between a datasource and estimator
185                       
186                } else {
187                        Dlsc ( i ) = new datalink ( Cs ( i )->_rvc(),Ds->_drv() ); //datalink between a datasource and estimator
188                }
189        }
190
191        vec ut(Ds->_urv()._dsize());
192        for ( int tK=0;tK<Ndat;tK++ ) {
193                Ds->getdata ( dt );                                     // read data
194                Ds->log_write ( );
195
196                for ( int i=0; i<Cs.length(); i++ ) {
197                        if (tK + Cs ( i )->_rvc().mint() > 0 ) {
198                                Cs(i) -> redesign();
199                                Cs(i) -> adapt( Dlsc(i) ->pushdown(dt));
200                                if (tK >= burnin){
201                                        vec uti=Cs ( i )->ctrlaction ( Dlsc(i) ->pushdown(dt) );                // update estimates
202                                        Dlsu(i)->filldown(uti, ut);
203                                }
204                        }
205                        if(tK<burnin) {
206                                ut = burn_pdf->sample();
207                        }
208                       
209                        Cs ( i )->log_write ();
210                }
211                Ds->write(ut);
212               
213                L->step();
214                Ds->step();                                                     // simulator step
215                //update buffered fdat links
216                for (int i=0; i<Dls_buf.length(); i++){
217                        Dls_buf(i)->store_data(dt);
218                }
219                       
220        }
221
222        L->finalize();
223        // ------------------ End of routine -----------------------------
224
225#ifdef MEX
226        mexlog* mL=dynamic_cast<mexlog*> ( L.get() );
227
228        if ( mL ) { // user wants output!!
229                if ( n_output<1 ) mexErrMsgTxt ( "Wrong number of output variables!" );
230                output[0] = mL->toCell();
231        }
232#endif
233        for (int i=0;i<Dlsu.length(); i++){delete Dlsu(i); delete Dlsc(i);}
234}
Note: See TracBrowser for help on using the browser.