root/bdm/stat/libBM.h @ 211

Revision 211, 15.2 kB (checked in by smidl, 16 years ago)

prejmenovani evalpdflog a evalcond

  • 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//!Default empty RV that can be used as default argument
129extern RV RV0;
130
131//! Class representing function \f$f(x)\f$ of variable \f$x\f$ represented by \c rv
132
133class fnc {
134protected:
135        //! Length of the output vector
136        int dimy;
137public:
138        //!default constructor
139        fnc ( int dy ) :dimy ( dy ) {};
140        //! function evaluates numerical value of \f$f(x)\f$ at \f$x=\f$ \c cond
141        virtual vec eval ( const vec &cond ) {
142                return vec ( 0 );
143        };
144
145        //! access function
146        int _dimy() const{return dimy;}
147
148        //! Destructor for future use;
149        virtual ~fnc() {};
150};
151
152class mpdf;
153
154//! Probability density function with numerical statistics, e.g. posterior density.
155
156class epdf {
157protected:
158        //! Identified of the random variable
159        RV rv;
160public:
161        //!default constructor
162        epdf() :rv ( ) {};
163
164        //!default constructor
165        epdf ( const RV &rv0 ) :rv ( rv0 ) {};
166
167//      //! Returns the required moment of the epdf
168//      virtual vec moment ( const int order = 1 );
169
170        //! Returns a sample, \f$x\f$ from density \f$epdf(rv)\f$
171        virtual vec sample () const =0;
172        //! Returns N samples from density \f$epdf(rv)\f$
173        virtual mat sample_m ( int N ) const;
174       
175        //! Compute log-probability of argument \c val
176        virtual double evallog ( const vec &val ) const =0;
177
178        //! Compute log-probability of multiple values argument \c val
179        virtual vec evallog_m ( const mat &Val ) const {
180                vec x ( Val.cols() );
181                for ( int i=0;i<Val.cols();i++ ) {x ( i ) =evallog ( 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->evallog ( 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_m ( 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->evallog ( 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 evallogcond ( const vec &dt, const vec &cond ) {this->condition ( cond );return ep->evallog ( dt );};
235
236        //! Matrix version of evallogcond
237        virtual vec evallogcond_m ( const mat &Dt, const vec &cond ) {this->condition ( cond );return ep->evallog_m ( Dt );};
238
239        //! Destructor for future use;
240        virtual ~mpdf() {};
241
242        //! Default constructor
243        mpdf ( const RV &rv0, const RV &rvc0 ) :rv ( rv0 ),rvc ( rvc0 ) {};
244        //! access function
245        RV _rvc() const {return rvc;}
246        //! access function
247        RV _rv() const {return rv;}
248        //!access function
249        epdf& _epdf() {return *ep;}
250};
251
252//!DataLink is a connection between an epdf and its superordinate epdf (Up)
253//! It is assumed that my val is fully present in "Up"
254class datalink_e2e {
255protected:
256        //! Remember how long val should be
257        int valsize;
258        //! Remember how long val of "Up" should be
259        int valupsize;
260        //! val-to-val link, indeces of the upper val
261        ivec v2v_up;
262public:
263        //! Constructor
264        datalink_e2e ( const RV &rv, const RV &rv_up ) :
265                        valsize ( rv.count() ), valupsize ( rv_up.count() ), v2v_up ( rv.dataind ( rv_up ) )  {
266                it_assert_debug ( v2v_up.length() ==valsize,"rv is not fully in rv_up" );
267        }
268        //! Get val for myself from val of "Up"
269        vec get_val ( const vec &val_up ) {it_assert_debug ( valupsize==val_up.length(),"Wrong val_up" ); return get_vec ( val_up,v2v_up );}
270        //! Fill val of "Up" by my pieces
271        void fill_val ( vec &val_up, const vec &val ) {
272                it_assert_debug ( valsize==val.length(),"Wrong val" );
273                it_assert_debug ( valupsize==val_up.length(),"Wrong val_up" );
274                set_subvector ( val_up, v2v_up, val );
275        }
276};
277
278//! data link between
279class datalink_m2e: public datalink_e2e {
280protected:
281        //! Remember how long cond should be
282        int condsize;
283        //!upper_val-to-local_cond link, indeces of the upper val
284        ivec v2c_up;
285        //!upper_val-to-local_cond link, ideces of the local cond
286        ivec v2c_lo;
287
288public:
289        //! Constructor
290        datalink_m2e ( const RV &rv,  const RV &rvc, const RV &rv_up ) :
291                        datalink_e2e ( rv,rv_up ), condsize ( rvc.count() ) {
292                //establish v2c connection
293                rvc.dataind ( rv_up, v2c_lo, v2c_up );
294        }
295        //!Construct condition
296        vec get_cond ( const vec &val_up ) {
297                vec tmp ( condsize );
298                set_subvector ( tmp,v2c_lo,val_up ( v2c_up ) );
299                return tmp;
300        }
301        void fill_val_cond ( vec &val_up, const vec &val, const vec &cond ) {
302                it_assert_debug ( valsize==val.length(),"Wrong val" );
303                it_assert_debug ( valupsize==val_up.length(),"Wrong val_up" );
304                set_subvector ( val_up, v2v_up, val );
305                set_subvector ( val_up, v2c_up, cond );
306        }
307};
308//!DataLink is a connection between mpdf and its superordinate (Up)
309//! This class links
310class datalink_m2m: public datalink_m2e {
311protected:
312        //!cond-to-cond link, indeces of the upper cond
313        ivec c2c_up;
314        //!cond-to-cond link, indeces of the local cond
315        ivec c2c_lo;
316public:
317        //! Constructor
318        datalink_m2m ( const RV &rv, const RV &rvc, const RV &rv_up, const RV &rvc_up ) :
319                        datalink_m2e ( rv, rvc, rv_up) {
320                //establish c2c connection
321                rvc.dataind ( rvc_up, c2c_lo, c2c_up );
322                it_assert_debug(c2c_lo.length()+v2c_lo.length()==condsize, "cond is not fully given");
323        }
324        //! Get cond for myself from val and cond of "Up"
325        vec get_cond ( const vec &val_up, const vec &cond_up ) {
326                vec tmp ( condsize );
327                set_subvector ( tmp,v2c_lo,val_up ( v2c_up ) );
328                set_subvector ( tmp,c2c_lo,cond_up ( c2c_up ) );
329                return tmp;
330        }
331        //! Fill
332
333};
334
335/*! \brief Unconditional mpdf, allows using epdf in the role of mpdf.
336
337*/
338class mepdf : public mpdf {
339public:
340        //!Default constructor
341        mepdf (const epdf* em ) :mpdf ( em->_rv(),RV() ) {ep=const_cast<epdf*>(em);};
342        void condition ( const vec &cond ) {}
343};
344
345//!\brief Abstract composition of pdfs, a base for specific classes
346//!this abstract class is common to epdf and mpdf
347class compositepdf {
348protected:
349        //!Number of mpdfs in the composite
350        int n;
351        //! Elements of composition
352        Array<mpdf*> mpdfs;
353public:
354        compositepdf ( Array<mpdf*> A0 ) : n ( A0.length() ), mpdfs ( A0 ) {};
355        //! find common rv, flag \param checkoverlap modifies whether overlaps are acceptable
356        RV getrv ( bool checkoverlap=false );
357        //! common rvc of all mpdfs is written to rvc
358        void setrvc ( const RV &rv, RV &rvc );
359};
360
361/*! \brief Abstract class for discrete-time sources of data.
362
363The 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.
364Moreover, for controlled systems, it is able to receive the desired control action and perform it in the next step. (Or as soon as possible).
365
366*/
367
368class DS {
369protected:
370        //!Observed variables, returned by \c getdata().
371        RV Drv;
372        //!Action variables, accepted by \c write().
373        RV Urv; //
374public:
375        //! Returns full vector of observed data
376        void getdata ( vec &dt );
377        //! Returns data records at indeces.
378        void getdata ( vec &dt, ivec &indeces );
379        //! Accepts action variable and schedule it for application.
380        void write ( vec &ut );
381        //! Accepts action variables at specific indeces
382        void write ( vec &ut, ivec &indeces );
383        /*! \brief Method that assigns random variables to the datasource.
384        Typically, the datasource will be constructed without knowledge of random variables. This method will associate existing variables with RVs.
385
386        (Inherited from m3k, may be deprecated soon).
387        */
388        void linkrvs ( RV &drv, RV &urv );
389
390        //! Moves from \f$t\f$ to \f$t+1\f$, i.e. perfroms the actions and reads response of the system.
391        void step();
392
393};
394
395/*! \brief Bayesian Model of the world, i.e. all uncertainty is modeled by probabilities.
396
397*/
398
399class BM {
400protected:
401        //!Random variable of the posterior
402        RV rv;
403        //!Logarithm of marginalized data likelihood.
404        double ll;
405        //!  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.
406        bool evalll;
407public:
408
409        //!Default constructor
410        BM ( const RV &rv0, double ll0=0,bool evalll0=true ) :rv ( rv0 ), ll ( ll0 ),evalll ( evalll0 ) {//Fixme: test rv
411        };
412        //!Copy constructor
413        BM ( const BM &B ) : rv ( B.rv ), ll ( B.ll ), evalll ( B.evalll ) {}
414
415        /*! \brief Incremental Bayes rule
416        @param dt vector of input data
417        */
418        virtual void bayes ( const vec &dt ) = 0;
419        //! Batch Bayes rule (columns of Dt are observations)
420        virtual void bayesB ( const mat &Dt );
421        //! Returns a reference to the epdf representing posterior density on parameters.
422        virtual const epdf& _epdf() const =0;
423
424        //! Returns a pointer to the epdf representing posterior density on parameters. Use with care!
425        virtual const epdf* _e() const =0;
426
427        //! Evaluates predictive log-likelihood of the given data record
428        //! I.e. marginal likelihood of the data with the posterior integrated out.
429        virtual double logpred ( const vec &dt ) const{it_error ( "Not implemented" );return 0.0;}
430        //! Matrix version of logpred
431        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;}
432
433        //!Constructs a predictive density (marginal density on data)
434        virtual epdf* predictor ( const RV &rv ) const {it_error ( "Not implemented" );return NULL;};
435
436        //! Destructor for future use;
437        virtual ~BM() {};
438        //!access function
439        const RV& _rv() const {return rv;}
440        //!access function
441        double _ll() const {return ll;}
442        //!access function
443        void set_evalll ( bool evl0 ) {evalll=evl0;}
444
445        //! Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually!
446        //! Prototype: BM* _copy_(){BM Tmp*=new Tmp(this*);  return Tmp; }
447        virtual BM* _copy_ ( bool changerv=false ) {it_error ( "function _copy_ not implemented for this BM" ); return NULL;};
448};
449
450/*!
451\brief Conditional Bayesian Filter
452
453Evaluates 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.
454
455This is an interface class used to assure that certain BM has operation \c condition .
456
457*/
458
459class BMcond {
460protected:
461        //! Identificator of the conditioning variable
462        RV rvc;
463public:
464        //! Substitute \c val for \c rvc.
465        virtual void condition ( const vec &val ) =0;
466        //! Default constructor
467        BMcond ( RV &rv0 ) :rvc ( rv0 ) {};
468        //! Destructor for future use
469        virtual ~BMcond() {};
470        //! access function
471        const RV& _rvc() const {return rvc;}
472};
473
474#endif // BM_H
Note: See TracBrowser for help on using the browser.