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