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

Revision 504, 12.4 kB (checked in by vbarta, 15 years ago)

returning shared pointers from epdf::marginal & epdf::condition; testsuite run leaks down from 8402 to 6510 bytes

  • Property svn:eol-style set to native
RevLine 
[107]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
[394]13#ifndef EMIX_H
14#define EMIX_H
[107]15
[477]16#define LOG2  0.69314718055995
[333]17
[461]18#include "../shared_ptr.h"
[384]19#include "exp_family.h"
[107]20
[286]21namespace bdm {
[107]22
[182]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
[211]35At present the only supported operation is evallogcond().
[182]36 */
37class mratio: public mpdf {
[192]38protected:
[182]39        //! Nominator in the form of mpdf
[192]40        const epdf* nom;
[504]41
[182]42        //!Denominator in the form of epdf
[504]43        shared_ptr<epdf> den;
44
[192]45        //!flag for destructor
46        bool destroynom;
[193]47        //!datalink between conditional and nom
48        datalink_m2e dl;
[487]49        //! dummy epdf that stores only rv and dim
50        epdf iepdf;
[192]51public:
52        //!Default constructor. By default, the given epdf is not copied!
[182]53        //! It is assumed that this function will be used only temporarily.
[487]54        mratio ( const epdf* nom0, const RV &rv, bool copy = false ) : mpdf ( ), dl ( ),iepdf() {
[286]55                // adjust rv and rvc
56                rvc = nom0->_rv().subt ( rv );
57                dimc = rvc._dsize();
[487]58                set_ep ( iepdf );
59                iepdf.set_parameters ( rv._dsize() );
60                iepdf.set_rv ( rv );
[477]61
[286]62                //prepare data structures
[477]63                if ( copy ) {
64                        it_error ( "todo" );
65                        destroynom = true;
66                } else {
67                        nom = nom0;
68                        destroynom = false;
69                }
70                it_assert_debug ( rvc.length() > 0, "Makes no sense to use this object!" );
71
[286]72                // build denominator
[192]73                den = nom->marginal ( rvc );
[477]74                dl.set_connection ( rv, rvc, nom0->_rv() );
[192]75        };
[211]76        double evallogcond ( const vec &val, const vec &cond ) {
[214]77                double tmp;
[487]78                vec nom_val ( dimension() + dimc );
[477]79                dl.pushup_cond ( nom_val, val, cond );
[214]80                tmp = exp ( nom->evallog ( nom_val ) - den->evallog ( cond ) );
81                return tmp;
[192]82        }
[182]83        //! Object takes ownership of nom and will destroy it
[477]84        void ownnom() {
85                destroynom = true;
86        }
[182]87        //! Default destructor
[477]88        ~mratio() {
89                if ( destroynom ) {
90                        delete nom;
91                }
92        }
[182]93};
94
[107]95/*!
96* \brief Mixture of epdfs
97
98Density function:
99\f[
100f(x) = \sum_{i=1}^{n} w_{i} f_i(x), \quad \sum_{i=1}^n w_i = 1.
101\f]
102where \f$f_i(x)\f$ is any density on random variable \f$x\f$, called \a component,
103
104*/
[145]105class emix : public epdf {
[162]106protected:
107        //! weights of the components
108        vec w;
109        //! Component (epdfs)
[504]110        Array<shared_ptr<epdf> > Coms;
111
[162]112public:
113        //!Default constructor
[286]114        emix ( ) : epdf ( ) {};
[182]115        //! Set weights \c w and components \c Coms
[224]116        //!By default Coms are copied inside. Parameter \c copy can be set to false if Coms live externally. Use method ownComs() if Coms should be destroyed by the destructor.
[504]117        void set_parameters ( const vec &w, const Array<shared_ptr<epdf> > &Coms );
[107]118
[162]119        vec sample() const;
120        vec mean() const {
[477]121                int i;
122                vec mu = zeros ( dim );
123                for ( i = 0; i < w.length(); i++ ) {
124                        mu += w ( i ) * Coms ( i )->mean();
125                }
[162]126                return mu;
127        }
[229]128        vec variance() const {
129                //non-central moment
[286]130                vec mom2 = zeros ( dim );
[477]131                for ( int i = 0; i < w.length(); i++ ) {
132                        mom2 += w ( i ) * ( Coms ( i )->variance() + pow ( Coms ( i )->mean(), 2 ) );
133                }
[229]134                //central moment
[477]135                return mom2 - pow ( mean(), 2 );
[229]136        }
[211]137        double evallog ( const vec &val ) const {
[162]138                int i;
139                double sum = 0.0;
[477]140                for ( i = 0; i < w.length(); i++ ) {
141                        sum += w ( i ) * exp ( Coms ( i )->evallog ( val ) );
142                }
143                if ( sum == 0.0 ) {
144                        sum = std::numeric_limits<double>::epsilon();
145                }
146                double tmp = log ( sum );
147                it_assert_debug ( std::isfinite ( tmp ), "Infinite" );
[214]148                return tmp;
[162]149        };
[211]150        vec evallog_m ( const mat &Val ) const {
[477]151                vec x = zeros ( Val.cols() );
[192]152                for ( int i = 0; i < w.length(); i++ ) {
[477]153                        x += w ( i ) * exp ( Coms ( i )->evallog_m ( Val ) );
[182]154                }
[192]155                return log ( x );
[182]156        };
[214]157        //! Auxiliary function that returns pdflog for each component
[211]158        mat evallog_M ( const mat &Val ) const {
[192]159                mat X ( w.length(), Val.cols() );
160                for ( int i = 0; i < w.length(); i++ ) {
[211]161                        X.set_row ( i, w ( i ) *exp ( Coms ( i )->evallog_m ( Val ) ) );
[189]162                }
163                return X;
164        };
[107]165
[504]166        shared_ptr<epdf> marginal ( const RV &rv ) const;
167        void marginal ( const RV &rv, emix &target ) const;
168        shared_ptr<mpdf> condition ( const RV &rv ) const;
[182]169
[107]170//Access methods
[162]171        //! returns a pointer to the internal mean value. Use with Care!
[477]172        vec& _w() {
173                return w;
174        }
[204]175
[193]176        //!access function
[504]177        shared_ptr<epdf> _Coms ( int i ) {
[477]178                return Coms ( i );
[286]179        }
[504]180
[477]181        void set_rv ( const RV &rv ) {
182                epdf::set_rv ( rv );
183                for ( int i = 0; i < Coms.length(); i++ ) {
184                        Coms ( i )->set_rv ( rv );
185                }
186        }
[107]187};
188
[333]189
190/*!
191* \brief Mixture of egiws
192
193*/
194class egiwmix : public egiw {
195protected:
196        //! weights of the components
197        vec w;
198        //! Component (epdfs)
199        Array<egiw*> Coms;
200        //!Flag if owning Coms
201        bool destroyComs;
202public:
203        //!Default constructor
204        egiwmix ( ) : egiw ( ) {};
205
206        //! Set weights \c w and components \c Coms
207        //!By default Coms are copied inside. Parameter \c copy can be set to false if Coms live externally. Use method ownComs() if Coms should be destroyed by the destructor.
[477]208        void set_parameters ( const vec &w, const Array<egiw*> &Coms, bool copy = false );
[333]209
210        //!return expected value
211        vec mean() const;
212
213        //!return a sample from the density
214        vec sample() const;
215
216        //!return the expected variance
[477]217        vec variance() const;
[333]218
219        // TODO!!! Defined to follow ANSI and/or for future development
220        void mean_mat ( mat &M, mat&R ) const {};
[477]221        double evallog_nn ( const vec &val ) const {
222                return 0;
223        };
224        double lognc () const {
225                return 0;
[504]226        }
[333]227
[504]228        shared_ptr<epdf> marginal ( const RV &rv ) const;
229        void marginal ( const RV &rv, emix &target ) const;
230
[333]231//Access methods
232        //! returns a pointer to the internal mean value. Use with Care!
[477]233        vec& _w() {
234                return w;
235        }
236        virtual ~egiwmix() {
237                if ( destroyComs ) {
238                        for ( int i = 0; i < Coms.length(); i++ ) {
239                                delete Coms ( i );
240                        }
241                }
242        }
[333]243        //! Auxiliary function for taking ownership of the Coms()
[477]244        void ownComs() {
245                destroyComs = true;
246        }
[333]247
248        //!access function
[477]249        egiw* _Coms ( int i ) {
250                return Coms ( i );
251        }
[333]252
[477]253        void set_rv ( const RV &rv ) {
254                egiw::set_rv ( rv );
255                for ( int i = 0; i < Coms.length(); i++ ) {
256                        Coms ( i )->set_rv ( rv );
257                }
[333]258        }
259
260        //! Approximation of a GiW mix by a single GiW pdf
261        egiw* approx();
262};
263
[115]264/*! \brief Chain rule decomposition of epdf
265
[145]266Probability density in the form of Chain-rule decomposition:
267\[
268f(x_1,x_2,x_3) = f(x_1|x_2,x_3)f(x_2,x_3)f(x_3)
269\]
270Note that
[115]271*/
[175]272class mprod: public compositepdf, public mpdf {
[162]273protected:
[192]274        //! Data link for each mpdfs
275        Array<datalink_m2m*> dls;
[461]276
[487]277        //! dummy epdf used only as storage for RV and dim
278        epdf iepdf;
[461]279
[162]280public:
[168]281        /*!\brief Constructor from list of mFacs,
[165]282        */
[487]283        mprod() : iepdf( ) { }
[477]284        mprod ( Array<mpdf*> mFacs ) :
[487]285                        iepdf ( ) {
[477]286                set_elements ( mFacs );
[461]287        }
288
[477]289        void set_elements ( Array<mpdf*> mFacs , bool own = false ) {
290
291                compositepdf::set_elements ( mFacs, own );
292                dls.set_size ( mFacs.length() );
293
[487]294                set_ep ( iepdf);
[477]295                RV rv = getrv ( true );
[395]296                set_rv ( rv );
[487]297                iepdf.set_parameters ( rv._dsize() );
298                setrvc (_rv(), rvc );
[192]299                // rv and rvc established = > we can link them with mpdfs
[477]300                for ( int i = 0; i < mpdfs.length(); i++ ) {
[286]301                        dls ( i ) = new datalink_m2m;
[477]302                        dls ( i )->set_connection ( mpdfs ( i )->_rv(), mpdfs ( i )->_rvc(), _rv(), _rvc() );
[181]303                }
304
[175]305        };
[124]306
[211]307        double evallogcond ( const vec &val, const vec &cond ) {
[162]308                int i;
[270]309                double res = 0.0;
[477]310                for ( i = mpdfs.length() - 1; i >= 0; i-- ) {
[193]311                        /*                      if ( mpdfs(i)->_rvc().count() >0) {
312                                                        mpdfs ( i )->condition ( dls ( i )->get_cond ( val,cond ) );
313                                                }
314                                                // add logarithms
[270]315                                                res += epdfs ( i )->evallog ( dls ( i )->pushdown ( val ) );*/
316                        res += mpdfs ( i )->evallogcond (
317                                   dls ( i )->pushdown ( val ),
[204]318                                   dls ( i )->get_cond ( val, cond )
319                               );
[145]320                }
[193]321                return res;
[162]322        }
[477]323        vec evallogcond_m ( const mat &Dt, const vec &cond ) {
324                vec tmp ( Dt.cols() );
325                for ( int i = 0; i < Dt.cols(); i++ ) {
326                        tmp ( i ) = evallogcond ( Dt.get_col ( i ), cond );
[395]327                }
328                return tmp;
329        };
[477]330        vec evallogcond_m ( const Array<vec> &Dt, const vec &cond ) {
331                vec tmp ( Dt.length() );
332                for ( int i = 0; i < Dt.length(); i++ ) {
333                        tmp ( i ) = evallogcond ( Dt ( i ), cond );
[395]334                }
[477]335                return tmp;
[395]336        };
337
338
[270]339        //TODO smarter...
340        vec samplecond ( const vec &cond ) {
[477]341                //! Ugly hack to help to discover if mpfs are not in proper order. Correct solution = check that explicitely.
[487]342                vec smp = std::numeric_limits<double>::infinity() * ones ( dimension() );
[165]343                vec smpi;
[192]344                // Hard assumption here!!! We are going backwards, to assure that samples that are needed from smp are already generated!
[477]345                for ( int i = ( mpdfs.length() - 1 ); i >= 0; i-- ) {
[487]346                        // generate contribution of this mpdf
347                        smpi = mpdfs(i)->samplecond(dls ( i )->get_cond ( smp , cond ));                       
[162]348                        // copy contribution of this pdf into smp
[270]349                        dls ( i )->pushup ( smp, smpi );
[145]350                }
[162]351                return smp;
352        }
[270]353        mat samplecond ( const vec &cond,  int N ) {
[477]354                mat Smp ( dimension(), N );
355                for ( int i = 0; i < N; i++ ) {
356                        Smp.set_col ( i, samplecond ( cond ) );
357                }
[162]358                return Smp;
359        }
360
361        ~mprod() {};
[395]362        //! Load from structure with elements:
363        //!  \code
364        //! { class='mprod';
365        //!   mpdfs = (..., ...);     // list of mpdfs in the order of chain rule
366        //! }
367        //! \endcode
368        //!@}
[477]369        void from_setting ( const Setting &set ) {
[395]370                Array<mpdf*> Atmp; //temporary Array
[477]371                UI::get ( Atmp, set, "mpdfs", UI::compulsory );
372                set_elements ( Atmp, true );
[395]373        }
[477]374
[107]375};
[477]376UIREGISTER ( mprod );
[107]377
[168]378//! Product of independent epdfs. For dependent pdfs, use mprod.
379class eprod: public epdf {
380protected:
381        //! Components (epdfs)
[170]382        Array<const epdf*> epdfs;
[168]383        //! Array of indeces
[270]384        Array<datalink*> dls;
[168]385public:
[477]386        eprod () : epdfs ( 0 ), dls ( 0 ) {};
387        void set_parameters ( const Array<const epdf*> &epdfs0, bool named = true ) {
388                epdfs = epdfs0;//.set_length ( epdfs0.length() );
[286]389                dls.set_length ( epdfs.length() );
390
[477]391                bool independent = true;
[286]392                if ( named ) {
[477]393                        for ( int i = 0; i < epdfs.length(); i++ ) {
394                                independent = rv.add ( epdfs ( i )->_rv() );
395                                it_assert_debug ( independent == true, "eprod:: given components are not independent." );
[286]396                        }
[477]397                        dim = rv._dsize();
398                } else {
399                        dim = 0;
400                        for ( int i = 0; i < epdfs.length(); i++ ) {
401                                dim += epdfs ( i )->dimension();
[286]402                        }
[204]403                }
[286]404                //
[477]405                int cumdim = 0;
406                int dimi = 0;
[286]407                int i;
[477]408                for ( i = 0; i < epdfs.length(); i++ ) {
[286]409                        dls ( i ) = new datalink;
[477]410                        if ( named ) {
411                                dls ( i )->set_connection ( epdfs ( i )->_rv() , rv );
412                        } else {
[286]413                                dimi = epdfs ( i )->dimension();
[477]414                                dls ( i )->set_connection ( dimi, dim, linspace ( cumdim, cumdim + dimi - 1 ) );
415                                cumdim += dimi;
[286]416                        }
417                }
[168]418        }
419
420        vec mean() const {
[270]421                vec tmp ( dim );
[477]422                for ( int i = 0; i < epdfs.length(); i++ ) {
[168]423                        vec pom = epdfs ( i )->mean();
[270]424                        dls ( i )->pushup ( tmp, pom );
[168]425                }
426                return tmp;
427        }
[229]428        vec variance() const {
[270]429                vec tmp ( dim ); //second moment
[477]430                for ( int i = 0; i < epdfs.length(); i++ ) {
[229]431                        vec pom = epdfs ( i )->mean();
[477]432                        dls ( i )->pushup ( tmp, pow ( pom, 2 ) );
[229]433                }
[477]434                return tmp - pow ( mean(), 2 );
[229]435        }
[168]436        vec sample() const {
[270]437                vec tmp ( dim );
[477]438                for ( int i = 0; i < epdfs.length(); i++ ) {
[168]439                        vec pom = epdfs ( i )->sample();
[270]440                        dls ( i )->pushup ( tmp, pom );
[168]441                }
442                return tmp;
443        }
[211]444        double evallog ( const vec &val ) const {
[477]445                double tmp = 0;
446                for ( int i = 0; i < epdfs.length(); i++ ) {
447                        tmp += epdfs ( i )->evallog ( dls ( i )->pushdown ( val ) );
[168]448                }
[477]449                it_assert_debug ( std::isfinite ( tmp ), "Infinite" );
[168]450                return tmp;
451        }
[170]452        //!access function
[477]453        const epdf* operator () ( int i ) const {
454                it_assert_debug ( i < epdfs.length(), "wrong index" );
455                return epdfs ( i );
456        }
[204]457
[193]458        //!Destructor
[477]459        ~eprod() {
460                for ( int i = 0; i < epdfs.length(); i++ ) {
461                        delete dls ( i );
462                }
463        }
[168]464};
465
466
[488]467/*! \brief Mixture of mpdfs with constant weights, all mpdfs are of equal RV and RVC
[124]468
469*/
[488]470class mmix : public mpdf {
471protected:
472        //! Component (mpdfs)
473        Array<shared_ptr<mpdf> > Coms;
474        //!weights of the components
475        vec w;
476        //! dummy epdfs
477        epdf dummy_epdf;
478public:
479        //!Default constructor
480        mmix() : Coms(0), dummy_epdf() { set_ep(dummy_epdf);    }
[461]481
[488]482        //! Set weights \c w and components \c R
483        void set_parameters ( const vec &w0, const Array<shared_ptr<mpdf> > &Coms0 ) {
484                //!\TODO check if all components are OK
485                Coms = Coms0;
486                w=w0;   
[503]487
[488]488                set_rv(Coms(0)->_rv());
[503]489                dummy_epdf.set_parameters(Coms(0)->_rv()._dsize());
[488]490                set_rvc(Coms(0)->_rvc());
[503]491                dimc = Coms(0)->_rvc()._dsize();
[488]492        }
493        double evallogcond (const vec &dt, const vec &cond) {
494                double ll=0.0;
495                for (int i=0;i<Coms.length();i++){
496                        ll+=Coms(i)->evallogcond(dt,cond);
497                }
498                return ll;
499        }
500
501        vec samplecond (const vec &cond);
502
503};
504
[254]505}
[107]506#endif //MX_H
Note: See TracBrowser for help on using the browser.