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

Revision 741, 40.1 kB (checked in by smidl, 14 years ago)

Stress tests are passing now. Missing validate calls are filled...

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