root/bdm/stat/libEF.h @ 214

Revision 214, 20.0 kB (checked in by smidl, 15 years ago)

debug asserts for infinite likelihoods

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