root/bdm/stat/libBM.h @ 145

Revision 145, 9.1 kB (checked in by smidl, 16 years ago)

Oprava dokumentace

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