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

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

logger now has ability to store settings - used in estimator. New mexfunction epdf_mean

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