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

Revision 676, 34.7 kB (checked in by smidl, 15 years ago)

logger refactoring

  • 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        //! TODO
396        int dim;
397
398        //! TODO
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 ), rv( m.rv ), dim( m.dim) { }
408        //!@}
409
410        //! \name Matematical operations
411        //!@{
412
413        //! 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
414        virtual vec samplecond ( const vec &cond ) {
415                bdm_error ( "Not implemented" );
416                return vec();
417        }
418
419        //! 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
420        virtual mat samplecond_m ( const vec &cond, int N );
421
422        //! Shortcut for conditioning and evaluation of the internal epdf. In some cases,  this operation can be implemented efficiently.
423        virtual double evallogcond ( const vec &dt, const vec &cond ) {
424                bdm_error ( "Not implemented" );
425                return 0.0;
426        }
427
428        //! Matrix version of evallogcond
429        virtual vec evallogcond_m ( const mat &Dt, const vec &cond ) {
430                vec v ( Dt.cols() );
431                for ( int i = 0; i < Dt.cols(); i++ ) {
432                        v ( i ) = evallogcond ( Dt.get_col ( i ), cond );
433                }
434                return v;
435        }
436
437        //! Array<vec> version of evallogcond
438        virtual vec evallogcond_m ( const Array<vec> &Dt, const vec &cond ) {
439                bdm_error ( "Not implemented" );
440                return vec();
441        }
442
443        //! \name Access to attributes
444        //! @{
445
446        const RV& _rv() const {
447                return rv;
448        }
449        const RV& _rvc() const {
450                return rvc;
451        }
452
453        int dimension() const {
454                return dim;
455        }
456        int dimensionc() {
457                return dimc;
458        }
459
460        //! Load from structure with elements:
461        //!  \code
462        //! { class = "mpdf_offspring",
463        //!   rv = {class="RV", names=(...),}; // RV describing meaning of random variable
464        //!   rvc= {class="RV", names=(...),}; // RV describing meaning of random variable in condition
465        //!   // elements of offsprings
466        //! }
467        //! \endcode
468        //!@}
469        void from_setting ( const Setting &set );
470        //!@}
471
472        //! \name Connection to other objects
473        //!@{
474        void set_rvc ( const RV &rvc0 ) {
475                rvc = rvc0;
476        }
477        void set_rv ( const RV &rv0 ) {
478                rv = rv0;
479        }
480
481        bool isnamed() {
482                return ( dim == rv._dsize() ) && ( dimc == rvc._dsize() );
483        }
484        //!@}
485};
486SHAREDPTR ( mpdf );
487
488//! Probability density function with numerical statistics, e.g. posterior density.
489class epdf : public mpdf {
490protected:
491        //! dimension of the random variable
492        int dim;
493        //! Description of the random variable
494        RV rv;
495
496public:
497        /*! \name Constructors
498         Construction of each epdf should support two types of constructors:
499        \li empty constructor,
500        \li copy constructor,
501
502        The following constructors should be supported for convenience:
503        \li constructor followed by calling \c set_parameters()
504        \li constructor accepting random variables calling \c set_rv()
505
506         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.
507        @{*/
508        epdf() : dim ( 0 ), rv() {};
509        epdf ( const epdf &e ) : dim ( e.dim ), rv ( e.rv ) {};
510        epdf ( const RV &rv0 ) : dim ( rv0._dsize() ) {
511                set_rv ( rv0 );
512        };
513        void set_parameters ( int dim0 ) {
514                dim = dim0;
515        }
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        //!Name its rv
577        void set_rv ( const RV &rv0 ) {
578                rv = rv0;
579        }
580
581        //! True if rv is assigned
582        bool isnamed() const {
583                bool b = ( dim == rv._dsize() );
584                return b;
585        }
586
587        //! Return name (fails when isnamed is false)
588        const RV& _rv() const {
589                //bdm_assert_debug ( isnamed(), "" );
590                return rv;
591        }
592        //! store values of the epdf on the following levels:
593        //!  #1 mean
594        //!  #2 mean + lower & upper bound
595        void log_register(logger &L, const string &prefix){
596                RV r;
597                if ( isnamed() ) {
598                        r = _rv();
599                } else {
600                        r = RV ( "", dimension() );
601                };
602                root::log_register(L,prefix);
603                logrec->ids.set_size(3);
604                if (log_level >0){
605                        logrec->ids(0) = logrec->L.add ( r, prefix + logrec->L.prefix_sep()+ "mean" );
606                }
607                if (log_level >1){
608                        logrec->ids(1) = logrec->L.add ( r, prefix + logrec->L.prefix_sep()+ "lb" );
609                        logrec->ids(2) = logrec->L.add ( r, prefix + logrec->L.prefix_sep()+ "ub" );
610                }
611        }
612        //!@}
613
614        //! \name Access to attributes
615        //! @{
616
617        //! Size of the random variable
618        int dimension() const {
619                return dim;
620        }
621        //! Load from structure with elements:
622        //!  \code
623        //! { rv = {class="RV", names=(...),}; // RV describing meaning of random variable
624        //!   // elements of offsprings
625        //! }
626        //! \endcode
627        //!@}
628        void from_setting ( const Setting &set ) {
629                shared_ptr<RV> r = UI::build<RV> ( set, "rv", UI::optional );
630                if ( r ) {
631                        set_rv ( *r );
632                }
633        }
634
635
636/*! \brief Unconditional mpdf, allows using epdf in the role of mpdf.
637
638*/
639
640
641/// MEPDF BEGINS HERE TODO
642        //! empty
643        vec samplecond ( const vec &cond ) {
644                return sample();
645        }
646        double evallogcond ( const vec &val, const vec &cond ) {
647                return evallog ( val );
648        }
649};
650SHAREDPTR ( epdf );
651
652//! Mpdf with internal epdf that is modified by function \c condition
653template <class EPDF>
654class mpdf_internal: public mpdf {
655protected :
656        //! Internal epdf used for sampling
657        EPDF iepdf;
658public:
659        //! constructor
660        mpdf_internal() : mpdf(), iepdf() {
661//              set_ep ( iepdf ); TODO!
662        }
663
664        //! Update \c iepdf so that it represents this mpdf conditioned on \c rvc = cond
665        //! This function provides convenient reimplementation in offsprings
666        virtual void condition ( const vec &cond ) {
667                bdm_error ( "Not implemented" );
668        }
669
670        //!access function to iepdf
671        EPDF& e() {
672                return iepdf;
673        }
674
675        //! Reimplements samplecond using \c condition()
676        vec samplecond ( const vec &cond );
677        //! Reimplements evallogcond using \c condition()
678        double evallogcond ( const vec &val, const vec &cond );
679        //! Efficient version of evallogcond for matrices
680        virtual vec evallogcond_m ( const mat &Dt, const vec &cond );
681        //! Efficient version of evallogcond for Array<vec>
682        virtual vec evallogcond_m ( const Array<vec> &Dt, const vec &cond );
683        //! Efficient version of samplecond
684        virtual mat samplecond_m ( const vec &cond, int N );
685};
686
687/*! \brief DataLink is a connection between two data vectors Up and Down
688
689Up can be longer than Down. Down must be fully present in Up (TODO optional)
690See chart:
691\dot
692digraph datalink {
693  node [shape=record];
694  subgraph cluster0 {
695    label = "Up";
696      up [label="<1>|<2>|<3>|<4>|<5>"];
697    color = "white"
698}
699  subgraph cluster1{
700    label = "Down";
701    labelloc = b;
702      down [label="<1>|<2>|<3>"];
703    color = "white"
704}
705    up:1 -> down:1;
706    up:3 -> down:2;
707    up:5 -> down:3;
708}
709\enddot
710
711*/
712class datalink {
713protected:
714        //! Remember how long val should be
715        int downsize;
716
717        //! Remember how long val of "Up" should be
718        int upsize;
719
720        //! val-to-val link, indices of the upper val
721        ivec v2v_up;
722
723public:
724        //! Constructor
725        datalink() : downsize ( 0 ), upsize ( 0 ) { }
726
727        //! Convenience constructor
728        datalink ( const RV &rv, const RV &rv_up ) {
729                set_connection ( rv, rv_up );
730        }
731
732        //! set connection, rv must be fully present in rv_up
733        virtual void set_connection ( const RV &rv, const RV &rv_up );
734
735        //! set connection using indices
736        virtual void set_connection ( int ds, int us, const ivec &upind );
737
738        //! Get val for myself from val of "Up"
739        vec pushdown ( const vec &val_up ) {
740                vec tmp ( downsize );
741                filldown ( val_up, tmp );
742                return tmp;
743        }
744        //! Get val for vector val_down from val of "Up"
745        virtual void filldown ( const vec &val_up, vec &val_down ) {
746                bdm_assert_debug ( upsize == val_up.length(), "Wrong val_up" );
747                val_down = val_up ( v2v_up );
748        }
749        //! Fill val of "Up" by my pieces
750        virtual void pushup ( vec &val_up, const vec &val ) {
751                bdm_assert_debug ( downsize == val.length(), "Wrong val" );
752                bdm_assert_debug ( upsize == val_up.length(), "Wrong val_up" );
753                set_subvector ( val_up, v2v_up, val );
754        }
755        //! access functions
756        int _upsize() {
757                return upsize;
758        }
759        //! access functions
760        int _downsize() {
761                return downsize;
762        }
763        //! for future use
764        virtual ~datalink(){}
765};
766
767/*! Extension of datalink to fill only part of Down
768*/
769class datalink_part : public datalink {
770protected:
771        //! indeces of values in vector downsize
772        ivec v2v_down;
773public:
774        void set_connection ( const RV &rv, const RV &rv_up );
775        //! Get val for vector val_down from val of "Up"
776        void filldown ( const vec &val_up, vec &val_down ) {
777                set_subvector ( val_down, v2v_down, val_up ( v2v_up ) );
778        }
779};
780
781/*! \brief Datalink that buffers delayed values - do not forget to call step()
782
783Up is current data, Down is their subset with possibly delayed values
784*/
785class datalink_buffered: public datalink_part {
786protected:
787        //! History, ordered as \f$[Up_{t-1},Up_{t-2}, \ldots]\f$
788        vec history;
789        //! rv of the history
790        RV Hrv;
791        //! h2v : indeces in down
792        ivec h2v_down;
793        //! h2v : indeces in history
794        ivec h2v_hist;
795        //! v2h: indeces of up too be pushed to h
796        ivec v2h_up;
797public:
798
799        datalink_buffered() : datalink_part(), history ( 0 ), h2v_down ( 0 ), h2v_hist ( 0 ) {};
800        //! push current data to history
801        void step ( const vec &val_up ) {
802                if ( v2h_up.length() > 0 ) {
803                        history.shift_right ( 0, v2h_up.length() );
804                  history.set_subvector ( 0, val_up(v2h_up) ); 
805                }
806        }
807        //! Get val for myself from val of "Up"
808        vec pushdown ( const vec &val_up ) {
809                vec tmp ( downsize );
810                filldown ( val_up, tmp );
811                return tmp;
812        }
813
814        void filldown ( const vec &val_up, vec &val_down ) {
815                bdm_assert_debug ( val_down.length() >= downsize, "short val_down" );
816
817                set_subvector ( val_down, v2v_down, val_up ( v2v_up ) ); // copy direct values
818                set_subvector ( val_down, h2v_down, history ( h2v_hist ) ); // copy delayed values
819        }
820
821        void set_connection ( const RV &rv, const RV &rv_up ) {
822                // create link between up and down
823                datalink_part::set_connection ( rv, rv_up );
824
825                // create rvs of history
826                // we can store only what we get in rv_up - everything else is removed
827                ivec valid_ids = rv.findself_ids ( rv_up );
828                RV rv_hist = rv.subselect ( find ( valid_ids >= 0 ) ); // select only rvs that are in rv_up
829                RV rv_hist0 =rv_hist.remove_time();  // these RVs will form history at time =0
830                // now we need to know what is needed from Up
831                rv_hist = rv_hist.expand_delayes(); // full regressor - including time 0
832                Hrv=rv_hist.subt(rv_hist0);   // remove time 0
833                history = zeros ( Hrv._dsize() );
834
835                // decide if we need to copy val to history
836                if (Hrv._dsize() >0) {
837                        v2h_up = rv_hist0.dataind(rv_up); // indeces of elements of rv_up to be copied
838                } // else v2h_up is empty
839               
840                Hrv.dataind ( rv, h2v_hist, h2v_down );
841
842                downsize = v2v_down.length() + h2v_down.length();
843                upsize = v2v_up.length();
844        }
845        //! set history of variable given by \c rv1 to values of \c hist.
846        void set_history(const RV& rv1, const vec &hist0){
847                bdm_assert(rv1._dsize()==hist0.length(),"hist is not compatible with given rv1");
848                ivec ind_H;
849                ivec ind_h0;
850                Hrv.dataind(rv1, ind_H, ind_h0); // find indeces of rv in
851                set_subvector(history, ind_H, hist0(ind_h0)); // copy given hist to appropriate places
852        }
853};
854
855//! buffered datalink from 2 vectors to 1
856class datalink_2to1_buffered {
857protected:
858        //! link 1st vector to down
859        datalink_buffered dl1;
860        //! link 2nd vector to down
861        datalink_buffered dl2;
862public:
863        //! set connection between RVs
864        void set_connection ( const RV &rv, const RV &rv_up1, const RV &rv_up2 ) {
865                dl1.set_connection ( rv, rv_up1 );
866                dl2.set_connection ( rv, rv_up2 );
867        }
868        //! fill values of down from the values of the two up vectors
869        void filldown ( const vec &val1, const vec &val2, vec &val_down ) {
870                bdm_assert_debug ( val_down.length() >= dl1._downsize() + dl2._downsize(), "short val_down" );
871                dl1.filldown ( val1, val_down );
872                dl2.filldown ( val2, val_down );
873        }
874        //! update buffer
875        void step ( const vec &dt, const vec &ut ) {
876                dl1.step ( dt );
877                dl2.step ( ut );
878        }
879};
880
881
882
883//! Data link with a condition.
884class datalink_m2e: public datalink {
885protected:
886        //! Remember how long cond should be
887        int condsize;
888
889        //!upper_val-to-local_cond link, indices of the upper val
890        ivec v2c_up;
891
892        //!upper_val-to-local_cond link, indices of the local cond
893        ivec v2c_lo;
894
895public:
896        //! Constructor
897        datalink_m2e() : condsize ( 0 ) { }
898
899        //! Set connection between vectors
900        void set_connection ( const RV &rv, const RV &rvc, const RV &rv_up );
901
902        //!Construct condition
903        vec get_cond ( const vec &val_up );
904
905        //! Copy corresponding values to Up.condition
906        void pushup_cond ( vec &val_up, const vec &val, const vec &cond );
907};
908
909//!DataLink is a connection between mpdf and its superordinate (Up)
910//! This class links
911class datalink_m2m: public datalink_m2e {
912protected:
913        //!cond-to-cond link, indices of the upper cond
914        ivec c2c_up;
915        //!cond-to-cond link, indices of the local cond
916        ivec c2c_lo;
917
918public:
919        //! Constructor
920        datalink_m2m() {};
921        //! Set connection between the vectors
922        void set_connection ( const RV &rv, const RV &rvc, const RV &rv_up, const RV &rvc_up ) {
923                datalink_m2e::set_connection ( rv, rvc, rv_up );
924                //establish c2c connection
925                rvc.dataind ( rvc_up, c2c_lo, c2c_up );
926                bdm_assert_debug ( c2c_lo.length() + v2c_lo.length() == condsize, "cond is not fully given" );
927        }
928
929        //! Get cond for myself from val and cond of "Up"
930        vec get_cond ( const vec &val_up, const vec &cond_up ) {
931                vec tmp ( condsize );
932                set_subvector ( tmp, v2c_lo, val_up ( v2c_up ) );
933                set_subvector ( tmp, c2c_lo, cond_up ( c2c_up ) );
934                return tmp;
935        }
936        //! Fill
937
938};
939
940
941//! \brief Combines RVs from a list of mpdfs to a single one.
942RV get_composite_rv ( const Array<shared_ptr<mpdf> > &mpdfs, bool checkoverlap = false );
943
944/*! \brief Abstract class for discrete-time sources of data.
945
946The class abstracts operations of:
947\li  data aquisition,
948\li  data-preprocessing, such as  scaling of data,
949\li  data resampling from the task of estimation and control.
950Moreover, for controlled systems, it is able to receive the desired control action and perform it in the next step. (Or as soon as possible).
951
952The DataSource has three main data interaction structures:
953\li input, \f$ u_t \f$,
954\li output \f$ y_t \f$,
955\li data, \f$ d_t=[y_t,u_t, \ldots ]\f$ a collection of all inputs and outputs and possibly some internal variables too.
956
957*/
958
959class DS : public root {
960protected:
961                //! size of data returned by \c getdata()
962        int dtsize;
963                //! size of data
964        int utsize;
965                //!size of output
966                int ytsize;
967        //!Description of data returned by \c getdata().
968        RV Drv;
969        //!Description of data witten by by \c write().
970        RV Urv; //
971                //!Description of output data
972                RV Yrv; //
973public:
974        //! default constructors
975                DS() : Drv(), Urv(),Yrv() {log_level=1;};
976
977        //! 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().
978        virtual int max_length() {return std::numeric_limits< int >::max();}
979        //! Returns full vector of observed data=[output, input]
980        virtual void getdata ( vec &dt ) const {
981                bdm_error ( "abstract class" );
982        }
983        //! Returns data records at indeces.
984        virtual void getdata ( vec &dt, const ivec &indeces ) {
985                bdm_error ( "abstract class" );
986        }
987
988        //! Accepts action variable and schedule it for application.
989        virtual void write (const vec &ut ) {
990                bdm_error ( "abstract class" );
991        }
992
993        //! Accepts action variables at specific indeces
994        virtual void write (const vec &ut, const ivec &indeces ) {
995                bdm_error ( "abstract class" );
996        }
997
998        //! Moves from \f$ t \f$ to \f$ t+1 \f$, i.e. perfroms the actions and reads response of the system.
999        virtual void step() 
1000        {
1001                bdm_error ( "abstract class" );
1002        }
1003
1004        //! Register DS for logging into logger L
1005        virtual void log_register (logger &L,  const string &prefix ) {
1006                bdm_assert ( ytsize == Yrv._dsize(), "invalid DS: ytsize (" + num2str ( ytsize ) + ") different from Drv " + num2str ( Yrv._dsize() ) );
1007                bdm_assert ( utsize == Urv._dsize(), "invalid DS: utsize (" + num2str ( utsize ) + ") different from Urv " + num2str ( Urv._dsize() ) );
1008
1009                root::log_register(L,prefix);
1010                //we know that
1011                if (log_level >0){
1012                        logrec->ids.set_size(2);
1013                        logrec->ids(0) = logrec->L.add ( Yrv, "" );
1014                        logrec->ids(1) = logrec->L.add ( Urv, "" );
1015                }
1016        }
1017        //! Register DS for logging into logger L
1018        virtual void log_write ( ) const {
1019                if (log_level >0) {
1020                        vec tmp ( Yrv._dsize() + Urv._dsize());
1021                        getdata ( tmp );
1022                        // d is first in getdata
1023                        logrec->L.logit ( logrec->ids(0), tmp.left ( Yrv._dsize() ) );
1024                        // u follows after d in getdata
1025                        logrec->L.logit ( logrec->ids(1), tmp.mid ( Yrv._dsize(), Urv._dsize() ) );
1026                }
1027        }
1028        //!access function
1029        virtual const RV& _drv() const {
1030                return Drv;
1031        }
1032        //!access function
1033        const RV& _urv() const {
1034                return Urv;
1035        }
1036        //!access function
1037        const RV& _yrv() const {
1038                return Yrv;
1039        }
1040        //! set random variables
1041        virtual void set_drv (const  RV &yrv, const RV &urv) {
1042                Yrv = yrv;
1043                Drv = concat(yrv,urv);
1044                Urv = urv;
1045        }
1046};
1047
1048/*! \brief Bayesian Model of a system, i.e. all uncertainty is modeled by probabilities.
1049
1050This object represents exact or approximate evaluation of the Bayes rule:
1051\f[
1052f(\theta_t | d_1,\ldots,d_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})}
1053\f]
1054
1055Access to the resulting posterior density is via function \c posterior().
1056
1057As a "side-effect" it also evaluates log-likelihood of the data, which can be accessed via function _ll().
1058It can also evaluate predictors of future values of \f$y_t\f$, see functions epredictor() and predictor().
1059
1060Alternatively, it can evaluate posterior density conditioned by a known constant, \f$ c_t \f$:
1061\f[
1062f(\theta_t | c_t, d_1,\ldots,d_t) \propto  f(y_t,\theta_t|c_t,\cdot, d_1,\ldots,d_{t-1})
1063\f]
1064
1065The value of \f$ c_t \f$ is set by function condition().
1066
1067*/
1068
1069class BM : public root {
1070protected:
1071        //! Random variable of the data (optional)
1072        RV drv;
1073        //!Logarithm of marginalized data likelihood.
1074        double ll;
1075        //!  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.
1076        bool evalll;
1077       
1078public:
1079        //! \name Constructors
1080        //! @{
1081
1082        BM() : ll ( 0 ), evalll ( true ) { };
1083        BM ( const BM &B ) :  drv ( B.drv ), ll ( B.ll ), evalll ( B.evalll ) {}
1084        //! \brief Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually!
1085        //! Prototype: \code BM* _copy_() const {return new BM(*this);} \endcode
1086        virtual BM* _copy_() const {
1087                return NULL;
1088        };
1089        //!@}
1090
1091        //! \name Mathematical operations
1092        //!@{
1093
1094        /*! \brief Incremental Bayes rule
1095        @param dt vector of input data
1096        */
1097        virtual void bayes ( const vec &dt ) = 0;
1098        //! Batch Bayes rule (columns of Dt are observations)
1099        virtual void bayesB ( const mat &Dt );
1100        //! Evaluates predictive log-likelihood of the given data record
1101        //! I.e. marginal likelihood of the data with the posterior integrated out.
1102        virtual double logpred ( const vec &dt ) const {
1103                bdm_error ( "Not implemented" );
1104                return 0.0;
1105        }
1106
1107        //! Matrix version of logpred
1108        vec logpred_m ( const mat &dt ) const {
1109                vec tmp ( dt.cols() );
1110                for ( int i = 0; i < dt.cols(); i++ ) {
1111                        tmp ( i ) = logpred ( dt.get_col ( i ) );
1112                }
1113                return tmp;
1114        }
1115
1116        //!Constructs a predictive density \f$ f(d_{t+1} |d_{t}, \ldots d_{0}) \f$
1117        virtual epdf* epredictor() const {
1118                bdm_error ( "Not implemented" );
1119                return NULL;
1120        };
1121        //!Constructs conditional density of 1-step ahead predictor \f$ f(d_{t+1} |d_{t+h-1}, \ldots d_{t}) \f$
1122        virtual mpdf* predictor() const {
1123                bdm_error ( "Not implemented" );
1124                return NULL;
1125        };
1126        //!@}
1127
1128        //! \name Extension to conditional BM
1129        //! This extension is useful e.g. in Marginalized Particle Filter (\ref bdm::MPF).
1130        //! Alternatively, it can be used for automated connection to DS when the condition is observed
1131        //!@{
1132
1133        //! Name of extension variable
1134        RV rvc;
1135        //! access function
1136        const RV& _rvc() const {
1137                return rvc;
1138        }
1139
1140        //! Substitute \c val for \c rvc.
1141        virtual void condition ( const vec &val ) {
1142                bdm_error ( "Not implemented!" );
1143        }
1144
1145        //!@}
1146
1147
1148        //! \name Access to attributes
1149        //!@{
1150        //! access function
1151        const RV& _drv() const {
1152                return drv;
1153        }
1154        //! access function
1155        void set_drv ( const RV &rv ) {
1156                drv = rv;
1157        }
1158        //! access to rv of the posterior
1159        void set_rv ( const RV &rv ) {
1160                const_cast<epdf&> ( posterior() ).set_rv ( rv );
1161        }
1162        //! return internal log-likelihood of the last data vector
1163        double _ll() const {
1164                return ll;
1165        }
1166        //! switch evaluation of log-likelihood on/off
1167        void set_evalll ( bool evl0 ) {
1168                evalll = evl0;
1169        }
1170        //! return posterior density
1171        virtual const epdf& posterior() const = 0;
1172        //!@}
1173
1174        //! \name Logging of results
1175        //!@{
1176
1177        //! Set boolean options from a string, recognized are: "logbounds,logll"
1178        virtual void set_options ( const string &opt ) {
1179                if ( opt.find ( "logbounds" ) != string::npos ) {
1180                        const_cast<epdf&>(posterior()).set_log_level(2) ;
1181                } else {
1182                        const_cast<epdf&>(posterior()).set_log_level(1) ;
1183                }
1184                if ( opt.find ( "logll" ) != string::npos ) {
1185                        log_level = 1;
1186                }
1187        }
1188
1189        //! Add all logged variables to a logger
1190        //! Log levels two digits: xy where
1191        //!  * y = 0/1 log-likelihood is to be logged
1192        //!  * x = level of the posterior (typically 0/1/2 for nothing/mean/bounds)
1193        virtual void log_register ( logger &L, const string &prefix = "" ) {
1194                root::log_register(L,prefix);           
1195
1196                const_cast<epdf&>(posterior()).log_register(L, prefix+L.prefix_sep()+"apost"); 
1197               
1198                if ((log_level) > 0){
1199                        logrec->ids.set_size(1);
1200                        logrec->ids(0) = L.add(RV("ll",1), prefix+L.prefix_sep()+"ll");
1201                }
1202        }
1203        //! Save results to the given logger, details of what is stored is configured by \c LIDs and \c options
1204        virtual void log_write ( ) const {
1205                posterior().log_write();
1206                if (log_level >0) { logrec->L.logit ( logrec->ids ( 0 ), ll );}
1207        }
1208        //!@}
1209        void from_setting ( const Setting &set ) {
1210                shared_ptr<RV> r = UI::build<RV> ( set, "drv", UI::optional );
1211                if ( r ) {
1212                        set_drv ( *r );
1213                }
1214                string opt;
1215                if ( UI::get ( opt, set, "options", UI::optional ) ) {
1216                        set_options ( opt );
1217                }
1218        }
1219
1220};
1221//! array of pointers to epdf
1222typedef Array<shared_ptr<epdf> > epdf_array;
1223//! array of pointers to mpdf
1224typedef Array<shared_ptr<mpdf> > mpdf_array;
1225
1226template<class EPDF>
1227vec mpdf_internal<EPDF>::samplecond ( const vec &cond ) {
1228        condition ( cond );
1229        vec temp = iepdf.sample();
1230        return temp;
1231}
1232
1233template<class EPDF>
1234mat mpdf_internal<EPDF>::samplecond_m ( const vec &cond, int N ) {
1235        condition ( cond );
1236        mat temp ( dimension(), N );
1237        vec smp ( dimension() );
1238        for ( int i = 0; i < N; i++ ) {
1239                smp = iepdf.sample();
1240                temp.set_col ( i, smp );
1241        }
1242
1243        return temp;
1244}
1245
1246template<class EPDF>
1247double mpdf_internal<EPDF>::evallogcond ( const vec &dt, const vec &cond ) {
1248        double tmp;
1249        condition ( cond );
1250        tmp = iepdf.evallog ( dt );
1251        return tmp;
1252}
1253
1254template<class EPDF>
1255vec mpdf_internal<EPDF>::evallogcond_m ( const mat &Dt, const vec &cond ) {
1256        condition ( cond );
1257        return iepdf.evallog_m ( Dt );
1258}
1259
1260template<class EPDF>
1261vec mpdf_internal<EPDF>::evallogcond_m ( const Array<vec> &Dt, const vec &cond ) {
1262        condition ( cond );
1263        return iepdf.evallog_m ( Dt );
1264}
1265
1266}; //namespace
1267#endif // BDMBASE_H
Note: See TracBrowser for help on using the browser.