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

Revision 768, 32.4 kB (checked in by mido, 14 years ago)

minor changes, BM::to_setting improved (BUT NOT TESTED)

  • 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        //! function substitutes given value into an appropriate position
364        virtual void condition ( const vec &val ) {};
365
366        //! access function
367        int dimension() const {
368                return dimy;
369        }
370        //! access function
371        int dimensionc() const {
372                return dimc;
373        }
374};
375
376class epdf;
377
378//! 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.
379class pdf : public root {
380protected:
381        //!dimension of the condition
382        int dimc;
383
384        //! random variable in condition
385        RV rvc;
386
387        //! dimension of random variable
388        int dim;
389
390        //! random variable
391        RV rv;
392
393public:
394        //! \name Constructors
395        //! @{
396
397        pdf() : dimc ( 0 ), rvc(), dim ( 0 ), rv() { }
398
399        pdf ( const pdf &m ) : dimc ( m.dimc ), rvc ( m.rvc ), dim ( m.dim ), rv ( m.rv ) { }
400
401        //!@}
402
403        //! \name Matematical operations
404        //!@{
405
406        //! 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
407        virtual vec samplecond ( const vec &cond ) = 0;
408
409        //! 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
410        virtual mat samplecond_mat ( const vec &cond, int N );
411
412        //! Shortcut for conditioning and evaluation of the internal epdf. In some cases,  this operation can be implemented efficiently.
413        virtual double evallogcond ( const vec &yt, const vec &cond ) = 0;
414
415        //! Matrix version of evallogcond
416        virtual vec evallogcond_mat ( const mat &Yt, const vec &cond ) {
417                vec v ( Yt.cols() );
418                for ( int i = 0; i < Yt.cols(); i++ ) {
419                        v ( i ) = evallogcond ( Yt.get_col ( i ), cond );
420                }
421                return v;
422        }
423
424        //! Array<vec> version of evallogcond
425        virtual vec evallogcond_mat ( const Array<vec> &Yt, const vec &cond ) {
426                vec v ( Yt.length() );
427                for ( int i = 0; i < Yt.length(); i++ ) {
428                        v ( i ) = evallogcond ( Yt( i ), cond );
429                }
430                return v;
431        }
432
433        //! \name Access to attributes
434        //! @{
435
436        const RV& _rv() const {
437                return rv;
438        }
439        const RV& _rvc() const {
440                return rvc;
441        }
442
443        int dimension() const {
444                return dim;
445        }
446        int dimensionc() {
447                return dimc;
448        }
449
450        //! access function
451        void set_dim ( int d ) {
452                dim = d;
453        }
454        //! access function
455        void set_dimc ( int d ) {
456                dimc = d;
457        }
458        //! Load from structure with elements:
459        //!  \code
460        //! { class = "pdf_offspring",
461        //!   rv = {class="RV", names=(...),}; // RV describing meaning of random variable
462        //!   rvc= {class="RV", names=(...),}; // RV describing meaning of random variable in condition
463        //!   // elements of offsprings
464        //! }
465        //! \endcode
466        //!@}
467        void from_setting ( const Setting &set );
468
469        void to_setting ( Setting &set ) const;
470        //!@}
471
472        //! \name Connection to other objects
473        //!@{
474        void set_rvc ( const RV &rvc0 ) {
475                rvc = rvc0;
476        }
477        void set_rv ( const RV &rv0 ) {
478                rv = rv0;
479        }
480
481        bool isnamed() const {
482                return ( dim == rv._dsize() ) && ( dimc == rvc._dsize() );
483        }
484        //!@}
485};
486SHAREDPTR ( pdf );
487
488//! Probability density function with numerical statistics, e.g. posterior density.
489class epdf : public pdf {
490
491public:
492        /*! \name Constructors
493         Construction of each epdf should support two types of constructors:
494        \li empty constructor,
495        \li copy constructor,
496
497        The following constructors should be supported for convenience:
498        \li constructor followed by calling \c set_parameters()
499        \li constructor accepting random variables calling \c set_rv()
500
501         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.
502        @{*/
503        epdf() {};
504        epdf ( const epdf &e ) : pdf ( e ) {};
505       
506        virtual void    validate (int dim0){
507                dim = dim0;
508        }
509       
510        //!@}
511
512        //! \name Matematical Operations
513        //!@{
514
515        //! Returns a sample, \f$ x \f$ from density \f$ f_x()\f$
516        virtual vec sample() const = 0;
517
518        //! Returns N samples, \f$ [x_1 , x_2 , \ldots \ \f$  from density \f$ f_x(rv)\f$
519        virtual mat sample_mat ( int N ) const;
520
521        //! Compute log-probability of argument \c val
522        //! In case the argument is out of suport return -Infinity
523        virtual double evallog ( const vec &val ) const = 0;
524       
525        //! Compute log-probability of multiple values argument \c val
526        virtual vec evallog_mat ( const mat &Val ) const;
527
528        //! Compute log-probability of multiple values argument \c val
529        virtual vec evallog_mat ( const Array<vec> &Avec ) const;
530
531        //! Return conditional density on the given RV, the remaining rvs will be in conditioning
532        virtual shared_ptr<pdf> condition ( const RV &rv ) const;
533
534        //! Return marginal density on the given RV, the remainig rvs are intergrated out
535        virtual shared_ptr<epdf> marginal ( const RV &rv ) const;
536
537        virtual vec mean() const = 0;
538
539        //! return expected variance (not covariance!)
540        virtual vec variance() const = 0;
541
542        //! Lower and upper bounds of \c percentage % quantile, returns mean-2*sigma as default
543        virtual void qbounds ( vec &lb, vec &ub, double percentage = 0.95 ) const {
544                vec mea = mean();
545                vec std = sqrt ( variance() );
546                lb = mea - 2 * std;
547                ub = mea + 2 * std;
548        };
549        //!@}
550
551        //! \name Connection to other classes
552        //! Description of the random quantity via attribute \c rv is optional.
553        //! For operations such as sampling \c rv does not need to be set. However, for \c marginalization
554        //! and \c conditioning \c rv has to be set. NB:
555        //! @{
556
557        //! store values of the epdf on the following levels:
558        //!  #1 mean
559        //!  #2 mean + lower & upper bound
560        void log_register ( logger &L, const string &prefix );
561
562        void log_write() const;
563        //!@}
564
565        //! \name Access to attributes
566        //! @{
567
568        //! Load from structure with elements:
569        //!  \code
570        //! { rv = {class="RV", names=(...),}; // RV describing meaning of random variable
571        //!   // elements of offsprings
572        //! }
573        //! \endcode
574        //!@}
575        void from_setting ( const Setting &set ) {
576                shared_ptr<RV> r = UI::build<RV> ( set, "rv", UI::optional );
577                if ( r ) {
578                        set_rv ( *r );
579                }
580        }
581
582        void to_setting ( Setting &set ) const {
583                // we do not want to store rvc, therfore, pdf::to_setting( set ) is omitted
584                root::to_setting(set);
585
586                UI::save( &rv, set, "rv" );
587        }
588
589        vec samplecond ( const vec &cond ) {
590                return sample();
591        }
592        double evallogcond ( const vec &val, const vec &cond ) {
593                return evallog ( val );
594        }
595};
596SHAREDPTR ( epdf );
597
598//! pdf with internal epdf that is modified by function \c condition
599template <class EPDF>
600class pdf_internal: public pdf {
601protected :
602        //! Internal epdf used for sampling
603        EPDF iepdf;
604public:
605        //! constructor
606        pdf_internal() : pdf(), iepdf() {
607        }
608
609        //! Update \c iepdf so that it represents this pdf conditioned on \c rvc = cond
610        //! This function provides convenient reimplementation in offsprings
611        virtual void condition ( const vec &cond ) = 0;
612
613        //!access function to iepdf
614        EPDF& e() {
615                return iepdf;
616        }
617
618        //! Reimplements samplecond using \c condition()
619        vec samplecond ( const vec &cond );
620        //! Reimplements evallogcond using \c condition()
621        double evallogcond ( const vec &val, const vec &cond );
622        //! Efficient version of evallogcond for matrices
623        virtual vec evallogcond_mat ( const mat &Dt, const vec &cond );
624        //! Efficient version of evallogcond for Array<vec>
625        virtual vec evallogcond_mat ( const Array<vec> &Dt, const vec &cond );
626        //! Efficient version of samplecond
627        virtual mat samplecond_mat ( const vec &cond, int N );
628
629        void validate() {
630                iepdf.validate();
631                if ( rv._dsize() < iepdf._rv()._dsize() ) {
632                        rv = iepdf._rv();
633                };
634                dim = iepdf.dimension();
635        }
636};
637
638/*! \brief DataLink is a connection between two data vectors Up and Down
639
640Up can be longer than Down. Down must be fully present in Up (TODO optional)
641See chart:
642\dot
643digraph datalink {
644  node [shape=record];
645  subgraph cluster0 {
646    label = "Up";
647      up [label="<1>|<2>|<3>|<4>|<5>"];
648    color = "white"
649}
650  subgraph cluster1{
651    label = "Down";
652    labelloc = b;
653      down [label="<1>|<2>|<3>"];
654    color = "white"
655}
656    up:1 -> down:1;
657    up:3 -> down:2;
658    up:5 -> down:3;
659}
660\enddot
661
662*/
663class datalink {
664protected:
665        //! Remember how long val should be
666        int downsize;
667
668        //! Remember how long val of "Up" should be
669        int upsize;
670
671        //! val-to-val link, indices of the upper val
672        ivec v2v_up;
673
674public:
675        //! Constructor
676        datalink() : downsize ( 0 ), upsize ( 0 ) { }
677
678        //! Convenience constructor
679        datalink ( const RV &rv, const RV &rv_up ) {
680                set_connection ( rv, rv_up );
681        }
682
683        //! set connection, rv must be fully present in rv_up
684        virtual void set_connection ( const RV &rv, const RV &rv_up );
685
686        //! set connection using indices
687        virtual void set_connection ( int ds, int us, const ivec &upind );
688
689        //! Get val for myself from val of "Up"
690        vec pushdown ( const vec &val_up ) {
691                vec tmp ( downsize );
692                filldown ( val_up, tmp );
693                return tmp;
694        }
695        //! Get val for vector val_down from val of "Up"
696        virtual void filldown ( const vec &val_up, vec &val_down ) {
697                bdm_assert_debug ( upsize == val_up.length(), "Wrong val_up" );
698                val_down = val_up ( v2v_up );
699        }
700        //! Fill val of "Up" by my pieces
701        virtual void pushup ( vec &val_up, const vec &val ) {
702                bdm_assert_debug ( downsize == val.length(), "Wrong val" );
703                bdm_assert_debug ( upsize == val_up.length(), "Wrong val_up" );
704                set_subvector ( val_up, v2v_up, val );
705        }
706        //! access functions
707        int _upsize() {
708                return upsize;
709        }
710        //! access functions
711        int _downsize() {
712                return downsize;
713        }
714        //! for future use
715        virtual ~datalink() {}
716};
717
718/*! Extension of datalink to fill only part of Down
719*/
720class datalink_part : public datalink {
721protected:
722        //! indeces of values in vector downsize
723        ivec v2v_down;
724public:
725        void set_connection ( const RV &rv, const RV &rv_up );
726        //! Get val for vector val_down from val of "Up"
727        void filldown ( const vec &val_up, vec &val_down ) {
728                set_subvector ( val_down, v2v_down, val_up ( v2v_up ) );
729        }
730};
731
732/*! \brief Datalink that buffers delayed values - do not forget to call step()
733
734Up is current data, Down is their subset with possibly delayed values
735*/
736class datalink_buffered: public datalink_part {
737protected:
738        //! History, ordered as \f$[Up_{t-1},Up_{t-2}, \ldots]\f$
739        vec history;
740        //! rv of the history
741        RV Hrv;
742        //! h2v : indeces in down
743        ivec h2v_down;
744        //! h2v : indeces in history
745        ivec h2v_hist;
746        //! v2h: indeces of up too be pushed to h
747        ivec v2h_up;
748public:
749
750        datalink_buffered() : datalink_part(), history ( 0 ), h2v_down ( 0 ), h2v_hist ( 0 ) {};
751        //! push current data to history
752        void store_data ( const vec &val_up ) {
753                if ( v2h_up.length() > 0 ) {
754                        history.shift_right ( 0, v2h_up.length() );
755                        history.set_subvector ( 0, val_up ( v2h_up ) );
756                }
757        }
758        //! Get val for myself from val of "Up"
759        vec pushdown ( const vec &val_up ) {
760                vec tmp ( downsize );
761                filldown ( val_up, tmp );
762                return tmp;
763        }
764
765        void filldown ( const vec &val_up, vec &val_down ) {
766                bdm_assert_debug ( val_down.length() >= downsize, "short val_down" );
767
768                set_subvector ( val_down, v2v_down, val_up ( v2v_up ) ); // copy direct values
769                set_subvector ( val_down, h2v_down, history ( h2v_hist ) ); // copy delayed values
770        }
771
772        void set_connection ( const RV &rv, const RV &rv_up );
773       
774        //! set history of variable given by \c rv1 to values of \c hist.
775        void set_history ( const RV& rv1, const vec &hist0 );
776};
777
778//! buffered datalink from 2 vectors to 1
779class datalink_2to1_buffered {
780protected:
781        //! link 1st vector to down
782        datalink_buffered dl1;
783        //! link 2nd vector to down
784        datalink_buffered dl2;
785public:
786        //! set connection between RVs
787        void set_connection ( const RV &rv, const RV &rv_up1, const RV &rv_up2 ) {
788                dl1.set_connection ( rv, rv_up1 );
789                dl2.set_connection ( rv, rv_up2 );
790        }
791        //! fill values of down from the values of the two up vectors
792        void filldown ( const vec &val1, const vec &val2, vec &val_down ) {
793                bdm_assert_debug ( val_down.length() >= dl1._downsize() + dl2._downsize(), "short val_down" );
794                dl1.filldown ( val1, val_down );
795                dl2.filldown ( val2, val_down );
796        }
797        //! update buffer
798        void step ( const vec &dt, const vec &ut ) {
799                dl1.store_data ( dt );
800                dl2.store_data ( ut );
801        }
802};
803
804
805
806//! Data link with a condition.
807class datalink_m2e: public datalink {
808protected:
809        //! Remember how long cond should be
810        int condsize;
811
812        //!upper_val-to-local_cond link, indices of the upper val
813        ivec v2c_up;
814
815        //!upper_val-to-local_cond link, indices of the local cond
816        ivec v2c_lo;
817
818public:
819        //! Constructor
820        datalink_m2e() : condsize ( 0 ) { }
821
822        //! Set connection between vectors
823        void set_connection ( const RV &rv, const RV &rvc, const RV &rv_up );
824
825        //!Construct condition
826        vec get_cond ( const vec &val_up );
827
828        //! Copy corresponding values to Up.condition
829        void pushup_cond ( vec &val_up, const vec &val, const vec &cond );
830};
831
832//!DataLink is a connection between pdf and its superordinate (Up)
833//! This class links
834class datalink_m2m: public datalink_m2e {
835protected:
836        //!cond-to-cond link, indices of the upper cond
837        ivec c2c_up;
838        //!cond-to-cond link, indices of the local cond
839        ivec c2c_lo;
840
841public:
842        //! Constructor
843        datalink_m2m() {};
844        //! Set connection between the vectors
845        void set_connection ( const RV &rv, const RV &rvc, const RV &rv_up, const RV &rvc_up ) {
846                datalink_m2e::set_connection ( rv, rvc, rv_up );
847                //establish c2c connection
848                rvc.dataind ( rvc_up, c2c_lo, c2c_up );
849//              bdm_assert_debug ( c2c_lo.length() + v2c_lo.length() == condsize, "cond is not fully given" );
850        }
851
852        //! Get cond for myself from val and cond of "Up"
853        vec get_cond ( const vec &val_up, const vec &cond_up ) {
854                vec tmp ( condsize );
855                fill_cond ( val_up, cond_up, tmp );
856                return tmp;
857        }
858        //! fill condition
859        void fill_cond ( const vec &val_up, const vec &cond_up, vec& cond_out ) {
860                bdm_assert_debug ( cond_out.length() >= condsize, "dl.fill_cond: cond_out is too small" );
861                set_subvector ( cond_out, v2c_lo, val_up ( v2c_up ) );
862                set_subvector ( cond_out, c2c_lo, cond_up ( c2c_up ) );
863        }
864        //! Fill
865
866};
867
868
869//! \brief Combines RVs from a list of pdfs to a single one.
870RV get_composite_rv ( const Array<shared_ptr<pdf> > &pdfs, bool checkoverlap = false );
871
872/*! \brief Abstract class for discrete-time sources of data.
873
874The class abstracts operations of:
875\li  data aquisition,
876\li  data-preprocessing, such as  scaling of data,
877\li  data resampling from the task of estimation and control.
878Moreover, for controlled systems, it is able to receive the desired control action and perform it in the next step. (Or as soon as possible).
879
880The DataSource has three main data interaction structures:
881\li input, \f$ u_t \f$,
882\li output \f$ y_t \f$,
883\li data, \f$ d_t=[y_t,u_t, \ldots ]\f$ a collection of all inputs and outputs and possibly some internal variables too.
884
885*/
886
887class DS : public root {
888protected:
889        //! size of data returned by \c getdata()
890        int dtsize;
891        //! size of data
892        int utsize;
893        //!size of output
894        int ytsize;
895        //!Description of data returned by \c getdata().
896        RV Drv;
897        //!Description of data witten by by \c write().
898        RV Urv; //
899        //!Description of output data
900        RV Yrv; //
901public:
902        //! default constructors
903        DS() : dtsize ( 0 ), utsize ( 0 ), ytsize ( 0 ), Drv(), Urv(), Yrv() {
904                log_level = 1;
905        };
906
907        //! 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().
908        virtual int max_length() {
909                return std::numeric_limits< int >::max();
910        }
911        //! Returns full vector of observed data=[output, input]
912        virtual void getdata ( vec &dt ) const = 0;
913
914        //! Returns data records at indeces.
915        virtual void getdata ( vec &dt, const ivec &indeces ) = 0;
916
917        //! Accepts action variable and schedule it for application.   
918        virtual void write ( const vec &ut ) = 0;
919
920        //! Accepts action variables at specific indeces
921        virtual void write ( const vec &ut, const ivec &indeces ) = 0;
922
923        //! Moves from \f$ t \f$ to \f$ t+1 \f$, i.e. perfroms the actions and reads response of the system.
924        virtual void step() = 0;
925
926        //! Register DS for logging into logger L
927        virtual void log_register ( logger &L,  const string &prefix );
928        //! Register DS for logging into logger L
929        virtual void log_write ( ) const;
930        //!access function
931        virtual const RV& _drv() const {
932                return Drv;
933        }
934        //!access function
935        const RV& _urv() const {
936                return Urv;
937        }
938        //!access function
939        const RV& _yrv() const {
940                return Yrv;
941        }
942        //! set random variables
943        virtual void set_drv ( const  RV &yrv, const RV &urv ) {
944                Yrv = yrv;
945                Drv = concat ( yrv, urv );
946                Urv = urv;
947        }
948};
949
950/*! \brief Bayesian Model of a system, i.e. all uncertainty is modeled by probabilities.
951
952This object represents exact or approximate evaluation of the Bayes rule:
953\f[
954f(\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})}
955\f]
956where:
957 * \f$ y_t \f$ is the variable
958Access to the resulting posterior density is via function \c posterior().
959
960As a "side-effect" it also evaluates log-likelihood of the data, which can be accessed via function _ll().
961It can also evaluate predictors of future values of \f$y_t\f$, see functions epredictor() and predictor().
962
963Alternatively, it can evaluate posterior density with rvc replaced by the given values, \f$ c_t \f$:
964\f[
965f(\theta_t | c_t, d_1,\ldots,d_t) \propto  f(y_t,\theta_t|c_t,\cdot, d_1,\ldots,d_{t-1})
966\f]
967
968
969*/
970
971class BM : public root {
972protected:
973        //! Random variable of the data (optional)
974        RV yrv;
975        //! size of the data record
976        int dimy;
977        //! Name of extension variable
978        RV rvc;
979        //! size of the conditioning vector
980        int dimc;
981
982        //!Logarithm of marginalized data likelihood.
983        double ll;
984        //!  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.
985        bool evalll;
986
987public:
988        //! \name Constructors
989        //! @{
990
991        BM() : yrv(), dimy ( 0 ), rvc(), dimc ( 0 ), ll ( 0 ), evalll ( true ) { };
992//      BM ( const BM &B ) :  yrv ( B.yrv ), dimy(B.dimy), rvc ( B.rvc ),dimc(B.dimc), ll ( B.ll ), evalll ( B.evalll ) {}
993        //! \brief Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually!
994        //! Prototype: \code BM* _copy() const {return new BM(*this);} \endcode
995        virtual BM* _copy() const {             return NULL;    }; // TODO NEBUDE TU TAKY LEPSI BDM_ERROR??!
996        //!@}
997
998        //! \name Mathematical operations
999        //!@{
1000
1001        /*! \brief Incremental Bayes rule
1002        @param dt vector of input data
1003        */
1004        virtual void bayes ( const vec &yt, const vec &cond = empty_vec ) = 0;
1005        //! Batch Bayes rule (columns of Dt are observations)
1006        virtual void bayes_batch ( const mat &Dt, const vec &cond = empty_vec );
1007        //! Batch Bayes rule (columns of Dt are observations, columns of Cond are conditions)
1008        virtual void bayes_batch ( const mat &Dt, const mat &Cond );
1009        //! Evaluates predictive log-likelihood of the given data record
1010        //! I.e. marginal likelihood of the data with the posterior integrated out.
1011        //! This function evaluates only \f$ y_t \f$, condition is assumed to be the last used in bayes().
1012        //! See bdm::BM::predictor for conditional version.
1013        virtual double logpred ( const vec &yt ) const = 0;
1014
1015        //! Matrix version of logpred
1016        vec logpred_mat ( const mat &Yt ) const {
1017                vec tmp ( Yt.cols() );
1018                for ( int i = 0; i < Yt.cols(); i++ ) {
1019                        tmp ( i ) = logpred ( Yt.get_col ( i ) );
1020                }
1021                return tmp;
1022        }
1023
1024        //!Constructs a predictive density \f$ f(d_{t+1} |d_{t}, \ldots d_{0}) \f$
1025        virtual epdf* epredictor() const = 0;
1026
1027        //!Constructs conditional density of 1-step ahead predictor \f$ f(d_{t+1} |d_{t+h-1}, \ldots d_{t}) \f$
1028        virtual pdf* predictor() const = 0;
1029
1030        //!@}
1031
1032
1033        //! \name Access to attributes
1034        //!@{
1035        //! access function
1036        const RV& _rvc() const {
1037                return rvc;
1038        }
1039        //! access function
1040        int dimensionc() const {
1041                return dimc;
1042        }
1043        //! access function
1044        int dimensiony() const {
1045                return dimy;
1046        }
1047        //! access function
1048        int dimension() const {
1049                return posterior().dimension();
1050        }
1051        //! access function
1052        const RV& _yrv() const {
1053                return yrv;
1054        }
1055        //! access function
1056        void set_yrv ( const RV &rv ) {
1057                yrv = rv;
1058        }
1059        //! access function
1060        void set_rvc ( const RV &rv ) {
1061                rvc = rv;
1062        }
1063        //! access to rv of the posterior
1064        void set_rv ( const RV &rv ) {
1065                const_cast<epdf&> ( posterior() ).set_rv ( rv );
1066        }
1067        //! access function
1068        void set_dim ( int dim ) {
1069                const_cast<epdf&> ( posterior() ).set_dim ( dim );
1070        }
1071        //! return internal log-likelihood of the last data vector
1072        double _ll() const {
1073                return ll;
1074        }
1075        //! switch evaluation of log-likelihood on/off
1076        void set_evalll ( bool evl0 ) {
1077                evalll = evl0;
1078        }
1079        //! return posterior density
1080        virtual const epdf& posterior() const = 0;
1081        //!@}
1082
1083        //! \name Logging of results
1084        //!@{
1085
1086        //! Set boolean options from a string, recognized are: "logbounds,logll"
1087        virtual void set_options ( const string &opt );
1088
1089        //! Add all logged variables to a logger
1090        //! Log levels two digits: xy where
1091        //!  * y = 0/1 log-likelihood is to be logged
1092        //!  * x = level of the posterior (typically 0/1/2 for nothing/mean/bounds)
1093        virtual void log_register ( logger &L, const string &prefix = "" );
1094
1095        //! Save results to the given logger, details of what is stored is configured by \c LIDs and \c options
1096        virtual void log_write ( ) const;
1097
1098        //!@}
1099        void from_setting ( const Setting &set ) {
1100                shared_ptr<RV> r = UI::build<RV> ( set, "yrv", UI::optional );
1101                if ( r ) {
1102                        set_yrv ( *r );
1103                }
1104                shared_ptr<RV> r2 = UI::build<RV> ( set, "rvc", UI::optional );
1105                if ( r2 ) {
1106                        rvc =   *r2;
1107                }
1108                shared_ptr<RV> r3 = UI::build<RV> ( set, "rv", UI::optional );
1109                if ( r3 ) {
1110                        set_rv ( *r3 );
1111                }
1112
1113                string opt;
1114                if ( UI::get ( opt, set, "options", UI::optional ) ) {
1115                        set_options ( opt );
1116                }
1117        }
1118
1119        void to_setting ( Setting &set ) const {
1120                root::to_setting( set );
1121                UI::save( &yrv, set, "yrv" );
1122                UI::save( &rvc, set, "rvc" );           
1123                UI::save( &posterior()._rv(), set, "rv" );
1124
1125                string opt;
1126                switch( posterior()._log_level() )
1127                {
1128                case 2:
1129                        opt = "logbounds ";
1130                        break;
1131                case 10:
1132                        opt = "logfull ";
1133                        break;
1134                default:
1135                        opt = "";
1136                        break;
1137                }
1138                if( log_level == 1 ) opt = opt + "logll";
1139                if( !opt.empty() )
1140                        UI::save( opt, set, "options" );
1141        }
1142};
1143
1144//! array of pointers to epdf
1145typedef Array<shared_ptr<epdf> > epdf_array;
1146//! array of pointers to pdf
1147typedef Array<shared_ptr<pdf> > pdf_array;
1148
1149template<class EPDF>
1150vec pdf_internal<EPDF>::samplecond ( const vec &cond ) {
1151        condition ( cond );
1152        vec temp = iepdf.sample();
1153        return temp;
1154}
1155
1156template<class EPDF>
1157mat pdf_internal<EPDF>::samplecond_mat ( const vec &cond, int N ) {
1158        condition ( cond );
1159        mat temp ( dimension(), N );
1160        vec smp ( dimension() );
1161        for ( int i = 0; i < N; i++ ) {
1162                smp = iepdf.sample();
1163                temp.set_col ( i, smp );
1164        }
1165
1166        return temp;
1167}
1168
1169template<class EPDF>
1170double pdf_internal<EPDF>::evallogcond ( const vec &yt, const vec &cond ) {
1171        double tmp;
1172        condition ( cond );
1173        tmp = iepdf.evallog ( yt );
1174        return tmp;
1175}
1176
1177template<class EPDF>
1178vec pdf_internal<EPDF>::evallogcond_mat ( const mat &Yt, const vec &cond ) {
1179        condition ( cond );
1180        return iepdf.evallog_mat ( Yt );
1181}
1182
1183template<class EPDF>
1184vec pdf_internal<EPDF>::evallogcond_mat ( const Array<vec> &Yt, const vec &cond ) {
1185        condition ( cond );
1186        return iepdf.evallog_mat ( Yt );
1187}
1188
1189}; //namespace
1190#endif // BDMBASE_H
Note: See TracBrowser for help on using the browser.