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

Revision 706, 6.7 kB (checked in by smidl, 15 years ago)

eol-native

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