root/bdm/stat/libBM.h @ 200

Revision 200, 15.1 kB (checked in by smidl, 16 years ago)

BM has now function _e() returning posterior of correct type

  • Property svn:eol-style set to native
Line 
1/*!
2  \file
3  \brief Bayesian Models (bm) that use Bayes rule to learn from observations
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 BM_H
14#define BM_H
15
16#include <itpp/itbase.h>
17#include "../itpp_ext.h"
18//#include <std>
19
20using namespace itpp;
21
22//! Structure of RV (used internally), i.e. expanded RVs
23class str {
24public:
25        //! vector id ids (non-unique!)
26        ivec ids;
27        //! vector of times
28        ivec times;
29        //!Default constructor
30        str ( ivec ids0, ivec times0 ) :ids ( ids0 ),times ( times0 ) {
31                it_assert_debug ( times0.length() ==ids0.length(),"Incompatible input" );
32        };
33};
34
35/*!
36* \brief Class representing variables, most often random variables
37
38* More?...
39*/
40
41class RV {
42protected:
43        //! size = sum of sizes
44        int tsize;
45        //! len = number of individual rvs
46        int len;
47        //! Vector of unique IDs
48        ivec ids;
49        //! Vector of sizes
50        ivec sizes;
51        //! Vector of shifts from current time
52        ivec times;
53        //! Array of names
54        Array<std::string> names;
55
56private:
57        //! auxiliary function used in constructor
58        void init ( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times );
59public:
60        //! Full constructor
61        RV ( Array<std::string> in_names, ivec in_sizes, ivec in_times );
62        //! Constructor with times=0
63        RV ( Array<std::string> in_names, ivec in_sizes );
64        //! Constructor with sizes=1, times=0
65        RV ( Array<std::string> in_names );
66        //! Constructor of empty RV
67        RV ();
68
69        //! Printing output e.g. for debugging.
70        friend std::ostream &operator<< ( std::ostream &os, const RV &rv );
71
72        //! Return number of scalars in the RV.
73        int count() const {return tsize;} ;
74        //! Return length (number of entries) of the RV.
75        int length() const {return len;} ;
76
77        //TODO why not inline and later??
78
79        //! Find indexes of self in another rv, \return ivec of the same size as self.
80        ivec findself ( const RV &rv2 ) const;
81        //! Compare if \c rv2 is identical to this \c RV
82        bool equal ( const RV &rv2 ) const;
83        //! Add (concat) another variable to the current one, \return true if all rv2 were added, false if rv2 is in conflict
84        bool add ( const RV &rv2 );
85        //! Subtract  another variable from the current one
86        RV subt ( const RV &rv2 ) const;
87        //! Select only variables at indeces ind
88        RV subselect ( const ivec &ind ) const;
89        //! Select only variables at indeces ind
90        RV operator() ( const ivec &ind ) const;
91        //! Shift \c time shifted by delta.
92        void t ( int delta );
93        //! generate \c str from rv, by expanding sizes
94        str tostr() const;
95        //! when this rv is a part of bigger rv, this function returns indeces of self in the data vector of the bigger crv.
96        //! Then, data can be copied via: data_of_this = cdata(ind);
97        ivec dataind ( const RV &crv ) const;
98        //! generate mutual indeces when copying data betwenn self and crv.
99        //! Data are copied via: data_of_this(selfi) = data_of_rv2(rv2i)
100        void dataind ( const RV &rv2, ivec &selfi, ivec &rv2i ) const;
101
102        //!access function
103        Array<std::string>& _names() {return names;};
104
105        //!access function
106        int id ( int at ) {return ids ( at );};
107        //!access function
108        int size ( int at ) {return sizes ( at );};
109        //!access function
110        int time ( int at ) {return times ( at );};
111        //!access function
112        std::string name ( int at ) {return names ( at );};
113
114        //!access function
115        void set_id ( int at, int id0 ) {ids ( at ) =id0;};
116        //!access function
117        void set_size ( int at, int size0 ) {sizes ( at ) =size0; tsize=sum ( sizes );};
118        //!access function
119        void set_time ( int at, int time0 ) {times ( at ) =time0;};
120
121        //!Assign unused ids to this rv
122        void newids();
123};
124
125//! Concat two random variables
126RV concat ( const RV &rv1, const RV &rv2 );
127
128
129//! Class representing function \f$f(x)\f$ of variable \f$x\f$ represented by \c rv
130
131class fnc {
132protected:
133        //! Length of the output vector
134        int dimy;
135public:
136        //!default constructor
137        fnc ( int dy ) :dimy ( dy ) {};
138        //! function evaluates numerical value of \f$f(x)\f$ at \f$x=\f$ \c cond
139        virtual vec eval ( const vec &cond ) {
140                return vec ( 0 );
141        };
142
143        //! access function
144        int _dimy() const{return dimy;}
145
146        //! Destructor for future use;
147        virtual ~fnc() {};
148};
149
150class mpdf;
151
152//! Probability density function with numerical statistics, e.g. posterior density.
153
154class epdf {
155protected:
156        //! Identified of the random variable
157        RV rv;
158public:
159        //!default constructor
160        epdf() :rv ( ) {};
161
162        //!default constructor
163        epdf ( const RV &rv0 ) :rv ( rv0 ) {};
164
165//      //! Returns the required moment of the epdf
166//      virtual vec moment ( const int order = 1 );
167
168        //! Returns a sample, \f$x\f$ from density \f$epdf(rv)\f$
169        virtual vec sample () const =0;
170        //! Returns N samples from density \f$epdf(rv)\f$
171        virtual mat sampleN ( int N ) const;
172        //! Compute probability of argument \c val
173        virtual double eval ( const vec &val ) const {return exp ( this->evalpdflog ( val ) );};
174
175        //! Compute log-probability of argument \c val
176        virtual double evalpdflog ( const vec &val ) const =0;
177
178        //! Compute log-probability of multiple values argument \c val
179        virtual vec evalpdflog_m ( const mat &Val ) const {
180                vec x ( Val.cols() );
181                for ( int i=0;i<Val.cols();i++ ) {x ( i ) =evalpdflog ( Val.get_col ( i ) ) ;}
182                return x;
183        }
184        //! Return conditional density on the given RV, the remaining rvs will be in conditioning
185        virtual mpdf* condition ( const RV &rv ) const  {it_warning ( "Not implemented" ); return NULL;}
186        //! Return marginal density on the given RV, the remainig rvs are intergrated out
187        virtual epdf* marginal ( const RV &rv ) const {it_warning ( "Not implemented" ); return NULL;}
188
189        //! return expected value
190        virtual vec mean() const =0;
191
192        //! Destructor for future use;
193        virtual ~epdf() {};
194        //! access function, possibly dangerous!
195        const RV& _rv() const {return rv;}
196        //! modifier function - useful when copying epdfs
197        void _renewrv ( const RV &in_rv ) {rv=in_rv;}
198        //!
199};
200
201
202//! Conditional probability density, e.g. modeling some dependencies.
203//TODO Samplecond can be generalized
204
205class mpdf {
206protected:
207        //! modeled random variable
208        RV rv;
209        //! random variable in condition
210        RV rvc;
211        //! pointer to internal epdf
212        epdf* ep;
213public:
214
215        //! Returns the required moment of the epdf
216//      virtual fnc moment ( const int order = 1 );
217        //! 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 \param ll is a return value of log-likelihood of the sample.
218        virtual vec samplecond ( const vec &cond, double &ll ) {
219                this->condition ( cond );
220                vec temp= ep->sample();
221                ll=ep->evalpdflog ( temp );return temp;
222        };
223        //! 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 \param ll is a return value of log-likelihood of the sample.
224        virtual mat samplecond ( const vec &cond, vec &ll, int N ) {
225                this->condition ( cond );
226                mat temp ( rv.count(),N ); vec smp ( rv.count() );
227                for ( int i=0;i<N;i++ ) {smp=ep->sample() ;temp.set_col ( i, smp );ll ( i ) =ep->evalpdflog ( smp );}
228                return temp;
229        };
230        //! Update \c ep so that it represents this mpdf conditioned on \c rvc = cond
231        virtual void condition ( const vec &cond ) {it_error ( "Not implemented" );};
232
233        //! Shortcut for conditioning and evaluation of the internal epdf. In some cases,  this operation can be implemented efficiently.
234        virtual double evalcond ( const vec &dt, const vec &cond ) {this->condition ( cond );return ep->eval ( dt );};
235
236        //! Destructor for future use;
237        virtual ~mpdf() {};
238
239        //! Default constructor
240        mpdf ( const RV &rv0, const RV &rvc0 ) :rv ( rv0 ),rvc ( rvc0 ) {};
241        //! access function
242        RV _rvc() const {return rvc;}
243        //! access function
244        RV _rv() const {return rv;}
245        //!access function
246        epdf& _epdf() {return *ep;}
247};
248
249//!DataLink is a connection between an epdf and its superordinate epdf (Up)
250//! It is assumed that my val is fully present in "Up"
251class datalink_e2e {
252protected:
253        //! Remember how long val should be
254        int valsize;
255        //! Remember how long val of "Up" should be
256        int valupsize;
257        //! val-to-val link, indeces of the upper val
258        ivec v2v_up;
259public:
260        //! Constructor
261        datalink_e2e ( const RV &rv, const RV &rv_up ) :
262                        valsize ( rv.count() ), valupsize ( rv_up.count() ), v2v_up ( rv.dataind ( rv_up ) )  {
263                it_assert_debug ( v2v_up.length() ==valsize,"rv is not fully in rv_up" );
264        }
265        //! Get val for myself from val of "Up"
266        vec get_val ( const vec &val_up ) {it_assert_debug ( valupsize==val_up.length(),"Wrong val_up" ); return get_vec ( val_up,v2v_up );}
267        //! Fill val of "Up" by my pieces
268        void fill_val ( vec &val_up, const vec &val ) {
269                it_assert_debug ( valsize==val.length(),"Wrong val" );
270                it_assert_debug ( valupsize==val_up.length(),"Wrong val_up" );
271                set_subvector ( val_up, v2v_up, val );
272        }
273};
274
275//! data link between
276class datalink_m2e: public datalink_e2e {
277protected:
278        //! Remember how long cond should be
279        int condsize;
280        //!upper_val-to-local_cond link, indeces of the upper val
281        ivec v2c_up;
282        //!upper_val-to-local_cond link, ideces of the local cond
283        ivec v2c_lo;
284
285public:
286        //! Constructor
287        datalink_m2e ( const RV &rv,  const RV &rvc, const RV &rv_up ) :
288                        datalink_e2e ( rv,rv_up ), condsize ( rvc.count() ) {
289                //establish v2c connection
290                rvc.dataind ( rv_up, v2c_lo, v2c_up );
291        }
292        //!Construct condition
293        vec get_cond ( const vec &val_up ) {
294                vec tmp ( condsize );
295                set_subvector ( tmp,v2c_lo,val_up ( v2c_up ) );
296                return tmp;
297        }
298        void fill_val_cond ( vec &val_up, const vec &val, const vec &cond ) {
299                it_assert_debug ( valsize==val.length(),"Wrong val" );
300                it_assert_debug ( valupsize==val_up.length(),"Wrong val_up" );
301                set_subvector ( val_up, v2v_up, val );
302                set_subvector ( val_up, v2c_up, cond );
303        }
304};
305//!DataLink is a connection between mpdf and its superordinate (Up)
306//! This class links
307class datalink_m2m: public datalink_m2e {
308protected:
309        //!cond-to-cond link, indeces of the upper cond
310        ivec c2c_up;
311        //!cond-to-cond link, indeces of the local cond
312        ivec c2c_lo;
313public:
314        //! Constructor
315        datalink_m2m ( const RV &rv, const RV &rvc, const RV &rv_up, const RV &rvc_up ) :
316                        datalink_m2e ( rv, rvc, rv_up) {
317                //establish c2c connection
318                rvc.dataind ( rvc_up, c2c_lo, c2c_up );
319                it_assert_debug(c2c_lo.length()+v2c_lo.length()==condsize, "cond is not fully given");
320        }
321        //! Get cond for myself from val and cond of "Up"
322        vec get_cond ( const vec &val_up, const vec &cond_up ) {
323                vec tmp ( condsize );
324                set_subvector ( tmp,v2c_lo,val_up ( v2c_up ) );
325                set_subvector ( tmp,c2c_lo,cond_up ( c2c_up ) );
326                return tmp;
327        }
328        //! Fill
329
330};
331
332/*! \brief Unconditional mpdf, allows using epdf in the role of mpdf.
333
334*/
335class mepdf : public mpdf {
336public:
337        //!Default constructor
338        mepdf ( epdf &em ) :mpdf ( em._rv(),RV() ) {ep=&em;};
339        void condition ( const vec &cond ) {}
340};
341
342//!\brief Abstract composition of pdfs, a base for specific classes
343//!this abstract class is common to epdf and mpdf
344class compositepdf {
345protected:
346        //!Number of mpdfs in the composite
347        int n;
348        //! Elements of composition
349        Array<mpdf*> mpdfs;
350public:
351        compositepdf ( Array<mpdf*> A0 ) : n ( A0.length() ), mpdfs ( A0 ) {};
352        //! find common rv, flag \param checkoverlap modifies whether overlaps are acceptable
353        RV getrv ( bool checkoverlap=false );
354        //! common rvc of all mpdfs is written to rvc
355        void setrvc ( const RV &rv, RV &rvc );
356};
357
358/*! \brief Abstract class for discrete-time sources of data.
359
360The class abstracts operations of: (i) data aquisition, (ii) data-preprocessing, (iii) scaling of data, and (iv) data resampling from the task of estimation and control.
361Moreover, for controlled systems, it is able to receive the desired control action and perform it in the next step. (Or as soon as possible).
362
363*/
364
365class DS {
366protected:
367        //!Observed variables, returned by \c getdata().
368        RV Drv;
369        //!Action variables, accepted by \c write().
370        RV Urv; //
371public:
372        //! Returns full vector of observed data
373        void getdata ( vec &dt );
374        //! Returns data records at indeces.
375        void getdata ( vec &dt, ivec &indeces );
376        //! Accepts action variable and schedule it for application.
377        void write ( vec &ut );
378        //! Accepts action variables at specific indeces
379        void write ( vec &ut, ivec &indeces );
380        /*! \brief Method that assigns random variables to the datasource.
381        Typically, the datasource will be constructed without knowledge of random variables. This method will associate existing variables with RVs.
382
383        (Inherited from m3k, may be deprecated soon).
384        */
385        void linkrvs ( RV &drv, RV &urv );
386
387        //! Moves from \f$t\f$ to \f$t+1\f$, i.e. perfroms the actions and reads response of the system.
388        void step();
389
390};
391
392/*! \brief Bayesian Model of the world, i.e. all uncertainty is modeled by probabilities.
393
394*/
395
396class BM {
397protected:
398        //!Random variable of the posterior
399        RV rv;
400        //!Logarithm of marginalized data likelihood.
401        double ll;
402        //!  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.
403        bool evalll;
404public:
405
406        //!Default constructor
407        BM ( const RV &rv0, double ll0=0,bool evalll0=true ) :rv ( rv0 ), ll ( ll0 ),evalll ( evalll0 ) {//Fixme: test rv
408        };
409        //!Copy constructor
410        BM ( const BM &B ) : rv ( B.rv ), ll ( B.ll ), evalll ( B.evalll ) {}
411
412        /*! \brief Incremental Bayes rule
413        @param dt vector of input data
414        */
415        virtual void bayes ( const vec &dt ) = 0;
416        //! Batch Bayes rule (columns of Dt are observations)
417        virtual void bayesB ( const mat &Dt );
418        //! Returns a reference to the epdf representing posterior density on parameters.
419        virtual const epdf& _epdf() const =0;
420
421        //! Returns a pointer to the epdf representing posterior density on parameters. Use with care!
422        virtual const epdf* _e() const =0;
423
424        //! Evaluates predictive log-likelihood of the given data record
425        //! I.e. marginal likelihood of the data with the posterior integrated out.
426        virtual double logpred ( const vec &dt ) const{it_error ( "Not implemented" );return 0.0;}
427        //! Matrix version of logpred
428        vec logpred_m ( const mat &dt ) const{vec tmp ( dt.cols() );for ( int i=0;i<dt.cols();i++ ) {tmp ( i ) =logpred ( dt.get_col ( i ) );}return tmp;}
429
430        //!Constructs a predictive density (marginal density on data)
431        virtual epdf* predictor ( const RV &rv ) const {it_error ( "Not implemented" );return NULL;};
432
433        //! Destructor for future use;
434        virtual ~BM() {};
435        //!access function
436        const RV& _rv() const {return rv;}
437        //!access function
438        double _ll() const {return ll;}
439        //!access function
440        void set_evalll ( bool evl0 ) {evalll=evl0;}
441
442        //! Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually!
443        //! Prototype: BM* _copy_(){BM Tmp*=new Tmp(this*);  return Tmp; }
444        virtual BM* _copy_ ( bool changerv=false ) {it_error ( "function _copy_ not implemented for this BM" ); return NULL;};
445};
446
447/*!
448\brief Conditional Bayesian Filter
449
450Evaluates conditional filtering density \f$f(rv|rvc,data)\f$ for a given \c rvc which is specified in each step by calling function \c condition.
451
452This is an interface class used to assure that certain BM has operation \c condition .
453
454*/
455
456class BMcond {
457protected:
458        //! Identificator of the conditioning variable
459        RV rvc;
460public:
461        //! Substitute \c val for \c rvc.
462        virtual void condition ( const vec &val ) =0;
463        //! Default constructor
464        BMcond ( RV &rv0 ) :rvc ( rv0 ) {};
465        //! Destructor for future use
466        virtual ~BMcond() {};
467        //! access function
468        const RV& _rvc() const {return rvc;}
469};
470
471#endif // BM_H
Note: See TracBrowser for help on using the browser.