root/bdm/stat/libBM.h @ 223

Revision 223, 15.4 kB (checked in by smidl, 15 years ago)

new experiment in pmsm

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