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

Revision 960, 44.0 kB (checked in by smidl, 14 years ago)

compilation fixes

  • 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
29//! Structure of RV, i.e. RVs expanded into a flat list of IDs, used for debugging.
30class str {
31public:
32        //! vector id ids (non-unique!)
33        ivec ids;
34        //! vector of times
35        ivec times;
36        //!Default constructor
37        str ( ivec ids0, ivec times0 ) : ids ( ids0 ), times ( times0 ) {
38                bdm_assert ( times0.length() == ids0.length(), "Incompatible input" );
39        };
40};
41
42/*!
43* \brief Class representing variables, most often random variables
44
45The 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.
46
47The class is implemented using global variables to assure uniqueness of description:
48
49 In is a vector
50\dot
51digraph datalink {
52rankdir=LR;
53subgraph cluster0 {
54node [shape=record];
55label = "MAP \n std::map<string,int>";
56map [label="{{\"a\"| \"b\" | \"c\"} | {<3> 3 |<1> 1|<2> 2}}"];
57color = "white"
58}
59subgraph cluster1{
60node [shape=record];
61label = "NAMES";
62names [label="{<1> \"b\" | <2> \"c\" | <3>\"a\" }"];
63color = "white"
64}
65subgraph cluster2{
66node [shape=record];
67label = "SIZES";
68labelloc = b;
69sizes [label="{<1>1 |<2> 4 |<3> 1}"];
70color = "white"
71}
72map:1 -> names:1;
73map:1 -> sizes:1;
74map:3 -> names:3;
75map:3 -> sizes:3;
76}
77\enddot
78*/
79
80class RV : public root {
81private:
82        typedef std::map<string, int> str2int_map;
83
84        //! Internal global variable storing sizes of RVs
85        static ivec SIZES;
86        //! Internal global variable storing names of RVs
87        static Array<string> NAMES;
88        //! TODO
89        const static int BUFFER_STEP;
90        //! TODO
91        static str2int_map MAP;
92
93public:
94
95protected:
96        //! size of the data vector
97        int dsize;
98        //! number of individual rvs
99        int len;
100        //! Vector of unique IDs
101        ivec ids;
102        //! Vector of shifts from current time
103        ivec times;
104
105private:
106        enum enum_dummy {dummy};
107
108        //! auxiliary function used in constructor
109        void init( const Array<std::string> &in_names, const ivec &in_sizes, const ivec &in_times );
110
111        //! auxiliary function assigning unique integer index related to the passed name and size of the random variable
112        int assign_id( const string &name, int size );
113
114        //! Private constructor from IDs, potentially dangerous since all ids must be valid!
115        //! dummy is there to prevent confusion with RV(" string");
116        explicit RV ( const ivec &ids0, enum_dummy dum ) : dsize ( 0 ), len ( ids0.length() ), ids ( ids0 ), times ( zeros_i ( ids0.length() ) ) {
117                dsize = countsize();
118        }
119public:
120        //! \name Constructors
121        //!@{
122
123        //! Full constructor
124        RV ( const Array<std::string> &in_names, const ivec &in_sizes, const ivec &in_times ) {
125                init ( in_names, in_sizes, in_times );
126        }
127
128        //! Constructor with times=0
129        RV ( const Array<std::string> &in_names, const ivec &in_sizes ) {
130                init ( in_names, in_sizes, zeros_i ( in_names.length() ) );
131        }
132
133        //! Constructor with sizes=1, times=0
134        RV ( const Array<std::string> &in_names ) {
135                init ( in_names, ones_i ( in_names.length() ), zeros_i ( in_names.length() ) );
136        }
137
138        //! Constructor of empty RV
139        RV() : dsize ( 0 ), len ( 0 ), ids ( 0 ), times ( 0 ) {}
140
141        //! Constructor of a single RV
142        RV ( string name, int sz, int tm = 0 );
143
144        //! Constructor of a single nameless RV
145        RV ( int sz, int tm = 0 );
146
147        // compiler-generated copy constructor is used
148        //!@}
149
150        //! \name Access functions
151        //!@{
152
153        //! State output, e.g. for debugging.
154        friend std::ostream &operator<< ( std::ostream &os, const RV &rv );
155
156        string to_string() const {
157                ostringstream o;
158                o << *this;
159                return o.str();
160        }
161
162        //! total size of a random variable
163        int _dsize() const {
164                return dsize;
165        }
166
167        //! access function
168        const ivec& _ids() const {
169                return ids;
170        }
171
172        //! Recount size of the corresponding data vector
173        int countsize() const;
174        //! Vector of cumulative sizes of RV
175        ivec cumsizes() const;
176        //! Number of named parts
177        int length() const {
178                return len;
179        }
180        int id ( int at ) const {
181                return ids ( at );
182        }
183        int size ( int at ) const {
184                return SIZES ( ids ( at ) );
185        }
186        int time ( int at ) const {
187                return times ( at );
188        }
189        std::string name ( int at ) const {
190                return NAMES ( ids ( at ) );
191        }
192        //! 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
193        std::string scalarname ( int scalat ) const;
194
195        void set_time ( int at, int time0 ) {
196                times ( at ) = time0;
197        }
198        //!@}
199
200        //! \name Algebra on Random Variables
201        //!@{
202
203        //! Find indices of self in another rv, \return ivec of the same size as self.
204        ivec findself ( const RV &rv2 ) const;
205        //! Find indices of self in another rv, ignore time, \return ivec of the same size as self.
206        ivec findself_ids ( const RV &rv2 ) const;
207        //! Compare if \c rv2 is identical to this \c RV
208        bool equal ( const RV &rv2 ) const;
209        //! Add (concat) another variable to the current one, \return true if all rv2 were added, false if rv2 is in conflict
210        bool add ( const RV &rv2 );
211        //! Subtract  another variable from the current one
212        RV subt ( const RV &rv2 ) const;
213        //! Select only variables at indices ind
214        RV subselect ( const ivec &ind ) const;
215
216        //! Select only variables at indices ind
217        RV operator() ( const ivec &ind ) const {
218                return subselect ( ind );
219        }
220
221        //! Select from data vector starting at di1 to di2
222        RV operator() ( int di1, int di2 ) const;
223
224        //! Shift \c time by delta.
225        void t_plus ( int delta );
226        //!@}
227
228        //! @{ \name Time manipulation functions
229        //! returns rvs with time set to 0 and removed duplicates
230        RV remove_time() const {
231                return RV ( unique ( ids ), dummy );
232        }
233        //! create new RV from the current one with time shifted by given value
234        RV copy_t ( int dt ) const {
235                RV tmp = *this;
236                tmp.t_plus ( dt );
237                return tmp;
238        }
239        //! return rvs with expanded delayes and sorted in the order of: \f$ [ rv_{0}, rv_{-1},\ldots  rv_{max_delay}]\f$
240        RV expand_delayes() const;
241        //!@}
242
243        //!\name Relation to vectors
244        //!@{
245
246        //! generate \c str from rv, by expanding sizes
247        str tostr() const;
248        //! when this rv is a part of bigger rv, this function returns indices of self in the data vector of the bigger crv.
249        //! Then, data can be copied via: data_of_this = cdata(ind);
250        ivec dataind ( const RV &crv ) const;
251        //! same as dataind but this time crv should not be complete supperset of rv.
252        ivec dataind_part ( const RV &crv ) const;
253        //! generate mutual indices when copying data between self and crv.
254        //! Data are copied via: data_of_this(selfi) = data_of_rv2(rv2i)
255        void dataind ( const RV &rv2, ivec &selfi, ivec &rv2i ) const;
256        //! Minimum time-offset
257        int mint() const {
258                return times.length() > 0 ? min ( times ) : 0;
259        }
260        //! Minimum time-offset of ids of given RVs
261        int mint ( const RV &rv ) const {
262                bvec belong = zeros_b ( len );
263                for ( int r = 0; r < rv.length(); r++ ) {
264                        belong = belong | ( ids == rv.id ( r ) );
265                }
266                return times.length() > 0 ? min ( get_from_bvec ( times, belong ) ) : 0;
267        }
268        //!@}
269
270        /*! \brief UI for class RV (description of data vectors)
271
272        \code
273        class = 'RV';
274        names = {'a', 'b', 'c', ...};   // UNIQUE IDENTIFIER same names = same variable
275                                                                        // names are also used when storing results
276        --- optional ---
277        sizes = [1, 2, 3, ...];         // size of each name. default = ones()
278                                                                        // if size = -1, it is found out from previous instances of the same name
279        times = [-1, -2, 0, ...];       // time shifts with respect to current time, default = zeros()
280        \endcode
281        */
282        void from_setting ( const Setting &set );
283
284        void to_setting ( Setting &set ) const;
285
286        //! Invalidate all named RVs. Use before initializing any RV instances, with care...
287        static void clear_all();
288        //! function for debugging RV related stuff
289        string show_all();
290
291};
292UIREGISTER ( RV );
293SHAREDPTR ( RV );
294
295//! Concat two random variables
296RV concat ( const RV &rv1, const RV &rv2 );
297
298
299
300//! This class stores a details that will be logged to a logger
301//!
302//! This is only the first part of the whole declaration, which has to be however separated into
303//! two different classes for allowing the compilation of source code. For more details
304//! see logger::add_setting(...) method and mainly log_level_template<T>::template<class U> void store( const enum T::log_level_enums log_level_enum, const U data ) const
305//! method. For the reason the second one is templated, it was necessary to declare this whole class.
306template<class T> class log_level_intermediate : public log_level_base {
307protected:
308        //! boolean flags related indicating which details will be logged to a logger
309        bitset<32> values;
310
311        //! default constructor is protected to prevent creating instances elsewhere than in log_level_template descendant class
312        log_level_intermediate( ) {
313                int len = names().length();
314                ids.set_size( len );
315                for( int i = 0; i<len; i++ )
316                {
317                        ids(i).set_size ( 1 );
318                        ids(i) = -1;
319                }       
320        }
321public:
322        //! a general utility transforming a comma-separated sequence of strings into an instance of Array<strings>
323        static Array<string> string2Array( const string &input )
324        {
325                string result = input;
326                string::size_type loc;
327                while( loc = result.find( ',' ), loc != string::npos )
328                        result[loc] = ' ';
329                return Array<string>("{ " + result + " }" );
330        } 
331
332        //! this method adds new id to its proper position and return the name of this position
333        string store_id_and_give_name( enum T::log_level_enums const log_level_enum,  int enum_subindex, int id ) {
334                if( ids(log_level_enum).length() <= enum_subindex )
335                        ids(log_level_enum).set_size( enum_subindex+1, true );
336                ids(log_level_enum)(enum_subindex) = id; 
337
338                // here we remove a "log" prefix from name, i.e., for instance it transforms "logevidence" to "evidence"
339                ostringstream stream;
340                string name_with_prefix = names()(log_level_enum);
341                string possible_log_prefix = name_with_prefix.substr(0,3);
342                if( possible_log_prefix == "log" )
343                        stream << name_with_prefix.substr(3,name_with_prefix.length()-3);
344                else 
345                        stream << name_with_prefix;
346
347                // add number to name only in the case there are more registered vectors with the same log_level_enum
348                if( ids(log_level_enum).length() > 1 )
349                        stream << "_" << enum_subindex;
350               
351                return stream.str();
352        }
353
354        //! string equivalents of the used enumerations which are filled with a help of #LOG_LEVEL macro within class T
355        const Array<string> &names() const
356        {
357                return T::log_level_names();
358        }
359
360        //! read only operator for testing individual fields of log_level
361        //!
362        //! it is necessary to acces it with a proper enumeration type, thus this approach is type-safe
363        bool operator [] (const enum T::log_level_enums &log_level_enum ) const
364        {
365                return values[log_level_enum];
366        }
367
368        //! operator for setting an individual field of log_level
369        //!
370        //! it is necessary to acces it with a proper enumeration type, thus this approach is type-safe
371        bitset<32>::reference operator [] (const enum T::log_level_enums &log_level_enum )
372        {
373                return values[log_level_enum];
374        }
375};
376//UIREGISTER IS FORBIDDEN FOR THIS CLASS,  AS IT SHOULD BE LOADED ONLY THROUGH THE SPECIALIZED UI::GET(...) METHOD
377
378
379/*!
380@brief Class for storing results (and semi-results) of an experiment
381
382This 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.
383*/
384class logger : public root {
385protected:
386        //! RVs of all logged variables.
387        Array<RV> entries;
388        //! Names of logged quantities, e.g. names of algorithm variants
389        Array<string> names;
390        //! Root Setting for storing Settings
391        Config setting_conf;
392        //! list of Settings for specific ids
393        Array<Setting*> settings;
394
395        //! log this instance to Setting
396        //!
397        //! this method has to be called only through \c log_level class to assure the validity of the passed id
398        template<class U> void log_setting ( int id, const U data ) {
399                UI::save(data, *settings ( id ) );
400        }
401
402        //! log this vector
403        //!
404        //! this method has to be called only through \c log_level class to assure the validity of the passed id
405        virtual void log_vector ( int id, const vec &v ) NOT_IMPLEMENTED_VOID;
406
407        //! log this double
408        //!
409        //! this method has to be called only through \c log_level class to assure the validity of the passed id
410        virtual void log_double ( int id, const double &d ) NOT_IMPLEMENTED_VOID;
411
412        //! it is necessary to allow log_levels to call log_setting, log_vector and log_double methods
413        template<class T> friend class log_level_template;
414public:
415        //!separator of prefixes of entries
416        //!
417        //! It is a constant string, thus it can be safely declared as public without creating any accessor method
418        const string separator;
419
420        //!Default constructor
421        logger ( const string separator ) : entries ( 0 ), names ( 0 ), separator ( separator ) {}
422
423        //!Destructor calls the finalize method
424        ~logger() {
425                finalize(); 
426        }
427
428        //! sets up the ids identifier in the passed log_level instance to permit future calls of the log_level_template<T>::store(...) method
429        //!
430        //! It also sets a pointer to logger or justify it is correctly assigned from previous call to this procedure
431        //! Entries with empty RV will be ignored
432        //!
433        //! passing the last parameter \c enum_subindex one can store multiple vectors in the position of one enum
434        template<class T> void add_vector ( log_level_intermediate<T> &log_level, enum T::log_level_enums const log_level_enum, const RV &rv, const string &prefix, int enum_subindex = 0 )
435        {
436                if( !log_level.registered_logger )
437                        log_level.registered_logger = this;
438                else
439                        bdm_assert_debug ( log_level.registered_logger == this, "This log_level is already registered to another logger!");
440
441                if ( rv._dsize() == 0 ) 
442                        return;
443               
444                int id = entries.length();
445                string adjusted_name = log_level.store_id_and_give_name( log_level_enum, enum_subindex, id );
446
447                names = concat ( names, prefix + separator + adjusted_name ); // diff
448                entries.set_length ( id + 1, true );
449                entries ( id ) = rv;
450        }
451
452        //! sets up the ids identifier in the passed log_level instance to permit future calls of the log_level_template<T>::store(...) method
453        //!
454        //! It also sets a pointer to logger or justify it is correctly assigned from previous call to this procedure
455        //!
456        //! To allow both arguments log_level and log_level_enum be templated, it was necessary to declare log_level_intermediate<T> class.
457        //! This way we check compatibility of the passed log_level and log_level_enum, which would be impossible using just log_level_base class
458        //! here.
459        //!
460        //!
461        //! passing the last parameter \c enum_subindex one can store multiple settings in the position of one enum
462        template<class T> void add_setting ( log_level_intermediate<T> &log_level, enum T::log_level_enums const log_level_enum,  const string &prefix, int enum_subindex = 0 ) {
463                if( !log_level.registered_logger )
464                        log_level.registered_logger = this;
465                else
466                        bdm_assert_debug ( log_level.registered_logger == this, "This log_level is already registered to another logger!");
467
468                Setting &root = setting_conf.getRoot(); 
469                int id = root.getLength(); //root must be group!!                       
470                string adjusted_name = log_level.store_id_and_give_name( log_level_enum, enum_subindex, id );
471                settings.set_length ( id + 1, true );                   
472                settings ( id ) = &root.add ( prefix + separator + adjusted_name, Setting::TypeList );         
473        }
474
475        //! Shifts storage position for another time step.
476        virtual void step() = 0;
477
478        //! Finalize storing information
479        //!
480        //! This method is called either directly or via destructor ~logger(), therefore it has to permit repetitive calls for the case it is called twice
481        virtual void finalize() {};
482
483        //! Initialize the storage
484        virtual void init() {};
485};
486
487//! This class stores a details that will be logged to a logger
488template<class T> class log_level_template : public log_level_intermediate<T> {
489public:
490
491        //! Set log_levels according to the Setting element
492        void from_setting ( const Setting &element )
493        {
494                string raw_log_level;
495                UI::get( raw_log_level, element );
496                Array<string> loaded_log_level = this->string2Array( raw_log_level );
497       
498                this->values.reset();
499
500                for( int i = 0; i < loaded_log_level.length(); i++ )
501                        for( int j = 0; j < this->names().length(); j++ ){
502                                if( loaded_log_level(i) == this->names()(j)  ) 
503                                {
504                                        this->values[j] = true;
505                                        break;
506                                } 
507                        }
508        }
509
510        //! Store log_levels into the Setting element
511        void to_setting ( Setting &element ) const 
512        {
513                // HERE WE WANT NOT TO DELETE PREVIOUS DATA STORED BY OTHER LOG_LEVELS, SEE SPECIAL IMPLEMENTATION OF UI::GET(...) FOR THIS CLASS
514                string string_to_write =  ( const char* ) element;
515
516                for( unsigned int i = 0; i < this->values.size(); i++ )
517                        if( this->values[i] ) 
518                        {
519                                if( string_to_write.length() > 0 )
520                                        string_to_write = string_to_write + ',';
521                                string_to_write = string_to_write + this->names()(i);
522                        }
523                       
524                element = string_to_write;
525        }
526
527        //! This method stores a vector to the proper place in registered logger
528        //!
529        //! parameter \c enum_subindex identifies the precise position of vector in the case there is more vectors registered to with this enum
530        void store( const enum T::log_level_enums log_level_enum, const vec &vect, int enum_subindex = 0 ) const
531        {
532                bdm_assert_debug( this->registered_logger != NULL, "You have to register instance to a logger first! Use root::log_register(...) method.");
533                bdm_assert_debug( ids( log_level_enum )( enum_subindex ) >= 0, "This particular vector was not added to logger! Use logger::add_vector(...) method.");
534                this->registered_logger->log_vector( ids( log_level_enum )( enum_subindex ), vect );
535        }
536
537        //! This method stores a double to the proper place in registered logger
538        //!
539        //! parameter \c enum_subindex identifies the precise position of double in the case there is more doubles registered to with this enum
540        void store( const enum T::log_level_enums log_level_enum, const double &dbl, int enum_subindex = 0 ) const
541        {
542                bdm_assert_debug( this->registered_logger != NULL, "You have to register instance to a logger first! See root::log_register(...) method.");
543                bdm_assert_debug( ids( log_level_enum )( enum_subindex ) >= 0, "This particular double was not added to logger! Use logger::add_vector(...) method.");
544                this->registered_logger->log_double( ids( log_level_enum )( enum_subindex ), dbl );
545        }
546
547        //! This method stores a Setting obtained by call of UI::save( data, .. ) to the proper place in registered logger
548        //!
549        //! parameter \c enum_subindex identifies the precise position of setting in the case there is more settings registered to with this enum
550        template<class U> void store( const enum T::log_level_enums log_level_enum, const U data, int enum_subindex = 0 ) const
551        {                       
552                bdm_assert_debug( this->registered_logger != NULL, "You have to register instance to a logger first! See root::log_register(...) method.");
553                bdm_assert_debug( ids( log_level_enum )(enum_subindex ) >= 0, "This particular vector was not added to logger! Use logger::add_setting(...) method.");
554                this->registered_logger->log_setting( ids( log_level_enum )( enum_subindex ), data);
555        }
556};
557//UIREGISTER IS FORBIDDEN FOR THIS CLASS,  AS IT SHOULD BE LOADED ONLY THROUGH THE SPECIALIZED UI::GET(...) METHOD
558
559
560/*!
561  \def LOG_LEVEL(classname,...)
562  \brief Macro for defining a log_level attribute with a specific set of enumerations related to a specific class
563
564  This macro has to be called within a class declaration. Its argument \a classname has to correspond to that wrapping class.
565  This macro defines a log_level instance which can be modified either directly or by the means of #UI class.
566
567  One of the main purposes of this macro is to allow variability in using enumerations. By relating them to their names through
568  an array of strings, we are no more dependant on their precise ordering. What is more, we can add or remove any without harming
569  any applications which are using this library.
570
571  \todo Write a more detailed explanation including also examples
572
573  \ref ui
574*/
575#define LOG_LEVEL(classname,...) public: enum log_level_enums { __VA_ARGS__ }; log_level_template<classname> log_level; private: friend class log_level_intermediate<classname>; static const Array<string> &log_level_names() { static const Array<string> log_level_names = log_level_template<classname>::string2Array( #__VA_ARGS__ ); return log_level_names; }
576
577
578//! Class representing function \f$f(x)\f$ of variable \f$x\f$ represented by \c rv
579class fnc : public root {       
580protected:
581        //! Length of the output vector
582        int dimy;
583        //! Length of the input vector
584        int dimc;
585public:
586        //!default constructor
587        fnc() {};
588        //! function evaluates numerical value of \f$f(x)\f$ at \f$x=\f$ \c cond
589        virtual vec eval ( const vec &cond ) {
590                return vec ( 0 );
591        };
592
593        //! access function
594        int dimension() const {
595                return dimy;
596        }
597        //! access function
598        int dimensionc() const {
599                return dimc;
600        }
601        void from_setting(const Setting &set){
602                UI::get(dimy, set, "dim", UI::optional);
603                UI::get(dimc, set, "dimc", UI::optional);
604        }
605};
606
607class epdf;
608
609//! 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.
610class pdf : public root {
611protected:
612        //!dimension of the condition
613        int dimc;
614
615        //! random variable in condition
616        RV rvc;
617
618        //! dimension of random variable
619        int dim;
620
621        //! random variable
622        RV rv;
623
624public:
625        //! \name Constructors
626        //! @{
627
628        pdf() : dimc ( 0 ), rvc(), dim ( 0 ), rv() { }
629
630        pdf ( const pdf &m ) : dimc ( m.dimc ), rvc ( m.rvc ), dim ( m.dim ), rv ( m.rv ) { }
631
632        //!@}
633
634        //! \name Matematical operations
635        //!@{
636
637        //! 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
638        virtual vec samplecond ( const vec &cond ) = 0;
639
640        //! 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
641        virtual mat samplecond_mat ( const vec &cond, int N );
642
643        //! Shortcut for conditioning and evaluation of the internal epdf. In some cases,  this operation can be implemented efficiently.
644        virtual double evallogcond ( const vec &yt, const vec &cond ) = 0;
645
646        //! Matrix version of evallogcond
647        virtual vec evallogcond_mat ( const mat &Yt, const vec &cond ) {
648                vec v ( Yt.cols() );
649                for ( int i = 0; i < Yt.cols(); i++ ) {
650                        v ( i ) = evallogcond ( Yt.get_col ( i ), cond );
651                }
652                return v;
653        }
654
655        //! Array<vec> version of evallogcond
656        virtual vec evallogcond_mat ( const Array<vec> &Yt, const vec &cond ) {
657                vec v ( Yt.length() );
658                for ( int i = 0; i < Yt.length(); i++ ) {
659                        v ( i ) = evallogcond ( Yt( i ), cond );
660                }
661                return v;
662        }
663
664        //! \name Access to attributes
665        //! @{
666
667        const RV& _rv() const {
668                return rv;
669        }
670        const RV& _rvc() const {
671                return rvc;
672        }
673
674        int dimension() const {
675                return dim;
676        }
677        int dimensionc() {
678                return dimc;
679        }
680
681        //! access function
682        void set_dim ( int d ) {
683                dim = d;
684        }
685        //! access function
686        void set_dimc ( int d ) {
687                dimc = d;
688        }
689        //! Load from structure with elements:
690        //!  \code
691        //! { class = "pdf_offspring",
692        //!   rv = {class="RV", names=(...),}; // RV describing meaning of random variable
693        //!   rvc= {class="RV", names=(...),}; // RV describing meaning of random variable in condition
694        //!   // elements of offsprings
695        //! }
696        //! \endcode
697        //!@}
698        void from_setting ( const Setting &set );
699
700        void to_setting ( Setting &set ) const;
701        //!@}
702
703        //! \name Connection to other objects
704        //!@{
705        void set_rvc ( const RV &rvc0 ) {
706                rvc = rvc0;
707        }
708        void set_rv ( const RV &rv0 ) {
709                rv = rv0;
710        }
711
712        //! Names of variables stored in RV are considered to be valid only if their size match size of the parameters (dim).
713        bool isnamed() const {
714                return ( dim == rv._dsize() ) && ( dimc == rvc._dsize() );
715        }
716        //!@}
717};
718SHAREDPTR ( pdf );
719
720//! Probability density function with numerical statistics, e.g. posterior density.
721class epdf : public pdf {
722        //! \var log_level_enums logmean
723        //! log mean value of the density when requested
724       
725        //! \var log_level_enums loglbound
726        //! log lower bound of the density (see function qbounds)
727       
728        //! \var log_level_enums logubound
729        //! log upper bound of the density (see function qbounds)
730       
731        //! \var log_level_enums logfull
732        //! log full record of the density in the form of setting
733        LOG_LEVEL(epdf,logmean,loglbound,logubound);
734
735public:
736        /*! \name Constructors
737         Construction of each epdf should support two types of constructors:
738        \li empty constructor,
739        \li copy constructor,
740
741        The following constructors should be supported for convenience:
742        \li constructor followed by calling \c set_parameters() WHICH IS OBSOLETE (TODO)
743        \li constructor accepting random variables calling \c set_rv()
744
745         All internal data structures are constructed as empty. Their values (including sizes) will be
746         set by method \c set_parameters() WHICH IS OBSOLETE (TODO). This way references can be initialized in constructors.
747        @{*/
748        epdf() {};
749        epdf ( const epdf &e ) : pdf ( e ) {};
750       
751       
752        //!@}
753
754        //! \name Matematical Operations
755        //!@{
756
757        //! Returns a sample, \f$ x \f$ from density \f$ f_x()\f$
758        virtual vec sample() const = 0;
759
760        //! Returns N samples, \f$ [x_1 , x_2 , \ldots \ \f$  from density \f$ f_x(rv)\f$
761        virtual mat sample_mat ( int N ) const;
762
763        //! Compute log-probability of argument \c val
764        //! In case the argument is out of suport return -Infinity
765        virtual double evallog ( const vec &val ) const = 0;
766       
767        //! Compute log-probability of multiple values argument \c val
768        virtual vec evallog_mat ( const mat &Val ) const;
769
770        //! Compute log-probability of multiple values argument \c val
771        virtual vec evallog_mat ( const Array<vec> &Avec ) const;
772
773        //! Return conditional density on the given RV, the remaining rvs will be in conditioning
774        virtual shared_ptr<pdf> condition ( const RV &rv ) const;
775
776        //! Return marginal density on the given RV, the remainig rvs are intergrated out
777        virtual shared_ptr<epdf> marginal ( const RV &rv ) const;
778
779        virtual vec mean() const = 0;
780
781        //! return expected variance (not covariance!)
782        virtual vec variance() const = 0;
783
784        //! return expected covariance -- default is diag(variance)!!
785        virtual mat covariance() const {return diag(variance());};
786       
787        //! Lower and upper bounds of \c percentage % quantile, returns mean-2*sigma as default
788        virtual void qbounds ( vec &lb, vec &ub, double percentage = 0.95 ) const {
789                vec mea = mean();
790                vec std = sqrt ( variance() );
791                lb = mea - 2 * std;
792                ub = mea + 2 * std;
793        };
794        //! Set statistics to match given input epdf. Typically it copies statistics from epdf of the same type and projects those form different types
795        //! \param pdf0 epdf to match
796        //! \param option placeholder for potential options
797        void set_statistics(const epdf *pdf0) NOT_IMPLEMENTED_VOID;
798        //!@}
799
800        //! \name Connection to other classes
801        //! Description of the random quantity via attribute \c rv is optional.
802        //! For operations such as sampling \c rv does not need to be set. However, for \c marginalization
803        //! and \c conditioning \c rv has to be set. NB:
804        //! @{
805
806        //! store values of the epdf on the following levels:
807        //!  #1 mean
808        //!  #2 mean + lower & upper bound
809        void log_register ( logger &L, const string &prefix );
810
811        void log_write() const;
812        //!@}
813
814        //! \name Access to attributes
815        //! @{
816
817        //! Load from structure with elements:
818        //!  \code
819        //! { rv = {class="RV", names=(...),}; // RV describing meaning of random variable
820        //!   // elements of offsprings
821        //! }
822        //! \endcode
823        //!@}
824        void from_setting ( const Setting &set );
825        void to_setting ( Setting &set ) const;
826
827        vec samplecond ( const vec &cond ) {
828                return sample();
829        }
830        double evallogcond ( const vec &val, const vec &cond ) {
831                return evallog ( val );
832        }
833};
834SHAREDPTR ( epdf );
835
836//! pdf with internal epdf that is modified by function \c condition
837template <class EPDF>
838class pdf_internal: public pdf {
839protected :
840        //! Internal epdf used for sampling
841        EPDF iepdf;
842public:
843        //! constructor
844        pdf_internal() : pdf(), iepdf() {
845        }
846
847        //! Update \c iepdf so that it represents this pdf conditioned on \c rvc = cond
848        //! This function provides convenient reimplementation in offsprings
849        virtual void condition ( const vec &cond ) = 0;
850
851        //!access function to iepdf
852        EPDF& e() {
853                return iepdf;
854        }
855
856        //! Reimplements samplecond using \c condition()
857        vec samplecond ( const vec &cond );
858        //! Reimplements evallogcond using \c condition()
859        double evallogcond ( const vec &val, const vec &cond );
860        //! Efficient version of evallogcond for matrices
861        virtual vec evallogcond_mat ( const mat &Dt, const vec &cond );
862        //! Efficient version of evallogcond for Array<vec>
863        virtual vec evallogcond_mat ( const Array<vec> &Dt, const vec &cond );
864        //! Efficient version of samplecond
865        virtual mat samplecond_mat ( const vec &cond, int N );
866
867        void validate() {
868                pdf::validate();
869                iepdf.validate();
870                if ( rv._dsize() < iepdf._rv()._dsize() ) {
871                        rv = iepdf._rv();
872                };
873                dim = iepdf.dimension();
874        }
875};
876
877/*! \brief DataLink is a connection between two data vectors Up and Down
878
879Up can be longer than Down. Down must be fully present in Up (TODO optional)
880See chart:
881\dot
882digraph datalink {
883  node [shape=record];
884  subgraph cluster0 {
885    label = "Up";
886      up [label="<1>|<2>|<3>|<4>|<5>"];
887    color = "white"
888}
889  subgraph cluster1{
890    label = "Down";
891    labelloc = b;
892      down [label="<1>|<2>|<3>"];
893    color = "white"
894}
895    up:1 -> down:1;
896    up:3 -> down:2;
897    up:5 -> down:3;
898}
899\enddot
900
901*/
902class datalink {
903protected:
904        //! Remember how long val should be
905        int downsize;
906
907        //! Remember how long val of "Up" should be
908        int upsize;
909
910        //! val-to-val link, indices of the upper val
911        ivec v2v_up;
912
913public:
914        //! Constructor
915        datalink() : downsize ( 0 ), upsize ( 0 ) { }
916
917        //! Convenience constructor
918        datalink ( const RV &rv, const RV &rv_up ) {
919                set_connection ( rv, rv_up );
920        }
921
922        //! set connection, rv must be fully present in rv_up
923        virtual void set_connection ( const RV &rv, const RV &rv_up );
924
925        //! set connection using indices
926        virtual void set_connection ( int ds, int us, const ivec &upind );
927
928        //! Get val for myself from val of "Up"
929        vec pushdown ( const vec &val_up ) {
930                vec tmp ( downsize );
931                filldown ( val_up, tmp );
932                return tmp;
933        }
934        //! Get val for vector val_down from val of "Up"
935        virtual void filldown ( const vec &val_up, vec &val_down ) {
936                bdm_assert_debug ( upsize == val_up.length(), "Wrong val_up" );
937                val_down = val_up ( v2v_up );
938        }
939        //! Fill val of "Up" by my pieces
940        virtual void pushup ( vec &val_up, const vec &val ) {
941                bdm_assert_debug ( downsize == val.length(), "Wrong val" );
942                bdm_assert_debug ( upsize == val_up.length(), "Wrong val_up" );
943                set_subvector ( val_up, v2v_up, val );
944        }
945        //! access functions
946        int _upsize() {
947                return upsize;
948        }
949        //! access functions
950        int _downsize() {
951                return downsize;
952        }
953        //! for future use
954        virtual ~datalink() {}
955};
956
957/*! Extension of datalink to fill only part of Down
958*/
959class datalink_part : public datalink {
960protected:
961        //! indices of values in vector downsize
962        ivec v2v_down;
963public:
964        void set_connection ( const RV &rv, const RV &rv_up );
965        //! Get val for vector val_down from val of "Up"
966        void filldown ( const vec &val_up, vec &val_down ) {
967                set_subvector ( val_down, v2v_down, val_up ( v2v_up ) );
968        }
969};
970
971/*! \brief Datalink that buffers delayed values - do not forget to call step()
972
973Up is current data, Down is their subset with possibly delayed values
974*/
975class datalink_buffered: public datalink_part {
976protected:
977        //! History, ordered as \f$[Up_{t-1},Up_{t-2}, \ldots]\f$
978        vec history;
979        //! rv of the history
980        RV Hrv;
981        //! h2v : indices in down
982        ivec h2v_down;
983        //! h2v : indices in history
984        ivec h2v_hist;
985        //! v2h: indices of up too be pushed to h
986        ivec v2h_up;
987public:
988
989        datalink_buffered() : datalink_part(), history ( 0 ), h2v_down ( 0 ), h2v_hist ( 0 ) {};
990        //! push current data to history
991        void store_data ( const vec &val_up ) {
992                if ( v2h_up.length() > 0 ) {
993                        history.shift_right ( 0, v2h_up.length() );
994                        history.set_subvector ( 0, val_up ( v2h_up ) );
995                }
996        }
997        //! Get val for myself from val of "Up"
998        vec pushdown ( const vec &val_up ) {
999                vec tmp ( downsize );
1000                filldown ( val_up, tmp );
1001                return tmp;
1002        }
1003
1004        void filldown ( const vec &val_up, vec &val_down ) {
1005                bdm_assert_debug ( val_down.length() >= downsize, "short val_down" );
1006
1007                set_subvector ( val_down, v2v_down, val_up ( v2v_up ) ); // copy direct values
1008                set_subvector ( val_down, h2v_down, history ( h2v_hist ) ); // copy delayed values
1009        }
1010
1011        void set_connection ( const RV &rv, const RV &rv_up );
1012       
1013        //! set history of variable given by \c rv1 to values of \c hist.
1014        void set_history ( const RV& rv1, const vec &hist0 );
1015};
1016
1017//! buffered datalink from 2 vectors to 1
1018class datalink_2to1_buffered {
1019protected:
1020        //! link 1st vector to down
1021        datalink_buffered dl1;
1022        //! link 2nd vector to down
1023        datalink_buffered dl2;
1024public:
1025        //! set connection between RVs
1026        void set_connection ( const RV &rv, const RV &rv_up1, const RV &rv_up2 ) {
1027                dl1.set_connection ( rv, rv_up1 );
1028                dl2.set_connection ( rv, rv_up2 );
1029        }
1030        //! fill values of down from the values of the two up vectors
1031        void filldown ( const vec &val1, const vec &val2, vec &val_down ) {
1032                bdm_assert_debug ( val_down.length() >= dl1._downsize() + dl2._downsize(), "short val_down" );
1033                dl1.filldown ( val1, val_down );
1034                dl2.filldown ( val2, val_down );
1035        }
1036        //! update buffer
1037        void step ( const vec &dt, const vec &ut ) {
1038                dl1.store_data ( dt );
1039                dl2.store_data ( ut );
1040        }
1041};
1042
1043
1044
1045//! Data link with a condition.
1046class datalink_m2e: public datalink {
1047protected:
1048        //! Remember how long cond should be
1049        int condsize;
1050
1051        //!upper_val-to-local_cond link, indices of the upper val
1052        ivec v2c_up;
1053
1054        //!upper_val-to-local_cond link, indices of the local cond
1055        ivec v2c_lo;
1056
1057public:
1058        //! Constructor
1059        datalink_m2e() : condsize ( 0 ) { }
1060
1061        //! Set connection between vectors
1062        void set_connection ( const RV &rv, const RV &rvc, const RV &rv_up );
1063
1064        //!Construct condition
1065        vec get_cond ( const vec &val_up );
1066
1067        //! Copy corresponding values to Up.condition
1068        void pushup_cond ( vec &val_up, const vec &val, const vec &cond );
1069};
1070
1071//!DataLink is a connection between pdf and its superordinate (Up)
1072//! This class links
1073class datalink_m2m: public datalink_m2e {
1074protected:
1075        //!cond-to-cond link, indices of the upper cond
1076        ivec c2c_up;
1077        //!cond-to-cond link, indices of the local cond
1078        ivec c2c_lo;
1079
1080public:
1081        //! Constructor
1082        datalink_m2m() {};
1083        //! Set connection between the vectors
1084        void set_connection ( const RV &rv, const RV &rvc, const RV &rv_up, const RV &rvc_up ) {
1085                datalink_m2e::set_connection ( rv, rvc, rv_up );
1086                //establish c2c connection
1087                rvc.dataind ( rvc_up, c2c_lo, c2c_up );
1088//              bdm_assert_debug ( c2c_lo.length() + v2c_lo.length() == condsize, "cond is not fully given" );
1089        }
1090
1091        //! Get cond for myself from val and cond of "Up"
1092        vec get_cond ( const vec &val_up, const vec &cond_up ) {
1093                vec tmp ( condsize );
1094                fill_cond ( val_up, cond_up, tmp );
1095                return tmp;
1096        }
1097        //! fill condition
1098        void fill_cond ( const vec &val_up, const vec &cond_up, vec& cond_out ) {
1099                bdm_assert_debug ( cond_out.length() >= condsize, "dl.fill_cond: cond_out is too small" );
1100                set_subvector ( cond_out, v2c_lo, val_up ( v2c_up ) );
1101                set_subvector ( cond_out, c2c_lo, cond_up ( c2c_up ) );
1102        }
1103        //! Fill
1104
1105};
1106
1107
1108//! \brief Combines RVs from a list of pdfs to a single one.
1109RV get_composite_rv ( const Array<shared_ptr<pdf> > &pdfs, bool checkoverlap = false );
1110
1111/*! \brief Abstract class for discrete-time sources of data.
1112
1113The class abstracts operations of:
1114\li  data aquisition,
1115\li  data-preprocessing, such as  scaling of data,
1116\li  data resampling from the task of estimation and control.
1117Moreover, for controlled systems, it is able to receive the desired control action and perform it in the next step. (Or as soon as possible).
1118
1119The DataSource has three main data interaction structures:
1120\li input, \f$ u_t \f$,
1121\li output \f$ d_t \f$,
1122In simulators, d_t may contain "hidden" variables as well.
1123*/
1124
1125class DS : public root {
1126        //! \var log_level_enums logdt
1127        //! log all outputs
1128
1129        //! \var log_level_enums logut
1130        //! log all inputs
1131        LOG_LEVEL(DS,logdt,logut);
1132
1133protected:
1134        //! size of data returned by \c getdata()
1135        int dtsize;
1136        //! size of data
1137        int utsize;
1138        //!Description of data returned by \c getdata().
1139        RV Drv;
1140        //!Description of data witten by by \c write().
1141        RV Urv; //
1142public:
1143        //! default constructors
1144        DS() : dtsize ( 0 ), utsize ( 0 ), Drv(), Urv(){
1145                log_level[logdt] = true;
1146                log_level[logut] = true;
1147        };
1148
1149        //! 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().
1150        virtual int max_length() {
1151                return std::numeric_limits< int >::max();
1152        }
1153        //! Returns full vector of observed data=[output, input]
1154        virtual void getdata ( vec &dt ) const = 0;
1155
1156        //! Returns data records at indices. Default is inefficent.
1157        virtual void getdata ( vec &dt, const ivec &indices ) {
1158                vec tmp(dtsize);
1159                getdata(tmp);
1160                dt = tmp(indices);
1161        };
1162
1163        //! Accepts action variable and schedule it for application.   
1164        virtual void write ( const vec &ut ) NOT_IMPLEMENTED_VOID;
1165
1166        //! Accepts action variables at specific indices
1167        virtual void write ( const vec &ut, const ivec &indices ) NOT_IMPLEMENTED_VOID;
1168
1169        //! Moves from \f$ t \f$ to \f$ t+1 \f$, i.e. perfroms the actions and reads response of the system.
1170        virtual void step() = 0;
1171
1172        //! Register DS for logging into logger L
1173        virtual void log_register ( logger &L,  const string &prefix );
1174        //! Register DS for logging into logger L
1175        virtual void log_write ( ) const;
1176        //!access function
1177        virtual const RV& _drv() const {
1178                return Drv;
1179        }
1180        //!access function
1181        const RV& _urv() const {
1182                return Urv;
1183        }
1184
1185        //! set random variables
1186        virtual void set_drv ( const  RV &drv, const RV &urv) {
1187                Drv = drv;
1188                Urv = urv;
1189        }
1190
1191        void from_setting ( const Setting &set );
1192
1193        void validate();
1194};
1195
1196/*! \brief Bayesian Model of a system, i.e. all uncertainty is modeled by probabilities.
1197
1198This object represents exact or approximate evaluation of the Bayes rule:
1199\f[
1200f(\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})}
1201\f]
1202where:
1203 * \f$ y_t \f$ is the variable
1204Access to the resulting posterior density is via function \c posterior().
1205
1206As a "side-effect" it also evaluates log-likelihood of the data, which can be accessed via function _ll().
1207It can also evaluate predictors of future values of \f$y_t\f$, see functions epredictor() and predictor().
1208
1209Alternatively, it can evaluate posterior density with rvc replaced by the given values, \f$ c_t \f$:
1210\f[
1211f(\theta_t | c_t, d_1,\ldots,d_t) \propto  f(y_t,\theta_t|c_t,\cdot, d_1,\ldots,d_{t-1})
1212\f]
1213
1214*/
1215
1216class BM : public root {
1217        //! \var log_level_enums logfull
1218        //! TODO DOPLNIT
1219
1220        //! \var log_level_enums logevidence
1221        //! TODO DOPLNIT
1222       
1223        //! \var log_level_enums logbounds
1224        //! TODO DOPLNIT       
1225        LOG_LEVEL(BM,logfull,logevidence,logbounds);
1226
1227protected:
1228        //! Random variable of the data (optional)
1229        RV yrv;
1230        //! size of the data record
1231        int dimy;
1232        //! Name of extension variable
1233        RV rvc;
1234        //! size of the conditioning vector
1235        int dimc;
1236
1237        //!Logarithm of marginalized data likelihood.
1238        double ll;
1239        //!  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.
1240        bool evalll;
1241
1242public:
1243        //! \name Constructors
1244        //! @{
1245
1246        BM() : yrv(), dimy ( 0 ), rvc(), dimc ( 0 ), ll ( 0 ), evalll ( true ) { };
1247        //      BM ( const BM &B ) :  yrv ( B.yrv ), dimy(B.dimy), rvc ( B.rvc ),dimc(B.dimc), ll ( B.ll ), evalll ( B.evalll ) {}
1248        //! \brief Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually!
1249        //! Prototype: \code BM* _copy() const {return new BM(*this);} \endcode
1250        virtual BM* _copy() const NOT_IMPLEMENTED(NULL);
1251        //!@}
1252
1253        //! \name Mathematical operations
1254        //!@{
1255
1256        /*! \brief Incremental Bayes rule
1257        @param dt vector of input data
1258        */
1259        virtual void bayes ( const vec &yt, const vec &cond = empty_vec ) = 0;
1260        //! Batch Bayes rule (columns of Dt are observations)
1261        virtual void bayes_batch ( const mat &Dt, const vec &cond = empty_vec );
1262        //! Batch Bayes rule (columns of Dt are observations, columns of Cond are conditions)
1263        virtual void bayes_batch ( const mat &Dt, const mat &Cond );
1264        //! Evaluates predictive log-likelihood of the given data record
1265        //! I.e. marginal likelihood of the data with the posterior integrated out.
1266        //! This function evaluates only \f$ y_t \f$, condition is assumed to be the last used in bayes().
1267        //! See bdm::BM::predictor for conditional version.
1268        virtual double logpred ( const vec &yt ) const NOT_IMPLEMENTED(0.0);
1269
1270        //! Matrix version of logpred
1271        vec logpred_mat ( const mat &Yt ) const {
1272                vec tmp ( Yt.cols() );
1273                for ( int i = 0; i < Yt.cols(); i++ ) {
1274                        tmp ( i ) = logpred ( Yt.get_col ( i ) );
1275                }
1276                return tmp;
1277        }
1278
1279        //!Constructs a predictive density \f$ f(d_{t+1} |d_{t}, \ldots d_{0}) \f$
1280        virtual epdf* epredictor(const vec &cond=vec()) const NOT_IMPLEMENTED(NULL);
1281
1282        //!Constructs conditional density of 1-step ahead predictor \f$ f(d_{t+1} |d_{t+h-1}, \ldots d_{t}) \f$
1283        virtual pdf* predictor() const NOT_IMPLEMENTED(NULL);
1284
1285        //!@}
1286
1287
1288        //! \name Access to attributes
1289        //!@{
1290        //! access function
1291        const RV& _rvc() const {
1292                return rvc;
1293        }
1294        //! access function
1295        int dimensionc() const {
1296                return dimc;
1297        }
1298        //! access function
1299        int dimensiony() const {
1300                return dimy;
1301        }
1302        //! access function
1303        int dimension() const {
1304                return posterior().dimension();
1305        }
1306        //! access function
1307        const RV& _rv() const {
1308                return posterior()._rv();
1309        }
1310        //! access function
1311        const RV& _yrv() const {
1312                return yrv;
1313        }
1314        //! access function
1315        void set_yrv ( const RV &rv ) {
1316                yrv = rv;
1317        }
1318        //! access function
1319        void set_rvc ( const RV &rv ) {
1320                rvc = rv;
1321        }
1322        //! access to rv of the posterior
1323        void set_rv ( const RV &rv ) {
1324                const_cast<epdf&> ( posterior() ).set_rv ( rv );
1325        }
1326        //! access function
1327        void set_dim ( int dim ) {
1328                const_cast<epdf&> ( posterior() ).set_dim ( dim );
1329        }
1330        //! return internal log-likelihood of the last data vector
1331        double _ll() const {
1332                return ll;
1333        }
1334        //! switch evaluation of log-likelihood on/off
1335        void set_evalll ( bool evl0 ) {
1336                evalll = evl0;
1337        }
1338        //! return posterior density
1339        virtual const epdf& posterior() const = 0;
1340       
1341        epdf& prior() {return const_cast<epdf&>(posterior());}
1342        //! set prior density -- same as posterior but writable
1343        virtual void set_prior(const epdf *pdf0) NOT_IMPLEMENTED_VOID;
1344       
1345        //!@}
1346
1347        //! \name Logging of results
1348        //!@{
1349
1350        //! Add all logged variables to a logger
1351        //! Log levels two digits: xy where
1352        //!  * y = 0/1 log-likelihood is to be logged
1353        //!  * x = level of the posterior (typically 0/1/2 for nothing/mean/bounds)
1354        virtual void log_register ( logger &L, const string &prefix = "" );
1355
1356        //! Save results to the given logger, details of what is stored is configured by \c LIDs and \c options
1357        virtual void log_write ( ) const;
1358
1359        //!@}
1360        void from_setting ( const Setting &set ) {
1361                UI::get(yrv, set, "yrv", UI::optional );
1362                UI::get(rvc, set, "rvc", UI::optional );
1363                RV r;
1364                UI::get(r, set, "rv", UI::optional );
1365                set_rv ( r );
1366
1367                UI::get ( log_level, set, "log_level", UI::optional );
1368        }
1369
1370        void to_setting ( Setting &set ) const {
1371                root::to_setting( set );
1372                UI::save( &yrv, set, "yrv" );
1373                UI::save( &rvc, set, "rvc" );           
1374                UI::save( &posterior()._rv(), set, "rv" );
1375                UI::save( log_level, set );
1376        }
1377
1378        void validate()
1379        {
1380                if ( log_level[logbounds] ) {
1381                        const_cast<epdf&> ( posterior() ).log_level[epdf::loglbound] = true;
1382                } else {
1383                        const_cast<epdf&> ( posterior() ).log_level[epdf::logmean] = true;;
1384                }
1385        }
1386};
1387
1388//! array of pointers to epdf
1389typedef Array<shared_ptr<epdf> > epdf_array;
1390//! array of pointers to pdf
1391typedef Array<shared_ptr<pdf> > pdf_array;
1392
1393template<class EPDF>
1394vec pdf_internal<EPDF>::samplecond ( const vec &cond ) {
1395        condition ( cond );
1396        vec temp = iepdf.sample();
1397        return temp;
1398}
1399
1400template<class EPDF>
1401mat pdf_internal<EPDF>::samplecond_mat ( const vec &cond, int N ) {
1402        condition ( cond );
1403        mat temp ( dimension(), N );
1404        vec smp ( dimension() );
1405        for ( int i = 0; i < N; i++ ) {
1406                smp = iepdf.sample();
1407                temp.set_col ( i, smp );
1408        }
1409
1410        return temp;
1411}
1412
1413template<class EPDF>
1414double pdf_internal<EPDF>::evallogcond ( const vec &yt, const vec &cond ) {
1415        double tmp;
1416        condition ( cond );
1417        tmp = iepdf.evallog ( yt );
1418        return tmp;
1419}
1420
1421template<class EPDF>
1422vec pdf_internal<EPDF>::evallogcond_mat ( const mat &Yt, const vec &cond ) {
1423        condition ( cond );
1424        return iepdf.evallog_mat ( Yt );
1425}
1426
1427template<class EPDF>
1428vec pdf_internal<EPDF>::evallogcond_mat ( const Array<vec> &Yt, const vec &cond ) {
1429        condition ( cond );
1430        return iepdf.evallog_mat ( Yt );
1431}
1432
1433}; //namespace
1434#endif // BDMBASE_H
Note: See TracBrowser for help on using the browser.