root/bdm/stat/libEF.h @ 204

Revision 204, 19.5 kB (checked in by smidl, 16 years ago)

merger is now in logarithms + new merge_test

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