root/bdm/stat/libEF.h @ 197

Revision 197, 18.0 kB (checked in by smidl, 16 years ago)

opravy v bdm

  • Property svn:eol-style set to native
Line 
1/*!
2  \file
3  \brief Probability distributions for Exponential Family models.
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 EF_H
14#define EF_H
15
16#include <itpp/itbase.h>
17#include "../math/libDC.h"
18#include "libBM.h"
19#include "../itpp_ext.h"
20//#include <std>
21
22using namespace itpp;
23
24
25//! Global Uniform_RNG
26extern Uniform_RNG UniRNG;
27//! Global Normal_RNG
28extern Normal_RNG NorRNG;
29//! Global Gamma_RNG
30extern Gamma_RNG GamRNG;
31
32/*!
33* \brief General conjugate exponential family posterior density.
34
35* More?...
36*/
37
38class eEF : public epdf {
39public:
40//      eEF() :epdf() {};
41        //! default constructor
42        eEF ( const RV &rv ) :epdf ( rv ) {};
43        //! logarithm of the normalizing constant, \f$\mathcal{I}\f$
44        virtual double lognc() const =0;
45        //!TODO decide if it is really needed
46        virtual void dupdate ( mat &v ) {it_error ( "Not implemented" );};
47        //!Evaluate normalized log-probability
48        virtual double evalpdflog_nn ( const vec &val ) const{it_error ( "Not implemented" );return 0.0;};
49        //!Evaluate normalized log-probability
50        virtual double evalpdflog ( const vec &val ) const {return evalpdflog_nn ( val )-lognc();}
51        //!Evaluate normalized log-probability for many samples
52        virtual vec evalpdflog ( const mat &Val ) const {
53                vec x ( Val.cols() );
54                for ( int i=0;i<Val.cols();i++ ) {x ( i ) =evalpdflog_nn ( Val.get_col ( i ) ) ;}
55                return x-lognc();
56        }
57        //!Power of the density, used e.g. to flatten the density
58        virtual void pow ( double p ) {it_error ( "Not implemented" );};
59};
60
61/*!
62* \brief Exponential family model.
63
64* More?...
65*/
66
67class mEF : public mpdf {
68
69public:
70        //! Default constructor
71        mEF ( const RV &rv0, const RV &rvc0 ) :mpdf ( rv0,rvc0 ) {};
72};
73
74//! Estimator for Exponential family
75class BMEF : public BM {
76protected:
77        //! forgetting factor
78        double frg;
79        //! cached value of lognc() in the previous step (used in evaluation of \c ll )
80        double last_lognc;
81public:
82        //! Default constructor
83        BMEF ( const RV &rv, double frg0=1.0 ) :BM ( rv ), frg ( frg0 ) {}
84        //! Copy constructor
85        BMEF ( const BMEF &B ) :BM ( B ), frg ( B.frg ), last_lognc ( B.last_lognc ) {}
86        //!get statistics from another model
87        virtual void set_statistics ( const BMEF* BM0 ) {it_error ( "Not implemented" );};
88        //! Weighted update of sufficient statistics (Bayes rule)
89        virtual void bayes ( const vec &data, const double w ) {};
90        //original Bayes
91        void bayes ( const vec &dt );
92        //!Flatten the posterior according to the given BMEF (of the same type!)
93        virtual void flatten ( const BMEF * B ) {it_error ( "Not implemented" );}
94        //!Flatten the posterior as if to keep nu0 data
95//      virtual void flatten ( double nu0 ) {it_error ( "Not implemented" );}
96       
97        BMEF* _copy_ ( bool changerv=false ) {it_error ( "function _copy_ not implemented for this BM" ); return NULL;};
98};
99
100template<class sq_T>
101class mlnorm;
102
103/*!
104* \brief Gaussian density with positive definite (decomposed) covariance matrix.
105
106* More?...
107*/
108template<class sq_T>
109class enorm : public eEF {
110protected:
111        //! mean value
112        vec mu;
113        //! Covariance matrix in decomposed form
114        sq_T R;
115        //! dimension (redundant from rv.count() for easier coding )
116        int dim;
117public:
118        //!Default constructor
119        enorm ( const RV &rv );
120        //! Set mean value \c mu and covariance \c R
121        void set_parameters ( const vec &mu,const sq_T &R );
122        ////! tupdate in exponential form (not really handy)
123        //void tupdate ( double phi, mat &vbar, double nubar );
124        //! dupdate in exponential form (not really handy)
125        void dupdate ( mat &v,double nu=1.0 );
126
127        vec sample() const;
128        //! TODO is it used?
129        mat sample ( int N ) const;
130        double eval ( const vec &val ) const ;
131        double evalpdflog_nn ( const vec &val ) const;
132        double lognc () const;
133        vec mean() const {return mu;}
134//      mlnorm<sq_T>* condition ( const RV &rvn ) const ;
135        mpdf* condition ( const RV &rvn ) const ;
136//      enorm<sq_T>* marginal ( const RV &rv ) const;
137        epdf* marginal ( const RV &rv ) const;
138//Access methods
139        //! returns a pointer to the internal mean value. Use with Care!
140        vec& _mu() {return mu;}
141
142        //! access function
143        void set_mu ( const vec mu0 ) { mu=mu0;}
144
145        //! returns pointers to the internal variance and its inverse. Use with Care!
146        sq_T& _R() {return R;}
147
148        //! access method
149//      mat getR () {return R.to_mat();}
150};
151
152/*!
153* \brief Gauss-inverse-Wishart density stored in LD form
154
155* For \f$p\f$-variate densities, given rv.count() should be \f$p\times\f$ V.rows().
156*
157*/
158class egiw : public eEF {
159protected:
160        //! Extended information matrix of sufficient statistics
161        ldmat V;
162        //! Number of data records (degrees of freedom) of sufficient statistics
163        double nu;
164        //! Dimension of the output
165        int xdim;
166        //! Dimension of the regressor
167        int nPsi;
168public:
169        //!Default constructor, assuming
170        egiw ( RV rv, mat V0, double nu0 ) : eEF ( rv ), V ( V0 ), nu ( nu0 ) {
171                xdim = rv.count() /V.rows();
172                it_assert_debug ( rv.count() ==xdim*V.rows(),"Incompatible V0." );
173                nPsi = V.rows()-xdim;
174        }
175        //!Full constructor for V in ldmat form
176        egiw ( RV rv, ldmat V0, double nu0 ) : eEF ( rv ), V ( V0 ), nu ( nu0 ) {
177                xdim = rv.count() /V.rows();
178                it_assert_debug ( rv.count() ==xdim*V.rows(),"Incompatible V0." );
179                nPsi = V.rows()-xdim;
180        }
181
182        vec sample() const;
183        vec mean() const;
184        void mean_mat ( mat &M, mat&R ) const;
185        //! In this instance, val= [theta, r]. For multivariate instances, it is stored columnwise val = [theta_1 theta_2 ... r_1 r_2 ]
186        double evalpdflog_nn ( const vec &val ) const;
187        double lognc () const;
188
189        //Access
190        //! returns a pointer to the internal statistics. Use with Care!
191        ldmat& _V() {return V;}
192        //! returns a pointer to the internal statistics. Use with Care!
193        double& _nu() {return nu;}
194        void pow ( double p ){V*=p;nu*=p;};
195};
196
197/*! \brief Dirichlet posterior density
198
199Continuous Dirichlet density of \f$n\f$-dimensional variable \f$x\f$
200\f[
201f(x|\beta) = \frac{\Gamma[\gamma]}{\prod_{i=1}^{n}\Gamma(\beta_i)} \prod_{i=1}^{n}x_i^{\beta_i-1}
202\f]
203where \f$\gamma=\sum_i \beta_i\f$.
204*/
205class eDirich: public eEF {
206protected:
207        //!sufficient statistics
208        vec beta;
209public:
210        //!Default constructor
211        eDirich ( const RV &rv, const vec &beta0 ) : eEF ( rv ),beta ( beta0 ) {it_assert_debug ( rv.count() ==beta.length(),"Incompatible statistics" ); };
212        //! Copy constructor
213        eDirich ( const eDirich &D0 ) : eEF ( D0.rv ),beta ( D0.beta ) {};
214        vec sample() const {it_error ( "Not implemented" );return vec_1 ( 0.0 );};
215        vec mean() const {return beta/sum ( beta );};
216        //! In this instance, val is ...
217        double evalpdflog_nn ( const vec &val ) const {return ( beta-1 ) *log ( val );};
218        double lognc () const {
219                double gam=sum ( beta );
220                double lgb=0.0;
221                for ( int i=0;i<beta.length();i++ ) {lgb+=lgamma ( beta ( i ) );}
222                return lgb-lgamma ( gam );
223        };
224        //!access function
225        vec& _beta()  {return beta;}
226        //!Set internal parameters
227        void set_parameters ( const vec &beta0 ) {
228                if ( beta0.length() !=beta.length() ) {
229                        it_assert_debug ( rv.length() ==1,"Undefined" );
230                        rv.set_size ( 0,beta0.length() );
231                }
232                beta= beta0;
233        }
234};
235
236//! \brief Estimator for Multinomial density
237class multiBM : public BMEF {
238protected:
239        //! Conjugate prior and posterior
240        eDirich est;
241        //! Pointer inside est to sufficient statistics
242        vec &beta;
243public:
244        //!Default constructor
245        multiBM ( const RV &rv, const vec beta0 ) : BMEF ( rv ),est ( rv,beta0 ),beta ( est._beta() ) {last_lognc=est.lognc();}
246        //!Copy constructor
247        multiBM ( const multiBM &B ) : BMEF ( B ),est ( rv,B.beta ),beta ( est._beta() ) {}
248        //! Sets sufficient statistics to match that of givefrom mB0
249        void set_statistics ( const BM* mB0 ) {const multiBM* mB=dynamic_cast<const multiBM*> ( mB0 ); beta=mB->beta;}
250        void bayes ( const vec &dt ) {
251                if ( frg<1.0 ) {beta*=frg;last_lognc=est.lognc();}
252                beta+=dt;
253                if ( evalll ) {ll=est.lognc()-last_lognc;}
254        }
255        double logpred ( const vec &dt ) const {
256                eDirich pred ( est );
257                vec &beta = pred._beta();
258
259                double lll;
260                if ( frg<1.0 )
261                        {beta*=frg;lll=pred.lognc();}
262                else
263                        if ( evalll ) {lll=last_lognc;}
264                        else{lll=pred.lognc();}
265
266                beta+=dt;
267                return pred.lognc()-lll;
268        }
269        void flatten ( const BMEF* B ) {
270                const multiBM* E=dynamic_cast<const multiBM*> ( B );
271                // sum(beta) should be equal to sum(B.beta)
272                const vec &Eb=E->beta;//const_cast<multiBM*> ( E )->_beta();
273                beta*= ( sum ( Eb) /sum ( beta ) );
274                if ( evalll ) {last_lognc=est.lognc();}
275        }
276        const epdf& _epdf() const {return est;};
277        void set_parameters ( const vec &beta0 ) {
278                est.set_parameters ( beta0 );
279                rv = est._rv();
280                if ( evalll ) {last_lognc=est.lognc();}
281        }
282};
283
284/*!
285 \brief Gamma posterior density
286
287 Multivariate Gamma density as product of independent univariate densities.
288 \f[
289 f(x|\alpha,\beta) = \prod f(x_i|\alpha_i,\beta_i)
290 \f]
291*/
292
293class egamma : public eEF {
294protected:
295        //! Vector \f$\alpha\f$
296        vec alpha;
297        //! Vector \f$\beta\f$
298        vec beta;
299public :
300        //! Default constructor
301        egamma ( const RV &rv ) :eEF ( rv ) {};
302        //! Sets parameters
303        void set_parameters ( const vec &a, const vec &b ) {alpha=a,beta=b;};
304        vec sample() const;
305        //! TODO: is it used anywhere?
306//      mat sample ( int N ) const;
307        double evalpdflog ( const vec &val ) const;
308        double lognc () const;
309        //! Returns poiter to alpha and beta. Potentially dengerous: use with care!
310        void _param ( vec* &a, vec* &b ) {a=&alpha;b=&beta;};
311        vec mean() const {vec pom ( alpha ); pom/=beta; return pom;}
312};
313/*
314//! Weighted mixture of epdfs with external owned components.
315class emix : public epdf {
316protected:
317        int n;
318        vec &w;
319        Array<epdf*> Coms;
320public:
321//! Default constructor
322        emix ( const RV &rv, vec &w0): epdf(rv), n(w0.length()), w(w0), Coms(n) {};
323        void set_parameters( int &i, double wi, epdf* ep){w(i)=wi;Coms(i)=ep;}
324        vec mean(){vec pom; for(int i=0;i<n;i++){pom+=Coms(i)->mean()*w(i);} return pom;};
325        vec sample() {it_error ( "Not implemented" );return 0;}
326};
327*/
328
329//!  Uniform distributed density on a rectangular support
330
331class euni: public epdf {
332protected:
333//! lower bound on support
334        vec low;
335//! upper bound on support
336        vec high;
337//! internal
338        vec distance;
339//! normalizing coefficients
340        double nk;
341//! cache of log( \c nk )
342        double lnk;
343public:
344        //! Defualt constructor
345        euni ( const RV rv ) :epdf ( rv ) {}
346        double eval ( const vec &val ) const  {return nk;}
347        double evalpdflog ( const vec &val ) const  {return lnk;}
348        vec sample() const {
349                vec smp ( rv.count() );
350#pragma omp critical
351                UniRNG.sample_vector ( rv.count(),smp );
352                return low+elem_mult ( distance,smp );
353        }
354        //! set values of \c low and \c high
355        void set_parameters ( const vec &low0, const vec &high0 ) {
356                distance = high0-low0;
357                it_assert_debug ( min ( distance ) >0.0,"bad support" );
358                low = low0;
359                high = high0;
360                nk = prod ( 1.0/distance );
361                lnk = log ( nk );
362        }
363        vec mean() const {vec pom=high; pom-=low; pom/=2.0; return pom;}
364};
365
366
367/*!
368 \brief Normal distributed linear function with linear function of mean value;
369
370 Mean value \f$mu=A*rvc+mu_0\f$.
371*/
372template<class sq_T>
373class mlnorm : public mEF {
374        //! Internal epdf that arise by conditioning on \c rvc
375        enorm<sq_T> epdf;
376        mat A;
377        vec mu_const;
378        vec& _mu; //cached epdf.mu;
379public:
380        //! Constructor
381        mlnorm (const RV &rv, const RV &rvc );
382        //! Set \c A and \c R
383        void set_parameters ( const  mat &A, const vec &mu0, const sq_T &R );
384//      //!Generate one sample of the posterior
385//      vec samplecond (const vec &cond, double &lik );
386//      //!Generate matrix of samples of the posterior
387//      mat samplecond (const vec &cond, vec &lik, int n );
388        //! Set value of \c rvc . Result of this operation is stored in \c epdf use function \c _ep to access it.
389        void condition (const vec &cond );
390       
391        template<class sq_M>
392        friend std::ostream &operator<< ( std::ostream &os,  mlnorm<sq_M> &ml );
393};
394
395/*!
396\brief  Gamma random walk
397
398Mean value, \f$\mu\f$, of this density is given by \c rvc .
399Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
400This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
401
402The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
403*/
404class mgamma : public mEF {
405protected:
406        //! Internal epdf that arise by conditioning on \c rvc
407        egamma epdf;
408        //! Constant \f$k\f$
409        double k;
410        //! cache of epdf.beta
411        vec* _beta;
412
413public:
414        //! Constructor
415        mgamma ( const RV &rv,const RV &rvc );
416        //! Set value of \c k
417        void set_parameters ( double k );
418        void condition ( const vec &val ) {*_beta=k/val;};
419};
420
421/*!
422\brief  Gamma random walk around a fixed point
423
424Mean value, \f$\mu\f$, of this density is given by a geometric combination of \c rvc and given fixed point, \f$p\f$. \f$l\f$ is the coefficient of the geometric combimation
425\f[ \mu = \mu_{t-1} ^{l} p^{1-l}\f]
426
427Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
428This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
429
430The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
431*/
432class mgamma_fix : public mgamma {
433protected:
434        //! parameter l
435        double l;
436        //! reference vector
437        vec refl;
438public:
439        //! Constructor
440        mgamma_fix ( const RV &rv,const RV &rvc ) : mgamma ( rv,rvc ),refl ( rv.count() ) {};
441        //! Set value of \c k
442        void set_parameters ( double k0 , vec ref0, double l0 ) {
443                mgamma::set_parameters ( k0 );
444                refl=pow ( ref0,1.0-l0 );l=l0;
445        };
446
447        void condition ( const vec &val ) {vec mean=elem_mult ( refl,pow ( val,l ) ); *_beta=k/mean;};
448};
449
450//! Switch between various resampling methods.
451enum RESAMPLING_METHOD { MULTINOMIAL = 0, STRATIFIED = 1, SYSTEMATIC = 3 };
452/*!
453\brief Weighted empirical density
454
455Used e.g. in particle filters.
456*/
457class eEmp: public epdf {
458protected :
459        //! Number of particles
460        int n;
461        //! Sample weights \f$w\f$
462        vec w;
463        //! Samples \f$x^{(i)}, i=1..n\f$
464        Array<vec> samples;
465public:
466        //! Default constructor
467        eEmp ( const RV &rv0 ,int n0 ) :epdf ( rv0 ),n ( n0 ),w ( n ),samples ( n ) {};
468        //! Set samples and weights
469        void set_parameters ( const vec &w0, const epdf* pdf0 );
470        //! Set sample
471        void set_samples ( const epdf* pdf0 );
472        //! Potentially dangerous, use with care.
473        vec& _w()  {return w;};
474        //! access function
475        Array<vec>& _samples() {return samples;};
476        //! Function performs resampling, i.e. removal of low-weight samples and duplication of high-weight samples such that the new samples represent the same density.
477        ivec resample ( RESAMPLING_METHOD method = SYSTEMATIC );
478        //! inherited operation : NOT implemneted
479        vec sample() const {it_error ( "Not implemented" );return 0;}
480        //! inherited operation : NOT implemneted
481        double evalpdflog ( const vec &val ) const {it_error ( "Not implemented" );return 0.0;}
482        vec mean() const {
483                vec pom=zeros ( rv.count() );
484                for ( int i=0;i<n;i++ ) {pom+=samples ( i ) *w ( i );}
485                return pom;
486        }
487};
488
489
490////////////////////////
491
492template<class sq_T>
493enorm<sq_T>::enorm ( const RV &rv ) :eEF ( rv ), mu ( rv.count() ),R ( rv.count() ),dim ( rv.count() ) {};
494
495template<class sq_T>
496void enorm<sq_T>::set_parameters ( const vec &mu0, const sq_T &R0 ) {
497//Fixme test dimensions of mu0 and R0;
498        mu = mu0;
499        R = R0;
500};
501
502template<class sq_T>
503void enorm<sq_T>::dupdate ( mat &v, double nu ) {
504        //
505};
506
507// template<class sq_T>
508// void enorm<sq_T>::tupdate ( double phi, mat &vbar, double nubar ) {
509//      //
510// };
511
512template<class sq_T>
513vec enorm<sq_T>::sample() const {
514        vec x ( dim );
515        NorRNG.sample_vector ( dim,x );
516        vec smp = R.sqrt_mult ( x );
517
518        smp += mu;
519        return smp;
520};
521
522template<class sq_T>
523mat enorm<sq_T>::sample ( int N ) const {
524        mat X ( dim,N );
525        vec x ( dim );
526        vec pom;
527        int i;
528
529        for ( i=0;i<N;i++ ) {
530                NorRNG.sample_vector ( dim,x );
531                pom = R.sqrt_mult ( x );
532                pom +=mu;
533                X.set_col ( i, pom );
534        }
535
536        return X;
537};
538
539template<class sq_T>
540double enorm<sq_T>::eval ( const vec &val ) const {
541        double pdfl,e;
542        pdfl = evalpdflog ( val );
543        e = exp ( pdfl );
544        return e;
545};
546
547template<class sq_T>
548double enorm<sq_T>::evalpdflog_nn ( const vec &val ) const {
549        // 1.83787706640935 = log(2pi)
550        return  -0.5* ( R.invqform ( mu-val ) );// - lognc();
551};
552
553template<class sq_T>
554inline double enorm<sq_T>::lognc () const {
555        // 1.83787706640935 = log(2pi)
556        return 0.5* ( R.cols() * 1.83787706640935 +R.logdet() );
557};
558
559template<class sq_T>
560mlnorm<sq_T>::mlnorm ( const RV &rv0, const RV &rvc0 ) :mEF ( rv0,rvc0 ),epdf ( rv0 ),A ( rv0.count(),rv0.count() ),_mu ( epdf._mu() ) {
561        ep =&epdf;
562}
563
564template<class sq_T>
565void mlnorm<sq_T>::set_parameters ( const mat &A0, const vec &mu0, const sq_T &R0 ) {
566        epdf.set_parameters ( zeros ( rv.count() ),R0 );
567        A = A0;
568        mu_const = mu0;
569}
570
571// template<class sq_T>
572// vec mlnorm<sq_T>::samplecond (const  vec &cond, double &lik ) {
573//      this->condition ( cond );
574//      vec smp = epdf.sample();
575//      lik = epdf.eval ( smp );
576//      return smp;
577// }
578
579// template<class sq_T>
580// mat mlnorm<sq_T>::samplecond (const vec &cond, vec &lik, int n ) {
581//      int i;
582//      int dim = rv.count();
583//      mat Smp ( dim,n );
584//      vec smp ( dim );
585//      this->condition ( cond );
586//
587//      for ( i=0; i<n; i++ ) {
588//              smp = epdf.sample();
589//              lik ( i ) = epdf.eval ( smp );
590//              Smp.set_col ( i ,smp );
591//      }
592//
593//      return Smp;
594// }
595
596template<class sq_T>
597void mlnorm<sq_T>::condition (const vec &cond ) {
598        _mu = A*cond + mu_const;
599//R is already assigned;
600}
601
602template<class sq_T>
603epdf* enorm<sq_T>::marginal ( const RV &rvn ) const {
604        ivec irvn = rvn.dataind ( rv );
605
606        sq_T Rn ( R,irvn );
607        enorm<sq_T>* tmp = new enorm<sq_T>( rvn );
608        tmp->set_parameters ( mu ( irvn ), Rn );
609        return tmp;
610}
611
612template<class sq_T>
613mpdf* enorm<sq_T>::condition ( const RV &rvn ) const {
614
615        RV rvc = rv.subt ( rvn );
616        it_assert_debug ( ( rvc.count() +rvn.count() ==rv.count() ),"wrong rvn" );
617        //Permutation vector of the new R
618        ivec irvn = rvn.dataind ( rv );
619        ivec irvc = rvc.dataind ( rv );
620        ivec perm=concat ( irvn , irvc );
621        sq_T Rn ( R,perm );
622
623        //fixme - could this be done in general for all sq_T?
624        mat S=Rn.to_mat();
625        //fixme
626        int n=rvn.count()-1;
627        int end=R.rows()-1;
628        mat S11 = S.get ( 0,n, 0, n );
629        mat S12 = S.get (0, n , rvn.count(), end );
630        mat S22 = S.get ( rvn.count(), end, rvn.count(), end );
631
632        vec mu1 = mu ( irvn );
633        vec mu2 = mu ( irvc );
634        mat A=S12*inv ( S22 );
635        sq_T R_n ( S11 - A *S12.T() );
636
637        mlnorm<sq_T>* tmp=new mlnorm<sq_T> ( rvn,rvc );
638
639        tmp->set_parameters ( A,mu1-A*mu2,R_n );
640        return tmp;
641}
642
643///////////
644
645template<class sq_T>
646std::ostream &operator<< ( std::ostream &os,  mlnorm<sq_T> &ml ){
647        os << "A:"<< ml.A<<endl;
648        os << "mu:"<< ml.mu_const<<endl;
649        os << "R:" << ml.epdf._R().to_mat() <<endl;
650        return os;
651};
652
653#endif //EF_H
Note: See TracBrowser for help on using the browser.