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

Revision 746, 40.3 kB (checked in by mido, 14 years ago)

mixef_init fills some data into mixef_init.out,
however, there are still some TODOs in this commit,
it is necessary to fill a few more bodies of the to_setting() method

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