root/library/bdm/stat/emix.h @ 944

Revision 944, 9.2 kB (checked in by smidl, 14 years ago)

Doc + new examples

  • Property svn:eol-style set to native
Line 
1/*!
2  \file
3  \brief Probability distributions for Mixtures of pdfs
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 EMIX_H
14#define EMIX_H
15
16#define LOG2  0.69314718055995
17
18#include "../shared_ptr.h"
19#include "exp_family.h"
20
21namespace bdm {
22
23//this comes first because it is used inside emix!
24
25/*! \brief Class representing ratio of two densities
26which arise e.g. by applying the Bayes rule.
27It represents density in the form:
28\f[
29f(rv|rvc) = \frac{f(rv,rvc)}{f(rvc)}
30\f]
31where \f$ f(rvc) = \int f(rv,rvc) d\ rv \f$.
32
33In particular this type of arise by conditioning of a mixture model.
34
35At present the only supported operation is evallogcond().
36 */
37class mratio: public pdf {
38protected:
39        //! Nominator in the form of pdf
40        const epdf* nom;
41
42        //!Denominator in the form of epdf
43        shared_ptr<epdf> den;
44
45        //!flag for destructor
46        bool destroynom;
47        //!datalink between conditional and nom
48        datalink_m2e dl;
49public:
50        //!Default constructor. By default, the given epdf is not copied!
51        //! It is assumed that this function will be used only temporarily.
52        mratio ( const epdf* nom0, const RV &rv, bool copy = false ) : pdf ( ), dl ( ) {
53                // adjust rv and rvc
54
55                set_rv ( rv ); 
56                dim = rv._dsize();
57
58                rvc = nom0->_rv().subt ( rv );
59                dimc = rvc._dsize();
60
61                //prepare data structures
62                if ( copy ) {
63                        bdm_error ( "todo" );
64                        // destroynom = true;
65                } else {
66                        nom = nom0;
67                        destroynom = false;
68                }
69                bdm_assert_debug ( rvc.length() > 0, "Makes no sense to use this object!" );
70
71                // build denominator
72                den = nom->marginal ( rvc );
73                dl.set_connection ( rv, rvc, nom0->_rv() );
74        };
75
76        double evallogcond ( const vec &val, const vec &cond ) {
77                double tmp;
78                vec nom_val ( dimension() + dimc );
79                dl.pushup_cond ( nom_val, val, cond );
80                tmp = exp ( nom->evallog ( nom_val ) - den->evallog ( cond ) );
81                return tmp;
82        }
83
84        //! 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
85        virtual vec samplecond ( const vec &cond ) NOT_IMPLEMENTED(0);
86
87        //! Object takes ownership of nom and will destroy it
88        void ownnom() {
89                destroynom = true;
90        }
91        //! Default destructor
92        ~mratio() {
93                if ( destroynom ) {
94                        delete nom;
95                }
96        }
97
98
99private:
100        // not implemented
101        mratio ( const mratio & );
102        mratio &operator= ( const mratio & );
103};
104
105class emix; //forward
106
107/*! Base class (Interface) for mixtures
108*/
109class emix_base : public epdf {
110        protected:
111        //! reference to vector of weights
112        vec &w;
113        //! function returning ith component
114        virtual const epdf * component(const int &i) const=0;
115       
116        virtual int no_coms() const=0;
117       
118        public:
119               
120                emix_base(vec &w0): w(w0){}
121               
122                void validate ();
123               
124                vec sample() const;
125               
126                vec mean() const;
127               
128                vec variance() const;
129               
130                double evallog ( const vec &val ) const;
131               
132                vec evallog_mat ( const mat &Val ) const;
133               
134                //! Auxiliary function that returns pdflog for each component
135                mat evallog_coms ( const mat &Val ) const;
136               
137                shared_ptr<epdf> marginal ( const RV &rv ) const;
138                //! Update already existing marginal density  \c target
139                void marginal ( const RV &rv, emix &target ) const;
140                shared_ptr<pdf> condition ( const RV &rv ) const;
141               
142                //Access methods       
143                //! returns a reference to the internal weights. Use with Care!
144                vec& _w() {
145                        return w;
146                }
147               
148                const vec& _w() const {
149                        return w;
150                }
151                //!access
152                const epdf* _com(int i) const {return component(i);}
153               
154};
155
156/*!
157* \brief Mixture of epdfs
158
159Density function:
160\f[
161f(x) = \sum_{i=1}^{n} w_{i} f_i(x), \quad \sum_{i=1}^n w_i = 1.
162\f]
163where \f$f_i(x)\f$ is any density on random variable \f$x\f$, called \a component,
164
165*/
166class emix : public emix_base {
167protected:
168        //! weights of the components
169        vec weights;
170
171        //! Component (epdfs)
172        Array<shared_ptr<epdf> > Coms;
173
174public:
175        //! Default constructor
176        emix ( ) : emix_base ( weights) { }
177       
178        const epdf* component(const int &i) const {return Coms(i).get();}
179        void validate();
180       
181
182        int no_coms() const {return Coms.length(); }
183
184        //! Load from structure with elements:
185        //!  \code
186        //! { class='emix';
187        //!   pdfs = (..., ...);     // list of pdfs in the mixture
188        //!   weights = ( 0.5, 0.5 ); // weights of pdfs in the mixture
189        //! }
190        //! \endcode
191        //!@}
192        void from_setting ( const Setting &set );
193
194        void set_rv ( const RV &rv ) {
195                epdf::set_rv ( rv );
196                for ( int i = 0; i < no_coms(); i++ ) {
197                        Coms( i )->set_rv ( rv );
198                }
199        }
200       
201        Array<shared_ptr<epdf> >& _Coms ( ) {
202                        return Coms;
203                }
204};
205SHAREDPTR ( emix );
206UIREGISTER ( emix );
207
208
209/*! \brief Chain rule decomposition of epdf
210
211Probability density in the form of Chain-rule decomposition:
212\[
213f(x_1,x_2,x_3) = f(x_1|x_2,x_3)f(x_2,x_3)f(x_3)
214\]
215Note that
216*/
217class mprod: public pdf {
218private:
219        Array<shared_ptr<pdf> > pdfs;
220
221        //! Data link for each pdfs
222        Array<shared_ptr<datalink_m2m> > dls;
223
224public:
225        //! \brief Default constructor
226        mprod() { }
227
228        /*!\brief Constructor from list of mFacs
229        */
230        mprod ( const Array<shared_ptr<pdf> > &mFacs ) {
231                set_elements ( mFacs );
232        }
233        //! Set internal \c pdfs from given values
234        void set_elements ( const Array<shared_ptr<pdf> > &mFacs );
235
236        double evallogcond ( const vec &val, const vec &cond );
237
238        vec evallogcond_mat ( const mat &Dt, const vec &cond );
239
240        vec evallogcond_mat ( const Array<vec> &Dt, const vec &cond );
241
242        //TODO smarter...
243        vec samplecond ( const vec &cond ) {
244                //! Ugly hack to help to discover if mpfs are not in proper order. Correct solution = check that explicitely.
245                vec smp = std::numeric_limits<double>::infinity() * ones ( dimension() );
246                vec smpi;
247                // Hard assumption here!!! We are going backwards, to assure that samples that are needed from smp are already generated!
248                for ( int i = ( pdfs.length() - 1 ); i >= 0; i-- ) {
249                        // generate contribution of this pdf
250                        smpi = pdfs ( i )->samplecond ( dls ( i )->get_cond ( smp , cond ) );
251                        // copy contribution of this pdf into smp
252                        dls ( i )->pushup ( smp, smpi );
253                }
254                return smp;
255        }
256
257        //! Load from structure with elements:
258        //!  \code
259        //! { class='mprod';
260        //!   pdfs = (..., ...);     // list of pdfs in the order of chain rule
261        //! }
262        //! \endcode
263        //!@}
264        void from_setting ( const Setting &set ) {
265                Array<shared_ptr<pdf> > temp_array; 
266                UI::get ( temp_array, set, "pdfs", UI::compulsory );
267                set_elements ( temp_array );
268        }
269};
270UIREGISTER ( mprod );
271SHAREDPTR ( mprod );
272
273
274//! Product of independent epdfs. For dependent pdfs, use mprod.
275class eprod_base: public epdf {
276protected:
277        //! Array of indices
278        Array<datalink*> dls;
279        //! interface for a factor
280        virtual const epdf* factor(int i) const NOT_IMPLEMENTED(NULL); 
281        //!number of factors
282        virtual const int no_factors() const =0;
283public:
284        //! Default constructor
285        eprod_base () :  dls (0) {};
286        //! Set internal
287        vec mean() const;
288
289        vec variance() const;
290
291        vec sample() const;
292
293        double evallog ( const vec &val ) const;
294
295        //!Destructor
296        ~eprod_base() {
297                for ( int i = 0; i < dls.length(); i++ ) {
298                        delete dls ( i );
299                }
300        }
301        void validate() {
302                dls.set_length ( no_factors() );
303               
304                bool independent = true;
305                dim = 0;
306                for ( int i = 0; i < no_factors(); i++ ) {
307                        independent = rv.add ( factor ( i )->_rv() );
308                        dim += factor ( i )->dimension();
309                        bdm_assert_debug ( independent, "eprod:: given components are not independent." );
310                };
311               
312                //
313                int cumdim = 0;
314                int dimi = 0;
315                int i;
316                for ( i = 0; i < no_factors(); i++ ) {
317                        dls ( i ) = new datalink;
318                        if ( isnamed() ) { // rvs are complete
319                                dls ( i )->set_connection ( factor ( i )->_rv() , rv );
320                        } else { //rvs are not reliable
321                                dimi = factor ( i )->dimension();
322                                dls ( i )->set_connection ( dimi, dim, linspace ( cumdim, cumdim + dimi - 1 ) );
323                                cumdim += dimi;
324                        }
325                }
326       
327        }
328};
329
330class eprod: public eprod_base{
331        protected:
332                Array<shared_ptr<epdf> > factors;
333        public:
334                const epdf* factor(int i) const {return factors(i).get();}
335                const int no_factors() const {return factors.length();}
336        void set_parameters ( const Array<shared_ptr<epdf> > &epdfs0) {
337                factors = epdfs0;
338        }
339        void from_setting(const Setting &set){
340                UI::get(factors,set,"pdfs",UI::compulsory);
341        }
342};
343UIREGISTER(eprod);
344
345//! similar to eprod but used only internally -- factors are external pointers
346class eprod_internal: public eprod_base{
347        protected:
348                Array<epdf* > factors;
349                const epdf* factor(int i) const {return factors(i);}
350                const int no_factors() const {return factors.length();}
351        public:
352                void set_parameters ( const Array<epdf *> &epdfs0) {
353                        factors = epdfs0;
354                }
355};
356
357/*! \brief Mixture of pdfs with constant weights, all pdfs are of equal RV and RVC
358
359*/
360class mmix : public pdf {
361protected:
362        //! Component (pdfs)
363        Array<shared_ptr<pdf> > Coms;
364        //!weights of the components
365        vec w;
366public:
367        //!Default constructor
368        mmix() : Coms ( 0 ) { };
369
370        double evallogcond ( const vec &dt, const vec &cond ) {
371                double ll = 0.0;
372                for ( int i = 0; i < Coms.length(); i++ ) {
373                        ll += Coms ( i )->evallogcond ( dt, cond );
374                }
375                return ll;
376        }
377
378        vec samplecond ( const vec &cond );
379
380        //! Load from structure with elements:
381        //!  \code
382        //! { class='mmix';
383        //!   pdfs = (..., ...);     // list of pdfs in the mixture
384        //!   weights = ( 0.5, 0.5 ); // weights of pdfs in the mixture
385        //! }
386        //! \endcode
387        //!@}
388        void from_setting ( const Setting &set );
389
390        virtual void validate();
391};
392SHAREDPTR ( mmix );
393UIREGISTER ( mmix );
394
395}
396#endif //MX_H
Note: See TracBrowser for help on using the browser.