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

Revision 883, 7.5 kB (checked in by smidl, 14 years ago)

bdmtoolbox + arx

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