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

Revision 763, 41.0 kB (checked in by smidl, 14 years ago)

changes in pdfs

  • 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 to_setting (Setting &set) const {
841                pdf::to_setting(set);
842                UI::save ( A, set, "A");
843                UI::save ( mu_const, set, "const");
844                UI::save ( _R(), set, "R");
845        }
846        void validate() {
847                pdf_internal<TEpdf<sq_T> >::validate();
848                bdm_assert ( A.rows() == mu_const.length(), "mlnorm: A vs. mu mismatch" );
849                bdm_assert ( A.rows() == _R().rows(), "mlnorm: A vs. R mismatch" );
850
851        }
852};
853UIREGISTER2 ( mlnorm, ldmat );
854SHAREDPTR2 ( mlnorm, ldmat );
855UIREGISTER2 ( mlnorm, fsqmat );
856SHAREDPTR2 ( mlnorm, fsqmat );
857UIREGISTER2 ( mlnorm, chmat );
858SHAREDPTR2 ( mlnorm, chmat );
859
860//! pdf with general function for mean value
861template<class sq_T>
862class mgnorm : public pdf_internal< enorm< sq_T > > {
863private:
864//                      vec &mu; WHY NOT?
865        shared_ptr<fnc> g;
866
867public:
868        //!default constructor
869        mgnorm() : pdf_internal<enorm<sq_T> >() { }
870        //!set mean function
871        inline void set_parameters ( const shared_ptr<fnc> &g0, const sq_T &R0 );
872        inline void condition ( const vec &cond );
873
874
875        /*! Create Normal density with given function of mean value
876        \f[ f(rv|rvc) = N( g(rvc), R) \f]
877        from structure
878        \code
879        class = 'mgnorm';
880        g.class =  'fnc';      // function for mean value evolution
881        g._fields_of_fnc = ...;
882
883        R = [1, 0;             // covariance matrix
884                0, 1];
885                --OR --
886        dR = [1, 1];           // diagonal of cavariance matrix
887
888        rv = RV({'name'})      // description of RV
889        rvc = RV({'name'})     // description of RV in condition
890        \endcode
891        */
892
893        void from_setting ( const Setting &set ) {
894                pdf::from_setting ( set );
895                shared_ptr<fnc> g = UI::build<fnc> ( set, "g", UI::compulsory );
896
897                mat R;
898                vec dR;
899                if ( UI::get ( dR, set, "dR" ) )
900                        R = diag ( dR );
901                else
902                        UI::get ( R, set, "R", UI::compulsory );
903
904                set_parameters ( g, R );
905                validate();
906        }
907        void validate() {
908                bdm_assert ( g->dimension() == this->dimension(), "incompatible function" );
909        }
910};
911
912UIREGISTER2 ( mgnorm, chmat );
913SHAREDPTR2 ( mgnorm, chmat );
914
915
916/*! (Approximate) Student t density with linear function of mean value
917
918The internal epdf of this class is of the type of a Gaussian (enorm).
919However, each conditioning is trying to assure the best possible approximation by taking into account the zeta function. See [] for reference.
920
921Perhaps a moment-matching technique?
922*/
923class mlstudent : public mlnorm<ldmat, enorm> {
924protected:
925        //! Variable \f$ \Lambda \f$ from theory
926        ldmat Lambda;
927        //! Reference to variable \f$ R \f$
928        ldmat &_R;
929        //! Variable \f$ R_e \f$
930        ldmat Re;
931public:
932        mlstudent () : mlnorm<ldmat, enorm> (),
933                        Lambda (),      _R ( iepdf._R() ) {}
934        //! constructor function
935        void set_parameters ( const mat &A0, const vec &mu0, const ldmat &R0, const ldmat& Lambda0 ) {
936                iepdf.set_parameters ( mu0, R0 );// was Lambda, why?
937                A = A0;
938                mu_const = mu0;
939                Re = R0;
940                Lambda = Lambda0;
941        }
942
943        void condition ( const vec &cond ); 
944
945        void validate() {
946                bdm_assert ( A.rows() == mu_const.length(), "mlstudent: A vs. mu mismatch" );
947                bdm_assert ( _R.rows() == A.rows(), "mlstudent: A vs. R mismatch" );
948
949        }
950};
951/*!
952\brief  Gamma random walk
953
954Mean value, \f$\mu\f$, of this density is given by \c rvc .
955Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
956This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
957
958The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
959*/
960class mgamma : public pdf_internal<egamma> {
961protected:
962
963        //! Constant \f$k\f$
964        double k;
965
966        //! cache of iepdf.beta
967        vec &_beta;
968
969public:
970        //! Constructor
971        mgamma() : pdf_internal<egamma>(), k ( 0 ),
972                        _beta ( iepdf._beta() ) {
973        }
974
975        //! Set value of \c k
976        void set_parameters ( double k, const vec &beta0 );
977
978        void condition ( const vec &val ) {
979                _beta = k / val;
980        };
981        /*! Create Gamma density with conditional mean value
982        \f[ f(rv|rvc) = \Gamma(k, k/rvc) \f]
983        from structure
984        \code
985          class = 'mgamma';
986          beta = [...];          // vector of initial alpha
987          k = 1.1;               // multiplicative constant k
988          rv = RV({'name'})      // description of RV
989          rvc = RV({'name'})     // description of RV in condition
990         \endcode
991        */
992        void from_setting ( const Setting &set ) {
993                pdf::from_setting ( set ); // reads rv and rvc
994                vec betatmp; // ugly but necessary
995                UI::get ( betatmp, set, "beta", UI::compulsory );
996                UI::get ( k, set, "k", UI::compulsory );
997                set_parameters ( k, betatmp );
998                validate();
999        }
1000        void validate() {
1001                pdf_internal<egamma>::validate();
1002
1003                dim = _beta.length();
1004                dimc = _beta.length();
1005        }
1006};
1007UIREGISTER ( mgamma );
1008SHAREDPTR ( mgamma );
1009
1010/*!
1011\brief  Inverse-Gamma random walk
1012
1013Mean value, \f$ \mu \f$, of this density is given by \c rvc .
1014Standard deviation of the random walk is proportional to one \f$ k \f$-th the mean.
1015This is achieved by setting \f$ \alpha=\mu/k^2+2 \f$ and \f$ \beta=\mu(\alpha-1)\f$.
1016
1017The standard deviation of the walk is then: \f$ \mu/\sqrt(k)\f$.
1018 */
1019class migamma : public pdf_internal<eigamma> {
1020protected:
1021        //! Constant \f$k\f$
1022        double k;
1023
1024        //! cache of iepdf.alpha
1025        vec &_alpha;
1026
1027        //! cache of iepdf.beta
1028        vec &_beta;
1029
1030public:
1031        //! \name Constructors
1032        //!@{
1033        migamma() : pdf_internal<eigamma>(),
1034                        k ( 0 ),
1035                        _alpha ( iepdf._alpha() ),
1036                        _beta ( iepdf._beta() ) {
1037        }
1038
1039        migamma ( const migamma &m ) : pdf_internal<eigamma>(),
1040                        k ( 0 ),
1041                        _alpha ( iepdf._alpha() ),
1042                        _beta ( iepdf._beta() ) {
1043        }
1044        //!@}
1045
1046        //! Set value of \c k
1047        void set_parameters ( int len, double k0 ) {
1048                k = k0;
1049                iepdf.set_parameters ( ( 1.0 / ( k*k ) + 2.0 ) *ones ( len ) /*alpha*/, ones ( len ) /*beta*/ );
1050                dimc = dimension();
1051        };
1052        void condition ( const vec &val ) {
1053                _beta = elem_mult ( val, ( _alpha - 1.0 ) );
1054        };
1055};
1056
1057
1058/*!
1059\brief  Gamma random walk around a fixed point
1060
1061Mean 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
1062\f[ \mu = \mu_{t-1} ^{l} p^{1-l}\f]
1063
1064Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
1065This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
1066
1067The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
1068*/
1069class mgamma_fix : public mgamma {
1070protected:
1071        //! parameter l
1072        double l;
1073        //! reference vector
1074        vec refl;
1075public:
1076        //! Constructor
1077        mgamma_fix () : mgamma (), refl () {};
1078        //! Set value of \c k
1079        void set_parameters ( double k0 , vec ref0, double l0 ) {
1080                mgamma::set_parameters ( k0, ref0 );
1081                refl = pow ( ref0, 1.0 - l0 );
1082                l = l0;
1083                dimc = dimension();
1084        };
1085
1086        void condition ( const vec &val ) {
1087                vec mean = elem_mult ( refl, pow ( val, l ) );
1088                _beta = k / mean;
1089        };
1090};
1091
1092
1093/*!
1094\brief  Inverse-Gamma random walk around a fixed point
1095
1096Mean 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
1097\f[ \mu = \mu_{t-1} ^{l} p^{1-l}\f]
1098
1099==== Check == vv =
1100Standard deviation of the random walk is proportional to one \f$k\f$-th the mean.
1101This is achieved by setting \f$\alpha=k\f$ and \f$\beta=k/\mu\f$.
1102
1103The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$.
1104 */
1105class migamma_ref : public migamma {
1106protected:
1107        //! parameter l
1108        double l;
1109        //! reference vector
1110        vec refl;
1111public:
1112        //! Constructor
1113        migamma_ref () : migamma (), refl () {};
1114        //! Set value of \c k
1115        void set_parameters ( double k0 , vec ref0, double l0 ) {
1116                migamma::set_parameters ( ref0.length(), k0 );
1117                refl = pow ( ref0, 1.0 - l0 );
1118                l = l0;
1119                dimc = dimension();
1120        };
1121
1122        void condition ( const vec &val ) {
1123                vec mean = elem_mult ( refl, pow ( val, l ) );
1124                migamma::condition ( mean );
1125        };
1126
1127
1128        /*! Create inverse-Gamma density with conditional mean value
1129        \f[ f(rv|rvc) = i\Gamma(k, k/(rvc^l \circ ref^{(1-l)}) \f]
1130        from structure
1131        \code
1132        class = 'migamma_ref';
1133        ref = [1e-5; 1e-5; 1e-2 1e-3];            // reference vector
1134        l = 0.999;                                // constant l
1135        k = 0.1;                                  // constant k
1136        rv = RV({'name'})                         // description of RV
1137        rvc = RV({'name'})                        // description of RV in condition
1138        \endcode
1139         */
1140        void from_setting ( const Setting &set );
1141
1142        // TODO dodelat void to_setting( Setting &set ) const;
1143};
1144
1145
1146UIREGISTER ( migamma_ref );
1147SHAREDPTR ( migamma_ref );
1148
1149/*! Log-Normal probability density
1150 only allow diagonal covariances!
1151
1152Density of the form \f$ \log(x)\sim \mathcal{N}(\mu,\sigma^2) \f$ , i.e.
1153\f[
1154x \sim \frac{1}{x\sigma\sqrt{2\pi}}\exp{-\frac{1}{2\sigma^2}(\log(x)-\mu)}
1155\f]
1156
1157Function from_setting loads mu and R in the same way as it does for enorm<>!
1158*/
1159class elognorm: public enorm<ldmat> {
1160public:
1161        vec sample() const {
1162                return exp ( enorm<ldmat>::sample() );
1163        };
1164        vec mean() const {
1165                vec var = enorm<ldmat>::variance();
1166                return exp ( mu - 0.5*var );
1167        };
1168
1169};
1170
1171/*!
1172\brief  Log-Normal random walk
1173
1174Mean value, \f$\mu\f$, is...
1175
1176 */
1177class mlognorm : public pdf_internal<elognorm> {
1178protected:
1179        //! parameter 1/2*sigma^2
1180        double sig2;
1181
1182        //! access
1183        vec &mu;
1184public:
1185        //! Constructor
1186        mlognorm() : pdf_internal<elognorm>(),
1187                        sig2 ( 0 ),
1188                        mu ( iepdf._mu() ) {
1189        }
1190
1191        //! Set value of \c k
1192        void set_parameters ( int size, double k ) {
1193                sig2 = 0.5 * log ( k * k + 1 );
1194                iepdf.set_parameters ( zeros ( size ), 2*sig2*eye ( size ) );
1195
1196                dimc = size;
1197        };
1198
1199        void condition ( const vec &val ) {
1200                mu = log ( val ) - sig2;//elem_mult ( refl,pow ( val,l ) );
1201        };
1202
1203        /*! Create logNormal random Walk
1204        \f[ f(rv|rvc) = log\mathcal{N}( \log(rvc)-0.5\log(k^2+1), k I) \f]
1205        from structure
1206        \code
1207        class = 'mlognorm';
1208        k   = 0.1;               // "variance" k
1209        mu0 = 0.1;               // Initial value of mean
1210        rv  = RV({'name'})       // description of RV
1211        rvc = RV({'name'})       // description of RV in condition
1212        \endcode
1213        */
1214        void from_setting ( const Setting &set );
1215
1216        // TODO dodelat void to_setting( Setting &set ) const;
1217
1218};
1219
1220UIREGISTER ( mlognorm );
1221SHAREDPTR ( mlognorm );
1222
1223/*! inverse Wishart density defined on Choleski decomposition
1224
1225*/
1226class eWishartCh : public epdf {
1227protected:
1228        //! Upper-Triagle of Choleski decomposition of \f$ \Psi \f$
1229        chmat Y;
1230        //! dimension of matrix  \f$ \Psi \f$
1231        int p;
1232        //! degrees of freedom  \f$ \nu \f$
1233        double delta;
1234public:
1235        //! Set internal structures
1236        void set_parameters ( const mat &Y0, const double delta0 ) {
1237                Y = chmat ( Y0 );
1238                delta = delta0;
1239                p = Y.rows();
1240                dim = p * p;
1241        }
1242        //! Set internal structures
1243        void set_parameters ( const chmat &Y0, const double delta0 ) {
1244                Y = Y0;
1245                delta = delta0;
1246                p = Y.rows();
1247                dim = p * p;
1248        }
1249        //! Sample matrix argument
1250        mat sample_mat() const {
1251                mat X = zeros ( p, p );
1252
1253                //sample diagonal
1254                for ( int i = 0; i < p; i++ ) {
1255                        GamRNG.setup ( 0.5* ( delta - i ) , 0.5 );   // no +1 !! index if from 0
1256#pragma omp critical
1257                        X ( i, i ) = sqrt ( GamRNG() );
1258                }
1259                //do the rest
1260                for ( int i = 0; i < p; i++ ) {
1261                        for ( int j = i + 1; j < p; j++ ) {
1262#pragma omp critical
1263                                X ( i, j ) = NorRNG.sample();
1264                        }
1265                }
1266                return X*Y._Ch();// return upper triangular part of the decomposition
1267        }
1268        vec sample () const {
1269                return vec ( sample_mat()._data(), p*p );
1270        }
1271        //! fast access function y0 will be copied into Y.Ch.
1272        void setY ( const mat &Ch0 ) {
1273                copy_vector ( dim, Ch0._data(), Y._Ch()._data() );
1274        }
1275        //! fast access function y0 will be copied into Y.Ch.
1276        void _setY ( const vec &ch0 ) {
1277                copy_vector ( dim, ch0._data(), Y._Ch()._data() );
1278        }
1279        //! access function
1280        const chmat& getY() const {
1281                return Y;
1282        }
1283};
1284
1285//! Inverse Wishart on Choleski decomposition
1286/*! Being computed by conversion from `standard' Wishart
1287*/
1288class eiWishartCh: public epdf {
1289protected:
1290        //! Internal instance of Wishart density
1291        eWishartCh W;
1292        //! size of Ch
1293        int p;
1294        //! parameter delta
1295        double delta;
1296public:
1297        //! constructor function
1298        void set_parameters ( const mat &Y0, const double delta0 ) {
1299                delta = delta0;
1300                W.set_parameters ( inv ( Y0 ), delta0 );
1301                p = Y0.rows();
1302        }
1303       
1304        virtual void    validate (){
1305      dim = W.dimension();
1306        }
1307       
1308       
1309        vec sample() const {
1310                mat iCh;
1311                iCh = inv ( W.sample_mat() );
1312                return vec ( iCh._data(), dim );
1313        }
1314        //! access function
1315        void _setY ( const vec &y0 ) {
1316                mat Ch ( p, p );
1317                mat iCh ( p, p );
1318                copy_vector ( dim, y0._data(), Ch._data() );
1319
1320                iCh = inv ( Ch );
1321                W.setY ( iCh );
1322        }
1323        virtual double evallog ( const vec &val ) const {
1324                chmat X ( p );
1325                const chmat& Y = W.getY();
1326
1327                copy_vector ( p*p, val._data(), X._Ch()._data() );
1328                chmat iX ( p );
1329                X.inv ( iX );
1330                // compute
1331//                              \frac{ |\Psi|^{m/2}|X|^{-(m+p+1)/2}e^{-tr(\Psi X^{-1})/2} }{ 2^{mp/2}\Gamma_p(m/2)},
1332                mat M = Y.to_mat() * iX.to_mat();
1333
1334                double log1 = 0.5 * p * ( 2 * Y.logdet() ) - 0.5 * ( delta + p + 1 ) * ( 2 * X.logdet() ) - 0.5 * trace ( M );
1335                //Fixme! Multivariate gamma omitted!! it is ok for sampling, but not otherwise!!
1336
1337                /*                              if (0) {
1338                                                        mat XX=X.to_mat();
1339                                                        mat YY=Y.to_mat();
1340
1341                                                        double log2 = 0.5*p*log(det(YY))-0.5*(delta+p+1)*log(det(XX))-0.5*trace(YY*inv(XX));
1342                                                        cout << log1 << "," << log2 << endl;
1343                                                }*/
1344                return log1;
1345        };
1346
1347};
1348
1349//! Random Walk on inverse Wishart
1350class rwiWishartCh : public pdf_internal<eiWishartCh> {
1351protected:
1352        //!square root of \f$ \nu-p-1 \f$ - needed for computation of \f$ \Psi \f$ from conditions
1353        double sqd;
1354        //!reference point for diagonal
1355        vec refl;
1356        //! power of the reference
1357        double l;
1358        //! dimension
1359        int p;
1360
1361public:
1362        rwiWishartCh() : sqd ( 0 ), l ( 0 ), p ( 0 ) {}
1363        //! constructor function
1364        void set_parameters ( int p0, double k, vec ref0, double l0 ) {
1365                p = p0;
1366                double delta = 2 / ( k * k ) + p + 3;
1367                sqd = sqrt ( delta - p - 1 );
1368                l = l0;
1369                refl = pow ( ref0, 1 - l );
1370
1371                iepdf.set_parameters ( eye ( p ), delta );
1372                dimc = iepdf.dimension();
1373        }
1374        void condition ( const vec &c ) {
1375                vec z = c;
1376                int ri = 0;
1377                for ( int i = 0; i < p*p; i += ( p + 1 ) ) {//trace diagonal element
1378                        z ( i ) = pow ( z ( i ), l ) * refl ( ri );
1379                        ri++;
1380                }
1381
1382                iepdf._setY ( sqd*z );
1383        }
1384};
1385
1386//! Switch between various resampling methods.
1387enum RESAMPLING_METHOD { MULTINOMIAL = 0, STRATIFIED = 1, SYSTEMATIC = 3 };
1388/*!
1389\brief Weighted empirical density
1390
1391Used e.g. in particle filters.
1392*/
1393class eEmp: public epdf {
1394protected :
1395        //! Number of particles
1396        int n;
1397        //! Sample weights \f$w\f$
1398        vec w;
1399        //! Samples \f$x^{(i)}, i=1..n\f$
1400        Array<vec> samples;
1401public:
1402        //! \name Constructors
1403        //!@{
1404        eEmp () : epdf (), w (), samples () {};
1405        //! copy constructor
1406        eEmp ( const eEmp &e ) : epdf ( e ), w ( e.w ), samples ( e.samples ) {};
1407        //!@}
1408
1409        //! Set samples and weights
1410        void set_statistics ( const vec &w0, const epdf &pdf0 );
1411        //! Set samples and weights
1412        void set_statistics ( const epdf &pdf0 , int n ) {
1413                set_statistics ( ones ( n ) / n, pdf0 );
1414        };
1415        //! Set sample
1416        void set_samples ( const epdf* pdf0 );
1417        //! Set sample
1418        void set_parameters ( int n0, bool copy = true ) {
1419                n = n0;
1420                w.set_size ( n0, copy );
1421                samples.set_size ( n0, copy );
1422        };
1423        //! Set samples
1424        void set_parameters ( const Array<vec> &Av ) {
1425                n = Av.size();
1426                w = 1 / n * ones ( n );
1427                samples = Av;
1428        };
1429        virtual void    validate (){
1430          bdm_assert (samples.length()==w.length(),"samples and weigths are of different lengths");
1431          n = w.length();
1432          if (n>0)
1433                epdf::validate ( samples ( 0 ).length() );
1434        }
1435        //! Potentially dangerous, use with care.
1436        vec& _w()  {
1437                return w;
1438        };
1439        //! Potentially dangerous, use with care.
1440        const vec& _w() const {
1441                return w;
1442        };
1443        //! access function
1444        Array<vec>& _samples() {
1445                return samples;
1446        };
1447        //! access function
1448        const vec& _sample ( int i ) const {
1449                return samples ( i );
1450        };
1451        //! access function
1452        const Array<vec>& _samples() const {
1453                return samples;
1454        };
1455        //! 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.
1456        //! The vector with indeces of new samples is returned in variable \c index.
1457        void resample ( ivec &index, RESAMPLING_METHOD method = SYSTEMATIC );
1458
1459        //! Resampling without returning index of new particles.
1460        void resample ( RESAMPLING_METHOD method = SYSTEMATIC ) {
1461                ivec ind;
1462                resample ( ind, method );
1463        };
1464
1465        //! inherited operation : NOT implemented
1466        vec sample() const {
1467                bdm_error ( "Not implemented" );
1468                return vec();
1469        }
1470
1471        //! inherited operation : NOT implemented
1472        double evallog ( const vec &val ) const {
1473                bdm_error ( "Not implemented" );
1474                return 0.0;
1475        }
1476
1477        vec mean() const {
1478                vec pom = zeros ( dim );
1479                for ( int i = 0; i < n; i++ ) {
1480                        pom += samples ( i ) * w ( i );
1481                }
1482                return pom;
1483        }
1484        vec variance() const {
1485                vec pom = zeros ( dim );
1486                for ( int i = 0; i < n; i++ ) {
1487                        pom += pow ( samples ( i ), 2 ) * w ( i );
1488                }
1489                return pom - pow ( mean(), 2 );
1490        }
1491        //! For this class, qbounds are minimum and maximum value of the population!
1492        void qbounds ( vec &lb, vec &ub, double perc = 0.95 ) const;
1493
1494        void to_setting ( Setting &set ) const {
1495                epdf::to_setting( set );
1496                UI::save ( samples, set, "samples" );
1497                UI::save ( w, set, "w" );
1498        }
1499
1500        void from_setting ( const Setting &set ) {
1501                epdf::from_setting( set );
1502               
1503                UI::get( samples, set, "samples", UI::compulsory );
1504                UI::get ( w, set, "w", UI::compulsory );
1505                validate();
1506        }
1507
1508};
1509UIREGISTER(eEmp);
1510
1511
1512////////////////////////
1513
1514template<class sq_T>
1515void enorm<sq_T>::set_parameters ( const vec &mu0, const sq_T &R0 ) {
1516//Fixme test dimensions of mu0 and R0;
1517        mu = mu0;
1518        R = R0;
1519        validate();
1520};
1521
1522template<class sq_T>
1523void enorm<sq_T>::from_setting ( const Setting &set ) {
1524        epdf::from_setting ( set ); //reads rv
1525
1526        UI::get ( mu, set, "mu", UI::compulsory );
1527        mat Rtmp;// necessary for conversion
1528        UI::get ( Rtmp, set, "R", UI::compulsory );
1529        R = Rtmp; // conversion
1530        validate();
1531}
1532
1533template<class sq_T>
1534void enorm<sq_T>::dupdate ( mat &v, double nu ) {
1535        //
1536};
1537
1538// template<class sq_T>
1539// void enorm<sq_T>::tupdate ( double phi, mat &vbar, double nubar ) {
1540//      //
1541// };
1542
1543template<class sq_T>
1544vec enorm<sq_T>::sample() const {
1545        vec x ( dim );
1546#pragma omp critical
1547        NorRNG.sample_vector ( dim, x );
1548        vec smp = R.sqrt_mult ( x );
1549
1550        smp += mu;
1551        return smp;
1552};
1553
1554// template<class sq_T>
1555// double enorm<sq_T>::eval ( const vec &val ) const {
1556//      double pdfl,e;
1557//      pdfl = evallog ( val );
1558//      e = exp ( pdfl );
1559//      return e;
1560// };
1561
1562template<class sq_T>
1563double enorm<sq_T>::evallog_nn ( const vec &val ) const {
1564        // 1.83787706640935 = log(2pi)
1565        double tmp = -0.5 * ( R.invqform ( mu - val ) );// - lognc();
1566        return  tmp;
1567};
1568
1569template<class sq_T>
1570inline double enorm<sq_T>::lognc () const {
1571        // 1.83787706640935 = log(2pi)
1572        double tmp = 0.5 * ( R.cols() * 1.83787706640935 + R.logdet() );
1573        return tmp;
1574};
1575
1576
1577// template<class sq_T>
1578// vec mlnorm<sq_T>::samplecond (const  vec &cond, double &lik ) {
1579//      this->condition ( cond );
1580//      vec smp = epdf.sample();
1581//      lik = epdf.eval ( smp );
1582//      return smp;
1583// }
1584
1585// template<class sq_T>
1586// mat mlnorm<sq_T>::samplecond (const vec &cond, vec &lik, int n ) {
1587//      int i;
1588//      int dim = rv.count();
1589//      mat Smp ( dim,n );
1590//      vec smp ( dim );
1591//      this->condition ( cond );
1592//
1593//      for ( i=0; i<n; i++ ) {
1594//              smp = epdf.sample();
1595//              lik ( i ) = epdf.eval ( smp );
1596//              Smp.set_col ( i ,smp );
1597//      }
1598//
1599//      return Smp;
1600// }
1601
1602
1603template<class sq_T>
1604shared_ptr<epdf> enorm<sq_T>::marginal ( const RV &rvn ) const {
1605        enorm<sq_T> *tmp = new enorm<sq_T> ();
1606        shared_ptr<epdf> narrow ( tmp );
1607        marginal ( rvn, *tmp );
1608        return narrow;
1609}
1610
1611template<class sq_T>
1612void enorm<sq_T>::marginal ( const RV &rvn, enorm<sq_T> &target ) const {
1613        bdm_assert ( isnamed(), "rv description is not assigned" );
1614        ivec irvn = rvn.dataind ( rv );
1615
1616        sq_T Rn ( R, irvn );  // select rows and columns of R
1617
1618        target.set_rv ( rvn );
1619        target.set_parameters ( mu ( irvn ), Rn );
1620}
1621
1622template<class sq_T>
1623shared_ptr<pdf> enorm<sq_T>::condition ( const RV &rvn ) const {
1624        mlnorm<sq_T> *tmp = new mlnorm<sq_T> ();
1625        shared_ptr<pdf> narrow ( tmp );
1626        condition ( rvn, *tmp );
1627        return narrow;
1628}
1629
1630template<class sq_T>
1631void enorm<sq_T>::condition ( const RV &rvn, pdf &target ) const {
1632        typedef mlnorm<sq_T> TMlnorm;
1633
1634        bdm_assert ( isnamed(), "rvs are not assigned" );
1635        TMlnorm &uptarget = dynamic_cast<TMlnorm &> ( target );
1636
1637        RV rvc = rv.subt ( rvn );
1638        bdm_assert ( ( rvc._dsize() + rvn._dsize() == rv._dsize() ), "wrong rvn" );
1639        //Permutation vector of the new R
1640        ivec irvn = rvn.dataind ( rv );
1641        ivec irvc = rvc.dataind ( rv );
1642        ivec perm = concat ( irvn , irvc );
1643        sq_T Rn ( R, perm );
1644
1645        //fixme - could this be done in general for all sq_T?
1646        mat S = Rn.to_mat();
1647        //fixme
1648        int n = rvn._dsize() - 1;
1649        int end = R.rows() - 1;
1650        mat S11 = S.get ( 0, n, 0, n );
1651        mat S12 = S.get ( 0, n , rvn._dsize(), end );
1652        mat S22 = S.get ( rvn._dsize(), end, rvn._dsize(), end );
1653
1654        vec mu1 = mu ( irvn );
1655        vec mu2 = mu ( irvc );
1656        mat A = S12 * inv ( S22 );
1657        sq_T R_n ( S11 - A *S12.T() );
1658
1659        uptarget.set_rv ( rvn );
1660        uptarget.set_rvc ( rvc );
1661        uptarget.set_parameters ( A, mu1 - A*mu2, R_n );
1662}
1663
1664////
1665///////
1666template<class sq_T>
1667void mgnorm<sq_T >::set_parameters ( const shared_ptr<fnc> &g0, const sq_T &R0 ) {
1668        g = g0;
1669        this->iepdf.set_parameters ( zeros ( g->dimension() ), R0 );
1670}
1671
1672template<class sq_T>
1673void mgnorm<sq_T >::condition ( const vec &cond ) {
1674        this->iepdf._mu() = g->eval ( cond );
1675};
1676
1677//! \todo unify this stuff with to_string()
1678template<class sq_T>
1679std::ostream &operator<< ( std::ostream &os,  mlnorm<sq_T> &ml ) {
1680        os << "A:" << ml.A << endl;
1681        os << "mu:" << ml.mu_const << endl;
1682        os << "R:" << ml._R() << endl;
1683        return os;
1684};
1685
1686}
1687#endif //EF_H
Note: See TracBrowser for help on using the browser.