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

Revision 626, 6.0 kB (checked in by smidl, 15 years ago)

Allow buffered datalinks in estimator

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