root/applications/pmsm/pmsm_ctrl.cpp @ 1250

Revision 1243, 8.0 kB (checked in by smidl, 14 years ago)

Contrallable PMSM DS + PI control

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