root/library/bdm/base/datasources.h @ 924

Revision 924, 9.0 kB (checked in by smidl, 14 years ago)

correction in MemDS and mgnorm

  • Property svn:eol-style set to native
Line 
1/*!
2  \file
3  \brief Common DataSources.
4  \author Vaclav Smidl.
5
6  -----------------------------------
7  BDM++ - C++ library for Bayesian Decision Making under Uncertainty
8
9  Using IT++ for numerical operations
10  -----------------------------------
11*/
12
13#ifndef DATASOURCE_H
14#define DATASOURCE_H
15
16#include "../base/bdmbase.h"
17#include "../stat/exp_family.h"
18#include "../base/user_info.h"
19
20namespace bdm {
21/*!
22* \brief Memory storage of off-line data column-wise
23
24The data are stored in an internal matrix \c Data . Each column of Data corresponds to one discrete time observation \f$t\f$. Access to this matrix is via indices \c rowid.
25
26The data can be loaded from a file.
27*/
28class MemDS : public DS {
29protected:
30        //! internal matrix of data
31        mat Data;
32        //! active column in the Data matrix
33        int time;
34
35public:
36        //!Default constructor
37        MemDS () {};
38
39        //! Convenience constructor
40        MemDS ( mat &Dat );
41
42        //! returns number of data in the file;
43        int max_length() {
44                return Data.cols();
45        }
46
47        void getdata ( vec &dt ) const;
48
49        void getdata ( vec &dt, const ivec &indices );
50
51        void set_drv ( const RV &drv );
52
53        void set_drv ( const RV &drv, const RV &urv )
54        {
55                if (urv._dsize()>0){
56                bdm_error ( "MemDS::urv is not supported" );
57                } else {
58                        DS::set_drv(drv,urv);
59                }
60                       
61        }
62
63        void write ( const vec &ut ) {
64                if (ut.size()>0){
65                        bdm_error ( "MemDS::write is not supported" );
66                }
67        }
68
69        void write ( const vec &ut, const ivec &indices ) {
70                if (ut.size()>0){
71                        bdm_error ( "MemDS::write is not supported" );
72                }
73        }
74
75        void step();
76
77        /*! Create object from the following structure
78        \code
79        { class = "MemDS";
80           Data = (...);            // Data matrix or data vector
81           --- optional ---
82           drv = {class="RV"; ...} // Identification how rows of the matrix Data will be known to others
83           time = 0;               // Index of the first column to user_info,
84        }
85        \endcode
86
87        If the optional fields are not given, they will be filled as follows:
88        \code
89        drv = {names=("ch0", "ch1", "ch2", ..."number_of_rows_of_Data");
90              sizes=( 1    1    1 ...);
91                  times=( 0    0    0 ...);
92                  };
93        time = 0;
94        \endcode
95        If \c rowid is given, \c drv will be named after indices in rowids.
96
97        Hence the data provided by method \c getdata() will be full column of matrix Data starting from the first record.
98        */
99        void from_setting ( const Setting &set );
100
101        void validate();
102};
103UIREGISTER ( MemDS );
104
105/*! Pseudovirtual class for reading data from files
106
107*/
108class FileDS: public MemDS {
109protected:
110        string filename;
111public:
112        void from_setting ( const Setting & set );
113};
114
115/*!
116* \brief Read Data Matrix from an IT file
117
118The constructor creates an internal matrix \c Data from an IT++ file. The file is binary and can be made using the IT++ library or the Matlab/Octave function itsave. NB: the data are stored columnwise, i.e. each column contains the data for time \f$t\f$!
119
120*/
121class ITppFileDS: public FileDS {
122
123public:
124        //! Convenience constructor
125        ITppFileDS ( const string &fname, const string &varname ) : FileDS() {
126                it_file it ( fname );
127                it << Name ( varname );
128                it >> Data;
129                time = 0;
130                //delays are ignored
131        };
132
133        ITppFileDS () : FileDS() {
134        };
135
136        void from_setting ( const Setting &set );
137
138        // TODO dodelat void to_setting( Setting &set ) const;
139};
140UIREGISTER ( ITppFileDS );
141SHAREDPTR ( ITppFileDS );
142
143/*!
144* \brief CSV file data storage
145The constructor creates \c Data matrix from the records in a CSV file \c fname. The orientation can be of two types:
1461. \c BY_COL which is default - the data are stored in columns; one column per time \f$t\f$, one row per data item.
1472. \c BY_ROW if the data are stored the classical CSV style. Then each column stores the values for data item, for ex. \f$[y_{t} y_{t-1} ...]\f$, one row for each discrete time instant.
148
149*/
150class CsvFileDS: public FileDS {
151public:
152        void from_setting ( const Setting & set );
153};
154
155
156
157// ARXDs - DELETED
158
159/*!  \brief Simulate data from a static pdf (epdf)
160
161Trivial example of a data source, could be used for tests of some estimation algorithms. For example, simulating data from a mixture model and feeding them to mixture model estimators.
162*/
163
164class EpdfDS: public DS {
165protected:
166        //! internal pointer to epdf from which we samplecond
167        shared_ptr<epdf> iepdf;
168        //! internal storage of data sample
169        vec dt;
170public:
171        void step() {
172                dt = iepdf->sample();
173        }
174        void getdata ( vec &dt_out ) const {
175                dt_out = dt;
176        }
177        void getdata ( vec &dt_out, const ivec &ids ) {
178                dt_out = dt ( ids );
179        }
180        const RV& _drv() const {
181                return iepdf->_rv();
182        }
183
184        //! Accepts action variable and schedule it for application.
185        virtual void write ( const vec &ut ) NOT_IMPLEMENTED_VOID;
186
187        //! Accepts action variables at specific indices
188        virtual void write ( const vec &ut, const ivec &indices ) NOT_IMPLEMENTED_VOID;
189
190        /*!
191        \code
192        class = "EpdfDS";
193        epdf = {class="epdf_offspring", ...}// uncondtitional density to sample from
194        \endcode
195
196        */
197        void from_setting ( const Setting &set ) {
198                iepdf = UI::build<epdf> ( set, "epdf", UI::compulsory );
199                bdm_assert ( iepdf->isnamed(), "Input epdf must be named, check if RV is given correctly" );
200                dt =  zeros ( iepdf->dimension() );
201                dtsize = dt.length();
202                set_drv ( iepdf->_rv(), RV() );
203                utsize = 0;
204        }
205
206        void validate() {
207                DS::validate();
208
209                dt = iepdf->sample();
210        }
211};
212UIREGISTER ( EpdfDS );
213
214/*!  \brief Simulate data from conditional density
215Still having only one density but allowing conditioning on either input or delayed values.
216*/
217class PdfDS : public DS {
218protected:
219        //! internal pointer to epdf from which we samplecond
220        shared_ptr<pdf> ipdf;
221        //! internal storage of data sample
222        vec yt;
223        //! input vector
224        vec ut;
225        //! datalink between ut and regressor
226        datalink_buffered ut2rgr;
227        //! datalink between yt and regressor
228        datalink_buffered yt2rgr;
229        //! numeric values of regressor
230        vec rgr;
231
232public:
233        void step();
234
235        void getdata ( vec &dt_out ) const;
236
237        void write ( const vec &ut0 ) {
238                ut = ut0;
239        }
240        void write ( const vec &ut0, const ivec &ind ) {
241                set_subvector ( ut, ind, ut0 );
242        }
243
244
245        //! Returns data records at indices.
246        virtual void getdata ( vec &dt, const ivec &indices ) NOT_IMPLEMENTED_VOID;
247
248
249        /*!
250        \code
251        class = "PdfDS";
252        pdf = {class="pdf_offspring", ...};  // pdf to simulate
253        --- optional ---
254        init_rv = {class="RV",names=...};      // define what rv to initialize - typically delayed values!
255        init_values = [...];                   // vector of initial values corresponding to init_rv
256        \endcode
257
258        If init_rv is not given, init_values are set to zero.
259        */
260        void from_setting ( const Setting &set ) {
261                ipdf = UI::build<pdf> ( set, "pdf", UI::compulsory );
262
263                RV Yrv = ipdf->_rv();
264                // get unique rvs form rvc
265                RV rgrv0 = ipdf->_rvc().remove_time();
266                // input is what in not in Yrv
267                Urv = rgrv0.subt ( Yrv );
268                set_drv ( concat(Yrv,Urv), Urv );
269                // connect input and output to rvc
270                ut2rgr.set_connection ( ipdf->_rvc(), Urv );
271                yt2rgr.set_connection ( ipdf->_rvc(), Yrv );
272
273                //set history - if given
274                shared_ptr<RV> rv_ini = UI::build<RV> ( set, "init_rv", UI::optional );
275                if ( rv_ini ) { // check if
276                        vec val;
277                        UI::get ( val, set, "init_values", UI::optional );
278                        if ( val.length() != rv_ini->_dsize() ) {
279                                bdm_error ( "init_rv and init_values fields have incompatible sizes" );
280                        } else {
281                                ut2rgr.set_history ( *rv_ini, val );
282                                yt2rgr.set_history ( *rv_ini, val );
283                        }
284                }
285
286                yt = zeros ( ipdf->dimension() );
287                rgr = zeros ( ipdf->dimensionc() );
288                ut = zeros ( Urv._dsize() );
289
290                utsize = ut.length();
291                dtsize = yt.length() + utsize;
292        }
293
294        void validate() {
295                DS::validate();
296
297                //taken from sample() - shift of history is not done here
298                ut2rgr.filldown ( ut, rgr );
299                yt2rgr.filldown ( yt, rgr );
300                yt = ipdf->samplecond ( rgr );
301        }
302};
303UIREGISTER ( PdfDS );
304
305//! State-space data source simulating two densities
306class StateDS : public DS {
307protected:
308        //!conditional pdf of the state evolution \f$ f(x_t|x_{t-1}) \f$
309        shared_ptr<pdf> IM;
310
311        //!conditional pdf of the observations \f$ f(d_t|x_t) \f$
312        shared_ptr<pdf> OM;
313
314        //! result storage
315        vec dt;
316        //! state storage
317        vec xt;
318        //! input storage
319        vec ut;
320
321        //! datalink from ut to IM.rvc
322        datalink_part u2imc;
323        //! datalink from ut to OM.rvc
324        datalink_part u2omc;
325public:
326        void getdata ( vec &dt0 ) const {
327                dt0 = dt;
328        }
329        void write ( const vec &ut0 ) {
330                ut = ut0;
331        }
332
333        void getdata ( vec &dt0, const ivec &indices ) {
334                dt0 = dt ( indices );
335        }
336
337        virtual void step();
338
339        //! set parameters
340        void set_parameters ( shared_ptr<pdf> IM0, shared_ptr<pdf> OM0 ) {
341                IM = IM0;
342                OM = OM0;
343        }
344        void set_initx ( const vec &x0 ) {
345                xt = x0;
346        }
347
348        virtual void write ( const vec &ut, const ivec &indices ) NOT_IMPLEMENTED_VOID;
349
350        /*! UI for stateDS
351
352        The DS is constructed from a structure with fields:
353        \code
354        class = "stateDS";
355        //Internal model
356        IM = { type = "pdf-offspring"; };
357        //Observation model
358        OM = { type = "pdf-offspring"; }
359        //initial state
360        x0 = [...]; //vector of data
361        \endcode
362        Both models must have defined \c rv. and \c rvc
363        Random variables not found in any rv are considered to be inputs.
364        */
365        void from_setting ( const Setting &set );
366
367        // TODO dodelat void to_setting( Setting &set ) const;
368
369        void validate();
370};
371
372UIREGISTER ( StateDS );
373SHAREDPTR ( StateDS );
374
375}; //namespace
376
377#endif // DS_H
Note: See TracBrowser for help on using the browser.