root/bdm/stat/libEF.h @ 211

Revision 211, 19.8 kB (checked in by smidl, 16 years ago)

prejmenovani evalpdflog a evalcond

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