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

Revision 870, 45.5 kB (checked in by mido, 14 years ago)

LOG_LEVEL final cut (or rather semifinal? I hope to improve work with ids soon)
and also it rests to adapt applications, work is in progress

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