root/library/bdm/base/bdmbase.h @ 822

Revision 822, 32.7 kB (checked in by smidl, 14 years ago)

too many abstracts in DS

  • Property svn:eol-style set to native
Line 
1/*!
2  \file
3  \brief Basic structures of probability calculus: random variables, probability densities, Bayes rule
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 BDMBASE_H
14#define BDMBASE_H
15
16#include <map>
17
18#include "../itpp_ext.h"
19#include "../bdmroot.h"
20#include "../shared_ptr.h"
21#include "user_info.h"
22
23using namespace libconfig;
24using namespace itpp;
25using namespace std;
26
27namespace bdm {
28//! Structure of RV, i.e. RVs expanded into a flat list of IDs, used for debugging.
29class str {
30public:
31        //! vector id ids (non-unique!)
32        ivec ids;
33        //! vector of times
34        ivec times;
35        //!Default constructor
36        str ( ivec ids0, ivec times0 ) : ids ( ids0 ), times ( times0 ) {
37                bdm_assert ( times0.length() == ids0.length(), "Incompatible input" );
38        };
39};
40
41/*!
42* \brief Class representing variables, most often random variables
43
44The purpose of this class is to decribe a vector of data. Such description is used for connecting various vectors between each other, see class datalink.
45
46The class is implemented using global variables to assure uniqueness of description:
47
48 In is a vector
49\dot
50digraph datalink {
51rankdir=LR;
52subgraph cluster0 {
53node [shape=record];
54label = "MAP \n std::map<string,int>";
55map [label="{{\"a\"| \"b\" | \"c\"} | {<3> 3 |<1> 1|<2> 2}}"];
56color = "white"
57}
58subgraph cluster1{
59node [shape=record];
60label = "NAMES";
61names [label="{<1> \"b\" | <2> \"c\" | <3>\"a\" }"];
62color = "white"
63}
64subgraph cluster2{
65node [shape=record];
66label = "SIZES";
67labelloc = b;
68sizes [label="{<1>1 |<2> 4 |<3> 1}"];
69color = "white"
70}
71map:1 -> names:1;
72map:1 -> sizes:1;
73map:3 -> names:3;
74map:3 -> sizes:3;
75}
76\enddot
77*/
78
79class RV : public root {
80private:
81        typedef std::map<string, int> str2int_map;
82
83        //! Internal global variable storing sizes of RVs
84        static ivec SIZES;
85        //! Internal global variable storing names of RVs
86        static Array<string> NAMES;
87
88        //! TODO
89        const static int BUFFER_STEP;
90
91        //! TODO
92        static str2int_map MAP;
93
94public:
95
96protected:
97        //! size of the data vector
98        int dsize;
99        //! number of individual rvs
100        int len;
101        //! Vector of unique IDs
102        ivec ids;
103        //! Vector of shifts from current time
104        ivec times;
105
106private:
107        enum enum_dummy {dummy};
108
109        //! auxiliary function used in constructor
110        void init( const Array<std::string> &in_names, const ivec &in_sizes, const ivec &in_times );
111
112        //! auxiliary function assigning unique integer index related to the passed name and size of the random variable
113        int assign_id( const string &name, int size );
114
115        //! Private constructor from IDs, potentially dangerous since all ids must be valid!
116        //! dummy is there to prevent confusion with RV(" string");
117        explicit RV ( const ivec &ids0, enum_dummy dum ) : dsize ( 0 ), len ( ids0.length() ), ids ( ids0 ), times ( zeros_i ( ids0.length() ) ) {
118                dsize = countsize();
119        }
120public:
121        //! \name Constructors
122        //!@{
123
124        //! Full constructor
125        RV ( const Array<std::string> &in_names, const ivec &in_sizes, const ivec &in_times ) {
126                init ( in_names, in_sizes, in_times );
127        }
128
129        //! Constructor with times=0
130        RV ( const Array<std::string> &in_names, const ivec &in_sizes ) {
131                init ( in_names, in_sizes, zeros_i ( in_names.length() ) );
132        }
133
134        //! Constructor with sizes=1, times=0
135        RV ( const Array<std::string> &in_names ) {
136                init ( in_names, ones_i ( in_names.length() ), zeros_i ( in_names.length() ) );
137        }
138
139        //! Constructor of empty RV
140        RV() : dsize ( 0 ), len ( 0 ), ids ( 0 ), times ( 0 ) {}
141
142        //! Constructor of a single RV with given id
143        RV ( string name, int sz, int tm = 0 );
144
145        // compiler-generated copy constructor is used
146        //!@}
147
148        //! \name Access functions
149        //!@{
150
151        //! State output, e.g. for debugging.
152        friend std::ostream &operator<< ( std::ostream &os, const RV &rv );
153
154        string to_string() const {
155                ostringstream o;
156                o << *this;
157                return o.str();
158        }
159
160        //! total size of a random variable
161        int _dsize() const {
162                return dsize;
163        }
164
165        //! access function
166        const ivec& _ids() const {
167                return ids;
168        }
169
170        //! Recount size of the corresponding data vector
171        int countsize() const;
172        //! Vector of cumulative sizes of RV
173        ivec cumsizes() const;
174        //! Number of named parts
175        int length() const {
176                return len;
177        }
178        int id ( int at ) const {
179                return ids ( at );
180        }
181        int size ( int at ) const {
182                return SIZES ( ids ( at ) );
183        }
184        int time ( int at ) const {
185                return times ( at );
186        }
187        std::string name ( int at ) const {
188                return NAMES ( ids ( at ) );
189        }
190        //! returns name of a scalar at position scalat, i.e. it can be in the middle of vector name, in that case it adds "_%d" to it
191        std::string scalarname ( int scalat ) const;
192
193        void set_time ( int at, int time0 ) {
194                times ( at ) = time0;
195        }
196        //!@}
197
198        //! \name Algebra on Random Variables
199        //!@{
200
201        //! Find indices of self in another rv, \return ivec of the same size as self.
202        ivec findself ( const RV &rv2 ) const;
203        //! Find indices of self in another rv, ignore time, \return ivec of the same size as self.
204        ivec findself_ids ( const RV &rv2 ) const;
205        //! Compare if \c rv2 is identical to this \c RV
206        bool equal ( const RV &rv2 ) const;
207        //! Add (concat) another variable to the current one, \return true if all rv2 were added, false if rv2 is in conflict
208        bool add ( const RV &rv2 );
209        //! Subtract  another variable from the current one
210        RV subt ( const RV &rv2 ) const;
211        //! Select only variables at indices ind
212        RV subselect ( const ivec &ind ) const;
213
214        //! Select only variables at indices ind
215        RV operator() ( const ivec &ind ) const {
216                return subselect ( ind );
217        }
218
219        //! Select from data vector starting at di1 to di2
220        RV operator() ( int di1, int di2 ) const;
221
222        //! Shift \c time by delta.
223        void t_plus ( int delta );
224        //!@}
225
226        //! @{ \name Time manipulation functions
227        //! returns rvs with time set to 0 and removed duplicates
228        RV remove_time() const {
229                return RV ( unique ( ids ), dummy );
230        }
231        //! create new RV from the current one with time shifted by given value
232        RV copy_t ( int dt ) const {
233                RV tmp = *this;
234                tmp.t_plus ( dt );
235                return tmp;
236        }
237        //! return rvs with expanded delayes and sorted in the order of: \f$ [ rv_{0}, rv_{-1},\ldots  rv_{max_delay}]\f$
238        RV expand_delayes() const;
239        //!@}
240
241        //!\name Relation to vectors
242        //!@{
243
244        //! generate \c str from rv, by expanding sizes
245        str tostr() const;
246        //! when this rv is a part of bigger rv, this function returns indices of self in the data vector of the bigger crv.
247        //! Then, data can be copied via: data_of_this = cdata(ind);
248        ivec dataind ( const RV &crv ) const;
249        //! same as dataind but this time crv should not be complete supperset of rv.
250        ivec dataind_part ( const RV &crv ) const;
251        //! generate mutual indices when copying data between self and crv.
252        //! Data are copied via: data_of_this(selfi) = data_of_rv2(rv2i)
253        void dataind ( const RV &rv2, ivec &selfi, ivec &rv2i ) const;
254        //! Minimum time-offset
255        int mint() const {
256                return times.length() > 0 ? min ( times ) : 0;
257        }
258        //! Minimum time-offset of ids of given RVs
259        int mint ( const RV &rv ) const {
260                bvec belong = zeros_b ( len );
261                for ( int r = 0; r < rv.length(); r++ ) {
262                        belong = belong | ( ids == rv.id ( r ) );
263                }
264                return times.length() > 0 ? min ( get_from_bvec ( times, belong ) ) : 0;
265        }
266        //!@}
267
268        /*! \brief UI for class RV (description of data vectors)
269
270        \code
271        class = 'RV';
272        names = {'a', 'b', 'c', ...};   // UNIQUE IDENTIFIER same names = same variable
273                                                                        // names are also used when storing results
274        --- optional ---
275        sizes = [1, 2, 3, ...];         // size of each name. default = ones()
276                                                                        // if size = -1, it is found out from previous instances of the same name
277        times = [-1, -2, 0, ...];       // time shifts with respect to current time, default = zeros()
278        \endcode
279        */
280        void from_setting ( const Setting &set );
281
282        void to_setting ( Setting &set ) const;
283
284        //! Invalidate all named RVs. Use before initializing any RV instances, with care...
285        static void clear_all();
286        //! function for debugging RV related stuff
287        string show_all();
288
289};
290UIREGISTER ( RV );
291SHAREDPTR ( RV );
292
293//! Concat two random variables
294RV concat ( const RV &rv1, const RV &rv2 );
295
296/*!
297@brief Class for storing results (and semi-results) of an experiment
298
299This class abstracts logging of results from implementation. This class replaces direct logging of results (e.g. to files or to global variables) by calling methods of a logger. Specializations of this abstract class for specific storage method are designed.
300*/
301class logger : public root {
302protected:
303        //! RVs of all logged variables.
304        Array<RV> entries;
305        //! Names of logged quantities, e.g. names of algorithm variants
306        Array<string> names;
307        //!separator of prefixes of entries
308        const string separator;
309        //! Root Setting for storing Settings
310        Config setting_conf;
311        //! list of Settings for specific ids
312        Array<Setting*> settings;
313public:
314        //!Default constructor
315        logger ( const string separator0 ) : entries ( 0 ), names ( 0 ), separator ( separator0 ) {}
316
317        //! returns an identifier which will be later needed for calling the \c logit() function
318        //! For empty RV it returns -1, this entry will be ignored by \c logit().
319        virtual int add_vector ( const RV &rv, string prefix = "" );
320
321        virtual int add_setting ( const string &prefix );
322
323        //! log this vector
324        virtual void log_vector ( int id, const vec &v ) = 0;
325
326        virtual Setting & log_to_setting ( int id ) {
327                return settings ( id )->add ( Setting::TypeGroup );
328        }
329        //! log this double
330        virtual void logit ( int id, const double &d ) = 0;
331
332        //! Shifts storage position for another time step.
333        virtual void step() = 0;
334
335        //! Finalize storing information
336        virtual void finalize() {};
337
338        //! Initialize the storage
339        virtual void init() {};
340
341        //!separator of prefixes for this logger
342        const string& prefix_sep() {
343                return separator;
344        }
345};
346
347
348//! Class representing function \f$f(x)\f$ of variable \f$x\f$ represented by \c rv
349class fnc : public root {
350protected:
351        //! Length of the output vector
352        int dimy;
353        //! Length of the input vector
354        int dimc;
355public:
356        //!default constructor
357        fnc() {};
358        //! function evaluates numerical value of \f$f(x)\f$ at \f$x=\f$ \c cond
359        virtual vec eval ( const vec &cond ) {
360                return vec ( 0 );
361        };
362
363        //! access function
364        int dimension() const {
365                return dimy;
366        }
367        //! access function
368        int dimensionc() const {
369                return dimc;
370        }
371        void from_setting(const Setting &set){
372                UI::get(dimy, set, "dim", UI::optional);
373                UI::get(dimc, set, "dimc", UI::optional);
374        }
375};
376
377class epdf;
378
379//! Conditional probability density, e.g. modeling \f$ f( x | y) \f$, where \f$ x \f$ is random variable, \c rv, and \f$ y \f$ is conditioning variable, \c rvc.
380class pdf : public root {
381protected:
382        //!dimension of the condition
383        int dimc;
384
385        //! random variable in condition
386        RV rvc;
387
388        //! dimension of random variable
389        int dim;
390
391        //! random variable
392        RV rv;
393
394public:
395        //! \name Constructors
396        //! @{
397
398        pdf() : dimc ( 0 ), rvc(), dim ( 0 ), rv() { }
399
400        pdf ( const pdf &m ) : dimc ( m.dimc ), rvc ( m.rvc ), dim ( m.dim ), rv ( m.rv ) { }
401
402        //!@}
403
404        //! \name Matematical operations
405        //!@{
406
407        //! Returns a sample from the density conditioned on \c cond, \f$x \sim epdf(rv|cond)\f$. \param cond is numeric value of \c rv
408        virtual vec samplecond ( const vec &cond ) = 0;
409
410        //! Returns \param N samples from the density conditioned on \c cond, \f$x \sim epdf(rv|cond)\f$. \param cond is numeric value of \c rv
411        virtual mat samplecond_mat ( const vec &cond, int N );
412
413        //! Shortcut for conditioning and evaluation of the internal epdf. In some cases,  this operation can be implemented efficiently.
414        virtual double evallogcond ( const vec &yt, const vec &cond ) = 0;
415
416        //! Matrix version of evallogcond
417        virtual vec evallogcond_mat ( const mat &Yt, const vec &cond ) {
418                vec v ( Yt.cols() );
419                for ( int i = 0; i < Yt.cols(); i++ ) {
420                        v ( i ) = evallogcond ( Yt.get_col ( i ), cond );
421                }
422                return v;
423        }
424
425        //! Array<vec> version of evallogcond
426        virtual vec evallogcond_mat ( const Array<vec> &Yt, const vec &cond ) {
427                vec v ( Yt.length() );
428                for ( int i = 0; i < Yt.length(); i++ ) {
429                        v ( i ) = evallogcond ( Yt( i ), cond );
430                }
431                return v;
432        }
433
434        //! \name Access to attributes
435        //! @{
436
437        const RV& _rv() const {
438                return rv;
439        }
440        const RV& _rvc() const {
441                return rvc;
442        }
443
444        int dimension() const {
445                return dim;
446        }
447        int dimensionc() {
448                return dimc;
449        }
450
451        //! access function
452        void set_dim ( int d ) {
453                dim = d;
454        }
455        //! access function
456        void set_dimc ( int d ) {
457                dimc = d;
458        }
459        //! Load from structure with elements:
460        //!  \code
461        //! { class = "pdf_offspring",
462        //!   rv = {class="RV", names=(...),}; // RV describing meaning of random variable
463        //!   rvc= {class="RV", names=(...),}; // RV describing meaning of random variable in condition
464        //!   // elements of offsprings
465        //! }
466        //! \endcode
467        //!@}
468        void from_setting ( const Setting &set );
469
470        void to_setting ( Setting &set ) const;
471        //!@}
472
473        //! \name Connection to other objects
474        //!@{
475        void set_rvc ( const RV &rvc0 ) {
476                rvc = rvc0;
477        }
478        void set_rv ( const RV &rv0 ) {
479                rv = rv0;
480        }
481
482        //! Names of variables stored in RV are considered to be valid only if their size match size of the parameters (dim).
483        bool isnamed() const {
484                return ( dim == rv._dsize() ) && ( dimc == rvc._dsize() );
485        }
486        //!@}
487};
488SHAREDPTR ( pdf );
489
490//! Probability density function with numerical statistics, e.g. posterior density.
491class epdf : public pdf {
492
493public:
494        /*! \name Constructors
495         Construction of each epdf should support two types of constructors:
496        \li empty constructor,
497        \li copy constructor,
498
499        The following constructors should be supported for convenience:
500        \li constructor followed by calling \c set_parameters()
501        \li constructor accepting random variables calling \c set_rv()
502
503         All internal data structures are constructed as empty. Their values (including sizes) will be set by method \c set_parameters(). This way references can be initialized in constructors.
504        @{*/
505        epdf() {};
506        epdf ( const epdf &e ) : pdf ( e ) {};
507               
508        //!@}
509
510        //! \name Matematical Operations
511        //!@{
512
513        //! Returns a sample, \f$ x \f$ from density \f$ f_x()\f$
514        virtual vec sample() const = 0;
515
516        //! Returns N samples, \f$ [x_1 , x_2 , \ldots \ \f$  from density \f$ f_x(rv)\f$
517        virtual mat sample_mat ( int N ) const;
518
519        //! Compute log-probability of argument \c val
520        //! In case the argument is out of suport return -Infinity
521        virtual double evallog ( const vec &val ) const = 0;
522       
523        //! Compute log-probability of multiple values argument \c val
524        virtual vec evallog_mat ( const mat &Val ) const;
525
526        //! Compute log-probability of multiple values argument \c val
527        virtual vec evallog_mat ( const Array<vec> &Avec ) const;
528
529        //! Return conditional density on the given RV, the remaining rvs will be in conditioning
530        virtual shared_ptr<pdf> condition ( const RV &rv ) const;
531
532        //! Return marginal density on the given RV, the remainig rvs are intergrated out
533        virtual shared_ptr<epdf> marginal ( const RV &rv ) const;
534
535        virtual vec mean() const = 0;
536
537        //! return expected variance (not covariance!)
538        virtual vec variance() const = 0;
539
540        //! return expected covariance -- default is diag(variance)!!
541        virtual mat covariance() const {return diag(variance());};
542       
543        //! Lower and upper bounds of \c percentage % quantile, returns mean-2*sigma as default
544        virtual void qbounds ( vec &lb, vec &ub, double percentage = 0.95 ) const {
545                vec mea = mean();
546                vec std = sqrt ( variance() );
547                lb = mea - 2 * std;
548                ub = mea + 2 * std;
549        };
550        //!@}
551
552        //! \name Connection to other classes
553        //! Description of the random quantity via attribute \c rv is optional.
554        //! For operations such as sampling \c rv does not need to be set. However, for \c marginalization
555        //! and \c conditioning \c rv has to be set. NB:
556        //! @{
557
558        //! store values of the epdf on the following levels:
559        //!  #1 mean
560        //!  #2 mean + lower & upper bound
561        void log_register ( logger &L, const string &prefix );
562
563        void log_write() const;
564        //!@}
565
566        //! \name Access to attributes
567        //! @{
568
569        //! Load from structure with elements:
570        //!  \code
571        //! { rv = {class="RV", names=(...),}; // RV describing meaning of random variable
572        //!   // elements of offsprings
573        //! }
574        //! \endcode
575        //!@}
576        void from_setting ( const Setting &set ) {
577                shared_ptr<RV> r = UI::build<RV> ( set, "rv", UI::optional );
578                if ( r ) {
579                        set_rv ( *r );
580                }
581        }
582
583        void to_setting ( Setting &set ) const {
584                // we do not want to store rvc, therfore, pdf::to_setting( set ) is omitted
585                root::to_setting(set);
586
587                UI::save( &rv, set, "rv" );
588        }
589
590        vec samplecond ( const vec &cond ) {
591                return sample();
592        }
593        double evallogcond ( const vec &val, const vec &cond ) {
594                return evallog ( val );
595        }
596};
597SHAREDPTR ( epdf );
598
599//! pdf with internal epdf that is modified by function \c condition
600template <class EPDF>
601class pdf_internal: public pdf {
602protected :
603        //! Internal epdf used for sampling
604        EPDF iepdf;
605public:
606        //! constructor
607        pdf_internal() : pdf(), iepdf() {
608        }
609
610        //! Update \c iepdf so that it represents this pdf conditioned on \c rvc = cond
611        //! This function provides convenient reimplementation in offsprings
612        virtual void condition ( const vec &cond ) = 0;
613
614        //!access function to iepdf
615        EPDF& e() {
616                return iepdf;
617        }
618
619        //! Reimplements samplecond using \c condition()
620        vec samplecond ( const vec &cond );
621        //! Reimplements evallogcond using \c condition()
622        double evallogcond ( const vec &val, const vec &cond );
623        //! Efficient version of evallogcond for matrices
624        virtual vec evallogcond_mat ( const mat &Dt, const vec &cond );
625        //! Efficient version of evallogcond for Array<vec>
626        virtual vec evallogcond_mat ( const Array<vec> &Dt, const vec &cond );
627        //! Efficient version of samplecond
628        virtual mat samplecond_mat ( const vec &cond, int N );
629
630        void validate() {
631                iepdf.validate();
632                if ( rv._dsize() < iepdf._rv()._dsize() ) {
633                        rv = iepdf._rv();
634                };
635                dim = iepdf.dimension();
636        }
637};
638
639/*! \brief DataLink is a connection between two data vectors Up and Down
640
641Up can be longer than Down. Down must be fully present in Up (TODO optional)
642See chart:
643\dot
644digraph datalink {
645  node [shape=record];
646  subgraph cluster0 {
647    label = "Up";
648      up [label="<1>|<2>|<3>|<4>|<5>"];
649    color = "white"
650}
651  subgraph cluster1{
652    label = "Down";
653    labelloc = b;
654      down [label="<1>|<2>|<3>"];
655    color = "white"
656}
657    up:1 -> down:1;
658    up:3 -> down:2;
659    up:5 -> down:3;
660}
661\enddot
662
663*/
664class datalink {
665protected:
666        //! Remember how long val should be
667        int downsize;
668
669        //! Remember how long val of "Up" should be
670        int upsize;
671
672        //! val-to-val link, indices of the upper val
673        ivec v2v_up;
674
675public:
676        //! Constructor
677        datalink() : downsize ( 0 ), upsize ( 0 ) { }
678
679        //! Convenience constructor
680        datalink ( const RV &rv, const RV &rv_up ) {
681                set_connection ( rv, rv_up );
682        }
683
684        //! set connection, rv must be fully present in rv_up
685        virtual void set_connection ( const RV &rv, const RV &rv_up );
686
687        //! set connection using indices
688        virtual void set_connection ( int ds, int us, const ivec &upind );
689
690        //! Get val for myself from val of "Up"
691        vec pushdown ( const vec &val_up ) {
692                vec tmp ( downsize );
693                filldown ( val_up, tmp );
694                return tmp;
695        }
696        //! Get val for vector val_down from val of "Up"
697        virtual void filldown ( const vec &val_up, vec &val_down ) {
698                bdm_assert_debug ( upsize == val_up.length(), "Wrong val_up" );
699                val_down = val_up ( v2v_up );
700        }
701        //! Fill val of "Up" by my pieces
702        virtual void pushup ( vec &val_up, const vec &val ) {
703                bdm_assert_debug ( downsize == val.length(), "Wrong val" );
704                bdm_assert_debug ( upsize == val_up.length(), "Wrong val_up" );
705                set_subvector ( val_up, v2v_up, val );
706        }
707        //! access functions
708        int _upsize() {
709                return upsize;
710        }
711        //! access functions
712        int _downsize() {
713                return downsize;
714        }
715        //! for future use
716        virtual ~datalink() {}
717};
718
719/*! Extension of datalink to fill only part of Down
720*/
721class datalink_part : public datalink {
722protected:
723        //! indeces of values in vector downsize
724        ivec v2v_down;
725public:
726        void set_connection ( const RV &rv, const RV &rv_up );
727        //! Get val for vector val_down from val of "Up"
728        void filldown ( const vec &val_up, vec &val_down ) {
729                set_subvector ( val_down, v2v_down, val_up ( v2v_up ) );
730        }
731};
732
733/*! \brief Datalink that buffers delayed values - do not forget to call step()
734
735Up is current data, Down is their subset with possibly delayed values
736*/
737class datalink_buffered: public datalink_part {
738protected:
739        //! History, ordered as \f$[Up_{t-1},Up_{t-2}, \ldots]\f$
740        vec history;
741        //! rv of the history
742        RV Hrv;
743        //! h2v : indeces in down
744        ivec h2v_down;
745        //! h2v : indeces in history
746        ivec h2v_hist;
747        //! v2h: indeces of up too be pushed to h
748        ivec v2h_up;
749public:
750
751        datalink_buffered() : datalink_part(), history ( 0 ), h2v_down ( 0 ), h2v_hist ( 0 ) {};
752        //! push current data to history
753        void store_data ( const vec &val_up ) {
754                if ( v2h_up.length() > 0 ) {
755                        history.shift_right ( 0, v2h_up.length() );
756                        history.set_subvector ( 0, val_up ( v2h_up ) );
757                }
758        }
759        //! Get val for myself from val of "Up"
760        vec pushdown ( const vec &val_up ) {
761                vec tmp ( downsize );
762                filldown ( val_up, tmp );
763                return tmp;
764        }
765
766        void filldown ( const vec &val_up, vec &val_down ) {
767                bdm_assert_debug ( val_down.length() >= downsize, "short val_down" );
768
769                set_subvector ( val_down, v2v_down, val_up ( v2v_up ) ); // copy direct values
770                set_subvector ( val_down, h2v_down, history ( h2v_hist ) ); // copy delayed values
771        }
772
773        void set_connection ( const RV &rv, const RV &rv_up );
774       
775        //! set history of variable given by \c rv1 to values of \c hist.
776        void set_history ( const RV& rv1, const vec &hist0 );
777};
778
779//! buffered datalink from 2 vectors to 1
780class datalink_2to1_buffered {
781protected:
782        //! link 1st vector to down
783        datalink_buffered dl1;
784        //! link 2nd vector to down
785        datalink_buffered dl2;
786public:
787        //! set connection between RVs
788        void set_connection ( const RV &rv, const RV &rv_up1, const RV &rv_up2 ) {
789                dl1.set_connection ( rv, rv_up1 );
790                dl2.set_connection ( rv, rv_up2 );
791        }
792        //! fill values of down from the values of the two up vectors
793        void filldown ( const vec &val1, const vec &val2, vec &val_down ) {
794                bdm_assert_debug ( val_down.length() >= dl1._downsize() + dl2._downsize(), "short val_down" );
795                dl1.filldown ( val1, val_down );
796                dl2.filldown ( val2, val_down );
797        }
798        //! update buffer
799        void step ( const vec &dt, const vec &ut ) {
800                dl1.store_data ( dt );
801                dl2.store_data ( ut );
802        }
803};
804
805
806
807//! Data link with a condition.
808class datalink_m2e: public datalink {
809protected:
810        //! Remember how long cond should be
811        int condsize;
812
813        //!upper_val-to-local_cond link, indices of the upper val
814        ivec v2c_up;
815
816        //!upper_val-to-local_cond link, indices of the local cond
817        ivec v2c_lo;
818
819public:
820        //! Constructor
821        datalink_m2e() : condsize ( 0 ) { }
822
823        //! Set connection between vectors
824        void set_connection ( const RV &rv, const RV &rvc, const RV &rv_up );
825
826        //!Construct condition
827        vec get_cond ( const vec &val_up );
828
829        //! Copy corresponding values to Up.condition
830        void pushup_cond ( vec &val_up, const vec &val, const vec &cond );
831};
832
833//!DataLink is a connection between pdf and its superordinate (Up)
834//! This class links
835class datalink_m2m: public datalink_m2e {
836protected:
837        //!cond-to-cond link, indices of the upper cond
838        ivec c2c_up;
839        //!cond-to-cond link, indices of the local cond
840        ivec c2c_lo;
841
842public:
843        //! Constructor
844        datalink_m2m() {};
845        //! Set connection between the vectors
846        void set_connection ( const RV &rv, const RV &rvc, const RV &rv_up, const RV &rvc_up ) {
847                datalink_m2e::set_connection ( rv, rvc, rv_up );
848                //establish c2c connection
849                rvc.dataind ( rvc_up, c2c_lo, c2c_up );
850//              bdm_assert_debug ( c2c_lo.length() + v2c_lo.length() == condsize, "cond is not fully given" );
851        }
852
853        //! Get cond for myself from val and cond of "Up"
854        vec get_cond ( const vec &val_up, const vec &cond_up ) {
855                vec tmp ( condsize );
856                fill_cond ( val_up, cond_up, tmp );
857                return tmp;
858        }
859        //! fill condition
860        void fill_cond ( const vec &val_up, const vec &cond_up, vec& cond_out ) {
861                bdm_assert_debug ( cond_out.length() >= condsize, "dl.fill_cond: cond_out is too small" );
862                set_subvector ( cond_out, v2c_lo, val_up ( v2c_up ) );
863                set_subvector ( cond_out, c2c_lo, cond_up ( c2c_up ) );
864        }
865        //! Fill
866
867};
868
869
870//! \brief Combines RVs from a list of pdfs to a single one.
871RV get_composite_rv ( const Array<shared_ptr<pdf> > &pdfs, bool checkoverlap = false );
872
873/*! \brief Abstract class for discrete-time sources of data.
874
875The class abstracts operations of:
876\li  data aquisition,
877\li  data-preprocessing, such as  scaling of data,
878\li  data resampling from the task of estimation and control.
879Moreover, for controlled systems, it is able to receive the desired control action and perform it in the next step. (Or as soon as possible).
880
881The DataSource has three main data interaction structures:
882\li input, \f$ u_t \f$,
883\li output \f$ y_t \f$,
884\li data, \f$ d_t=[y_t,u_t, \ldots ]\f$ a collection of all inputs and outputs and possibly some internal variables too.
885
886*/
887
888class DS : public root {
889protected:
890        //! size of data returned by \c getdata()
891        int dtsize;
892        //! size of data
893        int utsize;
894        //!size of output
895        int ytsize;
896        //!Description of data returned by \c getdata().
897        RV Drv;
898        //!Description of data witten by by \c write().
899        RV Urv; //
900        //!Description of output data
901        RV Yrv; //
902public:
903        //! default constructors
904        DS() : dtsize ( 0 ), utsize ( 0 ), ytsize ( 0 ), Drv(), Urv(), Yrv() {
905                log_level = 1;
906        };
907
908        //! Returns maximum number of provided data, by default it is set to maximum allowed length, shorter DS should overload this method! See, MemDS.max_length().
909        virtual int max_length() {
910                return std::numeric_limits< int >::max();
911        }
912        //! Returns full vector of observed data=[output, input]
913        virtual void getdata ( vec &dt ) const = 0;
914
915        //! Returns data records at indeces. Default is inefficent.
916        virtual void getdata ( vec &dt, const ivec &indeces ) {
917                vec tmp(dtsize);
918                getdata(tmp);
919                dt = tmp(indeces);
920        };
921
922        //! Accepts action variable and schedule it for application.   
923        virtual void write ( const vec &ut ) NOT_IMPLEMENTED_VOID;
924
925        //! Accepts action variables at specific indeces
926        virtual void write ( const vec &ut, const ivec &indeces ) NOT_IMPLEMENTED_VOID;
927
928        //! Moves from \f$ t \f$ to \f$ t+1 \f$, i.e. perfroms the actions and reads response of the system.
929        virtual void step() = 0;
930
931        //! Register DS for logging into logger L
932        virtual void log_register ( logger &L,  const string &prefix );
933        //! Register DS for logging into logger L
934        virtual void log_write ( ) const;
935        //!access function
936        virtual const RV& _drv() const {
937                return Drv;
938        }
939        //!access function
940        const RV& _urv() const {
941                return Urv;
942        }
943        //!access function
944        const RV& _yrv() const {
945                return Yrv;
946        }
947        //! set random variables
948        virtual void set_drv ( const  RV &yrv, const RV &urv ) {
949                Yrv = yrv;
950                Drv = concat ( yrv, urv );
951                Urv = urv;
952        }
953};
954
955/*! \brief Bayesian Model of a system, i.e. all uncertainty is modeled by probabilities.
956
957This object represents exact or approximate evaluation of the Bayes rule:
958\f[
959f(\theta_t | y_1,\ldots,y_t, u_1,\ldots,u_t) = \frac{f(y_t|\theta_t,\cdot) f(\theta_t|d_1,\ldots,d_{t-1})}{f(y_t|d_1,\ldots,d_{t-1})}
960\f]
961where:
962 * \f$ y_t \f$ is the variable
963Access to the resulting posterior density is via function \c posterior().
964
965As a "side-effect" it also evaluates log-likelihood of the data, which can be accessed via function _ll().
966It can also evaluate predictors of future values of \f$y_t\f$, see functions epredictor() and predictor().
967
968Alternatively, it can evaluate posterior density with rvc replaced by the given values, \f$ c_t \f$:
969\f[
970f(\theta_t | c_t, d_1,\ldots,d_t) \propto  f(y_t,\theta_t|c_t,\cdot, d_1,\ldots,d_{t-1})
971\f]
972
973
974*/
975
976class BM : public root {
977protected:
978        //! Random variable of the data (optional)
979        RV yrv;
980        //! size of the data record
981        int dimy;
982        //! Name of extension variable
983        RV rvc;
984        //! size of the conditioning vector
985        int dimc;
986
987        //!Logarithm of marginalized data likelihood.
988        double ll;
989        //!  If true, the filter will compute likelihood of the data record and store it in \c ll . Set to false if you want to save computational time.
990        bool evalll;
991
992public:
993        //! \name Constructors
994        //! @{
995
996        BM() : yrv(), dimy ( 0 ), rvc(), dimc ( 0 ), ll ( 0 ), evalll ( true ) { };
997//      BM ( const BM &B ) :  yrv ( B.yrv ), dimy(B.dimy), rvc ( B.rvc ),dimc(B.dimc), ll ( B.ll ), evalll ( B.evalll ) {}
998        //! \brief Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually!
999        //! Prototype: \code BM* _copy() const {return new BM(*this);} \endcode
1000        virtual BM* _copy() const {             return NULL;    }; // TODO NEBUDE TU TAKY LEPSI BDM_ERROR??!
1001        //!@}
1002
1003        //! \name Mathematical operations
1004        //!@{
1005
1006        /*! \brief Incremental Bayes rule
1007        @param dt vector of input data
1008        */
1009        virtual void bayes ( const vec &yt, const vec &cond = empty_vec ) = 0;
1010        //! Batch Bayes rule (columns of Dt are observations)
1011        virtual void bayes_batch ( const mat &Dt, const vec &cond = empty_vec );
1012        //! Batch Bayes rule (columns of Dt are observations, columns of Cond are conditions)
1013        virtual void bayes_batch ( const mat &Dt, const mat &Cond );
1014        //! Evaluates predictive log-likelihood of the given data record
1015        //! I.e. marginal likelihood of the data with the posterior integrated out.
1016        //! This function evaluates only \f$ y_t \f$, condition is assumed to be the last used in bayes().
1017        //! See bdm::BM::predictor for conditional version.
1018        virtual double logpred ( const vec &yt ) const = 0;
1019
1020        //! Matrix version of logpred
1021        vec logpred_mat ( const mat &Yt ) const {
1022                vec tmp ( Yt.cols() );
1023                for ( int i = 0; i < Yt.cols(); i++ ) {
1024                        tmp ( i ) = logpred ( Yt.get_col ( i ) );
1025                }
1026                return tmp;
1027        }
1028
1029        //!Constructs a predictive density \f$ f(d_{t+1} |d_{t}, \ldots d_{0}) \f$
1030        virtual epdf* epredictor() const = 0;
1031
1032        //!Constructs conditional density of 1-step ahead predictor \f$ f(d_{t+1} |d_{t+h-1}, \ldots d_{t}) \f$
1033        virtual pdf* predictor() const = 0;
1034
1035        //!@}
1036
1037
1038        //! \name Access to attributes
1039        //!@{
1040        //! access function
1041        const RV& _rvc() const {
1042                return rvc;
1043        }
1044        //! access function
1045        int dimensionc() const {
1046                return dimc;
1047        }
1048        //! access function
1049        int dimensiony() const {
1050                return dimy;
1051        }
1052        //! access function
1053        int dimension() const {
1054                return posterior().dimension();
1055        }
1056        //! access function
1057        const RV& _yrv() const {
1058                return yrv;
1059        }
1060        //! access function
1061        void set_yrv ( const RV &rv ) {
1062                yrv = rv;
1063        }
1064        //! access function
1065        void set_rvc ( const RV &rv ) {
1066                rvc = rv;
1067        }
1068        //! access to rv of the posterior
1069        void set_rv ( const RV &rv ) {
1070                const_cast<epdf&> ( posterior() ).set_rv ( rv );
1071        }
1072        //! access function
1073        void set_dim ( int dim ) {
1074                const_cast<epdf&> ( posterior() ).set_dim ( dim );
1075        }
1076        //! return internal log-likelihood of the last data vector
1077        double _ll() const {
1078                return ll;
1079        }
1080        //! switch evaluation of log-likelihood on/off
1081        void set_evalll ( bool evl0 ) {
1082                evalll = evl0;
1083        }
1084        //! return posterior density
1085        virtual const epdf& posterior() const = 0;
1086        //!@}
1087
1088        //! \name Logging of results
1089        //!@{
1090
1091        //! Set boolean options from a string, recognized are: "logbounds,logll"
1092        virtual void set_options ( const string &opt );
1093
1094        //! Add all logged variables to a logger
1095        //! Log levels two digits: xy where
1096        //!  * y = 0/1 log-likelihood is to be logged
1097        //!  * x = level of the posterior (typically 0/1/2 for nothing/mean/bounds)
1098        virtual void log_register ( logger &L, const string &prefix = "" );
1099
1100        //! Save results to the given logger, details of what is stored is configured by \c LIDs and \c options
1101        virtual void log_write ( ) const;
1102
1103        //!@}
1104        void from_setting ( const Setting &set ) {
1105                shared_ptr<RV> r = UI::build<RV> ( set, "yrv", UI::optional );
1106                if ( r ) {
1107                        set_yrv ( *r );
1108                }
1109                shared_ptr<RV> r2 = UI::build<RV> ( set, "rvc", UI::optional );
1110                if ( r2 ) {
1111                        rvc =   *r2;
1112                }
1113                shared_ptr<RV> r3 = UI::build<RV> ( set, "rv", UI::optional );
1114                if ( r3 ) {
1115                        set_rv ( *r3 );
1116                }
1117
1118                string opt;
1119                if ( UI::get ( opt, set, "options", UI::optional ) ) {
1120                        set_options ( opt );
1121                }
1122        }
1123
1124        void to_setting ( Setting &set ) const {
1125                root::to_setting( set );
1126                UI::save( &yrv, set, "yrv" );
1127                UI::save( &rvc, set, "rvc" );           
1128                UI::save( &posterior()._rv(), set, "rv" );
1129
1130                string opt;
1131                switch( posterior()._log_level() )
1132                {
1133                case 2:
1134                        opt = "logbounds ";
1135                        break;
1136                case 10:
1137                        opt = "logfull ";
1138                        break;
1139                default:
1140                        opt = "";
1141                        break;
1142                }
1143                if( log_level == 1 ) opt = opt + "logll";
1144                if( !opt.empty() )
1145                        UI::save( opt, set, "options" );
1146        }
1147};
1148
1149//! array of pointers to epdf
1150typedef Array<shared_ptr<epdf> > epdf_array;
1151//! array of pointers to pdf
1152typedef Array<shared_ptr<pdf> > pdf_array;
1153
1154template<class EPDF>
1155vec pdf_internal<EPDF>::samplecond ( const vec &cond ) {
1156        condition ( cond );
1157        vec temp = iepdf.sample();
1158        return temp;
1159}
1160
1161template<class EPDF>
1162mat pdf_internal<EPDF>::samplecond_mat ( const vec &cond, int N ) {
1163        condition ( cond );
1164        mat temp ( dimension(), N );
1165        vec smp ( dimension() );
1166        for ( int i = 0; i < N; i++ ) {
1167                smp = iepdf.sample();
1168                temp.set_col ( i, smp );
1169        }
1170
1171        return temp;
1172}
1173
1174template<class EPDF>
1175double pdf_internal<EPDF>::evallogcond ( const vec &yt, const vec &cond ) {
1176        double tmp;
1177        condition ( cond );
1178        tmp = iepdf.evallog ( yt );
1179        return tmp;
1180}
1181
1182template<class EPDF>
1183vec pdf_internal<EPDF>::evallogcond_mat ( const mat &Yt, const vec &cond ) {
1184        condition ( cond );
1185        return iepdf.evallog_mat ( Yt );
1186}
1187
1188template<class EPDF>
1189vec pdf_internal<EPDF>::evallogcond_mat ( const Array<vec> &Yt, const vec &cond ) {
1190        condition ( cond );
1191        return iepdf.evallog_mat ( Yt );
1192}
1193
1194}; //namespace
1195#endif // BDMBASE_H
Note: See TracBrowser for help on using the browser.