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

Revision 637, 39.0 kB (checked in by smidl, 15 years ago)

new Dirichlet random walk + numerics in egiw

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