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

Revision 956, 44.3 kB (checked in by sarka, 14 years ago)

to_setting

  • 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 {return delta/(delta-2)*H.to_mat();}
299                vec variance() const {return diag(covariance());}
300                        //! \name access
301                //! @{
302                        //! access function
303                        vec& _mu() {return mu;}
304                        //! access function
305                        sq_T& _H() {return H;}
306                        //! access function
307                        double& _delta() {return delta;}
308                        //!@}
309                        //! todo
310                        void from_setting(const Setting &set){
311                                epdf::from_setting(set);
312                                mat H0;
313                                UI::get(H0,set, "H");
314                                H= H0; // conversion!!
315                                UI::get(delta,set,"delta");
316                                UI::get(mu,set,"mu");
317                        }
318                        void to_setting(Setting &set) const{
319                                epdf::to_setting(set);
320                                UI::save(H.to_mat(), set, "H");
321                                UI::save(delta, set, "delta");
322                                UI::save(mu, set, "mu");
323                        }
324                        void validate() {
325                                eEF::validate();
326                                dim = H.rows();
327                        }
328};
329UIREGISTER2(estudent,fsqmat);
330UIREGISTER2(estudent,ldmat);
331UIREGISTER2(estudent,chmat);
332
333/*!
334* \brief Gauss-inverse-Wishart density stored in LD form
335
336* For \f$p\f$-variate densities, given rv.count() should be \f$p\times\f$ V.rows().
337*
338*/
339class egiw : public eEF {
340        //! \var log_level_enums logvariance
341        //! TODO DOPLNIT
342
343        //! \var log_level_enums logmean
344        //! TODO DOPLNIT
345        LOG_LEVEL(egiw,logmean, logvariance);
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        void to_setting ( Setting& set ) const;
452        void validate();
453        void log_register ( bdm::logger& L, const string& prefix );
454
455        void log_write() const;
456        //!@}
457};
458UIREGISTER ( egiw );
459SHAREDPTR ( egiw );
460
461/*! \brief Dirichlet posterior density
462
463Continuous Dirichlet density of \f$n\f$-dimensional variable \f$x\f$
464\f[
465f(x|\beta) = \frac{\Gamma[\gamma]}{\prod_{i=1}^{n}\Gamma(\beta_i)} \prod_{i=1}^{n}x_i^{\beta_i-1}
466\f]
467where \f$\gamma=\sum_i \beta_i\f$.
468*/
469class eDirich: public eEF {
470protected:
471        //!sufficient statistics
472        vec beta;
473public:
474        //!\name Constructors
475        //!@{
476
477        eDirich () : eEF () {};
478        eDirich ( const eDirich &D0 ) : eEF () {
479                set_parameters ( D0.beta );
480                validate();
481        };
482        eDirich ( const vec &beta0 ) {
483                set_parameters ( beta0 );
484                validate();
485        };
486        void set_parameters ( const vec &beta0 ) {
487                beta = beta0;
488                dim = beta.length();
489        }
490        //!@}
491
492        //! using sampling procedure from wikipedia
493        vec sample() const {
494                vec y ( beta.length() );
495                for ( int i = 0; i < beta.length(); i++ ) {
496                        GamRNG.setup ( beta ( i ), 1 );
497#pragma omp critical
498                        y ( i ) = GamRNG();
499                }
500                return y / sum ( y );
501        }
502
503        vec mean() const {
504                return beta / sum ( beta );
505        };
506        vec variance() const {
507                double gamma = sum ( beta );
508                return elem_mult ( beta, ( gamma - beta ) ) / ( gamma*gamma* ( gamma + 1 ) );
509        }
510        //! In this instance, val is ...
511        double evallog_nn ( const vec &val ) const {
512                double tmp;
513                tmp = ( beta - 1 ) * log ( val );
514                return tmp;
515        }
516
517        double lognc () const {
518                double tmp;
519                double gam = sum ( beta );
520                double lgb = 0.0;
521                for ( int i = 0; i < beta.length(); i++ ) {
522                        lgb += lgamma ( beta ( i ) );
523                }
524                tmp = lgb - lgamma ( gam );
525                return tmp;
526        }
527
528        //!access function
529        vec& _beta()  {
530                return beta;
531        }
532        /*! configuration structure
533        \code
534        class = 'eDirich';
535        beta  = [];           //parametr beta
536        \endcode
537        */
538        void from_setting ( const Setting &set );
539        void validate();
540        void to_setting ( Setting &set ) const;
541};
542UIREGISTER ( eDirich );
543
544/*! Random Walk on Dirichlet
545Using simple assignment
546 \f[ \beta = rvc / k + \beta_c \f]
547 hence, mean value = rvc, variance = (k+1)*mean*mean;
548
549 The greater k is, the greater is the variance of the random walk;
550
551 \f$ \beta_c \f$ is used as regularizing element to avoid corner cases, i.e. when one element of rvc is zero.
552 By default is it set to 0.1;
553*/
554
555class mDirich: public pdf_internal<eDirich> {
556protected:
557        //! constant \f$ k \f$ of the random walk
558        double k;
559        //! cache of beta_i
560        vec &_beta;
561        //! stabilizing coefficient \f$ \beta_c \f$
562        vec betac;
563public:
564        mDirich() : pdf_internal<eDirich>(), _beta ( iepdf._beta() ) {};
565        void condition ( const vec &val ) {
566                _beta =  val / k + betac;
567        };
568        /*! Create Dirichlet random walk
569        \f[ f(rv|rvc) = Di(rvc*k) \f]
570        from structure
571        \code
572        class = 'mDirich';
573        k = 1;                      // multiplicative constant k
574        --- optional ---
575        rv = RV({'name'},size)      // description of RV
576        beta0 = [];                 // initial value of beta
577        betac = [];                 // initial value of beta
578        \endcode
579        */
580        void from_setting ( const Setting &set );
581        void    to_setting  (Setting  &set) const;
582        void validate();
583};
584UIREGISTER ( mDirich );
585
586//! \brief Estimator for Multinomial density
587class multiBM : public BMEF {
588protected:
589        //! Conjugate prior and posterior
590        eDirich est;
591        //! Pointer inside est to sufficient statistics
592        vec &beta;
593public:
594        //!Default constructor
595        multiBM () : BMEF (), est (), beta ( est._beta() ) {
596                if ( beta.length() > 0 ) {
597                        last_lognc = est.lognc();
598                } else {
599                        last_lognc = 0.0;
600                }
601        }
602        //!Copy constructor
603        multiBM ( const multiBM &B ) : BMEF ( B ), est ( B.est ), beta ( est._beta() ) {}
604        //! Sets sufficient statistics to match that of givefrom mB0
605        void set_statistics ( const BM* mB0 ) {
606                const multiBM* mB = dynamic_cast<const multiBM*> ( mB0 );
607                beta = mB->beta;
608        }
609        void bayes ( const vec &yt, const vec &cond = empty_vec );
610
611        double logpred ( const vec &yt ) const;
612
613        void flatten ( const BMEF* B );
614
615        //! return correctly typed posterior (covariant return)
616        const eDirich& posterior() const {
617                return est;
618        };
619        //! constructor function
620        void set_parameters ( const vec &beta0 ) {
621                est.set_parameters ( beta0 );
622                est.validate();
623                if ( evalll ) {
624                        last_lognc = est.lognc();
625                }
626        }
627
628        void to_setting ( Setting &set ) const {
629                BMEF::to_setting ( set );
630                UI::save( &est, set, "prior" );
631        }
632};
633UIREGISTER( multiBM );
634
635/*!
636 \brief Gamma posterior density
637
638 Multivariate Gamma density as product of independent univariate densities.
639 \f[
640 f(x|\alpha,\beta) = \prod f(x_i|\alpha_i,\beta_i)
641 \f]
642*/
643
644class egamma : public eEF {
645protected:
646        //! Vector \f$\alpha\f$
647        vec alpha;
648        //! Vector \f$\beta\f$
649        vec beta;
650public :
651        //! \name Constructors
652        //!@{
653        egamma () : eEF (), alpha ( 0 ), beta ( 0 ) {};
654        egamma ( const vec &a, const vec &b ) {
655                set_parameters ( a, b );
656                validate();
657        };
658        void set_parameters ( const vec &a, const vec &b ) {
659                alpha = a, beta = b;
660        };
661        //!@}
662
663        vec sample() const;
664        double evallog ( const vec &val ) const;
665        double lognc () const;
666        //! Returns pointer to internal alpha. Potentially dengerous: use with care!
667        vec& _alpha() {
668                return alpha;
669        }
670        //! Returns pointer to internal beta. Potentially dengerous: use with care!
671        vec& _beta() {
672                return beta;
673        }
674        vec mean() const {
675                return elem_div ( alpha, beta );
676        }
677        vec variance() const {
678                return elem_div ( alpha, elem_mult ( beta, beta ) );
679        }
680
681        /*! Create Gamma density
682        \f[ f(rv|rvc) = \Gamma(\alpha, \beta) \f]
683        from structure
684        \code
685        class = 'egamma';
686        alpha = [...];         // vector of alpha
687        beta = [...];          // vector of beta
688        rv = RV({'name'})      // description of RV
689        \endcode
690        */
691        void from_setting ( const Setting &set );
692        void to_setting ( Setting &set ) const;
693        void validate(); 
694};
695UIREGISTER ( egamma );
696SHAREDPTR ( egamma );
697
698/*!
699 \brief Inverse-Gamma posterior density
700
701 Multivariate inverse-Gamma density as product of independent univariate densities.
702 \f[
703 f(x|\alpha,\beta) = \prod f(x_i|\alpha_i,\beta_i)
704 \f]
705
706Vector \f$\beta\f$ has different meaning (in fact it is 1/beta as used in definition of iG)
707
708 Inverse Gamma can be converted to Gamma using \f[
709 x\sim iG(a,b) => 1/x\sim G(a,1/b)
710\f]
711This relation is used in sampling.
712 */
713
714class eigamma : public egamma {
715protected:
716public :
717        //! \name Constructors
718        //! All constructors are inherited
719        //!@{
720        //!@}
721
722        vec sample() const {
723                return 1.0 / egamma::sample();
724        };
725        //! Returns poiter to alpha and beta. Potentially dangerous: use with care!
726        vec mean() const {
727                return elem_div ( beta, alpha - 1 );
728        }
729        vec variance() const {
730                vec mea = mean();
731                return elem_div ( elem_mult ( mea, mea ), alpha - 2 );
732        }
733};
734/*
735//! Weighted mixture of epdfs with external owned components.
736class emix : public epdf {
737protected:
738        int n;
739        vec &w;
740        Array<epdf*> Coms;
741public:
742//! Default constructor
743        emix ( const RV &rv, vec &w0): epdf(rv), n(w0.length()), w(w0), Coms(n) {};
744        void set_parameters( int &i, double wi, epdf* ep){w(i)=wi;Coms(i)=ep;}
745        vec mean(){vec pom; for(int i=0;i<n;i++){pom+=Coms(i)->mean()*w(i);} return pom;};
746};
747*/
748
749//!  Uniform distributed density on a rectangular support
750
751class euni: public epdf {
752protected:
753//! lower bound on support
754        vec low;
755//! upper bound on support
756        vec high;
757//! internal
758        vec distance;
759//! normalizing coefficients
760        double nk;
761//! cache of log( \c nk )
762        double lnk;
763public:
764        //! \name Constructors
765        //!@{
766        euni () : epdf () {}
767        euni ( const vec &low0, const vec &high0 ) {
768                set_parameters ( low0, high0 );
769        }
770        void set_parameters ( const vec &low0, const vec &high0 ) {
771                distance = high0 - low0;
772                low = low0;
773                high = high0;
774                nk = prod ( 1.0 / distance );
775                lnk = log ( nk );
776        }
777        //!@}
778
779        double evallog ( const vec &val ) const  {
780                if ( any ( val < low ) && any ( val > high ) ) {
781                        return -inf;
782                } else return lnk;
783        }
784        vec sample() const {
785                vec smp ( dim );
786#pragma omp critical
787                UniRNG.sample_vector ( dim , smp );
788                return low + elem_mult ( distance, smp );
789        }
790        //! set values of \c low and \c high
791        vec mean() const {
792                return ( high - low ) / 2.0;
793        }
794        vec variance() const {
795                return ( pow ( high, 2 ) + pow ( low, 2 ) + elem_mult ( high, low ) ) / 3.0;
796        }
797        /*! Create Uniform density
798        \f[ f(rv) = U(low,high) \f]
799        from structure
800         \code
801         class = 'euni'
802         high = [...];          // vector of upper bounds
803         low = [...];           // vector of lower bounds
804         rv = RV({'name'});     // description of RV
805         \endcode
806         */
807        void from_setting ( const Setting &set );
808        void    to_setting  (Setting  &set) const;
809        void validate();
810};
811UIREGISTER ( euni );
812
813//! Uniform density with conditional mean value
814class mguni : public pdf_internal<euni> {
815        //! function of the mean value
816        shared_ptr<fnc> mean;
817        //! distance from mean to both sides
818        vec delta;
819public:
820        void condition ( const vec &cond ) {
821                vec mea = mean->eval ( cond );
822                iepdf.set_parameters ( mea - delta, mea + delta );
823        }
824        //! load from
825        void from_setting ( const Setting &set ) {
826                pdf::from_setting ( set ); //reads rv and rvc
827                UI::get ( delta, set, "delta", UI::compulsory );
828                mean = UI::build<fnc> ( set, "mean", UI::compulsory );
829                iepdf.set_parameters ( -delta, delta );
830        }
831        void    to_setting  (Setting  &set) const {
832                pdf::to_setting ( set ); 
833                UI::save( iepdf.mean(), set, "delta");
834                UI::save(mean, set, "mean");
835        }
836        void validate(){
837                pdf_internal<euni>::validate();
838                dimc = mean->dimensionc();
839               
840        }
841
842};
843UIREGISTER ( mguni );
844/*!
845 \brief Normal distributed linear function with linear function of mean value;
846
847 Mean value \f$ \mu=A*\mbox{rvc}+\mu_0 \f$.
848*/
849template < class sq_T, template <typename> class TEpdf = enorm >
850class mlnorm : public pdf_internal< TEpdf<sq_T> > {
851protected:
852        //! Internal epdf that arise by conditioning on \c rvc
853        mat A;
854        //! Constant additive term
855        vec mu_const;
856//                      vec& _mu; //cached epdf.mu; !!!!!! WHY NOT?
857public:
858        //! \name Constructors
859        //!@{
860        mlnorm() : pdf_internal< TEpdf<sq_T> >() {};
861        mlnorm ( const mat &A, const vec &mu0, const sq_T &R ) : pdf_internal< TEpdf<sq_T> >() {
862                set_parameters ( A, mu0, R );
863                validate();
864        }
865
866        //! Set \c A and \c R
867        void set_parameters ( const  mat &A0, const vec &mu0, const sq_T &R0 ) {
868                this->iepdf.set_parameters ( zeros ( A0.rows() ), R0 );
869                A = A0;
870                mu_const = mu0;
871        }
872
873        //!@}
874        //! Set value of \c rvc . Result of this operation is stored in \c epdf use function \c _ep to access it.
875        void condition ( const vec &cond ) {
876                this->iepdf._mu() = A * cond + mu_const;
877//R is already assigned;
878        }
879
880        //!access function
881        const vec& _mu_const() const {
882                return mu_const;
883        }
884        //!access function
885        const mat& _A() const {
886                return A;
887        }
888        //!access function
889        mat _R() const {
890                return this->iepdf._R().to_mat();
891        }
892        //!access function
893        sq_T __R() const {
894                return this->iepdf._R();
895        }
896
897        //! Debug stream
898        template<typename sq_M>
899        friend std::ostream &operator<< ( std::ostream &os,  mlnorm<sq_M, enorm> &ml );
900
901        /*! Create Normal density with linear function of mean value
902         \f[ f(rv|rvc) = N(A*rvc+const, R) \f]
903        from structure
904        \code
905        class = 'mlnorm<ldmat>', (OR) 'mlnorm<chmat>', (OR) 'mlnorm<fsqmat>';
906        A     = [];                  // matrix or vector of appropriate dimension
907        R     = [];                  // square matrix of appropriate dimension
908        --- optional ---
909        const = zeros(A.rows);       // vector of constant term
910        \endcode
911        */
912        void from_setting ( const Setting &set ) {
913                pdf::from_setting ( set );
914
915                UI::get ( A, set, "A", UI::compulsory );
916                UI::get ( mu_const, set, "const", UI::optional);
917                mat R0;
918                UI::get ( R0, set, "R", UI::compulsory );
919                set_parameters ( A, mu_const, R0 );
920        }
921
922void to_setting (Setting &set) const {
923                pdf::to_setting(set);
924                UI::save ( A, set, "A");
925                UI::save ( mu_const, set, "const");
926                UI::save ( _R(), set, "R");
927        }
928
929void validate() {
930                pdf_internal<TEpdf<sq_T> >::validate();
931                if (mu_const.length()==0) { // default in from_setting
932                        mu_const=zeros(A.rows());
933                }
934                bdm_assert ( A.rows() == mu_const.length(), "mlnorm: A vs. mu mismatch" );
935                bdm_assert ( A.rows() == _R().rows(), "mlnorm: A vs. R mismatch" );
936                this->dimc = A.cols();
937
938        }
939};
940UIREGISTER2 ( mlnorm, ldmat );
941SHAREDPTR2 ( mlnorm, ldmat );
942UIREGISTER2 ( mlnorm, fsqmat );
943SHAREDPTR2 ( mlnorm, fsqmat );
944UIREGISTER2 ( mlnorm, chmat );
945SHAREDPTR2 ( mlnorm, chmat );
946
947//! \class mlgauss
948//!\brief Normal distribution with linear function of mean value. Same as mlnorm<fsqmat>.
949typedef mlnorm<fsqmat> mlgauss;
950UIREGISTER(mlgauss);
951
952//! pdf with general function for mean value
953template<class sq_T>
954class mgnorm : public pdf_internal< enorm< sq_T > > {
955private:
956//                      vec &mu; WHY NOT?
957        shared_ptr<fnc> g;
958
959public:
960        //!default constructor
961        mgnorm() : pdf_internal<enorm<sq_T> >() { }
962        //!set mean function
963        inline void set_parameters ( const shared_ptr<fnc> &g0, const sq_T &R0 );
964        inline void condition ( const vec &cond );
965
966
967        /*! Create Normal density with given function of mean value
968        \f[ f(rv|rvc) = N( g(rvc), R) \f]
969        from structure
970        \code
971        class = 'mgnorm';
972        g.class =  'fnc';      // function for mean value evolution
973        g._fields_of_fnc = ...;
974
975        R = [1, 0;             // covariance matrix
976                0, 1];
977                --OR --
978        dR = [1, 1];           // diagonal of cavariance matrix
979
980        rv = RV({'name'})      // description of RV
981        rvc = RV({'name'})     // description of RV in condition
982        \endcode
983        */
984
985
986void from_setting ( const Setting &set ) {
987                pdf::from_setting ( set );
988                shared_ptr<fnc> g = UI::build<fnc> ( set, "g", UI::compulsory );
989
990                mat R;
991                vec dR;
992                if ( UI::get ( dR, set, "dR" ) )
993                        R = diag ( dR );
994                else
995                        UI::get ( R, set, "R", UI::compulsory );
996
997                set_parameters ( g, R );
998                //validate();
999        }
1000       
1001
1002void to_setting  (Setting  &set) const {
1003                UI::save( g,set, "g");
1004                UI::save(iepdf._R().to_mat(),set, "R");
1005       
1006        }
1007
1008
1009
1010void validate() {
1011                this->iepdf.validate();
1012                bdm_assert ( g->dimension() == this->iepdf.dimension(), "incompatible function" );
1013                this->dim = g->dimension();
1014                this->dimc = g->dimensionc();
1015                this->iepdf.validate();
1016        }
1017
1018};
1019
1020UIREGISTER2 ( mgnorm, chmat );
1021UIREGISTER2 ( mgnorm, ldmat );
1022SHAREDPTR2 ( mgnorm, chmat );
1023
1024
1025/*! (Approximate) Student t density with linear function of mean value
1026
1027The internal epdf of this class is of the type of a Gaussian (enorm).
1028However, each conditioning is trying to assure the best possible approximation by taking into account the zeta function. See [] for reference.
1029
1030Perhaps a moment-matching technique?
1031*/
1032class mlstudent : public mlnorm<ldmat, enorm> {
1033protected:
1034        //! Variable \f$ \Lambda \f$ from theory
1035        ldmat Lambda;
1036        //! Reference to variable \f$ R \f$
1037        ldmat &_R;
1038        //! Variable \f$ R_e \f$
1039        ldmat Re;
1040public:
1041        mlstudent () : mlnorm<ldmat, enorm> (),
1042                        Lambda (),      _R ( iepdf._R() ) {}
1043        //! constructor function
1044        void set_parameters ( const mat &A0, const vec &mu0, const ldmat &R0, const ldmat& Lambda0 ) {
1045                iepdf.set_parameters ( mu0, R0 );// was Lambda, why?
1046                A = A0;
1047                mu_const = mu0;
1048                Re = R0;
1049                Lambda = Lambda0;
1050        }
1051
1052        void condition ( const vec &cond ); 
1053
1054        void validate() {
1055                mlnorm<ldmat, enorm>::validate();
1056                bdm_assert ( A.rows() == mu_const.length(), "mlstudent: A vs. mu mismatch" );
1057                bdm_assert ( _R.rows() == A.rows(), "mlstudent: A vs. R mismatch" );
1058
1059        }
1060};
1061
1062/*!
1063\brief  Gamma random walk
1064
1065Mean value, \f$\mu\f$, of this density is given by \c rvc .
1066Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
1067This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
1068
1069The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
1070*/
1071class mgamma : public pdf_internal<egamma> {
1072protected:
1073
1074        //! Constant \f$k\f$
1075        double k;
1076
1077        //! cache of iepdf.beta
1078        vec &_beta;
1079
1080public:
1081        //! Constructor
1082        mgamma() : pdf_internal<egamma>(), k ( 0 ),
1083                        _beta ( iepdf._beta() ) {
1084        }
1085
1086        //! Set value of \c k
1087        void set_parameters ( double k, const vec &beta0 );
1088
1089        void condition ( const vec &val ) {
1090                _beta = k / val;
1091        };
1092        /*! Create Gamma density with conditional mean value
1093        \f[ f(rv|rvc) = \Gamma(k, k/rvc) \f]
1094        from structure
1095        \code
1096          class = 'mgamma';
1097          beta = [...];          // vector of initial alpha
1098          k = 1.1;               // multiplicative constant k
1099          rv = RV({'name'})      // description of RV
1100          rvc = RV({'name'})     // description of RV in condition
1101         \endcode
1102        */
1103        void from_setting ( const Setting &set );
1104        void    to_setting  (Setting  &set) const;
1105        void validate();
1106};
1107UIREGISTER ( mgamma );
1108SHAREDPTR ( mgamma );
1109
1110/*!
1111\brief  Inverse-Gamma random walk
1112
1113Mean value, \f$ \mu \f$, of this density is given by \c rvc .
1114Standard deviation of the random walk is proportional to one \f$ k \f$-th the mean.
1115This is achieved by setting \f$ \alpha=\mu/k^2+2 \f$ and \f$ \beta=\mu(\alpha-1)\f$.
1116
1117The standard deviation of the walk is then: \f$ \mu/\sqrt(k)\f$.
1118 */
1119class migamma : public pdf_internal<eigamma> {
1120protected:
1121        //! Constant \f$k\f$
1122        double k;
1123
1124        //! cache of iepdf.alpha
1125        vec &_alpha;
1126
1127        //! cache of iepdf.beta
1128        vec &_beta;
1129
1130public:
1131        //! \name Constructors
1132        //!@{
1133        migamma() : pdf_internal<eigamma>(),
1134                        k ( 0 ),
1135                        _alpha ( iepdf._alpha() ),
1136                        _beta ( iepdf._beta() ) {
1137        }
1138
1139        migamma ( const migamma &m ) : pdf_internal<eigamma>(),
1140                        k ( 0 ),
1141                        _alpha ( iepdf._alpha() ),
1142                        _beta ( iepdf._beta() ) {
1143        }
1144        //!@}
1145
1146        //! Set value of \c k
1147        void set_parameters ( int len, double k0 ) {
1148                k = k0;
1149                iepdf.set_parameters ( ( 1.0 / ( k*k ) + 2.0 ) *ones ( len ) /*alpha*/, ones ( len ) /*beta*/ );               
1150        };
1151
1152        void    validate (){
1153                pdf_internal<eigamma>::validate();
1154                dimc = dimension();
1155};
1156
1157        void condition ( const vec &val ) {
1158                _beta = elem_mult ( val, ( _alpha - 1.0 ) );
1159        };
1160};
1161
1162
1163/*!
1164\brief  Gamma random walk around a fixed point
1165
1166Mean 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
1167\f[ \mu = \mu_{t-1} ^{l} p^{1-l}\f]
1168
1169Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
1170This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
1171
1172The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
1173*/
1174class mgamma_fix : public mgamma {
1175protected:
1176        //! parameter l
1177        double l;
1178        //! reference vector
1179        vec refl;
1180public:
1181        //! Constructor
1182        mgamma_fix () : mgamma (), refl () {};
1183        //! Set value of \c k
1184        void set_parameters ( double k0 , vec ref0, double l0 ) {
1185                mgamma::set_parameters ( k0, ref0 );
1186                refl = pow ( ref0, 1.0 - l0 );
1187                l = l0; 
1188        };
1189
1190        void    validate (){
1191                mgamma::validate();
1192                dimc = dimension();
1193        };
1194
1195        void condition ( const vec &val ) {
1196                vec mean = elem_mult ( refl, pow ( val, l ) );
1197                _beta = k / mean;
1198        };
1199};
1200
1201
1202/*!
1203\brief  Inverse-Gamma random walk around a fixed point
1204
1205Mean 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
1206\f[ \mu = \mu_{t-1} ^{l} p^{1-l}\f]
1207
1208==== Check == vv =
1209Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
1210This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
1211
1212The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
1213 */
1214class migamma_ref : public migamma {
1215protected:
1216        //! parameter l
1217        double l;
1218        //! reference vector
1219        vec refl;
1220public:
1221        //! Constructor
1222        migamma_ref () : migamma (), refl () {};
1223       
1224        //! Set value of \c k
1225        void set_parameters ( double k0 , vec ref0, double l0 ) {
1226                migamma::set_parameters ( ref0.length(), k0 );
1227                refl = pow ( ref0, 1.0 - l0 );
1228                l = l0;
1229        };
1230
1231        void validate(){
1232                migamma::validate();
1233                dimc = dimension();
1234        };
1235       
1236        void condition ( const vec &val ) {
1237                vec mean = elem_mult ( refl, pow ( val, l ) );
1238                migamma::condition ( mean );
1239        };
1240
1241
1242        /*! Create inverse-Gamma density with conditional mean value
1243        \f[ f(rv|rvc) = i\Gamma(k, k/(rvc^l \circ ref^{(1-l)}) \f]
1244        from structure
1245        \code
1246        class = 'migamma_ref';
1247        ref = [1e-5; 1e-5; 1e-2 1e-3];            // reference vector
1248        l = 0.999;                                // constant l
1249        k = 0.1;                                  // constant k
1250        rv = RV({'name'})                         // description of RV
1251        rvc = RV({'name'})                        // description of RV in condition
1252        \endcode
1253         */
1254        void from_setting ( const Setting &set );
1255        void to_setting  (Setting  &set) const; 
1256        // TODO dodelat void to_setting( Setting &set ) const;
1257};
1258
1259
1260UIREGISTER ( migamma_ref );
1261SHAREDPTR ( migamma_ref );
1262
1263/*! Log-Normal probability density
1264 only allow diagonal covariances!
1265
1266Density of the form \f$ \log(x)\sim \mathcal{N}(\mu,\sigma^2) \f$ , i.e.
1267\f[
1268x \sim \frac{1}{x\sigma\sqrt{2\pi}}\exp{-\frac{1}{2\sigma^2}(\log(x)-\mu)}
1269\f]
1270
1271Function from_setting loads mu and R in the same way as it does for enorm<>!
1272*/
1273class elognorm: public enorm<ldmat> {
1274public:
1275        vec sample() const {
1276                return exp ( enorm<ldmat>::sample() );
1277        };
1278        vec mean() const {
1279                vec var = enorm<ldmat>::variance();
1280                return exp ( mu - 0.5*var );
1281        };
1282
1283};
1284
1285/*!
1286\brief  Log-Normal random walk
1287
1288Mean value, \f$\mu\f$, is...
1289
1290 */
1291class mlognorm : public pdf_internal<elognorm> {
1292protected:
1293        //! parameter 1/2*sigma^2
1294        double sig2;
1295
1296        //! access
1297        vec &mu;
1298public:
1299        //! Constructor
1300        mlognorm() : pdf_internal<elognorm>(),
1301                        sig2 ( 0 ),
1302                        mu ( iepdf._mu() ) {
1303        }
1304
1305        //! Set value of \c k
1306        void set_parameters ( int size, double k ) {
1307                sig2 = 0.5 * log ( k * k + 1 );
1308                iepdf.set_parameters ( zeros ( size ), 2*sig2*eye ( size ) );
1309        };
1310       
1311        void validate(){
1312                pdf_internal<elognorm>::validate();
1313                dimc = iepdf.dimension();
1314        }
1315
1316        void condition ( const vec &val ) {
1317                mu = log ( val ) - sig2;//elem_mult ( refl,pow ( val,l ) );
1318        };
1319
1320        /*! Create logNormal random Walk
1321        \f[ f(rv|rvc) = log\mathcal{N}( \log(rvc)-0.5\log(k^2+1), k I) \f]
1322        from structure
1323        \code
1324        class = 'mlognorm';
1325        k   = 0.1;               // "variance" k
1326        mu0 = 0.1;               // Initial value of mean
1327        rv  = RV({'name'})       // description of RV
1328        rvc = RV({'name'})       // description of RV in condition
1329        \endcode
1330        */
1331        void from_setting ( const Setting &set );
1332        void to_setting  (Setting  &set) const; 
1333
1334        // TODO dodelat void to_setting( Setting &set ) const;
1335
1336};
1337
1338UIREGISTER ( mlognorm );
1339SHAREDPTR ( mlognorm );
1340
1341/*! inverse Wishart density defined on Choleski decomposition
1342
1343*/
1344class eWishartCh : public epdf {
1345protected:
1346        //! Upper-Triagle of Choleski decomposition of \f$ \Psi \f$
1347        chmat Y;
1348        //! dimension of matrix  \f$ \Psi \f$
1349        int p;
1350        //! degrees of freedom  \f$ \nu \f$
1351        double delta;
1352public:
1353        //! Set internal structures
1354        void set_parameters ( const mat &Y0, const double delta0 ) {
1355                Y = chmat ( Y0 );
1356                delta = delta0;
1357                p = Y.rows();   
1358        }
1359        //! Set internal structures
1360        void set_parameters ( const chmat &Y0, const double delta0 ) {
1361                Y = Y0;
1362                delta = delta0;
1363                p = Y.rows();
1364                }
1365       
1366        virtual void validate (){
1367                epdf::validate();
1368                dim = p * p;
1369        }
1370
1371        //! Sample matrix argument
1372        mat sample_mat() const {
1373                mat X = zeros ( p, p );
1374
1375                //sample diagonal
1376                for ( int i = 0; i < p; i++ ) {
1377                        GamRNG.setup ( 0.5* ( delta - i ) , 0.5 );   // no +1 !! index if from 0
1378#pragma omp critical
1379                        X ( i, i ) = sqrt ( GamRNG() );
1380                }
1381                //do the rest
1382                for ( int i = 0; i < p; i++ ) {
1383                        for ( int j = i + 1; j < p; j++ ) {
1384#pragma omp critical
1385                                X ( i, j ) = NorRNG.sample();
1386                        }
1387                }
1388                return X*Y._Ch();// return upper triangular part of the decomposition
1389        }
1390
1391        vec sample () const {
1392                return vec ( sample_mat()._data(), p*p );
1393        }
1394
1395        virtual vec mean() const NOT_IMPLEMENTED(0);
1396
1397        //! return expected variance (not covariance!)
1398        virtual vec variance() const NOT_IMPLEMENTED(0);
1399
1400        virtual double evallog ( const vec &val ) const NOT_IMPLEMENTED(0);
1401
1402        //! fast access function y0 will be copied into Y.Ch.
1403        void setY ( const mat &Ch0 ) {
1404                copy_vector ( dim, Ch0._data(), Y._Ch()._data() );
1405        }
1406
1407        //! fast access function y0 will be copied into Y.Ch.
1408        void _setY ( const vec &ch0 ) {
1409                copy_vector ( dim, ch0._data(), Y._Ch()._data() );
1410        }
1411
1412        //! access function
1413        const chmat& getY() const {
1414                return Y;
1415        }
1416};
1417
1418//! Inverse Wishart on Choleski decomposition
1419/*! Being computed by conversion from `standard' Wishart
1420*/
1421class eiWishartCh: public epdf {
1422protected:
1423        //! Internal instance of Wishart density
1424        eWishartCh W;
1425        //! size of Ch
1426        int p;
1427        //! parameter delta
1428        double delta;
1429public:
1430        //! constructor function
1431        void set_parameters ( const mat &Y0, const double delta0 ) {
1432                delta = delta0;
1433                W.set_parameters ( inv ( Y0 ), delta0 );
1434                p = Y0.rows();
1435        }
1436       
1437        virtual void    validate (){
1438                epdf::validate();
1439                W.validate();
1440                dim = W.dimension();
1441        }
1442       
1443       
1444        vec sample() const {
1445                mat iCh;
1446                iCh = inv ( W.sample_mat() );
1447                return vec ( iCh._data(), dim );
1448        }
1449        //! access function
1450        void _setY ( const vec &y0 ) {
1451                mat Ch ( p, p );
1452                mat iCh ( p, p );
1453                copy_vector ( dim, y0._data(), Ch._data() );
1454
1455                iCh = inv ( Ch );
1456                W.setY ( iCh );
1457        }
1458
1459        virtual double evallog ( const vec &val ) const {
1460                chmat X ( p );
1461                const chmat& Y = W.getY();
1462
1463                copy_vector ( p*p, val._data(), X._Ch()._data() );
1464                chmat iX ( p );
1465                X.inv ( iX );
1466                // compute
1467//                              \frac{ |\Psi|^{m/2}|X|^{-(m+p+1)/2}e^{-tr(\Psi X^{-1})/2} }{ 2^{mp/2}\Gamma_p(m/2)},
1468                mat M = Y.to_mat() * iX.to_mat();
1469
1470                double log1 = 0.5 * p * ( 2 * Y.logdet() ) - 0.5 * ( delta + p + 1 ) * ( 2 * X.logdet() ) - 0.5 * trace ( M );
1471                //Fixme! Multivariate gamma omitted!! it is ok for sampling, but not otherwise!!
1472
1473                /*                              if (0) {
1474                                                        mat XX=X.to_mat();
1475                                                        mat YY=Y.to_mat();
1476
1477                                                        double log2 = 0.5*p*log(det(YY))-0.5*(delta+p+1)*log(det(XX))-0.5*trace(YY*inv(XX));
1478                                                        cout << log1 << "," << log2 << endl;
1479                                                }*/
1480                return log1;
1481        };
1482
1483        virtual vec mean() const NOT_IMPLEMENTED(0);
1484
1485        //! return expected variance (not covariance!)
1486        virtual vec variance() const NOT_IMPLEMENTED(0);
1487};
1488
1489//! Random Walk on inverse Wishart
1490class rwiWishartCh : public pdf_internal<eiWishartCh> {
1491protected:
1492        //!square root of \f$ \nu-p-1 \f$ - needed for computation of \f$ \Psi \f$ from conditions
1493        double sqd;
1494        //!reference point for diagonal
1495        vec refl;
1496        //! power of the reference
1497        double l;
1498        //! dimension
1499        int p;
1500
1501public:
1502        rwiWishartCh() : sqd ( 0 ), l ( 0 ), p ( 0 ) {}
1503        //! constructor function
1504        void set_parameters ( int p0, double k, vec ref0, double l0 ) {
1505                p = p0;
1506                double delta = 2 / ( k * k ) + p + 3;
1507                sqd = sqrt ( delta - p - 1 );
1508                l = l0;
1509                refl = pow ( ref0, 1 - l );
1510                iepdf.set_parameters ( eye ( p ), delta );
1511        };
1512       
1513        void validate(){
1514                pdf_internal<eiWishartCh>::validate();
1515                dimc = iepdf.dimension();
1516        }
1517       
1518        void condition ( const vec &c ) {
1519                vec z = c;
1520                int ri = 0;
1521                for ( int i = 0; i < p*p; i += ( p + 1 ) ) {//trace diagonal element
1522                        z ( i ) = pow ( z ( i ), l ) * refl ( ri );
1523                        ri++;
1524                }
1525
1526                iepdf._setY ( sqd*z );
1527        }
1528};
1529
1530//! Switch between various resampling methods.
1531enum RESAMPLING_METHOD { MULTINOMIAL = 0, STRATIFIED = 1, SYSTEMATIC = 3 };
1532
1533//! Shortcut for multinomial.sample(int n). Various simplifications are allowed see RESAMPLING_METHOD
1534void resample(const vec &w, ivec &ind, RESAMPLING_METHOD=SYSTEMATIC);
1535
1536/*!
1537\brief Weighted empirical density
1538
1539Used e.g. in particle filters.
1540*/
1541class eEmp: public epdf {
1542protected :
1543        //! Number of particles
1544        int n;
1545        //! Sample weights \f$w\f$
1546        vec w;
1547        //! Samples \f$x^{(i)}, i=1..n\f$
1548        Array<vec> samples;
1549public:
1550        //! \name Constructors
1551        //!@{
1552        eEmp () : epdf (), w (), samples () {};
1553        //! copy constructor
1554        eEmp ( const eEmp &e ) : epdf ( e ), w ( e.w ), samples ( e.samples ) {};
1555        //!@}
1556
1557        //! Set samples and weights
1558        void set_statistics ( const vec &w0, const epdf &pdf0 );
1559        //! Set samples and weights
1560        void set_statistics ( const epdf &pdf0 , int n ) {
1561                set_statistics ( ones ( n ) / n, pdf0 );
1562        };
1563        //! Set sample
1564        void set_samples ( const epdf* pdf0 );
1565        //! Set sample
1566        void set_parameters ( int n0, bool copy = true ) {
1567                n = n0;
1568                w.set_size ( n0, copy );
1569                samples.set_size ( n0, copy );
1570        };
1571        //! Set samples
1572        void set_parameters ( const Array<vec> &Av ) {
1573                n = Av.size();
1574                w = 1 / n * ones ( n );
1575                samples = Av;
1576        };
1577        virtual void    validate ();
1578        //! Potentially dangerous, use with care.
1579        vec& _w()  {
1580                return w;
1581        };
1582        //! Potentially dangerous, use with care.
1583        const vec& _w() const {
1584                return w;
1585        };
1586        //! access function
1587        Array<vec>& _samples() {
1588                return samples;
1589        };
1590        //! access function
1591        const vec& _sample ( int i ) const {
1592                return samples ( i );
1593        };
1594        //! access function
1595        const Array<vec>& _samples() const {
1596                return samples;
1597        };
1598        //! 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.
1599        void resample ( RESAMPLING_METHOD method = SYSTEMATIC );
1600
1601        //! inherited operation : NOT implemented
1602        vec sample() const NOT_IMPLEMENTED(0);
1603
1604        //! inherited operation : NOT implemented
1605        double evallog ( const vec &val ) const NOT_IMPLEMENTED(0);
1606
1607        vec mean() const {
1608                vec pom = zeros ( dim );
1609                for ( int i = 0; i < n; i++ ) {
1610                        pom += samples ( i ) * w ( i );
1611                }
1612                return pom;
1613        }
1614        vec variance() const {
1615                vec pom = zeros ( dim );
1616                for ( int i = 0; i < n; i++ ) {
1617                        pom += pow ( samples ( i ), 2 ) * w ( i );
1618                }
1619                return pom - pow ( mean(), 2 );
1620        }
1621        //! For this class, qbounds are minimum and maximum value of the population!
1622        void qbounds ( vec &lb, vec &ub, double perc = 0.95 ) const;
1623
1624        void to_setting ( Setting &set ) const;
1625        void from_setting ( const Setting &set );
1626
1627};
1628UIREGISTER(eEmp);
1629
1630
1631////////////////////////
1632
1633template<class sq_T>
1634void enorm<sq_T>::set_parameters ( const vec &mu0, const sq_T &R0 ) {
1635//Fixme test dimensions of mu0 and R0;
1636        mu = mu0;
1637        R = R0;
1638        validate();
1639};
1640
1641template<class sq_T>
1642void enorm<sq_T>::from_setting ( const Setting &set ) {
1643        epdf::from_setting ( set ); //reads rv
1644
1645        UI::get ( mu, set, "mu", UI::compulsory );
1646        mat Rtmp;// necessary for conversion
1647        UI::get ( Rtmp, set, "R", UI::compulsory );
1648        R = Rtmp; // conversion
1649}
1650
1651template<class sq_T>
1652void enorm<sq_T>::validate() {
1653                eEF::validate();
1654                bdm_assert ( mu.length() == R.rows(), "mu and R parameters do not match" );
1655                dim = mu.length();
1656        }
1657
1658template<class sq_T>
1659void enorm<sq_T>::to_setting ( Setting &set ) const {
1660        epdf::to_setting ( set ); //reads rv   
1661        UI::save ( mu, set, "mu");
1662        UI::save ( R.to_mat(), set, "R");
1663}
1664
1665
1666
1667template<class sq_T>
1668void enorm<sq_T>::dupdate ( mat &v, double nu ) {
1669        //
1670};
1671
1672// template<class sq_T>
1673// void enorm<sq_T>::tupdate ( double phi, mat &vbar, double nubar ) {
1674//      //
1675// };
1676
1677template<class sq_T>
1678vec enorm<sq_T>::sample() const {
1679        vec x ( dim );
1680#pragma omp critical
1681        NorRNG.sample_vector ( dim, x );
1682        vec smp = R.sqrt_mult ( x );
1683
1684        smp += mu;
1685        return smp;
1686};
1687
1688// template<class sq_T>
1689// double enorm<sq_T>::eval ( const vec &val ) const {
1690//      double pdfl,e;
1691//      pdfl = evallog ( val );
1692//      e = exp ( pdfl );
1693//      return e;
1694// };
1695
1696template<class sq_T>
1697double enorm<sq_T>::evallog_nn ( const vec &val ) const {
1698        // 1.83787706640935 = log(2pi)
1699        double tmp = -0.5 * ( R.invqform ( mu - val ) );// - lognc();
1700        return  tmp;
1701};
1702
1703template<class sq_T>
1704inline double enorm<sq_T>::lognc () const {
1705        // 1.83787706640935 = log(2pi)
1706        double tmp = 0.5 * ( R.cols() * 1.83787706640935 + R.logdet() );
1707        return tmp;
1708};
1709
1710
1711// template<class sq_T>
1712// vec mlnorm<sq_T>::samplecond (const  vec &cond, double &lik ) {
1713//      this->condition ( cond );
1714//      vec smp = epdf.sample();
1715//      lik = epdf.eval ( smp );
1716//      return smp;
1717// }
1718
1719// template<class sq_T>
1720// mat mlnorm<sq_T>::samplecond (const vec &cond, vec &lik, int n ) {
1721//      int i;
1722//      int dim = rv.count();
1723//      mat Smp ( dim,n );
1724//      vec smp ( dim );
1725//      this->condition ( cond );
1726//
1727//      for ( i=0; i<n; i++ ) {
1728//              smp = epdf.sample();
1729//              lik ( i ) = epdf.eval ( smp );
1730//              Smp.set_col ( i ,smp );
1731//      }
1732//
1733//      return Smp;
1734// }
1735
1736
1737template<class sq_T>
1738shared_ptr<epdf> enorm<sq_T>::marginal ( const RV &rvn ) const {
1739        enorm<sq_T> *tmp = new enorm<sq_T> ();
1740        shared_ptr<epdf> narrow ( tmp );
1741        marginal ( rvn, *tmp );
1742        return narrow;
1743}
1744
1745template<class sq_T>
1746void enorm<sq_T>::marginal ( const RV &rvn, enorm<sq_T> &target ) const {
1747        bdm_assert ( isnamed(), "rv description is not assigned" );
1748        ivec irvn = rvn.dataind ( rv );
1749
1750        sq_T Rn ( R, irvn );  // select rows and columns of R
1751
1752        target.set_rv ( rvn );
1753        target.set_parameters ( mu ( irvn ), Rn );
1754}
1755
1756template<class sq_T>
1757shared_ptr<pdf> enorm<sq_T>::condition ( const RV &rvn ) const {
1758        mlnorm<sq_T> *tmp = new mlnorm<sq_T> ();
1759        shared_ptr<pdf> narrow ( tmp );
1760        condition ( rvn, *tmp );
1761        return narrow;
1762}
1763
1764template<class sq_T>
1765void enorm<sq_T>::condition ( const RV &rvn, pdf &target ) const {
1766        typedef mlnorm<sq_T> TMlnorm;
1767
1768        bdm_assert ( isnamed(), "rvs are not assigned" );
1769        TMlnorm &uptarget = dynamic_cast<TMlnorm &> ( target );
1770
1771        RV rvc = rv.subt ( rvn );
1772        bdm_assert ( ( rvc._dsize() + rvn._dsize() == rv._dsize() ), "wrong rvn" );
1773        //Permutation vector of the new R
1774        ivec irvn = rvn.dataind ( rv );
1775        ivec irvc = rvc.dataind ( rv );
1776        ivec perm = concat ( irvn , irvc );
1777        sq_T Rn ( R, perm );
1778
1779        //fixme - could this be done in general for all sq_T?
1780        mat S = Rn.to_mat();
1781        //fixme
1782        int n = rvn._dsize() - 1;
1783        int end = R.rows() - 1;
1784        mat S11 = S.get ( 0, n, 0, n );
1785        mat S12 = S.get ( 0, n , rvn._dsize(), end );
1786        mat S22 = S.get ( rvn._dsize(), end, rvn._dsize(), end );
1787
1788        vec mu1 = mu ( irvn );
1789        vec mu2 = mu ( irvc );
1790        mat A = S12 * inv ( S22 );
1791        sq_T R_n ( S11 - A *S12.T() );
1792
1793        uptarget.set_rv ( rvn );
1794        uptarget.set_rvc ( rvc );
1795        uptarget.set_parameters ( A, mu1 - A*mu2, R_n );
1796        uptarget.validate();
1797}
1798
1799/*! Dirac delta function distribution */
1800class dirac: public epdf{
1801        public: 
1802                vec point;
1803        public:
1804                double evallog (const vec &dt) const {return -inf;}
1805                vec mean () const {return point;}
1806                vec variance () const {return zeros(point.length());}
1807                void qbounds ( vec &lb, vec &ub, double percentage = 0.95 ) const { lb = point; ub = point;}
1808                //! access
1809                const vec& _point() {return point;}
1810                void set_point(const vec& p){point =p; dim=p.length();}
1811                vec sample() const {return point;}
1812        };
1813
1814////
1815///////
1816template<class sq_T>
1817void mgnorm<sq_T >::set_parameters ( const shared_ptr<fnc> &g0, const sq_T &R0 ) {
1818        g = g0;
1819        this->iepdf.set_parameters ( zeros ( g->dimension() ), R0 );
1820}
1821
1822template<class sq_T>
1823void mgnorm<sq_T >::condition ( const vec &cond ) {
1824        this->iepdf._mu() = g->eval ( cond );
1825};
1826
1827//! \todo unify this stuff with to_string()
1828template<class sq_T>
1829std::ostream &operator<< ( std::ostream &os,  mlnorm<sq_T> &ml ) {
1830        os << "A:" << ml.A << endl;
1831        os << "mu:" << ml.mu_const << endl;
1832        os << "R:" << ml._R() << endl;
1833        return os;
1834};
1835
1836}
1837#endif //EF_H
Note: See TracBrowser for help on using the browser.