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

Revision 792, 32.5 kB (checked in by smidl, 14 years ago)

sketch of class logged_options which is intendet to replace log_level in future, DOES NOT WORK AT THE MOMENT, 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        //! Names of variables stored in RV are considered to be valid only if their size match size of the parameters (dim).
482        bool isnamed() const {
483                return ( dim == rv._dsize() ) && ( dimc == rvc._dsize() );
484        }
485        //!@}
486};
487SHAREDPTR ( pdf );
488
489//! Probability density function with numerical statistics, e.g. posterior density.
490class epdf : public pdf {
491
492public:
493        /*! \name Constructors
494         Construction of each epdf should support two types of constructors:
495        \li empty constructor,
496        \li copy constructor,
497
498        The following constructors should be supported for convenience:
499        \li constructor followed by calling \c set_parameters()
500        \li constructor accepting random variables calling \c set_rv()
501
502         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.
503        @{*/
504        epdf() {};
505        epdf ( const epdf &e ) : pdf ( e ) {};
506       
507        virtual void    validate (int dim0){
508                dim = dim0;
509        }
510       
511        //!@}
512
513        //! \name Matematical Operations
514        //!@{
515
516        //! Returns a sample, \f$ x \f$ from density \f$ f_x()\f$
517        virtual vec sample() const = 0;
518
519        //! Returns N samples, \f$ [x_1 , x_2 , \ldots \ \f$  from density \f$ f_x(rv)\f$
520        virtual mat sample_mat ( int N ) const;
521
522        //! Compute log-probability of argument \c val
523        //! In case the argument is out of suport return -Infinity
524        virtual double evallog ( const vec &val ) const = 0;
525       
526        //! Compute log-probability of multiple values argument \c val
527        virtual vec evallog_mat ( const mat &Val ) const;
528
529        //! Compute log-probability of multiple values argument \c val
530        virtual vec evallog_mat ( const Array<vec> &Avec ) const;
531
532        //! Return conditional density on the given RV, the remaining rvs will be in conditioning
533        virtual shared_ptr<pdf> condition ( const RV &rv ) const;
534
535        //! Return marginal density on the given RV, the remainig rvs are intergrated out
536        virtual shared_ptr<epdf> marginal ( const RV &rv ) const;
537
538        virtual vec mean() const = 0;
539
540        //! return expected variance (not covariance!)
541        virtual vec variance() const = 0;
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.
916        virtual void getdata ( vec &dt, const ivec &indeces ) = 0;
917
918        //! Accepts action variable and schedule it for application.   
919        virtual void write ( const vec &ut ) = 0;
920
921        //! Accepts action variables at specific indeces
922        virtual void write ( const vec &ut, const ivec &indeces ) = 0;
923
924        //! Moves from \f$ t \f$ to \f$ t+1 \f$, i.e. perfroms the actions and reads response of the system.
925        virtual void step() = 0;
926
927        //! Register DS for logging into logger L
928        virtual void log_register ( logger &L,  const string &prefix );
929        //! Register DS for logging into logger L
930        virtual void log_write ( ) const;
931        //!access function
932        virtual const RV& _drv() const {
933                return Drv;
934        }
935        //!access function
936        const RV& _urv() const {
937                return Urv;
938        }
939        //!access function
940        const RV& _yrv() const {
941                return Yrv;
942        }
943        //! set random variables
944        virtual void set_drv ( const  RV &yrv, const RV &urv ) {
945                Yrv = yrv;
946                Drv = concat ( yrv, urv );
947                Urv = urv;
948        }
949};
950
951/*! \brief Bayesian Model of a system, i.e. all uncertainty is modeled by probabilities.
952
953This object represents exact or approximate evaluation of the Bayes rule:
954\f[
955f(\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})}
956\f]
957where:
958 * \f$ y_t \f$ is the variable
959Access to the resulting posterior density is via function \c posterior().
960
961As a "side-effect" it also evaluates log-likelihood of the data, which can be accessed via function _ll().
962It can also evaluate predictors of future values of \f$y_t\f$, see functions epredictor() and predictor().
963
964Alternatively, it can evaluate posterior density with rvc replaced by the given values, \f$ c_t \f$:
965\f[
966f(\theta_t | c_t, d_1,\ldots,d_t) \propto  f(y_t,\theta_t|c_t,\cdot, d_1,\ldots,d_{t-1})
967\f]
968
969
970*/
971
972class BM : public root {
973protected:
974        //! Random variable of the data (optional)
975        RV yrv;
976        //! size of the data record
977        int dimy;
978        //! Name of extension variable
979        RV rvc;
980        //! size of the conditioning vector
981        int dimc;
982
983        //!Logarithm of marginalized data likelihood.
984        double ll;
985        //!  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.
986        bool evalll;
987
988public:
989        //! \name Constructors
990        //! @{
991
992        BM() : yrv(), dimy ( 0 ), rvc(), dimc ( 0 ), ll ( 0 ), evalll ( true ) { };
993//      BM ( const BM &B ) :  yrv ( B.yrv ), dimy(B.dimy), rvc ( B.rvc ),dimc(B.dimc), ll ( B.ll ), evalll ( B.evalll ) {}
994        //! \brief Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually!
995        //! Prototype: \code BM* _copy() const {return new BM(*this);} \endcode
996        virtual BM* _copy() const {             return NULL;    }; // TODO NEBUDE TU TAKY LEPSI BDM_ERROR??!
997        //!@}
998
999        //! \name Mathematical operations
1000        //!@{
1001
1002        /*! \brief Incremental Bayes rule
1003        @param dt vector of input data
1004        */
1005        virtual void bayes ( const vec &yt, const vec &cond = empty_vec ) = 0;
1006        //! Batch Bayes rule (columns of Dt are observations)
1007        virtual void bayes_batch ( const mat &Dt, const vec &cond = empty_vec );
1008        //! Batch Bayes rule (columns of Dt are observations, columns of Cond are conditions)
1009        virtual void bayes_batch ( const mat &Dt, const mat &Cond );
1010        //! Evaluates predictive log-likelihood of the given data record
1011        //! I.e. marginal likelihood of the data with the posterior integrated out.
1012        //! This function evaluates only \f$ y_t \f$, condition is assumed to be the last used in bayes().
1013        //! See bdm::BM::predictor for conditional version.
1014        virtual double logpred ( const vec &yt ) const = 0;
1015
1016        //! Matrix version of logpred
1017        vec logpred_mat ( const mat &Yt ) const {
1018                vec tmp ( Yt.cols() );
1019                for ( int i = 0; i < Yt.cols(); i++ ) {
1020                        tmp ( i ) = logpred ( Yt.get_col ( i ) );
1021                }
1022                return tmp;
1023        }
1024
1025        //!Constructs a predictive density \f$ f(d_{t+1} |d_{t}, \ldots d_{0}) \f$
1026        virtual epdf* epredictor() const = 0;
1027
1028        //!Constructs conditional density of 1-step ahead predictor \f$ f(d_{t+1} |d_{t+h-1}, \ldots d_{t}) \f$
1029        virtual pdf* predictor() const = 0;
1030
1031        //!@}
1032
1033
1034        //! \name Access to attributes
1035        //!@{
1036        //! access function
1037        const RV& _rvc() const {
1038                return rvc;
1039        }
1040        //! access function
1041        int dimensionc() const {
1042                return dimc;
1043        }
1044        //! access function
1045        int dimensiony() const {
1046                return dimy;
1047        }
1048        //! access function
1049        int dimension() const {
1050                return posterior().dimension();
1051        }
1052        //! access function
1053        const RV& _yrv() const {
1054                return yrv;
1055        }
1056        //! access function
1057        void set_yrv ( const RV &rv ) {
1058                yrv = rv;
1059        }
1060        //! access function
1061        void set_rvc ( const RV &rv ) {
1062                rvc = rv;
1063        }
1064        //! access to rv of the posterior
1065        void set_rv ( const RV &rv ) {
1066                const_cast<epdf&> ( posterior() ).set_rv ( rv );
1067        }
1068        //! access function
1069        void set_dim ( int dim ) {
1070                const_cast<epdf&> ( posterior() ).set_dim ( dim );
1071        }
1072        //! return internal log-likelihood of the last data vector
1073        double _ll() const {
1074                return ll;
1075        }
1076        //! switch evaluation of log-likelihood on/off
1077        void set_evalll ( bool evl0 ) {
1078                evalll = evl0;
1079        }
1080        //! return posterior density
1081        virtual const epdf& posterior() const = 0;
1082        //!@}
1083
1084        //! \name Logging of results
1085        //!@{
1086
1087        //! Set boolean options from a string, recognized are: "logbounds,logll"
1088        virtual void set_options ( const string &opt );
1089
1090        //! Add all logged variables to a logger
1091        //! Log levels two digits: xy where
1092        //!  * y = 0/1 log-likelihood is to be logged
1093        //!  * x = level of the posterior (typically 0/1/2 for nothing/mean/bounds)
1094        virtual void log_register ( logger &L, const string &prefix = "" );
1095
1096        //! Save results to the given logger, details of what is stored is configured by \c LIDs and \c options
1097        virtual void log_write ( ) const;
1098
1099        //!@}
1100        void from_setting ( const Setting &set ) {
1101                shared_ptr<RV> r = UI::build<RV> ( set, "yrv", UI::optional );
1102                if ( r ) {
1103                        set_yrv ( *r );
1104                }
1105                shared_ptr<RV> r2 = UI::build<RV> ( set, "rvc", UI::optional );
1106                if ( r2 ) {
1107                        rvc =   *r2;
1108                }
1109                shared_ptr<RV> r3 = UI::build<RV> ( set, "rv", UI::optional );
1110                if ( r3 ) {
1111                        set_rv ( *r3 );
1112                }
1113
1114                string opt;
1115                if ( UI::get ( opt, set, "options", UI::optional ) ) {
1116                        set_options ( opt );
1117                }
1118        }
1119
1120        void to_setting ( Setting &set ) const {
1121                root::to_setting( set );
1122                UI::save( &yrv, set, "yrv" );
1123                UI::save( &rvc, set, "rvc" );           
1124                UI::save( &posterior()._rv(), set, "rv" );
1125
1126                string opt;
1127                switch( posterior()._log_level() )
1128                {
1129                case 2:
1130                        opt = "logbounds ";
1131                        break;
1132                case 10:
1133                        opt = "logfull ";
1134                        break;
1135                default:
1136                        opt = "";
1137                        break;
1138                }
1139                if( log_level == 1 ) opt = opt + "logll";
1140                if( !opt.empty() )
1141                        UI::save( opt, set, "options" );
1142        }
1143};
1144
1145//! array of pointers to epdf
1146typedef Array<shared_ptr<epdf> > epdf_array;
1147//! array of pointers to pdf
1148typedef Array<shared_ptr<pdf> > pdf_array;
1149
1150template<class EPDF>
1151vec pdf_internal<EPDF>::samplecond ( const vec &cond ) {
1152        condition ( cond );
1153        vec temp = iepdf.sample();
1154        return temp;
1155}
1156
1157template<class EPDF>
1158mat pdf_internal<EPDF>::samplecond_mat ( const vec &cond, int N ) {
1159        condition ( cond );
1160        mat temp ( dimension(), N );
1161        vec smp ( dimension() );
1162        for ( int i = 0; i < N; i++ ) {
1163                smp = iepdf.sample();
1164                temp.set_col ( i, smp );
1165        }
1166
1167        return temp;
1168}
1169
1170template<class EPDF>
1171double pdf_internal<EPDF>::evallogcond ( const vec &yt, const vec &cond ) {
1172        double tmp;
1173        condition ( cond );
1174        tmp = iepdf.evallog ( yt );
1175        return tmp;
1176}
1177
1178template<class EPDF>
1179vec pdf_internal<EPDF>::evallogcond_mat ( const mat &Yt, const vec &cond ) {
1180        condition ( cond );
1181        return iepdf.evallog_mat ( Yt );
1182}
1183
1184template<class EPDF>
1185vec pdf_internal<EPDF>::evallogcond_mat ( const Array<vec> &Yt, const vec &cond ) {
1186        condition ( cond );
1187        return iepdf.evallog_mat ( Yt );
1188}
1189
1190}; //namespace
1191#endif // BDMBASE_H
Note: See TracBrowser for help on using the browser.