root/library/bdm/stat/exp_family.h @ 970

Revision 970, 44.2 kB (checked in by smidl, 14 years ago)

Student + arx corrections

  • 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
17#include "../shared_ptr.h"
18#include "../base/bdmbase.h"
19#include "../math/chmat.h"
20
21namespace bdm {
22
23
24//! Global Uniform_RNG
25extern Uniform_RNG UniRNG;
26//! Global Normal_RNG
27extern Normal_RNG NorRNG;
28//! Global Gamma_RNG
29extern Gamma_RNG GamRNG;
30
31/*!
32* \brief General conjugate exponential family posterior density.
33
34* More?...
35*/
36
37class eEF : public epdf {
38public:
39//      eEF() :epdf() {};
40        //! default constructor
41        eEF () : epdf () {};
42        //! logarithm of the normalizing constant, \f$\mathcal{I}\f$
43        virtual double lognc() const = 0;
44
45        //!Evaluate normalized log-probability
46        virtual double evallog_nn ( const vec &val ) const NOT_IMPLEMENTED(0);
47
48        //!Evaluate normalized log-probability
49        virtual double evallog ( const vec &val ) const {
50                double tmp;
51                tmp = evallog_nn ( val ) - lognc();
52                return tmp;
53        }
54        //!Evaluate normalized log-probability for many samples
55        virtual vec evallog_mat ( const mat &Val ) const {
56                vec x ( Val.cols() );
57                for ( int i = 0; i < Val.cols(); i++ ) {
58                        x ( i ) = evallog_nn ( Val.get_col ( i ) ) ;
59                }
60                return x - lognc();
61        }
62        //!Evaluate normalized log-probability for many samples
63        virtual vec evallog_mat ( const Array<vec> &Val ) const {
64                vec x ( Val.length() );
65                for ( int i = 0; i < Val.length(); i++ ) {
66                        x ( i ) = evallog_nn ( Val ( i ) ) ;
67                }
68                return x - lognc();
69        }
70
71        //!Power of the density, used e.g. to flatten the density
72        virtual void pow ( double p ) NOT_IMPLEMENTED_VOID;
73};
74
75
76//! Estimator for Exponential family
77class BMEF : public BM {
78protected:
79        //! forgetting factor
80        double frg;
81        //! cached value of lognc() in the previous step (used in evaluation of \c ll )
82        double last_lognc;
83public:
84        //! Default constructor (=empty constructor)
85        BMEF ( double frg0 = 1.0 ) : BM (), frg ( frg0 ) {}
86        //! Copy constructor
87        BMEF ( const BMEF &B ) : BM ( B ), frg ( B.frg ), last_lognc ( B.last_lognc ) {}
88        //!get statistics from another model
89        virtual void set_statistics ( const BMEF* BM0 ) NOT_IMPLEMENTED_VOID;
90
91        //! Weighted update of sufficient statistics (Bayes rule)
92        virtual void bayes_weighted ( const vec &data, const vec &cond = empty_vec, const double w = 1.0 ) {};
93        //original Bayes
94        void bayes ( const vec &yt, const vec &cond = empty_vec );
95
96        //!Flatten the posterior according to the given BMEF (of the same type!)
97        virtual void flatten ( const BMEF * B ) NOT_IMPLEMENTED_VOID;
98
99
100        void to_setting ( Setting &set ) const
101        {                       
102                BM::to_setting( set );
103                UI::save(frg, set, "frg");
104        } 
105
106        void from_setting( const Setting &set) {
107                BM::from_setting(set);
108                if ( !UI::get ( frg, set, "frg" ) )
109                        frg = 1.0;
110        }
111
112        void validate() {
113                BM::validate(); 
114        }
115
116};
117
118/*! Dirac delta density with predefined transformation
119
120Density of the type:\f[ f(x_t | y_t) = \delta (x_t - g(y_t)) \f]
121where \f$ x_t \f$ is the \c rv, \f$ y_t \f$ is the \c rvc and g is a deterministic transformation of class fn.
122*/
123class mgdirac: public pdf{
124        protected:
125        shared_ptr<fnc> g;
126        public:
127                vec samplecond(const vec &cond) {
128                        bdm_assert_debug(cond.length()==g->dimensionc(),"given cond in not compatible with g");
129                        vec tmp = g->eval(cond);
130                        return tmp;
131                } 
132                double evallogcond ( const vec &yt, const vec &cond ){
133                        return std::numeric_limits< double >::max();
134                }
135                void from_setting(const Setting& set);
136                void to_setting(Setting &set) const;
137                void validate();
138};
139UIREGISTER(mgdirac);
140
141
142template<class sq_T, template <typename> class TEpdf>
143class mlnorm;
144
145/*!
146* \brief Gaussian density with positive definite (decomposed) covariance matrix.
147
148* More?...
149*/
150template<class sq_T>
151class enorm : public eEF {
152protected:
153        //! mean value
154        vec mu;
155        //! Covariance matrix in decomposed form
156        sq_T R;
157public:
158        //!\name Constructors
159        //!@{
160
161        enorm () : eEF (), mu (), R () {};
162        enorm ( const vec &mu, const sq_T &R ) {
163                set_parameters ( mu, R );
164        }
165        void set_parameters ( const vec &mu, const sq_T &R );
166        /*! Create Normal density
167        \f[ f(rv) = N(\mu, R) \f]
168        from structure
169        \code
170        class = 'enorm<ldmat>', (OR) 'enorm<chmat>', (OR) 'enorm<fsqmat>';
171        mu    = [];                  // mean value
172        R     = [];                  // variance, square matrix of appropriate dimension
173        \endcode
174        */
175        void from_setting ( const Setting &root );
176        void to_setting ( Setting &root ) const ;
177       
178        void validate();
179        //!@}
180
181        //! \name Mathematical operations
182        //!@{
183
184        //! dupdate in exponential form (not really handy)
185        void dupdate ( mat &v, double nu = 1.0 );
186
187        //! evaluate bhattacharya distance
188        double bhattacharyya(const enorm<sq_T> &e2){
189                bdm_assert(dim == e2.dimension(), "enorms of differnt dimensions");
190                sq_T P=R;
191                P.add(e2._R());
192               
193                double tmp = 0.125*P.invqform(mu - e2._mu()) + 0.5*(P.logdet() - 0.5*(R.logdet() + e2._R().logdet()));
194                return tmp;
195        }
196       
197        vec sample() const;
198
199        double evallog_nn ( const vec &val ) const;
200        double lognc () const;
201        vec mean() const {
202                return mu;
203        }
204        vec variance() const {
205                return diag ( R.to_mat() );
206        }
207        mat covariance() const {
208                return R.to_mat();
209        }
210        //      mlnorm<sq_T>* condition ( const RV &rvn ) const ; <=========== fails to cmpile. Why?
211        shared_ptr<pdf> condition ( const RV &rvn ) const;
212
213        // target not typed to mlnorm<sq_T, enorm<sq_T> > &
214        // because that doesn't compile (perhaps because we
215        // haven't finished defining enorm yet), but the type
216        // is required
217        void condition ( const RV &rvn, pdf &target ) const;
218
219        shared_ptr<epdf> marginal ( const RV &rvn ) const;
220        void marginal ( const RV &rvn, enorm<sq_T> &target ) const;
221        //!@}
222
223        //! \name Access to attributes
224        //!@{
225
226        vec& _mu() {
227                return mu;
228        }
229        const vec& _mu() const {
230                return mu;
231        }
232        void set_mu ( const vec mu0 ) {
233                mu = mu0;
234        }
235        sq_T& _R() {
236                return R;
237        }
238        const sq_T& _R() const {
239                return R;
240        }
241        //!@}
242
243};
244UIREGISTER2 ( enorm, chmat );
245SHAREDPTR2 ( enorm, chmat );
246UIREGISTER2 ( enorm, ldmat );
247SHAREDPTR2 ( enorm, ldmat );
248UIREGISTER2 ( enorm, fsqmat );
249SHAREDPTR2 ( enorm, fsqmat );
250
251//! \class bdm::egauss
252//!\brief Gaussian (Normal) distribution. Same as enorm<fsqmat>.
253typedef enorm<ldmat> egauss;
254UIREGISTER(egauss);
255
256
257//forward declaration
258class mstudent;
259
260/*! distribution of multivariate Student t density
261
262Based on article by Genest and Zidek,
263*/
264template<class sq_T>
265class estudent : public eEF{
266        protected:
267                //! mena value
268                vec mu;
269                //! matrix H
270                sq_T H;
271                //! degrees of freedom
272                double delta;
273        public:
274                double evallog_nn(const vec &val) const{
275                        double tmp = -0.5*H.logdet() - 0.5*(delta + dim) * log(1+ H.invqform(val - mu)/delta);
276                        return tmp;
277                }
278                double lognc() const {
279                        //log(pi) = 1.14472988584940
280                        double tmp = -lgamma(0.5*(delta+dim))+lgamma(0.5*delta) + 0.5*dim*(log(delta) + 1.14472988584940);
281                        return tmp;
282                }
283                void marginal (const RV &rvm, estudent<sq_T> &marg) const {
284                        ivec ind = rvm.findself_ids(rv); // indices of rvm in rv
285                        marg._mu() = mu(ind);
286                        marg._H() = sq_T(H,ind);
287                        marg._delta() = delta;
288                        marg.validate();
289                }
290                shared_ptr<epdf> marginal(const RV &rvm) const {
291                        shared_ptr<estudent<sq_T> > tmp = new estudent<sq_T>;
292                        marginal(rvm, *tmp);
293                        return tmp;
294                }
295                vec sample() const NOT_IMPLEMENTED(vec(0))
296               
297                vec mean() const {return mu;}
298                mat covariance() const {
299                        return delta/(delta-2)*H.to_mat();
300                }
301                vec variance() const {return diag(covariance());}
302                        //! \name access
303                //! @{
304                        //! access function
305                        vec& _mu() {return mu;}
306                        //! access function
307                        sq_T& _H() {return H;}
308                        //! access function
309                        double& _delta() {return delta;}
310                        //!@}
311                        //! todo
312                        void from_setting(const Setting &set){
313                                epdf::from_setting(set);
314                                mat H0;
315                                UI::get(H0,set, "H");
316                                H= H0; // conversion!!
317                                UI::get(delta,set,"delta");
318                                UI::get(mu,set,"mu");
319                        }
320                        void to_setting(Setting &set) const{
321                                epdf::to_setting(set);
322                                UI::save(H.to_mat(), set, "H");
323                                UI::save(delta, set, "delta");
324                                UI::save(mu, set, "mu");
325                        }
326                        void validate() {
327                                eEF::validate();
328                                dim = H.rows();
329                        }
330};
331UIREGISTER2(estudent,fsqmat);
332UIREGISTER2(estudent,ldmat);
333UIREGISTER2(estudent,chmat);
334
335/*!
336* \brief Gauss-inverse-Wishart density stored in LD form
337
338* For \f$p\f$-variate densities, given rv.count() should be \f$p\times\f$ V.rows().
339*
340*/
341class egiw : public eEF {
342        //! \var log_level_enums logvartheta
343        //! Log variance of the theta part
344
345        LOG_LEVEL(egiw,logvartheta);
346
347protected:
348        //! Extended information matrix of sufficient statistics
349        ldmat V;
350        //! Number of data records (degrees of freedom) of sufficient statistics
351        double nu;
352        //! Dimension of the output
353        int dimx;
354        //! Dimension of the regressor
355        int nPsi;
356public:
357        //!\name Constructors
358        //!@{
359        egiw() : eEF() {};
360        egiw ( int dimx0, ldmat V0, double nu0 = -1.0 ) : eEF() {
361                set_parameters ( dimx0, V0, nu0 );
362                validate();
363        };
364
365        void set_parameters ( int dimx0, ldmat V0, double nu0 = -1.0 );
366        //!@}
367
368        vec sample() const;
369        mat sample_mat ( int n ) const;
370        vec mean() const;
371        vec variance() const;
372        void sample_mat ( mat &Mi, chmat &Ri ) const;
373
374        void factorize ( mat &M, ldmat &Vz, ldmat &Lam ) const;
375        //! LS estimate of \f$\theta\f$
376        vec est_theta() const;
377
378        //! Covariance of the LS estimate
379        ldmat est_theta_cov() const;
380
381        //! expected values of the linear coefficient and the covariance matrix are written to \c M and \c R , respectively
382        void mean_mat ( mat &M, mat&R ) const;
383        //! In this instance, val= [theta, r]. For multivariate instances, it is stored columnwise val = [theta_1 theta_2 ... r_1 r_2 ]
384        double evallog_nn ( const vec &val ) const;
385        double lognc () const;
386        void pow ( double p ) {
387                V *= p;
388                nu *= p;
389        };
390
391        //! marginal density (only student for now)
392        shared_ptr<epdf> marginal(const RV &rvm) const {
393                bdm_assert(dimx==1, "Not supported");
394                //TODO - this is too trivial!!!
395                ivec ind = rvm.findself_ids(rv);
396                if (min(ind)==0) { //assume it si
397                        shared_ptr<estudent<ldmat> > tmp = new estudent<ldmat>;
398                        mat M;
399                        ldmat Vz;
400                        ldmat Lam;
401                        factorize(M,Vz,Lam);
402                       
403                        tmp->_mu() = M.get_col(0);
404                        ldmat H;
405                        Vz.inv(H);
406                        H *=Lam._D()(0)/nu;
407                        tmp->_H() = H;
408                        tmp->_delta() = nu;
409                        tmp->validate();
410                        return tmp;
411                }
412                return NULL;
413        }
414        //! \name Access attributes
415        //!@{
416
417        ldmat& _V() {
418                return V;
419        }
420        const ldmat& _V() const {
421                return V;
422        }
423        double& _nu()  {
424                return nu;
425        }
426        const double& _nu() const {
427                return nu;
428        }
429        const int & _dimx() const {
430                return dimx;
431        }
432
433        /*! Create Gauss-inverse-Wishart density
434        \f[ f(rv) = GiW(V,\nu) \f]
435        from structure
436        \code
437        class = 'egiw';
438        V     = [];               // square matrix
439        dV    = [];               // vector of diagonal of V (when V not given)
440        nu    = [];               // scalar \nu ((almost) degrees of freedom)
441                                                          // when missing, it will be computed to obtain proper pdf
442        dimx  = [];               // dimension of the wishart part
443        rv = RV({'name'})         // description of RV
444        rvc = RV({'name'})        // description of RV in condition
445        log_level = 'tri';                // set the level of logged details
446        \endcode
447
448        \sa log_level_enums
449        */
450        void from_setting ( const Setting &set );
451        //! see egiw::from_setting
452        void to_setting ( Setting& set ) const;
453        void validate();
454        void log_register ( bdm::logger& L, const string& prefix );
455
456        void log_write() const;
457        //!@}
458};
459UIREGISTER ( egiw );
460SHAREDPTR ( egiw );
461
462/*! \brief Dirichlet posterior density
463
464Continuous Dirichlet density of \f$n\f$-dimensional variable \f$x\f$
465\f[
466f(x|\beta) = \frac{\Gamma[\gamma]}{\prod_{i=1}^{n}\Gamma(\beta_i)} \prod_{i=1}^{n}x_i^{\beta_i-1}
467\f]
468where \f$\gamma=\sum_i \beta_i\f$.
469*/
470class eDirich: public eEF {
471protected:
472        //!sufficient statistics
473        vec beta;
474public:
475        //!\name Constructors
476        //!@{
477
478        eDirich () : eEF () {};
479        eDirich ( const eDirich &D0 ) : eEF () {
480                set_parameters ( D0.beta );
481                validate();
482        };
483        eDirich ( const vec &beta0 ) {
484                set_parameters ( beta0 );
485                validate();
486        };
487        void set_parameters ( const vec &beta0 ) {
488                beta = beta0;
489                dim = beta.length();
490        }
491        //!@}
492
493        //! using sampling procedure from wikipedia
494        vec sample() const {
495                vec y ( beta.length() );
496                for ( int i = 0; i < beta.length(); i++ ) {
497                        GamRNG.setup ( beta ( i ), 1 );
498#pragma omp critical
499                        y ( i ) = GamRNG();
500                }
501                return y / sum ( y );
502        }
503
504        vec mean() const {
505                return beta / sum ( beta );
506        };
507        vec variance() const {
508                double gamma = sum ( beta );
509                return elem_mult ( beta, ( gamma - beta ) ) / ( gamma*gamma* ( gamma + 1 ) );
510        }
511        //! In this instance, val is ...
512        double evallog_nn ( const vec &val ) const {
513                double tmp;
514                tmp = ( beta - 1 ) * log ( val );
515                return tmp;
516        }
517
518        double lognc () const {
519                double tmp;
520                double gam = sum ( beta );
521                double lgb = 0.0;
522                for ( int i = 0; i < beta.length(); i++ ) {
523                        lgb += lgamma ( beta ( i ) );
524                }
525                tmp = lgb - lgamma ( gam );
526                return tmp;
527        }
528
529        //!access function
530        vec& _beta()  {
531                return beta;
532        }
533        /*! configuration structure
534        \code
535        class = 'eDirich';
536        beta  = [];           //parametr beta
537        \endcode
538        */
539        void from_setting ( const Setting &set );
540        void validate();
541        void to_setting ( Setting &set ) const;
542};
543UIREGISTER ( eDirich );
544
545/*! Random Walk on Dirichlet
546Using simple assignment
547 \f[ \beta = rvc / k + \beta_c \f]
548 hence, mean value = rvc, variance = (k+1)*mean*mean;
549
550 The greater k is, the greater is the variance of the random walk;
551
552 \f$ \beta_c \f$ is used as regularizing element to avoid corner cases, i.e. when one element of rvc is zero.
553 By default is it set to 0.1;
554*/
555
556class mDirich: public pdf_internal<eDirich> {
557protected:
558        //! constant \f$ k \f$ of the random walk
559        double k;
560        //! cache of beta_i
561        vec &_beta;
562        //! stabilizing coefficient \f$ \beta_c \f$
563        vec betac;
564public:
565        mDirich() : pdf_internal<eDirich>(), _beta ( iepdf._beta() ) {};
566        void condition ( const vec &val ) {
567                _beta =  val / k + betac;
568        };
569        /*! Create Dirichlet random walk
570        \f[ f(rv|rvc) = Di(rvc*k) \f]
571        from structure
572        \code
573        class = 'mDirich';
574        k = 1;                      // multiplicative constant k
575        --- optional ---
576        rv = RV({'name'},size)      // description of RV
577        beta0 = [];                 // initial value of beta
578        betac = [];                 // initial value of beta
579        \endcode
580        */
581        void from_setting ( const Setting &set );
582        void    to_setting  (Setting  &set) const;
583        void validate();
584};
585UIREGISTER ( mDirich );
586
587//! \brief Estimator for Multinomial density
588class multiBM : public BMEF {
589protected:
590        //! Conjugate prior and posterior
591        eDirich est;
592        //! Pointer inside est to sufficient statistics
593        vec &beta;
594public:
595        //!Default constructor
596        multiBM () : BMEF (), est (), beta ( est._beta() ) {
597                if ( beta.length() > 0 ) {
598                        last_lognc = est.lognc();
599                } else {
600                        last_lognc = 0.0;
601                }
602        }
603        //!Copy constructor
604        multiBM ( const multiBM &B ) : BMEF ( B ), est ( B.est ), beta ( est._beta() ) {}
605        //! Sets sufficient statistics to match that of givefrom mB0
606        void set_statistics ( const BM* mB0 ) {
607                const multiBM* mB = dynamic_cast<const multiBM*> ( mB0 );
608                beta = mB->beta;
609        }
610        void bayes ( const vec &yt, const vec &cond = empty_vec );
611
612        double logpred ( const vec &yt ) const;
613
614        void flatten ( const BMEF* B );
615
616        //! return correctly typed posterior (covariant return)
617        const eDirich& posterior() const {
618                return est;
619        };
620        //! constructor function
621        void set_parameters ( const vec &beta0 ) {
622                est.set_parameters ( beta0 );
623                est.validate();
624                if ( evalll ) {
625                        last_lognc = est.lognc();
626                }
627        }
628
629        void to_setting ( Setting &set ) const {
630                BMEF::to_setting ( set );
631                UI::save( &est, set, "prior" );
632        }
633};
634UIREGISTER( multiBM );
635
636/*!
637 \brief Gamma posterior density
638
639 Multivariate Gamma density as product of independent univariate densities.
640 \f[
641 f(x|\alpha,\beta) = \prod f(x_i|\alpha_i,\beta_i)
642 \f]
643*/
644
645class egamma : public eEF {
646protected:
647        //! Vector \f$\alpha\f$
648        vec alpha;
649        //! Vector \f$\beta\f$
650        vec beta;
651public :
652        //! \name Constructors
653        //!@{
654        egamma () : eEF (), alpha ( 0 ), beta ( 0 ) {};
655        egamma ( const vec &a, const vec &b ) {
656                set_parameters ( a, b );
657                validate();
658        };
659        void set_parameters ( const vec &a, const vec &b ) {
660                alpha = a, beta = b;
661        };
662        //!@}
663
664        vec sample() const;
665        double evallog ( const vec &val ) const;
666        double lognc () const;
667        //! Returns pointer to internal alpha. Potentially dengerous: use with care!
668        vec& _alpha() {
669                return alpha;
670        }
671        //! Returns pointer to internal beta. Potentially dengerous: use with care!
672        vec& _beta() {
673                return beta;
674        }
675        vec mean() const {
676                return elem_div ( alpha, beta );
677        }
678        vec variance() const {
679                return elem_div ( alpha, elem_mult ( beta, beta ) );
680        }
681
682        /*! Create Gamma density
683        \f[ f(rv|rvc) = \Gamma(\alpha, \beta) \f]
684        from structure
685        \code
686        class = 'egamma';
687        alpha = [...];         // vector of alpha
688        beta = [...];          // vector of beta
689        rv = RV({'name'})      // description of RV
690        \endcode
691        */
692        void from_setting ( const Setting &set );
693        void to_setting ( Setting &set ) const;
694        void validate(); 
695};
696UIREGISTER ( egamma );
697SHAREDPTR ( egamma );
698
699/*!
700 \brief Inverse-Gamma posterior density
701
702 Multivariate inverse-Gamma density as product of independent univariate densities.
703 \f[
704 f(x|\alpha,\beta) = \prod f(x_i|\alpha_i,\beta_i)
705 \f]
706
707Vector \f$\beta\f$ has different meaning (in fact it is 1/beta as used in definition of iG)
708
709 Inverse Gamma can be converted to Gamma using \f[
710 x\sim iG(a,b) => 1/x\sim G(a,1/b)
711\f]
712This relation is used in sampling.
713 */
714
715class eigamma : public egamma {
716protected:
717public :
718        //! \name Constructors
719        //! All constructors are inherited
720        //!@{
721        //!@}
722
723        vec sample() const {
724                return 1.0 / egamma::sample();
725        };
726        //! Returns poiter to alpha and beta. Potentially dangerous: use with care!
727        vec mean() const {
728                return elem_div ( beta, alpha - 1 );
729        }
730        vec variance() const {
731                vec mea = mean();
732                return elem_div ( elem_mult ( mea, mea ), alpha - 2 );
733        }
734};
735/*
736//! Weighted mixture of epdfs with external owned components.
737class emix : public epdf {
738protected:
739        int n;
740        vec &w;
741        Array<epdf*> Coms;
742public:
743//! Default constructor
744        emix ( const RV &rv, vec &w0): epdf(rv), n(w0.length()), w(w0), Coms(n) {};
745        void set_parameters( int &i, double wi, epdf* ep){w(i)=wi;Coms(i)=ep;}
746        vec mean(){vec pom; for(int i=0;i<n;i++){pom+=Coms(i)->mean()*w(i);} return pom;};
747};
748*/
749
750//!  Uniform distributed density on a rectangular support
751
752class euni: public epdf {
753protected:
754//! lower bound on support
755        vec low;
756//! upper bound on support
757        vec high;
758//! internal
759        vec distance;
760//! normalizing coefficients
761        double nk;
762//! cache of log( \c nk )
763        double lnk;
764public:
765        //! \name Constructors
766        //!@{
767        euni () : epdf () {}
768        euni ( const vec &low0, const vec &high0 ) {
769                set_parameters ( low0, high0 );
770        }
771        void set_parameters ( const vec &low0, const vec &high0 ) {
772                distance = high0 - low0;
773                low = low0;
774                high = high0;
775                nk = prod ( 1.0 / distance );
776                lnk = log ( nk );
777        }
778        //!@}
779
780        double evallog ( const vec &val ) const  {
781                if ( any ( val < low ) && any ( val > high ) ) {
782                        return -inf;
783                } else return lnk;
784        }
785        vec sample() const {
786                vec smp ( dim );
787#pragma omp critical
788                UniRNG.sample_vector ( dim , smp );
789                return low + elem_mult ( distance, smp );
790        }
791        //! set values of \c low and \c high
792        vec mean() const {
793                return ( high - low ) / 2.0;
794        }
795        vec variance() const {
796                return ( pow ( high, 2 ) + pow ( low, 2 ) + elem_mult ( high, low ) ) / 3.0;
797        }
798        /*! Create Uniform density
799        \f[ f(rv) = U(low,high) \f]
800        from structure
801         \code
802         class = 'euni'
803         high = [...];          // vector of upper bounds
804         low = [...];           // vector of lower bounds
805         rv = RV({'name'});     // description of RV
806         \endcode
807         */
808        void from_setting ( const Setting &set );
809        void    to_setting  (Setting  &set) const;
810        void validate();
811};
812UIREGISTER ( euni );
813
814//! Uniform density with conditional mean value
815class mguni : public pdf_internal<euni> {
816        //! function of the mean value
817        shared_ptr<fnc> mean;
818        //! distance from mean to both sides
819        vec delta;
820public:
821        void condition ( const vec &cond ) {
822                vec mea = mean->eval ( cond );
823                iepdf.set_parameters ( mea - delta, mea + delta );
824        }
825        //! load from
826        void from_setting ( const Setting &set ) {
827                pdf::from_setting ( set ); //reads rv and rvc
828                UI::get ( delta, set, "delta", UI::compulsory );
829                mean = UI::build<fnc> ( set, "mean", UI::compulsory );
830                iepdf.set_parameters ( -delta, delta );
831        }
832        void    to_setting  (Setting  &set) const {
833                pdf::to_setting ( set ); 
834                UI::save( iepdf.mean(), set, "delta");
835                UI::save(mean, set, "mean");
836        }
837        void validate(){
838                pdf_internal<euni>::validate();
839                dimc = mean->dimensionc();
840               
841        }
842
843};
844UIREGISTER ( mguni );
845/*!
846 \brief Normal distributed linear function with linear function of mean value;
847
848 Mean value \f$ \mu=A*\mbox{rvc}+\mu_0 \f$.
849*/
850template < class sq_T, template <typename> class TEpdf = enorm >
851class mlnorm : public pdf_internal< TEpdf<sq_T> > {
852protected:
853        //! Internal epdf that arise by conditioning on \c rvc
854        mat A;
855        //! Constant additive term
856        vec mu_const;
857//                      vec& _mu; //cached epdf.mu; !!!!!! WHY NOT?
858public:
859        //! \name Constructors
860        //!@{
861        mlnorm() : pdf_internal< TEpdf<sq_T> >() {};
862        mlnorm ( const mat &A, const vec &mu0, const sq_T &R ) : pdf_internal< TEpdf<sq_T> >() {
863                set_parameters ( A, mu0, R );
864                validate();
865        }
866
867        //! Set \c A and \c R
868        void set_parameters ( const  mat &A0, const vec &mu0, const sq_T &R0 ) {
869                this->iepdf.set_parameters ( zeros ( A0.rows() ), R0 );
870                A = A0;
871                mu_const = mu0;
872        }
873
874        //!@}
875        //! Set value of \c rvc . Result of this operation is stored in \c epdf use function \c _ep to access it.
876        void condition ( const vec &cond ) {
877                this->iepdf._mu() = A * cond + mu_const;
878//R is already assigned;
879        }
880
881        //!access function
882        const vec& _mu_const() const {
883                return mu_const;
884        }
885        //!access function
886        const mat& _A() const {
887                return A;
888        }
889        //!access function
890        mat _R() const {
891                return this->iepdf._R().to_mat();
892        }
893        //!access function
894        sq_T __R() const {
895                return this->iepdf._R();
896        }
897
898        //! Debug stream
899        template<typename sq_M>
900        friend std::ostream &operator<< ( std::ostream &os,  mlnorm<sq_M, enorm> &ml );
901
902        /*! Create Normal density with linear function of mean value
903         \f[ f(rv|rvc) = N(A*rvc+const, R) \f]
904        from structure
905        \code
906        class = 'mlnorm<ldmat>', (OR) 'mlnorm<chmat>', (OR) 'mlnorm<fsqmat>';
907        A     = [];                  // matrix or vector of appropriate dimension
908        R     = [];                  // square matrix of appropriate dimension
909        --- optional ---
910        const = zeros(A.rows);       // vector of constant term
911        \endcode
912        */
913        void from_setting ( const Setting &set ) {
914                pdf::from_setting ( set );
915
916                UI::get ( A, set, "A", UI::compulsory );
917                UI::get ( mu_const, set, "const", UI::optional);
918                mat R0;
919                UI::get ( R0, set, "R", UI::compulsory );
920                set_parameters ( A, mu_const, R0 );
921        }
922
923void to_setting (Setting &set) const {
924                pdf::to_setting(set);
925                UI::save ( A, set, "A");
926                UI::save ( mu_const, set, "const");
927                UI::save ( _R(), set, "R");
928        }
929
930void validate() {
931                pdf_internal<TEpdf<sq_T> >::validate();
932                if (mu_const.length()==0) { // default in from_setting
933                        mu_const=zeros(A.rows());
934                }
935                bdm_assert ( A.rows() == mu_const.length(), "mlnorm: A vs. mu mismatch" );
936                bdm_assert ( A.rows() == _R().rows(), "mlnorm: A vs. R mismatch" );
937                this->dimc = A.cols();
938
939        }
940};
941UIREGISTER2 ( mlnorm, ldmat );
942SHAREDPTR2 ( mlnorm, ldmat );
943UIREGISTER2 ( mlnorm, fsqmat );
944SHAREDPTR2 ( mlnorm, fsqmat );
945UIREGISTER2 ( mlnorm, chmat );
946SHAREDPTR2 ( mlnorm, chmat );
947
948//! \class mlgauss
949//!\brief Normal distribution with linear function of mean value. Same as mlnorm<fsqmat>.
950typedef mlnorm<fsqmat> mlgauss;
951UIREGISTER(mlgauss);
952
953//! pdf with general function for mean value
954template<class sq_T>
955class mgnorm : public pdf_internal< enorm< sq_T > > {
956private:
957//                      vec &mu; WHY NOT?
958        shared_ptr<fnc> g;
959
960public:
961        //!default constructor
962        mgnorm() : pdf_internal<enorm<sq_T> >() { }
963        //!set mean function
964        inline void set_parameters ( const shared_ptr<fnc> &g0, const sq_T &R0 );
965        inline void condition ( const vec &cond );
966
967
968        /*! Create Normal density with given function of mean value
969        \f[ f(rv|rvc) = N( g(rvc), R) \f]
970        from structure
971        \code
972        class = 'mgnorm';
973        g.class =  'fnc';      // function for mean value evolution
974        g._fields_of_fnc = ...;
975
976        R = [1, 0;             // covariance matrix
977                0, 1];
978                --OR --
979        dR = [1, 1];           // diagonal of cavariance matrix
980
981        rv = RV({'name'})      // description of RV
982        rvc = RV({'name'})     // description of RV in condition
983        \endcode
984        */
985
986
987void from_setting ( const Setting &set ) {
988                pdf::from_setting ( set );
989                shared_ptr<fnc> g = UI::build<fnc> ( set, "g", UI::compulsory );
990
991                mat R;
992                vec dR;
993                if ( UI::get ( dR, set, "dR" ) )
994                        R = diag ( dR );
995                else
996                        UI::get ( R, set, "R", UI::compulsory );
997
998                set_parameters ( g, R );
999                //validate();
1000        }
1001       
1002
1003void to_setting  (Setting  &set) const {
1004                UI::save( g,set, "g");
1005                UI::save(this->iepdf._R().to_mat(),set, "R");
1006       
1007        }
1008
1009
1010
1011void validate() {
1012                this->iepdf.validate();
1013                bdm_assert ( g->dimension() == this->iepdf.dimension(), "incompatible function" );
1014                this->dim = g->dimension();
1015                this->dimc = g->dimensionc();
1016                this->iepdf.validate();
1017        }
1018
1019};
1020
1021UIREGISTER2 ( mgnorm, chmat );
1022UIREGISTER2 ( mgnorm, ldmat );
1023SHAREDPTR2 ( mgnorm, chmat );
1024
1025
1026/*! (Approximate) Student t density with linear function of mean value
1027
1028The internal epdf of this class is of the type of a Gaussian (enorm).
1029However, each conditioning is trying to assure the best possible approximation by taking into account the zeta function. See [] for reference.
1030
1031Perhaps a moment-matching technique?
1032*/
1033class mlstudent : public mlnorm<ldmat, enorm> {
1034protected:
1035        //! Variable \f$ \Lambda \f$ from theory
1036        ldmat Lambda;
1037        //! Reference to variable \f$ R \f$
1038        ldmat &_R;
1039        //! Variable \f$ R_e \f$
1040        ldmat Re;
1041public:
1042        mlstudent () : mlnorm<ldmat, enorm> (),
1043                        Lambda (),      _R ( iepdf._R() ) {}
1044        //! constructor function
1045        void set_parameters ( const mat &A0, const vec &mu0, const ldmat &R0, const ldmat& Lambda0 ) {
1046                iepdf.set_parameters ( mu0, R0 );// was Lambda, why?
1047                A = A0;
1048                mu_const = mu0;
1049                Re = R0;
1050                Lambda = Lambda0;
1051        }
1052
1053        void condition ( const vec &cond ); 
1054
1055        void validate() {
1056                mlnorm<ldmat, enorm>::validate();
1057                bdm_assert ( A.rows() == mu_const.length(), "mlstudent: A vs. mu mismatch" );
1058                bdm_assert ( _R.rows() == A.rows(), "mlstudent: A vs. R mismatch" );
1059
1060        }
1061};
1062
1063/*!
1064\brief  Gamma random walk
1065
1066Mean value, \f$\mu\f$, of this density is given by \c rvc .
1067Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
1068This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
1069
1070The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
1071*/
1072class mgamma : public pdf_internal<egamma> {
1073protected:
1074
1075        //! Constant \f$k\f$
1076        double k;
1077
1078        //! cache of iepdf.beta
1079        vec &_beta;
1080
1081public:
1082        //! Constructor
1083        mgamma() : pdf_internal<egamma>(), k ( 0 ),
1084                        _beta ( iepdf._beta() ) {
1085        }
1086
1087        //! Set value of \c k
1088        void set_parameters ( double k, const vec &beta0 );
1089
1090        void condition ( const vec &val ) {
1091                _beta = k / val;
1092        };
1093        /*! Create Gamma density with conditional mean value
1094        \f[ f(rv|rvc) = \Gamma(k, k/rvc) \f]
1095        from structure
1096        \code
1097          class = 'mgamma';
1098          beta = [...];          // vector of initial alpha
1099          k = 1.1;               // multiplicative constant k
1100          rv = RV({'name'})      // description of RV
1101          rvc = RV({'name'})     // description of RV in condition
1102         \endcode
1103        */
1104        void from_setting ( const Setting &set );
1105        void    to_setting  (Setting  &set) const;
1106        void validate();
1107};
1108UIREGISTER ( mgamma );
1109SHAREDPTR ( mgamma );
1110
1111/*!
1112\brief  Inverse-Gamma random walk
1113
1114Mean value, \f$ \mu \f$, of this density is given by \c rvc .
1115Standard deviation of the random walk is proportional to one \f$ k \f$-th the mean.
1116This is achieved by setting \f$ \alpha=\mu/k^2+2 \f$ and \f$ \beta=\mu(\alpha-1)\f$.
1117
1118The standard deviation of the walk is then: \f$ \mu/\sqrt(k)\f$.
1119 */
1120class migamma : public pdf_internal<eigamma> {
1121protected:
1122        //! Constant \f$k\f$
1123        double k;
1124
1125        //! cache of iepdf.alpha
1126        vec &_alpha;
1127
1128        //! cache of iepdf.beta
1129        vec &_beta;
1130
1131public:
1132        //! \name Constructors
1133        //!@{
1134        migamma() : pdf_internal<eigamma>(),
1135                        k ( 0 ),
1136                        _alpha ( iepdf._alpha() ),
1137                        _beta ( iepdf._beta() ) {
1138        }
1139
1140        migamma ( const migamma &m ) : pdf_internal<eigamma>(),
1141                        k ( 0 ),
1142                        _alpha ( iepdf._alpha() ),
1143                        _beta ( iepdf._beta() ) {
1144        }
1145        //!@}
1146
1147        //! Set value of \c k
1148        void set_parameters ( int len, double k0 ) {
1149                k = k0;
1150                iepdf.set_parameters ( ( 1.0 / ( k*k ) + 2.0 ) *ones ( len ) /*alpha*/, ones ( len ) /*beta*/ );               
1151        };
1152
1153        void    validate (){
1154                pdf_internal<eigamma>::validate();
1155                dimc = dimension();
1156};
1157
1158        void condition ( const vec &val ) {
1159                _beta = elem_mult ( val, ( _alpha - 1.0 ) );
1160        };
1161};
1162
1163
1164/*!
1165\brief  Gamma random walk around a fixed point
1166
1167Mean 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
1168\f[ \mu = \mu_{t-1} ^{l} p^{1-l}\f]
1169
1170Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
1171This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
1172
1173The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
1174*/
1175class mgamma_fix : public mgamma {
1176protected:
1177        //! parameter l
1178        double l;
1179        //! reference vector
1180        vec refl;
1181public:
1182        //! Constructor
1183        mgamma_fix () : mgamma (), refl () {};
1184        //! Set value of \c k
1185        void set_parameters ( double k0 , vec ref0, double l0 ) {
1186                mgamma::set_parameters ( k0, ref0 );
1187                refl = pow ( ref0, 1.0 - l0 );
1188                l = l0; 
1189        };
1190
1191        void    validate (){
1192                mgamma::validate();
1193                dimc = dimension();
1194        };
1195
1196        void condition ( const vec &val ) {
1197                vec mean = elem_mult ( refl, pow ( val, l ) );
1198                _beta = k / mean;
1199        };
1200};
1201
1202
1203/*!
1204\brief  Inverse-Gamma random walk around a fixed point
1205
1206Mean 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
1207\f[ \mu = \mu_{t-1} ^{l} p^{1-l}\f]
1208
1209==== Check == vv =
1210Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
1211This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
1212
1213The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
1214 */
1215class migamma_ref : public migamma {
1216protected:
1217        //! parameter l
1218        double l;
1219        //! reference vector
1220        vec refl;
1221public:
1222        //! Constructor
1223        migamma_ref () : migamma (), refl () {};
1224       
1225        //! Set value of \c k
1226        void set_parameters ( double k0 , vec ref0, double l0 ) {
1227                migamma::set_parameters ( ref0.length(), k0 );
1228                refl = pow ( ref0, 1.0 - l0 );
1229                l = l0;
1230        };
1231
1232        void validate(){
1233                migamma::validate();
1234                dimc = dimension();
1235        };
1236       
1237        void condition ( const vec &val ) {
1238                vec mean = elem_mult ( refl, pow ( val, l ) );
1239                migamma::condition ( mean );
1240        };
1241
1242
1243        /*! Create inverse-Gamma density with conditional mean value
1244        \f[ f(rv|rvc) = i\Gamma(k, k/(rvc^l \circ ref^{(1-l)}) \f]
1245        from structure
1246        \code
1247        class = 'migamma_ref';
1248        ref = [1e-5; 1e-5; 1e-2 1e-3];            // reference vector
1249        l = 0.999;                                // constant l
1250        k = 0.1;                                  // constant k
1251        rv = RV({'name'})                         // description of RV
1252        rvc = RV({'name'})                        // description of RV in condition
1253        \endcode
1254         */
1255        void from_setting ( const Setting &set );
1256
1257        void to_setting  (Setting  &set) const; 
1258};
1259
1260
1261UIREGISTER ( migamma_ref );
1262SHAREDPTR ( migamma_ref );
1263
1264/*! Log-Normal probability density
1265 only allow diagonal covariances!
1266
1267Density of the form \f$ \log(x)\sim \mathcal{N}(\mu,\sigma^2) \f$ , i.e.
1268\f[
1269x \sim \frac{1}{x\sigma\sqrt{2\pi}}\exp{-\frac{1}{2\sigma^2}(\log(x)-\mu)}
1270\f]
1271
1272Function from_setting loads mu and R in the same way as it does for enorm<>!
1273*/
1274class elognorm: public enorm<ldmat> {
1275public:
1276        vec sample() const {
1277                return exp ( enorm<ldmat>::sample() );
1278        };
1279        vec mean() const {
1280                vec var = enorm<ldmat>::variance();
1281                return exp ( mu - 0.5*var );
1282        };
1283
1284};
1285
1286/*!
1287\brief  Log-Normal random walk
1288
1289Mean value, \f$\mu\f$, is...
1290
1291 */
1292class mlognorm : public pdf_internal<elognorm> {
1293protected:
1294        //! parameter 1/2*sigma^2
1295        double sig2;
1296
1297        //! access
1298        vec &mu;
1299public:
1300        //! Constructor
1301        mlognorm() : pdf_internal<elognorm>(),
1302                        sig2 ( 0 ),
1303                        mu ( iepdf._mu() ) {
1304        }
1305
1306        //! Set value of \c k
1307        void set_parameters ( int size, double k ) {
1308                sig2 = 0.5 * log ( k * k + 1 );
1309                iepdf.set_parameters ( zeros ( size ), 2*sig2*eye ( size ) );
1310        };
1311       
1312        void validate(){
1313                pdf_internal<elognorm>::validate();
1314                dimc = iepdf.dimension();
1315        }
1316
1317        void condition ( const vec &val ) {
1318                mu = log ( val ) - sig2;//elem_mult ( refl,pow ( val,l ) );
1319        };
1320
1321        /*! Create logNormal random Walk
1322        \f[ f(rv|rvc) = log\mathcal{N}( \log(rvc)-0.5\log(k^2+1), k I) \f]
1323        from structure
1324        \code
1325        class = 'mlognorm';
1326        k   = 0.1;               // "variance" k
1327        mu0 = 0.1;               // Initial value of mean
1328        rv  = RV({'name'})       // description of RV
1329        rvc = RV({'name'})       // description of RV in condition
1330        \endcode
1331        */
1332        void from_setting ( const Setting &set );
1333       
1334        void to_setting  (Setting  &set) const; 
1335};
1336
1337UIREGISTER ( mlognorm );
1338SHAREDPTR ( mlognorm );
1339
1340/*! inverse Wishart density defined on Choleski decomposition
1341
1342*/
1343class eWishartCh : public epdf {
1344protected:
1345        //! Upper-Triagle of Choleski decomposition of \f$ \Psi \f$
1346        chmat Y;
1347        //! dimension of matrix  \f$ \Psi \f$
1348        int p;
1349        //! degrees of freedom  \f$ \nu \f$
1350        double delta;
1351public:
1352        //! Set internal structures
1353        void set_parameters ( const mat &Y0, const double delta0 ) {
1354                Y = chmat ( Y0 );
1355                delta = delta0;
1356                p = Y.rows();   
1357        }
1358        //! Set internal structures
1359        void set_parameters ( const chmat &Y0, const double delta0 ) {
1360                Y = Y0;
1361                delta = delta0;
1362                p = Y.rows();
1363                }
1364       
1365        virtual void validate (){
1366                epdf::validate();
1367                dim = p * p;
1368        }
1369
1370        //! Sample matrix argument
1371        mat sample_mat() const {
1372                mat X = zeros ( p, p );
1373
1374                //sample diagonal
1375                for ( int i = 0; i < p; i++ ) {
1376                        GamRNG.setup ( 0.5* ( delta - i ) , 0.5 );   // no +1 !! index if from 0
1377#pragma omp critical
1378                        X ( i, i ) = sqrt ( GamRNG() );
1379                }
1380                //do the rest
1381                for ( int i = 0; i < p; i++ ) {
1382                        for ( int j = i + 1; j < p; j++ ) {
1383#pragma omp critical
1384                                X ( i, j ) = NorRNG.sample();
1385                        }
1386                }
1387                return X*Y._Ch();// return upper triangular part of the decomposition
1388        }
1389
1390        vec sample () const {
1391                return vec ( sample_mat()._data(), p*p );
1392        }
1393
1394        virtual vec mean() const NOT_IMPLEMENTED(0);
1395
1396        //! return expected variance (not covariance!)
1397        virtual vec variance() const NOT_IMPLEMENTED(0);
1398
1399        virtual double evallog ( const vec &val ) const NOT_IMPLEMENTED(0);
1400
1401        //! fast access function y0 will be copied into Y.Ch.
1402        void setY ( const mat &Ch0 ) {
1403                copy_vector ( dim, Ch0._data(), Y._Ch()._data() );
1404        }
1405
1406        //! fast access function y0 will be copied into Y.Ch.
1407        void _setY ( const vec &ch0 ) {
1408                copy_vector ( dim, ch0._data(), Y._Ch()._data() );
1409        }
1410
1411        //! access function
1412        const chmat& getY() const {
1413                return Y;
1414        }
1415};
1416
1417//! Inverse Wishart on Choleski decomposition
1418/*! Being computed by conversion from `standard' Wishart
1419*/
1420class eiWishartCh: public epdf {
1421protected:
1422        //! Internal instance of Wishart density
1423        eWishartCh W;
1424        //! size of Ch
1425        int p;
1426        //! parameter delta
1427        double delta;
1428public:
1429        //! constructor function
1430        void set_parameters ( const mat &Y0, const double delta0 ) {
1431                delta = delta0;
1432                W.set_parameters ( inv ( Y0 ), delta0 );
1433                p = Y0.rows();
1434        }
1435       
1436        virtual void    validate (){
1437                epdf::validate();
1438                W.validate();
1439                dim = W.dimension();
1440        }
1441       
1442       
1443        vec sample() const {
1444                mat iCh;
1445                iCh = inv ( W.sample_mat() );
1446                return vec ( iCh._data(), dim );
1447        }
1448        //! access function
1449        void _setY ( const vec &y0 ) {
1450                mat Ch ( p, p );
1451                mat iCh ( p, p );
1452                copy_vector ( dim, y0._data(), Ch._data() );
1453
1454                iCh = inv ( Ch );
1455                W.setY ( iCh );
1456        }
1457
1458        virtual double evallog ( const vec &val ) const {
1459                chmat X ( p );
1460                const chmat& Y = W.getY();
1461
1462                copy_vector ( p*p, val._data(), X._Ch()._data() );
1463                chmat iX ( p );
1464                X.inv ( iX );
1465                // compute
1466//                              \frac{ |\Psi|^{m/2}|X|^{-(m+p+1)/2}e^{-tr(\Psi X^{-1})/2} }{ 2^{mp/2}\Gamma_p(m/2)},
1467                mat M = Y.to_mat() * iX.to_mat();
1468
1469                double log1 = 0.5 * p * ( 2 * Y.logdet() ) - 0.5 * ( delta + p + 1 ) * ( 2 * X.logdet() ) - 0.5 * trace ( M );
1470                //Fixme! Multivariate gamma omitted!! it is ok for sampling, but not otherwise!!
1471
1472                /*                              if (0) {
1473                                                        mat XX=X.to_mat();
1474                                                        mat YY=Y.to_mat();
1475
1476                                                        double log2 = 0.5*p*log(det(YY))-0.5*(delta+p+1)*log(det(XX))-0.5*trace(YY*inv(XX));
1477                                                        cout << log1 << "," << log2 << endl;
1478                                                }*/
1479                return log1;
1480        };
1481
1482        virtual vec mean() const NOT_IMPLEMENTED(0);
1483
1484        //! return expected variance (not covariance!)
1485        virtual vec variance() const NOT_IMPLEMENTED(0);
1486};
1487
1488//! Random Walk on inverse Wishart
1489class rwiWishartCh : public pdf_internal<eiWishartCh> {
1490protected:
1491        //!square root of \f$ \nu-p-1 \f$ - needed for computation of \f$ \Psi \f$ from conditions
1492        double sqd;
1493        //!reference point for diagonal
1494        vec refl;
1495        //! power of the reference
1496        double l;
1497        //! dimension
1498        int p;
1499
1500public:
1501        rwiWishartCh() : sqd ( 0 ), l ( 0 ), p ( 0 ) {}
1502        //! constructor function
1503        void set_parameters ( int p0, double k, vec ref0, double l0 ) {
1504                p = p0;
1505                double delta = 2 / ( k * k ) + p + 3;
1506                sqd = sqrt ( delta - p - 1 );
1507                l = l0;
1508                refl = pow ( ref0, 1 - l );
1509                iepdf.set_parameters ( eye ( p ), delta );
1510        };
1511       
1512        void validate(){
1513                pdf_internal<eiWishartCh>::validate();
1514                dimc = iepdf.dimension();
1515        }
1516       
1517        void condition ( const vec &c ) {
1518                vec z = c;
1519                int ri = 0;
1520                for ( int i = 0; i < p*p; i += ( p + 1 ) ) {//trace diagonal element
1521                        z ( i ) = pow ( z ( i ), l ) * refl ( ri );
1522                        ri++;
1523                }
1524
1525                iepdf._setY ( sqd*z );
1526        }
1527};
1528
1529//! Switch between various resampling methods.
1530enum RESAMPLING_METHOD { MULTINOMIAL = 0, STRATIFIED = 1, SYSTEMATIC = 3 };
1531
1532//! Shortcut for multinomial.sample(int n). Various simplifications are allowed see RESAMPLING_METHOD
1533void resample(const vec &w, ivec &ind, RESAMPLING_METHOD=SYSTEMATIC);
1534
1535/*!
1536\brief Weighted empirical density
1537
1538Used e.g. in particle filters.
1539*/
1540class eEmp: public epdf {
1541protected :
1542        //! Number of particles
1543        int n;
1544        //! Sample weights \f$w\f$
1545        vec w;
1546        //! Samples \f$x^{(i)}, i=1..n\f$
1547        Array<vec> samples;
1548public:
1549        //! \name Constructors
1550        //!@{
1551        eEmp () : epdf (), w (), samples () {};
1552        //! copy constructor
1553        eEmp ( const eEmp &e ) : epdf ( e ), w ( e.w ), samples ( e.samples ) {};
1554        //!@}
1555
1556        //! Set samples and weights
1557        void set_statistics ( const vec &w0, const epdf &pdf0 );
1558        //! Set samples and weights
1559        void set_statistics ( const epdf &pdf0 , int n ) {
1560                set_statistics ( ones ( n ) / n, pdf0 );
1561        };
1562        //! Set sample
1563        void set_samples ( const epdf* pdf0 );
1564        //! Set sample
1565        void set_parameters ( int n0, bool copy = true ) {
1566                n = n0;
1567                w.set_size ( n0, copy );
1568                samples.set_size ( n0, copy );
1569        };
1570        //! Set samples
1571        void set_parameters ( const Array<vec> &Av ) {
1572                n = Av.size();
1573                w = 1 / n * ones ( n );
1574                samples = Av;
1575        };
1576        virtual void    validate ();
1577        //! Potentially dangerous, use with care.
1578        vec& _w()  {
1579                return w;
1580        };
1581        //! Potentially dangerous, use with care.
1582        const vec& _w() const {
1583                return w;
1584        };
1585        //! access function
1586        Array<vec>& _samples() {
1587                return samples;
1588        };
1589        //! access function
1590        const vec& _sample ( int i ) const {
1591                return samples ( i );
1592        };
1593        //! access function
1594        const Array<vec>& _samples() const {
1595                return samples;
1596        };
1597        //! 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.
1598        void resample ( RESAMPLING_METHOD method = SYSTEMATIC );
1599
1600        //! inherited operation : NOT implemented
1601        vec sample() const NOT_IMPLEMENTED(0);
1602
1603        //! inherited operation : NOT implemented
1604        double evallog ( const vec &val ) const NOT_IMPLEMENTED(0);
1605
1606        vec mean() const {
1607                vec pom = zeros ( dim );
1608                for ( int i = 0; i < n; i++ ) {
1609                        pom += samples ( i ) * w ( i );
1610                }
1611                return pom;
1612        }
1613        vec variance() const {
1614                vec pom = zeros ( dim );
1615                for ( int i = 0; i < n; i++ ) {
1616                        pom += pow ( samples ( i ), 2 ) * w ( i );
1617                }
1618                return pom - pow ( mean(), 2 );
1619        }
1620        //! For this class, qbounds are minimum and maximum value of the population!
1621        void qbounds ( vec &lb, vec &ub, double perc = 0.95 ) const;
1622
1623        void to_setting ( Setting &set ) const;
1624        void from_setting ( const Setting &set );
1625
1626};
1627UIREGISTER(eEmp);
1628
1629
1630////////////////////////
1631
1632template<class sq_T>
1633void enorm<sq_T>::set_parameters ( const vec &mu0, const sq_T &R0 ) {
1634//Fixme test dimensions of mu0 and R0;
1635        mu = mu0;
1636        R = R0;
1637        validate();
1638};
1639
1640template<class sq_T>
1641void enorm<sq_T>::from_setting ( const Setting &set ) {
1642        epdf::from_setting ( set ); //reads rv
1643
1644        UI::get ( mu, set, "mu", UI::compulsory );
1645        mat Rtmp;// necessary for conversion
1646        UI::get ( Rtmp, set, "R", UI::compulsory );
1647        R = Rtmp; // conversion
1648}
1649
1650template<class sq_T>
1651void enorm<sq_T>::validate() {
1652                eEF::validate();
1653                bdm_assert ( mu.length() == R.rows(), "mu and R parameters do not match" );
1654                dim = mu.length();
1655        }
1656
1657template<class sq_T>
1658void enorm<sq_T>::to_setting ( Setting &set ) const {
1659        epdf::to_setting ( set ); //reads rv   
1660        UI::save ( mu, set, "mu");
1661        UI::save ( R.to_mat(), set, "R");
1662}
1663
1664
1665
1666template<class sq_T>
1667void enorm<sq_T>::dupdate ( mat &v, double nu ) {
1668        //
1669};
1670
1671// template<class sq_T>
1672// void enorm<sq_T>::tupdate ( double phi, mat &vbar, double nubar ) {
1673//      //
1674// };
1675
1676template<class sq_T>
1677vec enorm<sq_T>::sample() const {
1678        vec x ( dim );
1679#pragma omp critical
1680        NorRNG.sample_vector ( dim, x );
1681        vec smp = R.sqrt_mult ( x );
1682
1683        smp += mu;
1684        return smp;
1685};
1686
1687// template<class sq_T>
1688// double enorm<sq_T>::eval ( const vec &val ) const {
1689//      double pdfl,e;
1690//      pdfl = evallog ( val );
1691//      e = exp ( pdfl );
1692//      return e;
1693// };
1694
1695template<class sq_T>
1696double enorm<sq_T>::evallog_nn ( const vec &val ) const {
1697        // 1.83787706640935 = log(2pi)
1698        double tmp = -0.5 * ( R.invqform ( mu - val ) );// - lognc();
1699        return  tmp;
1700};
1701
1702template<class sq_T>
1703inline double enorm<sq_T>::lognc () const {
1704        // 1.83787706640935 = log(2pi)
1705        double tmp = 0.5 * ( R.cols() * 1.83787706640935 + R.logdet() );
1706        return tmp;
1707};
1708
1709
1710// template<class sq_T>
1711// vec mlnorm<sq_T>::samplecond (const  vec &cond, double &lik ) {
1712//      this->condition ( cond );
1713//      vec smp = epdf.sample();
1714//      lik = epdf.eval ( smp );
1715//      return smp;
1716// }
1717
1718// template<class sq_T>
1719// mat mlnorm<sq_T>::samplecond (const vec &cond, vec &lik, int n ) {
1720//      int i;
1721//      int dim = rv.count();
1722//      mat Smp ( dim,n );
1723//      vec smp ( dim );
1724//      this->condition ( cond );
1725//
1726//      for ( i=0; i<n; i++ ) {
1727//              smp = epdf.sample();
1728//              lik ( i ) = epdf.eval ( smp );
1729//              Smp.set_col ( i ,smp );
1730//      }
1731//
1732//      return Smp;
1733// }
1734
1735
1736template<class sq_T>
1737shared_ptr<epdf> enorm<sq_T>::marginal ( const RV &rvn ) const {
1738        enorm<sq_T> *tmp = new enorm<sq_T> ();
1739        shared_ptr<epdf> narrow ( tmp );
1740        marginal ( rvn, *tmp );
1741        return narrow;
1742}
1743
1744template<class sq_T>
1745void enorm<sq_T>::marginal ( const RV &rvn, enorm<sq_T> &target ) const {
1746        bdm_assert ( isnamed(), "rv description is not assigned" );
1747        ivec irvn = rvn.dataind ( rv );
1748
1749        sq_T Rn ( R, irvn );  // select rows and columns of R
1750
1751        target.set_rv ( rvn );
1752        target.set_parameters ( mu ( irvn ), Rn );
1753}
1754
1755template<class sq_T>
1756shared_ptr<pdf> enorm<sq_T>::condition ( const RV &rvn ) const {
1757        mlnorm<sq_T> *tmp = new mlnorm<sq_T> ();
1758        shared_ptr<pdf> narrow ( tmp );
1759        condition ( rvn, *tmp );
1760        return narrow;
1761}
1762
1763template<class sq_T>
1764void enorm<sq_T>::condition ( const RV &rvn, pdf &target ) const {
1765        typedef mlnorm<sq_T> TMlnorm;
1766
1767        bdm_assert ( isnamed(), "rvs are not assigned" );
1768        TMlnorm &uptarget = dynamic_cast<TMlnorm &> ( target );
1769
1770        RV rvc = rv.subt ( rvn );
1771        bdm_assert ( ( rvc._dsize() + rvn._dsize() == rv._dsize() ), "wrong rvn" );
1772        //Permutation vector of the new R
1773        ivec irvn = rvn.dataind ( rv );
1774        ivec irvc = rvc.dataind ( rv );
1775        ivec perm = concat ( irvn , irvc );
1776        sq_T Rn ( R, perm );
1777
1778        //fixme - could this be done in general for all sq_T?
1779        mat S = Rn.to_mat();
1780        //fixme
1781        int n = rvn._dsize() - 1;
1782        int end = R.rows() - 1;
1783        mat S11 = S.get ( 0, n, 0, n );
1784        mat S12 = S.get ( 0, n , rvn._dsize(), end );
1785        mat S22 = S.get ( rvn._dsize(), end, rvn._dsize(), end );
1786
1787        vec mu1 = mu ( irvn );
1788        vec mu2 = mu ( irvc );
1789        mat A = S12 * inv ( S22 );
1790        sq_T R_n ( S11 - A *S12.T() );
1791
1792        uptarget.set_rv ( rvn );
1793        uptarget.set_rvc ( rvc );
1794        uptarget.set_parameters ( A, mu1 - A*mu2, R_n );
1795        uptarget.validate();
1796}
1797
1798/*! Dirac delta function distribution */
1799class dirac: public epdf{
1800        public: 
1801                vec point;
1802        public:
1803                double evallog (const vec &dt) const {return -inf;}
1804                vec mean () const {return point;}
1805                vec variance () const {return zeros(point.length());}
1806                void qbounds ( vec &lb, vec &ub, double percentage = 0.95 ) const { lb = point; ub = point;}
1807                //! access
1808                const vec& _point() {return point;}
1809                void set_point(const vec& p){point =p; dim=p.length();}
1810                vec sample() const {return point;}
1811        };
1812
1813////
1814///////
1815template<class sq_T>
1816void mgnorm<sq_T >::set_parameters ( const shared_ptr<fnc> &g0, const sq_T &R0 ) {
1817        g = g0;
1818        this->iepdf.set_parameters ( zeros ( g->dimension() ), R0 );
1819}
1820
1821template<class sq_T>
1822void mgnorm<sq_T >::condition ( const vec &cond ) {
1823        this->iepdf._mu() = g->eval ( cond );
1824};
1825
1826//! \todo unify this stuff with to_string()
1827template<class sq_T>
1828std::ostream &operator<< ( std::ostream &os,  mlnorm<sq_T> &ml ) {
1829        os << "A:" << ml.A << endl;
1830        os << "mu:" << ml.mu_const << endl;
1831        os << "R:" << ml._R() << endl;
1832        return os;
1833};
1834
1835}
1836#endif //EF_H
Note: See TracBrowser for help on using the browser.