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

Revision 679, 34.8 kB (checked in by smidl, 15 years ago)

Major changes in BM -- OK is only test suite and tests/tutorial -- the rest is broken!!!

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