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

Revision 730, 41.5 kB (checked in by smidl, 15 years ago)

Reworked epdf_harness - testing is now more general.

Corrections of existing tests.

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