root/bdm/stat/libBM.h @ 170

Revision 170, 10.2 kB (checked in by smidl, 16 years ago)

Mixtures of EF and related changes to libEF and BM

  • 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 <std>
18
19using namespace itpp;
20
21//! Structure of RV (used internally)
22class str{
23public:
24        ivec ids;
25        ivec times;
26        str(ivec ids0, ivec times0):ids(ids0),times(times0){
27                it_assert_debug(times0.length()==ids0.length(),"Incompatible input");
28        };
29};
30
31/*!
32* \brief Class representing variables, most often random variables
33
34* More?...
35*/
36
37class RV {
38protected:
39        //! size = sum of sizes
40        int tsize;
41        //! len = number of individual rvs
42        int len;
43        //! Vector of unique IDs
44        ivec ids;
45        //! Vector of sizes
46        ivec sizes;
47        //! Vector of shifts from current time
48        ivec times;
49        //! Array of names
50        Array<std::string> names;
51
52private:
53        //! auxiliary function used in constructor
54        void init (ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times );
55public:
56        //! Full constructor
57        RV ( Array<std::string> in_names, ivec in_sizes, ivec in_times );
58        //! Constructor with times=0
59        RV ( Array<std::string> in_names, ivec in_sizes );
60        //! Constructor with sizes=1, times=0
61        RV ( Array<std::string> in_names );
62        //! Constructor of empty RV
63        RV ();
64
65        //! Printing output e.g. for debugging.
66        friend std::ostream &operator<< ( std::ostream &os, const RV &rv );
67
68        //! Return number of scalars in the RV.
69        int count() const {return tsize;} ;
70        //! Return length (number of entries) of the RV.
71        int length() const {return len;} ;
72
73        //TODO why not inline and later??
74
75        //! Find indexes of self in another rv, \return ivec of the same size as self.
76        ivec findself (const RV &rv2 ) const;
77        //! Compare if \c rv2 is identical to this \c RV
78        bool equal (const RV &rv2 ) const;
79        //! Add (concat) another variable to the current one, \return true if all rv2 were added, false if rv2 is in conflict
80        bool add ( const RV &rv2 );
81        //! Subtract  another variable from the current one
82        RV subt ( const RV rv2 ) const;
83        //! Select only variables at indeces ind
84        RV subselect ( ivec ind ) const;
85        //! Select only variables at indeces ind
86        RV operator() ( ivec ind ) const;
87        //! Shift \c time shifted by delta.
88        void t ( int delta );
89        //! generate \c str from rv, by expanding sizes
90        str tostr() const;
91        //! generate indeces into \param crv data vector that form data vector of self.
92        ivec dataind(RV crv) const;
93
94        //!access function
95        Array<std::string>& _names() {return names;};
96
97        //!access function
98        int id ( int at ) {return ids ( at );};
99        //!access function
100        int size ( int at ) {return sizes ( at );};
101        //!access function
102        int time ( int at ) {return times ( at );};
103        //!access function
104        std::string name ( int at ) {return names ( at );};
105        //!Assign unused ids to this rv
106        void newids();
107};
108
109//! Concat two random variables
110RV concat ( const RV &rv1, const RV &rv2 );
111
112
113//! Class representing function \f$f(x)\f$ of variable \f$x\f$ represented by \c rv
114
115class fnc {
116protected:
117        //! Length of the output vector
118        int dimy;
119public:
120        //!default constructor
121        fnc ( int dy ) :dimy ( dy ) {};
122        //! function evaluates numerical value of \f$f(x)\f$ at \f$x=\f$ \c cond
123        virtual vec eval ( const vec &cond ) {
124                return vec ( 0 );
125        };
126
127        //! access function
128        int _dimy() const{return dimy;}
129
130        //! Destructor for future use;
131        virtual ~fnc() {};
132};
133
134
135//! Probability density function with numerical statistics, e.g. posterior density.
136
137class epdf {
138protected:
139        //! Identified of the random variable
140        RV rv;
141public:
142        //!default constructor
143        epdf() :rv ( ) {};
144
145        //!default constructor
146        epdf ( const RV &rv0 ) :rv ( rv0 ) {};
147
148//      //! Returns the required moment of the epdf
149//      virtual vec moment ( const int order = 1 );
150       
151        //! Returns a sample, \f$x\f$ from density \f$epdf(rv)\f$
152        virtual vec sample () const =0;
153        //! Returns N samples from density \f$epdf(rv)\f$
154        virtual mat sampleN ( int N ) const;
155        //! Compute probability of argument \c val
156        virtual double eval ( const vec &val ) const {return exp ( this->evalpdflog ( val ) );};
157
158        //! Compute log-probability of argument \c val
159        virtual double evalpdflog ( const vec &val ) const =0;
160
161        //! Compute log-probability of multiple values argument \c val
162        virtual vec evalpdflog ( const mat &Val ) const {
163                vec x ( Val.cols() );
164                for ( int i=0;i<Val.cols();i++ ) {x ( i ) =evalpdflog( Val.get_col(i) ) ;}
165                return x;
166        }
167
168        //! return expected value
169        virtual vec mean() const =0;
170
171        //! Destructor for future use;
172        virtual ~epdf() {};
173        //! access function, possibly dangerous!
174        const RV& _rv() const {return rv;}
175        //! modifier function - useful when copying epdfs
176        void _renewrv(const RV &in_rv){rv=in_rv;}
177};
178
179
180//! Conditional probability density, e.g. modeling some dependencies.
181//TODO Samplecond can be generalized
182
183class mpdf {
184protected:
185        //! modeled random variable
186        RV rv;
187        //! random variable in condition
188        RV rvc;
189        //! pointer to internal epdf
190        epdf* ep;
191public:
192
193        //! Returns the required moment of the epdf
194//      virtual fnc moment ( const int order = 1 );
195        //! 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.
196        virtual vec samplecond (const vec &cond, double &ll ) {this->condition ( cond );
197        vec temp= ep->sample();
198        ll=ep->evalpdflog ( temp );return temp;};
199        //! 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.
200        virtual mat samplecond (const vec &cond, vec &ll, int N ) {
201                this->condition ( cond );
202                mat temp ( rv.count(),N ); vec smp ( rv.count() ); 
203                for ( int i=0;i<N;i++ ) {smp=ep->sample() ;temp.set_col ( i, smp );ll ( i ) =ep->evalpdflog ( smp );}
204                return temp;
205        };
206        //! Update \c ep so that it represents this mpdf conditioned on \c rvc = cond
207        virtual void condition ( const vec &cond ) {};
208
209        //! Shortcut for conditioning and evaluation of the internal epdf. In some cases,  this operation can be implemented efficiently.
210        virtual double evalcond ( const vec &dt, const vec &cond ) {this->condition ( cond );return ep->eval ( dt );};
211
212        //! Destructor for future use;
213        virtual ~mpdf() {};
214
215        //! Default constructor
216        mpdf ( const RV &rv0, const RV &rvc0 ) :rv ( rv0 ),rvc ( rvc0 ) {};
217        //! access function
218        RV _rvc() {return rvc;}
219        //! access function
220        RV _rv() {return rv;}
221        //!access function
222        epdf& _epdf() {return *ep;}
223};
224
225/*! \brief Unconditional mpdf, allows using epdf in the role of mpdf.
226
227WARNING: the class does not check validity of the \c ep pointer nor its existence.
228*/
229class mepdf : public mpdf {
230public:
231        //!Default constructor
232        mepdf (epdf &em ) :mpdf ( em._rv(),RV() ) {ep=&em;};
233};
234
235/*! \brief Abstract class for discrete-time sources of data.
236
237The 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.
238Moreover, for controlled systems, it is able to receive the desired control action and perform it in the next step. (Or as soon as possible).
239
240*/
241
242class DS {
243protected:
244        //!Observed variables, returned by \c getdata().
245        RV Drv;
246        //!Action variables, accepted by \c write().
247        RV Urv; //
248public:
249        //! Returns full vector of observed data
250        void getdata ( vec &dt );
251        //! Returns data records at indeces.
252        void getdata ( vec &dt, ivec &indeces );
253        //! Accepts action variable and schedule it for application.
254        void write ( vec &ut );
255        //! Accepts action variables at specific indeces
256        void write ( vec &ut, ivec &indeces );
257        /*! \brief Method that assigns random variables to the datasource.
258        Typically, the datasource will be constructed without knowledge of random variables. This method will associate existing variables with RVs.
259
260        (Inherited from m3k, may be deprecated soon).
261        */
262        void linkrvs ( RV &drv, RV &urv );
263
264        //! Moves from \f$t\f$ to \f$t+1\f$, i.e. perfroms the actions and reads response of the system.
265        void step();
266
267};
268
269/*! \brief Bayesian Model of the world, i.e. all uncertainty is modeled by probabilities.
270
271*/
272
273class BM {
274protected:
275        //!Random variable of the posterior
276        RV rv;
277        //!Logarithm of marginalized data likelihood.
278        double ll;
279        //!  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.
280        bool evalll;
281public:
282
283        //!Default constructor
284        BM ( const RV &rv0, double ll0=0,bool evalll0=true ) :rv ( rv0 ), ll ( ll0 ),evalll ( evalll0) {//Fixme: test rv
285        };
286        //!Copy constructor
287        BM (const BM &B) : rv(B.rv), ll(B.ll), evalll(B.evalll) {}
288
289        /*! \brief Incremental Bayes rule
290        @param dt vector of input data
291        */
292        virtual void bayes ( const vec &dt ) = 0;
293        //! Batch Bayes rule (columns of Dt are observations)
294        virtual void bayesB (const mat &Dt );
295        //! Returns a pointer to the epdf representing posterior density on parameters. Use with care!
296        virtual const epdf& _epdf() const =0;
297
298        //! Evaluates predictive log-likelihood of the given data record
299        //! I.e. marginal likelihood of the data with the posterior integrated out.
300        virtual double logpred(const vec &dt)const{it_error("Not implemented");return 0.0;}
301       
302        //! Destructor for future use;
303        virtual ~BM() {};
304        //!access function
305        const RV& _rv() const {return rv;}
306        //!access function
307        double _ll() const {return ll;}
308        //!access function
309        void set_evalll(bool evl0){evalll=evl0;}
310       
311        //! Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually!
312        //! Prototype: BM* _copy_(){BM Tmp*=new Tmp(this*);  return Tmp; }
313        virtual BM* _copy_(bool changerv=false){it_error("function _copy_ not implemented for this BM"); return NULL;};
314};
315
316/*!
317\brief Conditional Bayesian Filter
318
319Evaluates 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.
320
321This is an interface class used to assure that certain BM has operation \c condition .
322
323*/
324
325class BMcond {
326protected:
327        //! Identificator of the conditioning variable
328        RV rvc;
329public:
330        //! Substitute \c val for \c rvc.
331        virtual void condition ( const vec &val ) =0;
332        //! Default constructor
333        BMcond ( RV &rv0 ) :rvc ( rv0 ) {};
334        //! Destructor for future use
335        virtual ~BMcond() {};
336        //! access function
337        const RV& _rvc() const {return rvc;}
338};
339
340#endif // BM_H
Note: See TracBrowser for help on using the browser.