root/bdm/stat/libBM.h @ 190

Revision 190, 14.4 kB (checked in by smidl, 16 years ago)

adaptation of merger for changes and creation of datalink class

  • 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 epdf and its superordinate (Up)
250//! It is assumed that my val is fully present in "Up"
251class datalink {
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;
259        public:
260        //! Constructor
261        datalink ( const RV &rv, const RV &rv_up ) :
262                valsize(rv.count()), valupsize(rv_up.count()), v2v_up ( rv.dataind ( rv_up ) )  {it_assert_debug(v2v_up.length()==valsize,"rv is not fully in rv_up");}
263        //! Get val for myself from val of "Up"
264        vec get_val ( const vec &val_up ) {it_assert_debug(valupsize==val_up.length(),"Wrong val_up"); return get_vec ( val_up,v2v_up );}
265        //! Fill val of "Up" by my pieces
266        void fill_val ( vec &val_up, const vec &val ) {it_assert_debug(valsize==val.length(),"Wrong val");it_assert_debug(valupsize==val_up.length(),"Wrong val_up");set_subvector ( val_up, v2v_up, val );}
267};
268
269//!DataLink is a connection between mpdf and its superordinate (Up)
270//! This class links
271class datalink_mpdf: public datalink {
272protected:
273        //!upper_val-to-local_cond link, indeces of the upper val
274        ivec v2c_up;
275        //!upper_val-to-local_cond link, ideces of the local cond
276        ivec v2c_lo;
277        //!cond-to-cond link, indeces of the upper cond
278        ivec c2c_up;
279        //!cond-to-cond link, indeces of the local cond
280        ivec c2c_lo;
281        //! size of cond
282        int csize;
283public:
284        //! Constructor
285        datalink_mpdf ( const mpdf &Me, const mpdf &Up ) :
286                        datalink ( Me._rv(),Up._rv() ) {
287                //establish v2c connection
288                Me._rvc().dataind ( Up._rv(), v2c_lo, v2c_up );
289                //establish c2c connection
290                Me._rvc().dataind ( Up._rvc(), c2c_lo, c2c_up );
291                csize = Me._rvc().count();
292        }
293        //! Get cond for myself from val and cond of "Up"
294        vec get_cond ( const vec &val_up, const vec &cond_up ) {
295                vec tmp(csize);
296                set_subvector(tmp,v2c_lo,val_up(v2c_up));
297                set_subvector(tmp,c2c_lo,cond_up(c2c_up));
298                return tmp;
299        }
300        //! Fill
301
302};
303
304/*! \brief Unconditional mpdf, allows using epdf in the role of mpdf.
305
306WARNING: the class does not check validity of the \c ep pointer nor its existence.
307*/
308class mepdf : public mpdf {
309public:
310        //!Default constructor
311        mepdf ( epdf &em ) :mpdf ( em._rv(),RV() ) {ep=&em;};
312        void condition ( const vec &cond ) {}
313};
314
315//!\brief Abstract composition of pdfs, a base for specific classes
316class compositepdf {
317protected:
318        //!Number of mpdfs in the composite
319        int n;
320        //! Elements of composition
321        Array<mpdf*> mpdfs;
322        //! Indeces of rvs in common rv
323        Array<ivec> rvsinrv;
324        //! Indeces of rvc in common rv
325        Array<ivec> irvcs_rv;
326        //! Indeces of common rv in rvc
327        Array<ivec> irv_rvcs;
328public:
329        compositepdf ( Array<mpdf*> A0 ) : n ( A0.length() ), mpdfs ( A0 ), rvsinrv ( n ), irvcs_rv ( n ),irv_rvcs ( n ) {};
330        //! find common rv, flag \param checkoverlap modifies whether overlaps are acceptable
331        RV getrv ( bool checkoverlap=false );
332        //! common rvc of all mpdfs is written to rvc
333        void setrvc ( const RV &rv, RV &rvc );
334        //! fill all rv*inrv* according to
335        void setindices ( const RV &rv );
336};
337
338/*! \brief Abstract class for discrete-time sources of data.
339
340The 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.
341Moreover, for controlled systems, it is able to receive the desired control action and perform it in the next step. (Or as soon as possible).
342
343*/
344
345class DS {
346protected:
347        //!Observed variables, returned by \c getdata().
348        RV Drv;
349        //!Action variables, accepted by \c write().
350        RV Urv; //
351public:
352        //! Returns full vector of observed data
353        void getdata ( vec &dt );
354        //! Returns data records at indeces.
355        void getdata ( vec &dt, ivec &indeces );
356        //! Accepts action variable and schedule it for application.
357        void write ( vec &ut );
358        //! Accepts action variables at specific indeces
359        void write ( vec &ut, ivec &indeces );
360        /*! \brief Method that assigns random variables to the datasource.
361        Typically, the datasource will be constructed without knowledge of random variables. This method will associate existing variables with RVs.
362
363        (Inherited from m3k, may be deprecated soon).
364        */
365        void linkrvs ( RV &drv, RV &urv );
366
367        //! Moves from \f$t\f$ to \f$t+1\f$, i.e. perfroms the actions and reads response of the system.
368        void step();
369
370};
371
372/*! \brief Bayesian Model of the world, i.e. all uncertainty is modeled by probabilities.
373
374*/
375
376class BM {
377protected:
378        //!Random variable of the posterior
379        RV rv;
380        //!Logarithm of marginalized data likelihood.
381        double ll;
382        //!  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.
383        bool evalll;
384public:
385
386        //!Default constructor
387        BM ( const RV &rv0, double ll0=0,bool evalll0=true ) :rv ( rv0 ), ll ( ll0 ),evalll ( evalll0 ) {//Fixme: test rv
388        };
389        //!Copy constructor
390        BM ( const BM &B ) : rv ( B.rv ), ll ( B.ll ), evalll ( B.evalll ) {}
391
392        /*! \brief Incremental Bayes rule
393        @param dt vector of input data
394        */
395        virtual void bayes ( const vec &dt ) = 0;
396        //! Batch Bayes rule (columns of Dt are observations)
397        virtual void bayesB ( const mat &Dt );
398        //! Returns a pointer to the epdf representing posterior density on parameters. Use with care!
399        virtual const epdf& _epdf() const =0;
400
401        //! Evaluates predictive log-likelihood of the given data record
402        //! I.e. marginal likelihood of the data with the posterior integrated out.
403        virtual double logpred ( const vec &dt ) const{it_error ( "Not implemented" );return 0.0;}
404        //! Matrix version of logpred
405        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;}
406
407        //!Constructs a predictive density (marginal density on data)
408        virtual epdf* predictor ( const RV &rv ) {it_error ( "Not implemented" );return NULL;};
409
410        //! Destructor for future use;
411        virtual ~BM() {};
412        //!access function
413        const RV& _rv() const {return rv;}
414        //!access function
415        double _ll() const {return ll;}
416        //!access function
417        void set_evalll ( bool evl0 ) {evalll=evl0;}
418
419        //! Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually!
420        //! Prototype: BM* _copy_(){BM Tmp*=new Tmp(this*);  return Tmp; }
421        virtual BM* _copy_ ( bool changerv=false ) {it_error ( "function _copy_ not implemented for this BM" ); return NULL;};
422};
423
424/*!
425\brief Conditional Bayesian Filter
426
427Evaluates 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.
428
429This is an interface class used to assure that certain BM has operation \c condition .
430
431*/
432
433class BMcond {
434protected:
435        //! Identificator of the conditioning variable
436        RV rvc;
437public:
438        //! Substitute \c val for \c rvc.
439        virtual void condition ( const vec &val ) =0;
440        //! Default constructor
441        BMcond ( RV &rv0 ) :rvc ( rv0 ) {};
442        //! Destructor for future use
443        virtual ~BMcond() {};
444        //! access function
445        const RV& _rvc() const {return rvc;}
446};
447
448#endif // BM_H
Note: See TracBrowser for help on using the browser.