root/bdm/stat/libEF.h @ 225

Revision 225, 23.1 kB (checked in by smidl, 15 years ago)

prestavba mpf_test do inv-gamma

  • 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 evallog_nn ( const vec &val ) const{it_error ( "Not implemented" );return 0.0;};
49        //!Evaluate normalized log-probability
50        virtual double evallog ( const vec &val ) const {double tmp;tmp= evallog_nn ( val )-lognc();it_assert_debug(std::isfinite(tmp),"Infinite value"); return tmp;}
51        //!Evaluate normalized log-probability for many samples
52        virtual vec evallog ( const mat &Val ) const {
53                vec x ( Val.cols() );
54                for ( int i=0;i<Val.cols();i++ ) {x ( i ) =evallog_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 evallog_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        const sq_T& _R() const {return R;}
148
149        //! access method
150//      mat getR () {return R.to_mat();}
151};
152
153/*!
154* \brief Gauss-inverse-Wishart density stored in LD form
155
156* For \f$p\f$-variate densities, given rv.count() should be \f$p\times\f$ V.rows().
157*
158*/
159class egiw : public eEF {
160protected:
161        //! Extended information matrix of sufficient statistics
162        ldmat V;
163        //! Number of data records (degrees of freedom) of sufficient statistics
164        double nu;
165        //! Dimension of the output
166        int xdim;
167        //! Dimension of the regressor
168        int nPsi;
169public:
170        //!Default constructor, if nu0<0 a minimal nu0 will be computed
171        egiw ( RV rv, mat V0, double nu0=-1.0 ) : eEF ( rv ), V ( V0 ), nu ( nu0 ) {
172                xdim = rv.count() /V.rows();
173                it_assert_debug ( rv.count() ==xdim*V.rows(),"Incompatible V0." );
174                nPsi = V.rows()-xdim;
175                //set mu to have proper normalization and
176                if (nu0<0){
177                        nu = 0.1 +nPsi +2*xdim +2; // +2 assures finite expected value of R
178                        // terms before that are sufficient for finite normalization
179                }
180        }
181        //!Full constructor for V in ldmat form
182        egiw ( RV rv, ldmat V0, double nu0=-1.0 ) : eEF ( rv ), V ( V0 ), nu ( nu0 ) {
183                xdim = rv.count() /V.rows();
184                it_assert_debug ( rv.count() ==xdim*V.rows(),"Incompatible V0." );
185                nPsi = V.rows()-xdim;
186                if (nu0<0){
187                        nu = 0.1 +nPsi +2*xdim +2; // +2 assures finite expected value of R
188                        // terms before that are sufficient for finite normalization
189                }
190        }
191
192        vec sample() const;
193        vec mean() const;
194        void mean_mat ( mat &M, mat&R ) const;
195        //! In this instance, val= [theta, r]. For multivariate instances, it is stored columnwise val = [theta_1 theta_2 ... r_1 r_2 ]
196        double evallog_nn ( const vec &val ) const;
197        double lognc () const;
198
199        //Access
200        //! returns a pointer to the internal statistics. Use with Care!
201        ldmat& _V() {return V;}
202        //! returns a pointer to the internal statistics. Use with Care!
203        const ldmat& _V() const {return V;}
204        //! returns a pointer to the internal statistics. Use with Care!
205        double& _nu()  {return nu;}
206        const double& _nu() const {return nu;}
207        void pow ( double p ) {V*=p;nu*=p;};
208};
209
210/*! \brief Dirichlet posterior density
211
212Continuous Dirichlet density of \f$n\f$-dimensional variable \f$x\f$
213\f[
214f(x|\beta) = \frac{\Gamma[\gamma]}{\prod_{i=1}^{n}\Gamma(\beta_i)} \prod_{i=1}^{n}x_i^{\beta_i-1}
215\f]
216where \f$\gamma=\sum_i \beta_i\f$.
217*/
218class eDirich: public eEF {
219protected:
220        //!sufficient statistics
221        vec beta;
222public:
223        //!Default constructor
224        eDirich ( const RV &rv, const vec &beta0 ) : eEF ( rv ),beta ( beta0 ) {it_assert_debug ( rv.count() ==beta.length(),"Incompatible statistics" ); };
225        //! Copy constructor
226        eDirich ( const eDirich &D0 ) : eEF ( D0.rv ),beta ( D0.beta ) {};
227        vec sample() const {it_error ( "Not implemented" );return vec_1 ( 0.0 );};
228        vec mean() const {return beta/sum ( beta );};
229        //! In this instance, val is ...
230        double evallog_nn ( const vec &val ) const {double tmp; tmp=( beta-1 ) *log ( val );            it_assert_debug(std::isfinite(tmp),"Infinite value");
231        return tmp;};
232        double lognc () const {
233                double tmp;
234                double gam=sum ( beta );
235                double lgb=0.0;
236                for ( int i=0;i<beta.length();i++ ) {lgb+=lgamma ( beta ( i ) );}
237                tmp= lgb-lgamma ( gam );
238                it_assert_debug(std::isfinite(tmp),"Infinite value");
239                return tmp;
240        };
241        //!access function
242        vec& _beta()  {return beta;}
243        //!Set internal parameters
244        void set_parameters ( const vec &beta0 ) {
245                if ( beta0.length() !=beta.length() ) {
246                        it_assert_debug ( rv.length() ==1,"Undefined" );
247                        rv.set_size ( 0,beta0.length() );
248                }
249                beta= beta0;
250        }
251};
252
253//! \brief Estimator for Multinomial density
254class multiBM : public BMEF {
255protected:
256        //! Conjugate prior and posterior
257        eDirich est;
258        //! Pointer inside est to sufficient statistics
259        vec &beta;
260public:
261        //!Default constructor
262        multiBM ( const RV &rv, const vec beta0 ) : BMEF ( rv ),est ( rv,beta0 ),beta ( est._beta() ) {if(beta.length()>0){last_lognc=est.lognc();}else{last_lognc=0.0;}}
263        //!Copy constructor
264        multiBM ( const multiBM &B ) : BMEF ( B ),est ( rv,B.beta ),beta ( est._beta() ) {}
265        //! Sets sufficient statistics to match that of givefrom mB0
266        void set_statistics ( const BM* mB0 ) {const multiBM* mB=dynamic_cast<const multiBM*> ( mB0 ); beta=mB->beta;}
267        void bayes ( const vec &dt ) {
268                if ( frg<1.0 ) {beta*=frg;last_lognc=est.lognc();}
269                beta+=dt;
270                if ( evalll ) {ll=est.lognc()-last_lognc;}
271        }
272        double logpred ( const vec &dt ) const {
273                eDirich pred ( est );
274                vec &beta = pred._beta();
275
276                double lll;
277                if ( frg<1.0 )
278                        {beta*=frg;lll=pred.lognc();}
279                else
280                        if ( evalll ) {lll=last_lognc;}
281                        else{lll=pred.lognc();}
282
283                beta+=dt;
284                return pred.lognc()-lll;
285        }
286        void flatten ( const BMEF* B ) {
287                const multiBM* E=dynamic_cast<const multiBM*> ( B );
288                // sum(beta) should be equal to sum(B.beta)
289                const vec &Eb=E->beta;//const_cast<multiBM*> ( E )->_beta();
290                beta*= ( sum ( Eb ) /sum ( beta ) );
291                if ( evalll ) {last_lognc=est.lognc();}
292        }
293        const epdf& _epdf() const {return est;};
294        const eDirich* _e() const {return &est;};
295        void set_parameters ( const vec &beta0 ) {
296                est.set_parameters ( beta0 );
297                rv = est._rv();
298                if ( evalll ) {last_lognc=est.lognc();}
299        }
300};
301
302/*!
303 \brief Gamma posterior density
304
305 Multivariate Gamma density as product of independent univariate densities.
306 \f[
307 f(x|\alpha,\beta) = \prod f(x_i|\alpha_i,\beta_i)
308 \f]
309*/
310
311class egamma : public eEF {
312protected:
313        //! Vector \f$\alpha\f$
314        vec alpha;
315        //! Vector \f$\beta\f$
316        vec beta;
317public :
318        //! Default constructor
319        egamma ( const RV &rv ) :eEF ( rv ), alpha(rv.count()), beta(rv.count()) {};
320        //! Sets parameters
321        void set_parameters ( const vec &a, const vec &b ) {alpha=a,beta=b;};
322        vec sample() const;
323        //! TODO: is it used anywhere?
324//      mat sample ( int N ) const;
325        double evallog ( const vec &val ) const;
326        double lognc () const;
327        //! Returns poiter to alpha and beta. Potentially dengerous: use with care!
328        void _param ( vec* &a, vec* &b ) {a=&alpha;b=&beta;};
329        vec mean() const {vec pom ( alpha ); pom/=beta; return pom;}
330};
331
332/*!
333 \brief Inverse-Gamma posterior density
334
335 Multivariate inverse-Gamma density as product of independent univariate densities.
336 \f[
337 f(x|\alpha,\beta) = \prod f(x_i|\alpha_i,\beta_i)
338 \f]
339
340 Inverse Gamma can be converted to Gamma using \[
341 x\sim iG(a,b) => 1/x\sim G(a,1/b)
342\]
343This relation is used in sampling.
344 */
345
346class eigamma : public eEF {
347        protected:
348        //! Vector \f$\alpha\f$
349                vec* alpha;
350        //! Vector \f$\beta\f$ (in fact it is 1/beta as used in definition of iG)
351                vec* beta;
352                //!internal egamma
353                egamma eg;
354        public :
355        //! Default constructor
356                eigamma ( const RV &rv ) :eEF ( rv ), eg(rv) {eg._param(alpha,beta);};
357        //! Sets parameters
358                void set_parameters ( const vec &a, const vec &b ) {*alpha=a,*beta=b;};
359                vec sample() const {return 1.0/eg.sample();};
360        //! TODO: is it used anywhere?
361//      mat sample ( int N ) const;
362                double evallog ( const vec &val ) const {return eg.evallog(val);};
363                double lognc () const {return eg.lognc();};
364        //! Returns poiter to alpha and beta. Potentially dangerous: use with care!
365                void _param ( vec* &a, vec* &b ) {a=alpha;b=beta;};
366                vec mean() const {return elem_div(*beta,*alpha-1);}
367};
368/*
369//! Weighted mixture of epdfs with external owned components.
370class emix : public epdf {
371protected:
372        int n;
373        vec &w;
374        Array<epdf*> Coms;
375public:
376//! Default constructor
377        emix ( const RV &rv, vec &w0): epdf(rv), n(w0.length()), w(w0), Coms(n) {};
378        void set_parameters( int &i, double wi, epdf* ep){w(i)=wi;Coms(i)=ep;}
379        vec mean(){vec pom; for(int i=0;i<n;i++){pom+=Coms(i)->mean()*w(i);} return pom;};
380        vec sample() {it_error ( "Not implemented" );return 0;}
381};
382*/
383
384//!  Uniform distributed density on a rectangular support
385
386class euni: public epdf {
387protected:
388//! lower bound on support
389        vec low;
390//! upper bound on support
391        vec high;
392//! internal
393        vec distance;
394//! normalizing coefficients
395        double nk;
396//! cache of log( \c nk )
397        double lnk;
398public:
399        //! Defualt constructor
400        euni ( const RV rv ) :epdf ( rv ) {}
401        double eval ( const vec &val ) const  {return nk;}
402        double evallog ( const vec &val ) const  {return lnk;}
403        vec sample() const {
404                vec smp ( rv.count() );
405#pragma omp critical
406                UniRNG.sample_vector ( rv.count(),smp );
407                return low+elem_mult ( distance,smp );
408        }
409        //! set values of \c low and \c high
410        void set_parameters ( const vec &low0, const vec &high0 ) {
411                distance = high0-low0;
412                it_assert_debug ( min ( distance ) >0.0,"bad support" );
413                low = low0;
414                high = high0;
415                nk = prod ( 1.0/distance );
416                lnk = log ( nk );
417        }
418        vec mean() const {vec pom=high; pom-=low; pom/=2.0; return pom;}
419};
420
421
422/*!
423 \brief Normal distributed linear function with linear function of mean value;
424
425 Mean value \f$mu=A*rvc+mu_0\f$.
426*/
427template<class sq_T>
428class mlnorm : public mEF {
429protected:
430        //! Internal epdf that arise by conditioning on \c rvc
431        enorm<sq_T> epdf;
432        mat A;
433        vec mu_const;
434        vec& _mu; //cached epdf.mu;
435public:
436        //! Constructor
437        mlnorm ( const RV &rv, const RV &rvc );
438        //! Set \c A and \c R
439        void set_parameters ( const  mat &A, const vec &mu0, const sq_T &R );
440//      //!Generate one sample of the posterior
441//      vec samplecond (const vec &cond, double &lik );
442//      //!Generate matrix of samples of the posterior
443//      mat samplecond (const vec &cond, vec &lik, int n );
444        //! Set value of \c rvc . Result of this operation is stored in \c epdf use function \c _ep to access it.
445        void condition ( const vec &cond );
446
447        //!access function
448        vec& _mu_const() {return mu_const;}
449        //!access function
450        mat& _A() {return A;}
451        //!access function
452        mat _R() {return epdf._R().to_mat();}
453
454        template<class sq_M>
455        friend std::ostream &operator<< ( std::ostream &os,  mlnorm<sq_M> &ml );
456};
457
458/*! (Approximate) Student t density with linear function of mean value
459*/
460class mlstudent : public mlnorm<ldmat> {
461protected:
462        ldmat Lambda;
463        ldmat &_R;
464        ldmat Re;
465public:
466        mlstudent ( const RV &rv0, const RV &rvc0 ) :mlnorm<ldmat> ( rv0,rvc0 ),
467                        Lambda ( rv0.count() ),
468                        _R ( epdf._R() ) {}
469        void set_parameters ( const mat &A0, const vec &mu0, const ldmat &R0, const ldmat& Lambda0) {
470                epdf.set_parameters ( zeros ( rv.count() ),Lambda );
471                A = A0;
472                mu_const = mu0;
473                Re=R0;
474                Lambda = Lambda0;
475        }
476        void condition ( const vec &cond ) {
477                _mu = A*cond + mu_const;
478                double zeta;
479                //ugly hack!
480                if ((cond.length()+1)==Lambda.rows()){
481                        zeta = Lambda.invqform ( concat(cond, vec_1(1.0)) );
482                } else {
483                        zeta = Lambda.invqform ( cond );
484                }
485                _R = Re;
486                _R*=( 1+zeta );// / ( nu ); << nu is in Re!!!!!!
487        };
488
489};
490/*!
491\brief  Gamma random walk
492
493Mean value, \f$\mu\f$, of this density is given by \c rvc .
494Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
495This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
496
497The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
498*/
499class mgamma : public mEF {
500protected:
501        //! Internal epdf that arise by conditioning on \c rvc
502        egamma epdf;
503        //! Constant \f$k\f$
504        double k;
505        //! cache of epdf.beta
506        vec* _beta;
507
508public:
509        //! Constructor
510        mgamma ( const RV &rv,const RV &rvc ): mEF ( rv,rvc ), epdf ( rv ) {vec* tmp; epdf._param ( tmp,_beta );ep=&epdf;};
511        //! Set value of \c k
512        void set_parameters ( double k );
513        void condition ( const vec &val ) {*_beta=k/val;};
514};
515
516/*!
517\brief  Inverse-Gamma random walk
518
519Mean value, \f$\mu\f$, of this density is given by \c rvc .
520Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
521This is achieved by setting \f$\alpha=\mu/k+2\f$ and \f$\beta=\mu(\alpha-1)\f$.
522
523The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
524 */
525class migamma : public mEF {
526        protected:
527        //! Internal epdf that arise by conditioning on \c rvc
528                eigamma epdf;
529        //! Constant \f$k\f$
530                double k;
531        //! cache of epdf.beta
532                vec* _beta;
533                //! chaceh of epdf.alpha
534                vec* _alpha;
535
536        public:
537        //! Constructor
538                migamma ( const RV &rv,const RV &rvc ): mEF ( rv,rvc ), epdf ( rv ) {epdf._param ( _alpha,_beta );ep=&epdf;};
539        //! Set value of \c k
540                void set_parameters ( double k0 ){k=k0;*_alpha=1.0/(k*k)+2;};
541                void condition ( const vec &val ) {
542                        *_beta=elem_mult(val,(*_alpha-1));
543                };
544};
545
546/*!
547\brief  Gamma random walk around a fixed point
548
549Mean 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
550\f[ \mu = \mu_{t-1} ^{l} p^{1-l}\f]
551
552Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
553This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
554
555The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
556*/
557class mgamma_fix : public mgamma {
558protected:
559        //! parameter l
560        double l;
561        //! reference vector
562        vec refl;
563public:
564        //! Constructor
565        mgamma_fix ( const RV &rv,const RV &rvc ) : mgamma ( rv,rvc ),refl ( rv.count() ) {};
566        //! Set value of \c k
567        void set_parameters ( double k0 , vec ref0, double l0 ) {
568                mgamma::set_parameters ( k0 );
569                refl=pow ( ref0,1.0-l0 );l=l0;
570        };
571
572        void condition ( const vec &val ) {vec mean=elem_mult ( refl,pow ( val,l ) ); *_beta=k/mean;};
573};
574
575
576/*!
577\brief  Inverse-Gamma random walk around a fixed point
578
579Mean 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
580\f[ \mu = \mu_{t-1} ^{l} p^{1-l}\f]
581
582==== Check == vv =
583Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
584This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
585
586The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
587 */
588class migamma_fix : public migamma {
589        protected:
590        //! parameter l
591                double l;
592        //! reference vector
593                vec refl;
594        public:
595        //! Constructor
596                migamma_fix ( const RV &rv,const RV &rvc ) : migamma ( rv,rvc ),refl ( rv.count() ) {};
597        //! Set value of \c k
598                void set_parameters ( double k0 , vec ref0, double l0 ) {
599                        migamma::set_parameters ( k0 );
600                        refl=pow ( ref0,1.0-l0 );l=l0;
601                };
602
603                void condition ( const vec &val ) {vec mean=elem_mult ( refl,pow ( val,l ) ); migamma::condition(mean);};
604};
605//! Switch between various resampling methods.
606enum RESAMPLING_METHOD { MULTINOMIAL = 0, STRATIFIED = 1, SYSTEMATIC = 3 };
607/*!
608\brief Weighted empirical density
609
610Used e.g. in particle filters.
611*/
612class eEmp: public epdf {
613protected :
614        //! Number of particles
615        int n;
616        //! Sample weights \f$w\f$
617        vec w;
618        //! Samples \f$x^{(i)}, i=1..n\f$
619        Array<vec> samples;
620public:
621        //! Default constructor
622        eEmp ( const RV &rv0 ,int n0 ) :epdf ( rv0 ),n ( n0 ),w ( n ),samples ( n ) {};
623        //! Set samples and weights
624        void set_parameters ( const vec &w0, const epdf* pdf0 );
625        //! Set sample
626        void set_samples ( const epdf* pdf0 );
627        //! Set sample
628        void set_n ( int n0, bool copy=true ){w.set_size(n0,copy);samples.set_size(n0,copy);};
629        //! Potentially dangerous, use with care.
630        vec& _w()  {return w;};
631        //! Potentially dangerous, use with care.
632        const vec& _w() const {return w;};
633        //! access function
634        Array<vec>& _samples() {return samples;};
635        //! access function
636        const Array<vec>& _samples() const {return samples;};
637        //! 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.
638        ivec resample ( RESAMPLING_METHOD method = SYSTEMATIC );
639        //! inherited operation : NOT implemneted
640        vec sample() const {it_error ( "Not implemented" );return 0;}
641        //! inherited operation : NOT implemneted
642        double evallog ( const vec &val ) const {it_error ( "Not implemented" );return 0.0;}
643        vec mean() const {
644                vec pom=zeros ( rv.count() );
645                for ( int i=0;i<n;i++ ) {pom+=samples ( i ) *w ( i );}
646                return pom;
647        }
648};
649
650
651////////////////////////
652
653template<class sq_T>
654enorm<sq_T>::enorm ( const RV &rv ) :eEF ( rv ), mu ( rv.count() ),R ( rv.count() ),dim ( rv.count() ) {};
655
656template<class sq_T>
657void enorm<sq_T>::set_parameters ( const vec &mu0, const sq_T &R0 ) {
658//Fixme test dimensions of mu0 and R0;
659        mu = mu0;
660        R = R0;
661};
662
663template<class sq_T>
664void enorm<sq_T>::dupdate ( mat &v, double nu ) {
665        //
666};
667
668// template<class sq_T>
669// void enorm<sq_T>::tupdate ( double phi, mat &vbar, double nubar ) {
670//      //
671// };
672
673template<class sq_T>
674vec enorm<sq_T>::sample() const {
675        vec x ( dim );
676        NorRNG.sample_vector ( dim,x );
677        vec smp = R.sqrt_mult ( x );
678
679        smp += mu;
680        return smp;
681};
682
683template<class sq_T>
684mat enorm<sq_T>::sample ( int N ) const {
685        mat X ( dim,N );
686        vec x ( dim );
687        vec pom;
688        int i;
689
690        for ( i=0;i<N;i++ ) {
691                NorRNG.sample_vector ( dim,x );
692                pom = R.sqrt_mult ( x );
693                pom +=mu;
694                X.set_col ( i, pom );
695        }
696
697        return X;
698};
699
700// template<class sq_T>
701// double enorm<sq_T>::eval ( const vec &val ) const {
702//      double pdfl,e;
703//      pdfl = evallog ( val );
704//      e = exp ( pdfl );
705//      return e;
706// };
707
708template<class sq_T>
709double enorm<sq_T>::evallog_nn ( const vec &val ) const {
710        // 1.83787706640935 = log(2pi)
711        double tmp=-0.5* ( R.invqform ( mu-val ) );// - lognc();
712        return  tmp;
713};
714
715template<class sq_T>
716inline double enorm<sq_T>::lognc () const {
717        // 1.83787706640935 = log(2pi)
718        double tmp=0.5* ( R.cols() * 1.83787706640935 +R.logdet() );
719        return tmp;
720};
721
722template<class sq_T>
723mlnorm<sq_T>::mlnorm ( const RV &rv0, const RV &rvc0 ) :mEF ( rv0,rvc0 ),epdf ( rv0 ),A ( rv0.count(),rv0.count() ),_mu ( epdf._mu() ) {
724        ep =&epdf;
725}
726
727template<class sq_T>
728void mlnorm<sq_T>::set_parameters ( const mat &A0, const vec &mu0, const sq_T &R0 ) {
729        epdf.set_parameters ( zeros ( rv.count() ),R0 );
730        A = A0;
731        mu_const = mu0;
732}
733
734// template<class sq_T>
735// vec mlnorm<sq_T>::samplecond (const  vec &cond, double &lik ) {
736//      this->condition ( cond );
737//      vec smp = epdf.sample();
738//      lik = epdf.eval ( smp );
739//      return smp;
740// }
741
742// template<class sq_T>
743// mat mlnorm<sq_T>::samplecond (const vec &cond, vec &lik, int n ) {
744//      int i;
745//      int dim = rv.count();
746//      mat Smp ( dim,n );
747//      vec smp ( dim );
748//      this->condition ( cond );
749//
750//      for ( i=0; i<n; i++ ) {
751//              smp = epdf.sample();
752//              lik ( i ) = epdf.eval ( smp );
753//              Smp.set_col ( i ,smp );
754//      }
755//
756//      return Smp;
757// }
758
759template<class sq_T>
760void mlnorm<sq_T>::condition ( const vec &cond ) {
761        _mu = A*cond + mu_const;
762//R is already assigned;
763}
764
765template<class sq_T>
766epdf* enorm<sq_T>::marginal ( const RV &rvn ) const {
767        ivec irvn = rvn.dataind ( rv );
768
769        sq_T Rn ( R,irvn );
770        enorm<sq_T>* tmp = new enorm<sq_T> ( rvn );
771        tmp->set_parameters ( mu ( irvn ), Rn );
772        return tmp;
773}
774
775template<class sq_T>
776mpdf* enorm<sq_T>::condition ( const RV &rvn ) const {
777
778        RV rvc = rv.subt ( rvn );
779        it_assert_debug ( ( rvc.count() +rvn.count() ==rv.count() ),"wrong rvn" );
780        //Permutation vector of the new R
781        ivec irvn = rvn.dataind ( rv );
782        ivec irvc = rvc.dataind ( rv );
783        ivec perm=concat ( irvn , irvc );
784        sq_T Rn ( R,perm );
785
786        //fixme - could this be done in general for all sq_T?
787        mat S=Rn.to_mat();
788        //fixme
789        int n=rvn.count()-1;
790        int end=R.rows()-1;
791        mat S11 = S.get ( 0,n, 0, n );
792        mat S12 = S.get ( 0, n , rvn.count(), end );
793        mat S22 = S.get ( rvn.count(), end, rvn.count(), end );
794
795        vec mu1 = mu ( irvn );
796        vec mu2 = mu ( irvc );
797        mat A=S12*inv ( S22 );
798        sq_T R_n ( S11 - A *S12.T() );
799
800        mlnorm<sq_T>* tmp=new mlnorm<sq_T> ( rvn,rvc );
801
802        tmp->set_parameters ( A,mu1-A*mu2,R_n );
803        return tmp;
804}
805
806///////////
807
808template<class sq_T>
809std::ostream &operator<< ( std::ostream &os,  mlnorm<sq_T> &ml ) {
810        os << "A:"<< ml.A<<endl;
811        os << "mu:"<< ml.mu_const<<endl;
812        os << "R:" << ml.epdf._R().to_mat() <<endl;
813        return os;
814};
815
816#endif //EF_H
Note: See TracBrowser for help on using the browser.