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

Revision 527, 8.3 kB (checked in by vbarta, 15 years ago)

using shared_ptr in UI (optionally so far; loading & saving Array<T *> still works but should be phased out); testsuite run leaks down from 8822 to 480 bytes

  • 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
17#include "../base/bdmbase.h"
18#include "../stat/exp_family.h"
19#include "../base/user_info.h"
20
21namespace bdm {
22/*!
23* \brief Memory storage of off-line data column-wise
24
25The 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 and \c delays.
26
27The data can be loaded from a file.
28*/
29class MemDS : public DS {
30protected:
31        //! internal matrix of data
32        mat Data;
33        //! active column in the Data matrix
34        int time;
35        //!  vector of rows that are presented in Dt
36        ivec rowid;
37        //! vector of delays that are presented in Dt
38        ivec delays;
39
40public:
41        void getdata ( vec &dt );
42        void getdata ( vec &dt, const ivec &indeces );
43        void set_rvs ( RV &drv, RV &urv );
44        void write ( vec &ut ) {
45                it_error ( "MemDS::write is not supported" );
46        }
47        void write ( vec &ut, ivec &indices ) {
48                it_error ( "MemDS::write is not supported" );
49        }
50        void step();
51        //!Default constructor
52        MemDS () {};
53        MemDS ( mat &Dat, ivec &rowid0, ivec &delays0 );
54};
55
56/*! Pseudovirtual class for reading data from files
57
58*/
59class FileDS: public MemDS {
60
61public:
62        void getdata ( vec &dt ) {
63                it_assert_debug ( dt.length() == Data.rows(), "" );
64                dt = Data.get_col ( time );
65        };
66        void getdata ( vec &dt, const ivec &indeces ) {
67                it_assert_debug ( dt.length() == indeces.length(), "" );
68                vec tmp ( indeces.length() );
69                tmp = Data.get_col ( time );
70                dt = tmp ( indeces );
71        };
72        //! returns number of data in the file;
73        int ndat() {
74                return Data.cols();
75        }
76        //! no sense to log this type
77        void log_add ( logger &L ) {};
78        //! no sense to log this type
79        void logit ( logger &L ) {};
80};
81
82/*!
83* \brief Read Data Matrix from an IT file
84
85The 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$!
86
87*/
88class ITppFileDS: public FileDS {
89
90public:
91        ITppFileDS ( const string &fname, const string &varname ) : FileDS() {
92                it_file it ( fname );
93                it << Name ( varname );
94                it >> Data;
95                time = 0;
96                //rowid and delays are ignored
97        };
98
99        ITppFileDS () : FileDS() {
100        };
101
102        void from_setting ( const Setting &set );
103
104        // TODO dodelat void to_setting( Setting &set ) const;
105
106};
107
108UIREGISTER ( ITppFileDS );
109
110/*!
111* \brief CSV file data storage
112The constructor creates \c Data matrix from the records in a CSV file \c fname. The orientation can be of two types:
1131. \c BY_COL which is default - the data are stored in columns; one column per time \f$t\f$, one row per data item.
1142. \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.
115
116*/
117class CsvFileDS: public FileDS {
118
119public:
120        //! Constructor - create DS from a CSV file.
121        CsvFileDS ( const string& fname, const string& orientation = "BY_COL" );
122};
123
124
125
126/*!
127\brief Generator of ARX data
128
129*/
130class ArxDS : public DS {
131protected:
132        //! Rv of the regressor
133        RV Rrv;
134        //! History, ordered as \f$[y_t, u_t, y_{t-1 }, u_{t-1}, \ldots]\f$
135        vec H;
136        //! (future) input
137        vec U;
138        //! temporary variable for regressor
139        vec rgr;
140        //! data link: H -> rgr
141        datalink rgrlnk;
142        //! model of Y - linear Gaussian
143        mlnorm<chmat> model;
144        //! options
145        bool opt_L_theta;
146        //! loggers
147        int L_theta;
148        int L_R;
149        int dt_size;
150public:
151        void getdata ( vec &dt ) {
152                //it_assert_debug ( dt.length() ==Drv.count(),"ArxDS" );
153                dt = H;
154        };
155        void getdata ( vec &dt, const ivec &indices ) {
156                it_assert_debug ( dt.length() == indices.length(), "ArxDS" );
157                dt = H ( indices );
158        };
159        void write ( vec &ut ) {
160                //it_assert_debug ( ut.length() ==Urv.count(),"ArxDS" );
161                U = ut;
162        };
163        void write ( vec &ut, const ivec &indices ) {
164                it_assert_debug ( ut.length() == indices.length(), "ArxDS" );
165                set_subvector ( U, indices, ut );
166        };
167        void step();
168        //!Default constructor
169        ArxDS ( ) {};
170        //! Set parameters of the internal model, H is maximum time delay
171        void set_parameters ( const mat &Th0, const vec mu0, const chmat &sqR0 ) {
172                model.set_parameters ( Th0, mu0, sqR0 );
173        };
174        //! Set
175        void set_drv ( const RV &yrv, const RV &urv, const RV &rrv ) {
176                Rrv = rrv;
177                Urv = urv;
178                dt_size = yrv._dsize() + urv._dsize();
179
180                RV drv = concat ( yrv, urv );
181                Drv = drv;
182                int td = rrv.mint();
183                H.set_size ( drv._dsize() * ( -td + 1 ) );
184                U.set_size ( Urv._dsize() );
185                for ( int i = -1; i >= td; i-- ) {
186                        drv.t ( -1 );
187                        Drv.add ( drv ); //shift u1
188                }
189                rgrlnk.set_connection ( rrv, Drv );
190
191                dtsize = Drv._dsize();
192                utsize = Urv._dsize();
193        }
194        //! set options from a string
195        void set_options ( const string &s ) {
196                opt_L_theta = ( s.find ( "L_theta" ) != string::npos );
197        };
198        virtual void log_add ( logger &L ) {
199                //DS::log_add ( L ); too long!!
200                L_dt = L.add ( Drv ( 0, dt_size ), "" );
201                L_ut = L.add ( Urv, "" );
202
203                mat &A = model._A();
204                mat R = model._R();
205                if ( opt_L_theta ) {
206                        L_theta = L.add ( RV ( "{th }", vec_1 ( A.rows() * A.cols() ) ), "t" );
207                }
208                if ( opt_L_theta ) {
209                        L_R = L.add ( RV ( "{R }", vec_1 ( R.rows() * R.cols() ) ), "r" );
210                }
211        }
212        virtual void logit ( logger &L ) {
213                //DS::logit ( L );
214                L.logit ( L_dt, H.left ( dt_size ) );
215                L.logit ( L_ut, U );
216
217                mat &A = model._A();
218                mat R = model._R();
219                if ( opt_L_theta ) {
220                        L.logit ( L_theta, vec ( A._data(), A.rows() *A.cols() ) );
221                };
222                if ( opt_L_theta ) {
223                        L.logit ( L_R, vec ( R._data(), R.rows() *R.rows() ) );
224                };
225        }
226
227        // TODO dokumentace - aktualizovat
228        /*! UI for ArxDS using factorized description!
229
230        The ArxDS is constructed from a structure with fields:
231        \code
232        system = {
233                type = "ArxDS";
234                // description of y variables
235                y = {type="rv"; names=["y", "u"];};
236                // description of u variable
237                u = {type="rv"; names=[];}
238                // description of regressor
239                rgr = {type="rv";
240                        names = ["y","y","y","u"];
241                        times = [-1, -2, -3, -1];
242                }
243
244                // theta
245                theta = [0.8, -0.3, 0.4, 1.0,
246                                 0.0, 0.0, 0.0, 0.0];
247                // offset (optional)
248                offset = [0.0, 0.0];
249                //variance
250                r = [0.1, 0.0,
251                         0.0, 1.0];
252                //options: L_theta = log value of theta,
253                opt = "L_theta";
254        };
255        \endcode
256
257        Result is ARX data source offering with full history as Drv.
258        */
259        void from_setting ( const Setting &set );
260
261        // TODO dodelat void to_setting( Setting &set ) const;
262};
263
264UIREGISTER ( ArxDS );
265
266class stateDS : public DS {
267private:
268        //!conditional pdf of the state evolution \f$ f(x_t|x_{t-1}) \f$
269        shared_ptr<mpdf> IM;
270
271        //!conditional pdf of the observations \f$ f(d_t|x_t) \f$
272        shared_ptr<mpdf> OM;
273
274protected:
275        //! result storage
276        vec dt;
277        //! state storage
278        vec xt;
279        //! input storage
280        vec ut;
281        //! Logger
282        int L_xt;
283
284public:
285        void getdata ( vec &dt0 ) {
286                dt0 = dt;
287        }
288        void getdata ( vec &dt0, const ivec &indeces ) {
289                dt0 = dt ( indeces );
290        }
291
292        stateDS ( const shared_ptr<mpdf> &IM0, const shared_ptr<mpdf> &OM0, int usize ) : IM ( IM0 ), OM ( OM0 ),
293                dt ( OM0->dimension() ), xt ( IM0->dimension() ),
294                ut ( usize ), L_xt(0) { }
295
296        stateDS() : L_xt(0) { }
297
298        virtual void step() {
299                xt = IM->samplecond ( concat ( xt, ut ) );
300                dt = OM->samplecond ( concat ( xt, ut ) );
301        }
302
303        virtual void log_add ( logger &L ) {
304                DS::log_add ( L );
305                L_xt = L.add ( IM->_rv(), "true" );
306        }
307        virtual void logit ( logger &L ) {
308                DS::logit ( L );
309                L.logit ( L_xt, xt );
310        }
311
312        /*! UI for stateDS
313
314        The DS is constructed from a structure with fields:
315        \code
316        system = {
317                type = "stateDS";
318                //Internal model
319                IM = { type = "mpdf"; //<-- valid offspring! e.g. "mlnorm"
320                        rv = { //description of x_t
321                                names=["name1",...];
322                                sizes=[2,1]; // optional default=[1,1...];
323                                times=[0,0]; // optional default=[0,0...];
324                                }
325                        rvu= { //description of  u_t
326                                //optional default=empty
327                                }
328
329                        // remaining fields depending on the chosen type
330                        };
331                //Observation model
332                OM = { type = "mpdf-offspring";
333                        rv = {}; //description of d_t
334                        rvu = {type="internal", path="system.IM.rvu"}; //description of u_t
335
336                        //remaining fields
337                }
338        };
339        \endcode
340        */
341        void from_setting ( const Setting &set );
342
343        // TODO dodelat void to_setting( Setting &set ) const;
344
345};
346
347UIREGISTER ( stateDS );
348
349}; //namespace
350
351#endif // DS_H
Note: See TracBrowser for help on using the browser.