root/applications/bdmtoolbox/mex/estimator.cpp @ 658

Revision 658, 6.2 kB (checked in by smidl, 15 years ago)

fix crash

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 "estim/particles.h"
55#include "estim/kalman.h"
56
57//#include "mex_datasource.h"
58
59using namespace bdm;
60
61#ifdef MEX
62#include <itpp/itmex.h>
63#include "mex/mex_BM.h"
64#include "mex/mex_logger.h"
65#include "mex/mex_datasource.h"
66
67void mexFunction ( int n_output, mxArray *output[], int n_input, const mxArray *input[] ) {
68        // Check the number of inputs and output arguments
69        if ( n_input<2 ) mexErrMsgTxt ( "Usage:\n"
70                                                "result=estimator(system, estimators, experiment, logger)\n"
71                                                "  system     = struct('class','datasource',...);  % Estimated system\n"
72                                                "  estimators = {struct('class','estimator',...),  % Estimators\n"
73                                                "                struct('class','estimator',...),...} \n"
74                                                "  === optional ==="
75                                                "  experiment = struct('ndat',10);                 % number of data in experiment, full length of finite datasources, 10 otherwise \n"
76                                                "  logger     = struct('class','mexlogger');       % How to store results, default=mexlog, i.e. matlab structure\n\n"
77                                                "see documentation of classes datasource, BM, and mexlogger and their offsprings in BDM." );
78
79        RV::clear_all();
80        //CONFIG
81        UImxArray Cfg;
82        try {
83                Cfg.addGroup ( input[0],"system" );
84                Cfg.addList ( input[1],"estimators" );
85                if ( n_input>2 ) {
86                        Cfg.addGroup ( input[2],"experiment" );
87                }
88                if ( n_input>3 ) {
89                        Cfg.addGroup ( input[3],"logger" );
90                }/*else{
91                // define logger as mexlog
92                Setting &S=Cfg.getRoot();
93                S.add("logger",Setting::TypeGroup);
94                S["logger"].add("class",Setting::TypeString);
95                S["logger"]["class"]="mexlog";
96                S["logger"].add("maxlen",Setting::TypeInt);
97                int maxlen;
98                S["experiment"].lookupValue("ndat",maxlen);
99                S["logger"]["maxlen"]=maxlen;
100        }*/
101        } catch ( SettingException e ) {
102                it_error ( "error: "+string ( e.getPath() ) );
103        }
104
105        //DBG
106        Cfg.writeFile ( "estimator.cfg" );
107
108#else
109int main ( int argc, char* argv[] ) {
110        const char *fname;
111        if ( argc>1 ) {
112                fname = argv[1];
113        } else {
114                fname="estimator.cfg";
115        }
116        UIFile Cfg ( fname );
117#endif
118
119        shared_ptr<DS> Ds = UI::build<DS> ( Cfg, "system" );
120        Array<shared_ptr<BM> > Es;
121        UI::get ( Es,Cfg, "estimators" );
122        long Ndat=10;
123        if ( Cfg.exists ( "experiment" ) ) {
124                if ( Cfg.lookupValue ( "experiment.ndat",Ndat ) ) {
125                        bdm_assert ( Ndat<=Ds->max_length(), "Data source has less data then required" );
126                };
127        } else {
128                if ( Ds->max_length() < std::numeric_limits< int >::max() ) {
129                        Ndat=Ds->max_length();
130                }
131                ;// else Ndat=10;
132        }
133        shared_ptr<logger> L = UI::build<logger> ( Cfg, "logger",UI::optional );
134        if ( !L ) {
135#ifdef MEX
136                //mex logger has only from_setting constructor - we  have to fill it...
137                L=new mexlog ( Ndat );
138#else
139                L=new stdlog();
140#endif
141        }
142
143        Ds->log_add ( *L );
144        string Ename;
145        Setting &S=Cfg;
146        for ( int i=0; i<Es.length(); i++ ) {
147                try {
148                        UI::get ( Ename, S["estimators"][i], "name" );
149                } catch ( UIException e ) {
150                        Ename="Est"+num2str ( i );
151                }
152
153                Es ( i )->log_add ( *L,Ename ); // estimate
154        }
155        L->init();
156
157        vec dt=zeros ( Ds->_drv()._dsize() );   //data variable
158        Array<datalink*> Dls ( Es.length() );
159        Array<datalink_buffered*> Dls_buf (0);
160        for ( int i=0; i<Es.length(); i++ ) {
161                if (Es ( i )->_drv().mint()<0){ 
162                        //delayed values are required
163                       
164                        //create delayed dl
165                        int ith_buf=Dls_buf.size();
166                        Dls_buf.set_size( ith_buf + 1, true);
167                        Dls_buf(ith_buf) = new datalink_buffered(); 
168                        //add dl to list of buffered DS
169                        Dls(i) = Dls_buf(ith_buf);
170                        Dls(i)->set_connection ( Es ( i )->_drv(),Ds->_drv() ); //datalink between a datasource and estimator
171                       
172                } else {
173                        Dls ( i ) = new datalink ( Es ( i )->_drv(),Ds->_drv() ); //datalink between a datasource and estimator
174                }
175        }
176
177        for ( int tK=0;tK<Ndat;tK++ ) {
178                Ds->getdata ( dt );                                     // read data
179                Ds->logit ( *L );
180
181                for ( int i=0; i<Es.length(); i++ ) {
182                        Es ( i )->bayes ( Dls ( i )->pushdown ( dt ) );         // update estimates
183                        Es ( i )->logit ( *L );
184                }
185               
186                L->step();
187                Ds->step();                                                     // simulator step
188                //update buffered fdat links
189                for (int i=0; i<Dls_buf.length(); i++){
190                        Dls_buf(i)->step(dt);
191                }
192                       
193        }
194
195        L->finalize();
196        // ------------------ End of routine -----------------------------
197
198#ifdef MEX
199        mexlog* mL=dynamic_cast<mexlog*> ( L.get() );
200
201        if ( mL ) { // user wants output!!
202                if ( n_output<1 ) mexErrMsgTxt ( "Wrong number of output variables!" );
203                output[0] = mL->toCell();
204        }
205#endif
206        for (int i=0;i<Dls.length(); i++){delete Dls(i);}
207}
Note: See TracBrowser for help on using the browser.