Debian Codegraph @

contrib/ms-sbvar/switch_dw/switching/dw_mdd_switch.c

raw
1 /*
2 * Copyright (C) 1996-2011 Daniel Waggoner and Tao Zha
3 *
4 * This free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * It is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * If you did not received a copy of the GNU General Public License
15 * with this software, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include "dw_mdd_switch.h"
19 #include "dw_matrix.h"
20 #include "dw_array.h"
21 #include "dw_matrix_rand.h"
22 #include "dw_ascii.h"
23 #include "dw_rand.h"
24 #include "dw_math.h"
25 #include "dw_matrix_sort.h"
26 #include "dw_switch.h"
27 #include "dw_switchio.h"
28 #include "dw_dirichlet_restrictions.h"
29 #include "dw_elliptical.h"
30 #include "dw_parse_cmd.h"
31 #include "dw_metropolis_simulation.h"
32 #include "dw_std.h"
33
34 #include <math.h>
35 #include <string.h>
36 #include <time.h>
37
38 static PRECISION ComputeLinear(TMatrix proposal, PRECISION log_c, int *intercept);
39 static PRECISION ComputeInverseLinear(TMatrix posterior, PRECISION log_c, int *intercept);
40 static int sv_NumberDirichletDistributions(TMarkovStateVariable *sv);
41 static int* sv_DirichletDimensions(int *DirichletDim, TMarkovStateVariable *sv);
42
43 #define USE_MODE 0x01
44 #define USE_MEAN 0x02
45
46 #define SORTED_LEVEL_CUTS 1
47 #define LINEAR_LEVEL_CUTS 2
48 #define EXP_LEVEL_CUTS 3
49
50 #define USE_GAUSSIAN 1
51 #define USE_POWER 2
52 #define USE_TRUNCATED_POWER 3
53 #define USE_STEP 4
54 #define USE_TRUNCATED_GAUSSIAN 5
55 #define USE_UNIFORM 6
56
57 /*******************************************************************************/
58 /*********** Waggoner/Zha method for computing marginal data density ***********/
59 /*******************************************************************************/
60 /*
61 Let h(x) and f(x) be properly scaled probability density functions and let c
62 be an unknown constant. We use the following notation.
63
64 x - parameters
65 y - data
66 f(x) - posterior distribution = p(x|y)
67 h(x) - proposal distribution
68 c - marginal data distribution = p(y)
69 c*f(x) - likelihood*prior = p(y|x)*p(x)
70
71 Assumes:
72 proposal : N x 2 matrix with proposal[i][0] = ln(h(x(i))) and
73 proposal[i][1] = ln(c*f(x(i))) where x(i) is sampled from h(x).
74 posterior : M x 2 matrix with posterior[i][0] = ln(h(x(i))) and
75 posterior[i][1] = ln(c*f(x(i))) where x(i) is sampled from f(x).
76 L1 : cutoff value (c*f(x) > L1)
77 L2 : cutoff value for (h(x) < L2)
78
79 Returns:
80 Estimate of c or MINUS_INFINITY if no proposal draws satisfied the
81 restriction given by the cutoff values of L1 and L2.
82
83 Notes:
84 Let S be the set of all x such that c*f(x) > exp(L1) and h(x) < exp(L2).
85 Then c = p(L1,L2)/I(L1,L2) where p(L1,L2) is the probability that x, sampled
86 from h(x), is in S and I(L1,L2) is the integral with respect to x over the
87 set S of
88
89 h(x)/(c*f(x)) * f(x)
90
91 p(L1,L2) can be approximated from the proposal draws by
92
93 (number of draws in S) / (total number of draws)
94
95 I(L1,L2) can be approximated from the posterior draws by summing
96
97 h(x)/(c*f(x))
98
99 over all posterior draws with x in S and then dividing by the total number
100 of posterior draws.
101 */
102 PRECISION ComputeLogMarginalDensity_WaggonerZha(TMatrix proposal, TMatrix posterior, PRECISION L1, PRECISION L2, int *in_proposal, int *in_posterior, PRECISION *I)
103 {
104 int i;
105
106 if (L1 == MINUS_INFINITY)
107 if (L2 == PLUS_INFINITY)
108 {
109 *in_proposal=RowM(proposal);
110
111 *in_posterior=RowM(posterior);
112 (*I)=MINUS_INFINITY;
113 for (i=RowM(posterior)-1; i >= 0; i--)
114 (*I)=AddLogs(*I,ElementM(posterior,i,0) - ElementM(posterior,i,1));
115 }
116 else
117 {
118 for (*in_proposal=0, i=RowM(proposal)-1; i >= 0; i--)
119 if (ElementM(proposal,i,0) <= L2)
120 (*in_proposal)++;
121
122 (*I)=MINUS_INFINITY;
123 for (*in_posterior=0, i=RowM(posterior)-1; i >= 0; i--)
124 if (ElementM(posterior,i,0) <= L2)
125 {
126 (*in_posterior)++;
127 (*I)=AddLogs(*I,ElementM(posterior,i,0) - ElementM(posterior,i,1));
128 }
129 }
130 else
131 if (L2 == PLUS_INFINITY)
132 {
133 for (*in_proposal=0, i=RowM(proposal)-1; i >= 0; i--)
134 if (ElementM(proposal,i,1) >= L1)
135 (*in_proposal)++;
136
137 (*I)=MINUS_INFINITY;
138 for (*in_posterior=0, i=RowM(posterior)-1; i >= 0; i--)
139 if (ElementM(posterior,i,1) >= L1)
140 {
141 (*in_posterior)++;
142 (*I)=AddLogs(*I,ElementM(posterior,i,0) - ElementM(posterior,i,1));
143 }
144 }
145 else
146 {
147 for (*in_proposal=0, i=RowM(proposal)-1; i >= 0; i--)
148 if ((ElementM(proposal,i,1) >= L1) && (ElementM(proposal,i,0) <= L2))
149 (*in_proposal)++;
150
151 (*I)=MINUS_INFINITY;
152 for (*in_posterior=0, i=RowM(posterior)-1; i >= 0; i--)
153 if ((ElementM(posterior,i,1) >= L1) && (ElementM(posterior,i,0) <= L2))
154 {
155 (*in_posterior)++;
156 (*I)=AddLogs(*I,ElementM(posterior,i,0) - ElementM(posterior,i,1));
157 }
158 }
159
160 if ((*in_posterior) > 0) (*I)-=log((PRECISION)RowM(posterior));
161
162 return ((*in_proposal) == 0) ? MINUS_INFINITY : log((PRECISION)(*in_proposal)/(PRECISION)RowM(proposal)) - (*I);
163 }
164 /*******************************************************************************/
165 /*******************************************************************************/
166 /*******************************************************************************/
167
168 /*******************************************************************************/
169 /************************** Bridge Method Alternative **************************/
170 /*******************************************************************************/
171 static PRECISION BridgeDifference(TMatrix proposal, TMatrix posterior, PRECISION logr)
172 {
173 int i;
174 PRECISION x, r, sum1=MINUS_INFINITY, sum2=MINUS_INFINITY, n1=RowM(posterior), n2=RowM(proposal);
175
176 for (r=n2/n1, i=RowM(proposal)-1; i >= 0; i--)
177 if ((x=ElementM(proposal,i,0)+logr-ElementM(proposal,i,1)) < 0)
178 sum2=AddLogs(sum2,-log(1+r*exp(x)));
179 else
180 sum2=AddLogs(sum2,-x-log(exp(-x)+r));
181
182 for (r=n1/n2, i=RowM(posterior)-1; i >= 0; i--)
183 if ((x=ElementM(posterior,i,1)-ElementM(posterior,i,0)-logr) < 0)
184 sum1=AddLogs(sum1,-log(1+r*exp(x)));
185 else
186 sum1=AddLogs(sum1,-x-log(exp(-x)+r));
187
188 return sum2 - sum1;
189 }
190 #define MAX_C 1.0E50
191 #define TOL 1.0E-7
192 PRECISION ComputeLogMarginalDensity_Bridge(TMatrix proposal, TMatrix posterior)
193 {
194 PRECISION min_c, max_c, mid_c=0.0, diff;
195 int i;
196
197 // Bracket the zero
198 if ((diff=BridgeDifference(proposal,posterior,mid_c)) < 0.0)
199 {
200 max_c=mid_c;
201 for (min_c=-1.0; min_c > -MAX_C; max_c=min_c, min_c*=10)
202 if ((diff=BridgeDifference(proposal,posterior,min_c)) > 0) break;
203 if (min_c <= -MAX_C) return min_c;
204 }
205 else
206 {
207 min_c=mid_c;
208 for (max_c=1.0; max_c < MAX_C; min_c=max_c, max_c*=10)
209 if ((diff=BridgeDifference(proposal,posterior,max_c)) < 0) break;
210 if (max_c >= MAX_C) return max_c;
211 }
212
213 // Divide and conququer
214 diff=BridgeDifference(proposal,posterior,mid_c=(min_c + max_c)/2.0);
215 for (i=0; i < 50; i++)
216 {
217 if (diff > 0)
218 min_c=mid_c;
219 else
220 max_c=mid_c;
221 if ((fabs(diff=BridgeDifference(proposal,posterior,mid_c=(min_c + max_c)/2.0)) < TOL)) break;
222 }
223 return mid_c;
224 }
225 #undef MAX_C
226 #undef TOL
227 /*******************************************************************************/
228 /*******************************************************************************/
229 /*******************************************************************************/
230
231 /*******************************************************************************/
232 /************ Mueller's method for computing marginal data density *************/
233 /*******************************************************************************/
234 #define MAX_C 1E50
235 static PRECISION ComputeLinear(TMatrix proposal, PRECISION log_c, int *intercept)
236 {
237 int i;
238 PRECISION slope=0.0, tmp;
239 for (*intercept=0, i=RowM(proposal)-1; i >= 0; i--)
240 if (log_c <= (tmp=ElementM(proposal,i,0) - ElementM(proposal,i,1)))
241 {
242 (*intercept)++;
243 slope+=exp(log_c-tmp);
244 }
245 return slope;
246 }
247 static PRECISION ComputeInverseLinear(TMatrix posterior, PRECISION log_c, int *intercept)
248 {
249 int i;
250 PRECISION slope=0.0, tmp;
251 for (*intercept=0, i=RowM(posterior)-1; i >= 0; i--)
252 if (log_c >= (tmp=ElementM(posterior,i,0)-ElementM(posterior,i,1)))
253 {
254 (*intercept)++;
255 slope+=exp(tmp-log_c);
256 }
257 return slope;
258 }
259 PRECISION ComputeLogMarginalDensity_Mueller(TMatrix proposal, TMatrix posterior,int *in1, int *in2)
260 {
261 PRECISION log_c=0.0, slope1, slope2, N1=1.0/(PRECISION)RowM(proposal), N2=1.0/(PRECISION)RowM(posterior),
262 intercept1, intercept2, max_log_c, min_log_c, diff, tmp;
263 int min_in1, max_in1, min_in2, max_in2;
264
265 slope1=ComputeLinear(proposal,log_c,in1);
266 slope2=ComputeInverseLinear(posterior,log_c,in2);
267 diff=N1*((PRECISION)(*in1) - slope1) - N2*((PRECISION)(*in2) - slope2);
268
269 // Bracket the intersection
270 if (diff < 0.0)
271 {
272 do
273 if (log_c < -MAX_C)
274 return log_c;
275 else
276 {
277 max_in1=*in1;
278 max_in2=*in2;
279 max_log_c=log_c;
280 log_c=10*(log_c-1);
281 slope1=ComputeLinear(proposal,log_c,in1);
282 slope2=ComputeInverseLinear(posterior,log_c,in2);
283 diff=N1*((PRECISION)(*in1) - slope1) - N2*((PRECISION)(*in2) - slope2);
284 }
285 while (diff < 0.0);
286 min_in1=*in1;
287 min_in2=*in2;
288 min_log_c=log_c;
289 }
290 else
291 {
292 do
293 if (log_c > MAX_C)
294 return log_c;
295 else
296 {
297 min_in1=*in1;
298 min_in2=*in2;
299 min_log_c=log_c;
300 log_c=10*(log_c+1);
301 slope1=ComputeLinear(proposal,log_c,in1);
302 slope2=ComputeInverseLinear(posterior,log_c,in2);
303 diff=N1*((PRECISION)(*in1) - slope1) - N2*((PRECISION)(*in2) - slope2);
304 }
305 while (diff >= 0.0);
306 max_in1=*in1;
307 max_in2=*in2;
308 max_log_c=log_c;
309 }
310
311 // At this point diff(min_log_c) >= 0 and diff(max_log_c) < 0.
312 while ((min_in1 != max_in1) || (min_in2 != max_in2))
313 {
314 log_c=(min_log_c + max_log_c)/2.0;
315 slope1=ComputeLinear(proposal,log_c,in1);
316 slope2=ComputeInverseLinear(posterior,log_c,in2);
317 diff=N1*((PRECISION)(*in1) - slope1) - N2*((PRECISION)(*in2) - slope2);
318 if (diff > 0)
319 {
320 min_in1=*in1;
321 min_in2=*in2;
322 min_log_c=log_c;
323 }
324 else
325 {
326 max_in1=*in1;
327 max_in2=*in2;
328 max_log_c=log_c;
329 }
330 }
331
332 slope1=N1*ComputeLinear(proposal,min_log_c,in1);
333 intercept1=N1*(PRECISION)(*in1);
334 slope2=N2*ComputeInverseLinear(posterior,min_log_c,in2);
335 intercept2=N2*(PRECISION)(*in2);
336
337 tmp=intercept1-intercept2;
338 if (slope1 > 0)
339 {
340 tmp+=sqrt(tmp*tmp + 4*slope1*slope2);
341 if (tmp >= 2.0*slope1)
342 tmp=min_log_c + log(tmp) - log(2.0*slope1);
343 else
344 return -min_log_c;
345 }
346 else
347 {
348 if (tmp > 0)
349 if (slope2 > tmp)
350 tmp=min_log_c + log(slope2) - log(tmp);
351 else
352 return -min_log_c;
353 else
354 return -max_log_c;
355 }
356 return (tmp > max_log_c) ? -max_log_c : -tmp;
357 }
358 #undef MAX_C
359 /*******************************************************************************/
360 /*******************************************************************************/
361 /*******************************************************************************/
362
363
364 /*******************************************************************************/
365 /* Read/interpret posterior draws and setup elliptical/Dirichlet distributions */
366 /*******************************************************************************/
367 /*
368 Assumes the file has 2 + ntheta + nq columns. The data is arranged as:
369
370 posterior likelihood theta q
371
372 (1) Loops through posterior draws computing first and second moments of theta,
373 the mode of the posterior and the first and second moments of each
374 individual element of q
375
376 (2) Sets the value of the center and scale dependent on the value of flag.
377 The center will be either the mode or mean of theta and the scale will
378 satisfy scale*scale'=E[(theta-center)(theta-center)'].
379
380 (3) Sets the values of alpha.
381
382 The vector center, the matrix scale, and array alpha must be properly allocated of
383 the proper size.
384
385 If 0 < percentage_draws < 1 then the first percentage_draws of the posterior draws
386 are used to the center, the scale, and alpha. If -1 < percentage_draws < 0, then
387 the last (1 - percentage_draws) are used to compute the center, the scale and alpha.
388 Otherwise, all the draws are used.
389 */
390 void PosteriorDistributionInfo(FILE *f_in, int flag, TVector center, TMatrix scale,
391 PRECISION *alpha, int *dirichlet_dims, PRECISION alpha_scale, int ndraws)
392 {
393 int i, j, k, n, p, ntheta, nq, n_dirichlet, ntotal;
394 TVector theta=(TVector)NULL, theta_sum=(TVector)NULL, b=(TVector)NULL, b_sum=(TVector)NULL,
395 b_square=(TVector)NULL, theta_mode=(TVector)NULL;
396 TMatrix theta_square=(TMatrix)NULL, theta_square_tmp=(TMatrix)NULL, quadratic_form=(TMatrix)NULL;
397 PRECISION max=MINUS_INFINITY, inc, tmp, sum, *x;
398
399 // set dimensions and allocate memory
400 ntheta=center ? DimV(center) : 0;
401 n_dirichlet=dirichlet_dims ? dw_DimA(dirichlet_dims) : 0;
402 for (i=nq=0; i < n_dirichlet; i++) nq+=dirichlet_dims[i]-1;
403 ntotal=2+ntheta+nq;
404
405 if (ntheta > 0)
406 {
407 theta=CreateVector(ntheta);
408 InitializeVector(theta_sum=CreateVector(ntheta),0.0);
409 InitializeMatrix(theta_square=CreateMatrix(ntheta,ntheta),0.0);
410 theta_square_tmp=CreateMatrix(ntheta,ntheta);
411 theta_mode=CreateVector(ntheta);
412 quadratic_form=CreateMatrix(ntheta,ntheta);
413 }
414
415 if (nq > 0)
416 {
417 b=CreateVector(nq+n_dirichlet);
418 b_sum=InitializeVector(CreateVector(nq+n_dirichlet),0.0);
419 b_square=InitializeVector(CreateVector(nq+n_dirichlet),0.0);
420 }
421
422 // loop and accumulate 1st and 2nd non-central moments and posterior mode
423 for (i=0; i < ndraws; i++)
424 {
425 x=dw_ReadDelimitedLine_floating(f_in,' ',REMOVE_EMPTY_FIELDS,MINUS_INFINITY);
426 if (!x || (dw_DimA(x) != ntotal))
427 {
428 printf("Error reading posterior file\n");
429 dw_exit(0);
430 }
431 if (ntheta > 0)
432 {
433 memcpy(pElementV(theta),x+2,ntheta*sizeof(PRECISION));
434 if (x[0] > max)
435 {
436 max=x[0];
437 EquateVector(theta_mode,theta);
438 }
439 AddVV(theta_sum,theta_sum,theta);
440 OuterProduct(theta_square_tmp,theta,theta);
441 AddMM(theta_square,theta_square,theta_square_tmp);
442 }
443
444 if (nq > 0)
445 {
446 for (n=2+ntheta, j=k=0; j < n_dirichlet; k+=dirichlet_dims[j], n+=dirichlet_dims[j]-1, j++)
447 {
448 memcpy(pElementV(b)+k,x+n,(dirichlet_dims[j]-1)*sizeof(PRECISION));
449 for (sum=1.0, p=dirichlet_dims[j]-2; p >= 0; p--)
450 sum-=ElementV(b,k+p);
451 ElementV(b,k+dirichlet_dims[j]-1)=(sum > 0.0) ? sum : 0.0;
452 }
453 AddVV(b_sum,b_sum,b);
454 for (p=DimV(b)-1; p >= 0; p--)
455 ElementV(b_square,p)+=ElementV(b,p)*ElementV(b,p);
456 }
457
458 dw_FreeArray(x);
459 }
460
461 if (ntheta > 0)
462 {
463 // scale 1st and 2nd non-central moments
464 ProductVS(theta_sum,theta_sum,1.0/(PRECISION)ndraws);
465 ProductMS(theta_square,theta_square,1.0/(PRECISION)ndraws);
466
467 // set center and scale using flag
468 if (flag & USE_MODE)
469 {
470 EquateVector(center,theta_mode);
471 OuterProduct(theta_square_tmp,theta_mode,theta_mode);
472 AddMM(theta_square,theta_square,theta_square_tmp);
473 OuterProduct(theta_square_tmp,theta_sum,theta_mode);
474 SubtractMM(theta_square,theta_square,theta_square_tmp);
475 OuterProduct(theta_square_tmp,theta_mode,theta_sum);
476 SubtractMM(theta_square,theta_square,theta_square_tmp);
477 CholeskyLT(scale,theta_square);
478 Transpose(scale,scale);
479 }
480 else
481 {
482 EquateVector(center,theta_sum);
483 OuterProduct(theta_square_tmp,theta_sum,theta_sum);
484 SubtractMM(theta_square,theta_square,theta_square_tmp);
485 CholeskyLT(scale,theta_square);
486 Transpose(scale,scale);
487 }
488 }
489
490 // compute alpha
491 if (nq > 0)
492 {
493 // scale 1st and 2nd non-central moments
494 ProductVS(b_sum,b_sum,1.0/(PRECISION)ndraws);
495 ProductVS(b_square,b,1.0/(PRECISION)ndraws);
496
497 // compute alpha
498 for (k=i=0; k < n_dirichlet; i+=dirichlet_dims[k], k++)
499 {
500 for (max=0.0, j=dirichlet_dims[k]-1; j >= 0; j--)
501 if ((tmp=ElementV(b_sum,i+j)*(1.0-ElementV(b_sum,i+j))
502 /(ElementV(b_square,i+j) - ElementV(b_sum,i+j)*ElementV(b_sum,i+j))) > max) max=tmp;
503 max-=1.0;
504 for (inc=0.0, j=dirichlet_dims[k]-1; j >= 0; j--)
505 if ((tmp=1.1 - max*ElementV(b_sum,i+j)) > inc) inc=tmp;
506 for (j=dirichlet_dims[k]-1; j >= 0; j--)
507 alpha[i+j]=alpha_scale*max*ElementV(b_sum,i+j)+inc;
508 }
509 }
510 else
511 if (n_dirichlet > 0)
512 for (i=0; i < n_dirichlet; i++) alpha[i]=0.0;
513
514 if (ntheta > 0)
515 {
516 FreeVector(theta);
517 FreeVector(theta_sum);
518 FreeMatrix(theta_square);
519 FreeMatrix(theta_square_tmp);
520 FreeVector(theta_mode);
521 FreeMatrix(quadratic_form);
522 }
523 if (nq > 0)
524 {
525 FreeVector(b);
526 FreeVector(b_sum);
527 FreeVector(b_square);
528 }
529 }
530
531 /*
532 Assumes the file has 2 + ntheta + nq columns. The data is arranged as:
533
534 posterior likelihood theta q
535
536 Creates and returns a vector containing the radius of each draw of theta,
537 computed used the center and scale.
538 */
539 TVector PosteriorRadius(FILE *f_in, TVector center, TMatrix scale, int ndraws)
540 {
541 int i, ntheta, ntotal;
542 TVector theta, Radii=(TVector)NULL;
543 TMatrix quadratic_form;
544 PRECISION *x;
545
546 ntheta=center ? DimV(center) : 0;
547 ntotal=ntheta+2;
548
549 if (ntheta > 0)
550 {
551 theta=CreateVector(ntheta);
552 quadratic_form=CreateMatrix(ntheta,ntheta);
553
554 Radii=CreateVector(ndraws);
555 quadratic_form=ProductTransposeMM((TMatrix)NULL,scale,scale);
556 Inverse_LU(quadratic_form,quadratic_form);
557 ForceSymmetric(quadratic_form);
558
559 for (i=0; i < ndraws; i++)
560 {
561 x=dw_ReadDelimitedLine_floating(f_in,' ',REMOVE_EMPTY_FIELDS,MINUS_INFINITY);
562 if (!x || (dw_DimA(x) < ntotal))
563 {
564 printf("Error reading posterior file\n");
565 dw_exit(0);
566 }
567 memcpy(pElementV(theta),x+2,ntheta*sizeof(PRECISION));
568 SubtractVV(theta,theta,center);
569 ElementV(Radii,i)=sqrt(InnerProduct(theta,theta,quadratic_form));
570 dw_FreeArray(x);
571 }
572
573 FreeVector(theta);
574 FreeMatrix(quadratic_form);
575 }
576
577 return Radii;
578 }
579
580 TElliptical* CreateEllipticalFromPosterior_TruncatedGaussian(TVector R, int dim, TVector center, TMatrix scale,
581 PRECISION p_lo, PRECISION p_hi)
582 {
583 TElliptical *elliptical=(TElliptical*)NULL;
584 PRECISION a, b;
585 TMatrix V;
586 int i;
587
588 if (dim > 0)
589 {
590 SortVectorAscending(R,R);
591
592 i=floor(p_lo*(PRECISION)(DimV(R)-1));
593 a=(i < DimV(R)-1) ? 0.5*(ElementV(R,i+1) + ElementV(R,i)) : ElementV(R,i);
594 i=floor(p_hi*(PRECISION)(DimV(R)-1));
595 b=(i < DimV(R)-1) ? 0.5*(ElementV(R,i+1) + ElementV(R,i)) : ElementV(R,i);
596
597 V=ProductTransposeMM((TMatrix)NULL,scale,scale);
598 elliptical=CreateElliptical_TruncatedGaussian(dim,center,V,a,b);
599 FreeMatrix(V);
600 }
601
602 return elliptical;
603 }
604
605 TElliptical* CreateEllipticalFromPosterior_Gaussian(__attribute__ ((unused)) TVector R, int dim, TVector center, TMatrix scale)
606 {
607 TElliptical *elliptical=(TElliptical*)NULL;
608 TMatrix variance;
609 if (dim > 0)
610 {
611 elliptical=CreateElliptical_Gaussian(dim,center,variance=ProductTransposeMM((TMatrix)NULL,scale,scale));
612 FreeMatrix(variance);
613 }
614 return elliptical;
615 }
616
617 static PRECISION GetPower_truncatedpower(int dim, PRECISION lower_bound, PRECISION upper_bound)
618 {
619 PRECISION lo=0.0001, hi=1.0, mid;
620 int i;
621 if (VarianceScale_TruncatedPower(dim,lower_bound,upper_bound,lo) > 1.0)
622 return lo;
623 for (i=0; i < 20; i++)
624 if (VarianceScale_TruncatedPower(dim,lower_bound,upper_bound,hi) < 1.0)
625 {
626 lo=hi;
627 hi*=2.0;
628 }
629 else
630 {
631 for (i=0; i < 30; i++)
632 {
633 mid=0.5*(lo+hi);
634 if (VarianceScale_TruncatedPower(dim,lower_bound,upper_bound,mid) < 1.0)
635 lo=mid;
636 else
637 hi=mid;
638 }
639 return mid;
640 }
641 return hi;
642 }
643
644 TElliptical* CreateEllipticalFromPosterior_TruncatedPower(TVector R, int dim, TVector center, TMatrix scale,
645 PRECISION p_lo, PRECISION p_hi)
646 {
647 TElliptical *elliptical=(TElliptical*)NULL;
648 PRECISION a, b, power;
649 int i;
650
651 if (dim > 0)
652 {
653 SortVectorAscending(R,R);
654
655 i=floor(p_lo*(PRECISION)(DimV(R)-1));
656 a=(i < DimV(R)-1) ? 0.5*(ElementV(R,i+1) + ElementV(R,i)) : ElementV(R,i);
657 i=floor(p_hi*(PRECISION)(DimV(R)-1));
658 b=(i < DimV(R)-1) ? 0.5*(ElementV(R,i+1) + ElementV(R,i)) : ElementV(R,i);
659 power=GetPower_truncatedpower(dim,a,b);
660
661 // The code below uses the old method to choosing the power and b. The new
662 // method chooses the power by trying to match the scale of the variance.
663 /* i=floor(0.10*(PRECISION)DimV(R)); */
664 /* a=(i > 0) ? 0.5*(sqrt(ElementV(R,i-1)) + sqrt(ElementV(R,i))) : sqrt(ElementV(R,i)); */
665 /* i=floor(0.90*(PRECISION)DimV(R)); */
666 /* b=(i > 0) ? 0.5*(sqrt(ElementV(R,i-1)) + sqrt(ElementV(R,i))) : sqrt(ElementV(R,i)); */
667 /* power=log(0.10/0.90)/log(a/b); */
668 /* b/=pow(0.90,1/power); */
669 /* i=floor(0.10*(PRECISION)DimV(R)); */
670 /* a=(i > 0) ? 0.5*(ElementV(R,i-1) + ElementV(R,i)) : ElementV(R,i); */
671 /* i=floor(0.90*(PRECISION)DimV(R)); */
672 /* b=(i > 0) ? 0.5*(ElementV(R,i-1) + ElementV(R,i)) : ElementV(R,i); */
673 /* power=log(0.10/0.90)/log(a/b); */
674 /* b/=pow(0.90,1/power); */
675
676 elliptical=CreateElliptical_TruncatedPower(dim,center,scale,a,b,power);
677 }
678
679 return elliptical;
680 }
681
682 TElliptical* CreateEllipticalFromPosterior_Power(TVector R, int dim, TVector center, TMatrix scale, PRECISION p_hi)
683 {
684 TElliptical *elliptical=(TElliptical*)NULL;
685 PRECISION b, power;
686 int i;
687
688 if (dim > 0)
689 {
690 SortVectorAscending(R,R);
691
692 i=floor(p_hi*(PRECISION)(DimV(R)-1));
693 b=(i < DimV(R)-1) ? 0.5*(ElementV(R,i+1) + ElementV(R,i)) : ElementV(R,i);
694 power=GetPower_truncatedpower(dim,0.0,b);
695
696 // The code below uses the old method to choosing the power and b. The new
697 // method chooses the power by trying to match the scale of the variance.
698 /* i=floor(0.20*(PRECISION)DimV(R)); */
699 /* PRECISION a = (i > 0) ? 0.5*(sqrt(ElementV(R,i-1)) + sqrt(ElementV(R,i))) : sqrt(ElementV(R,i)); */
700 /* i=floor(0.80*(PRECISION)DimV(R)); */
701 /* b=(i > 0) ? 0.5*(sqrt(ElementV(R,i-1)) + sqrt(ElementV(R,i))) : sqrt(ElementV(R,i)); */
702 /* power=log(0.20/0.80)/log(a/b); */
703 /* b/=pow(0.80,1/power); */
704 /* i=floor(0.20*(PRECISION)DimV(R)); */
705 /* PRECISION a = (i > 0) ? 0.5*(ElementV(R,i-1) + ElementV(R,i)) : ElementV(R,i); */
706 /* i=floor(0.80*(PRECISION)DimV(R)); */
707 /* b=(i > 0) ? 0.5*(ElementV(R,i-1) + ElementV(R,i)) : ElementV(R,i); */
708 /* power=log(0.20/0.80)/log(a/b); */
709 /* b/=pow(0.80,1/power); */
710
711 elliptical=CreateElliptical_Power(dim,center,scale,b,power);
712 }
713
714 return elliptical;
715 }
716
717 TElliptical* CreateEllipticalFromPosterior_Uniform(TVector R, int dim, TVector center, TMatrix scale, PRECISION p_lo, PRECISION p_hi)
718 {
719 TElliptical *elliptical=(TElliptical*)NULL;
720 PRECISION a, b;
721 int i;
722
723 if (dim > 0)
724 {
725 SortVectorAscending(R,R);
726
727 i=floor(p_lo*(PRECISION)(DimV(R)-1));
728 a=(i < DimV(R)-1) ? 0.5*(ElementV(R,i+1) + ElementV(R,i)) : ElementV(R,i);
729 i=floor(p_hi*(PRECISION)(DimV(R)-1));
730 b=(i < DimV(R)-1) ? 0.5*(ElementV(R,i+1) + ElementV(R,i)) : ElementV(R,i);
731
732 elliptical=CreateElliptical_Uniform(dim,center,scale,a,b);
733 }
734
735 return elliptical;
736 }
737
738 TElliptical* CreateEllipticalFromPosterior_Step(TVector R, int dim, TVector center, TMatrix scale, PRECISION p_lo, PRECISION p_hi)
739 {
740 TElliptical *elliptical=(TElliptical*)NULL;
741 PRECISION *table, inc, x, y;
742 int i, j, k, m=30;
743
744 if (dim > 0)
745 {
746 table=(PRECISION*)dw_malloc((m+1)*sizeof(PRECISION));
747
748 SortVectorAscending(R,R);
749
750 for (k=m; k >= 1; k--)
751 {
752 inc=(p_hi-p_lo)/(PRECISION)k;
753 for (x=p_lo, j=0; j <= k; x+=inc, j++)
754 {
755 i=floor(y=x*(PRECISION)(DimV(R)-1));
756 if (i >= DimV(R)-1)
757 table[j]=ElementV(R,DimV(R)-1);
758 else
759 table[j]=(1.0-y+i)*ElementV(R,i) + (y-i)*ElementV(R,i+1);
760 //table[j]=(i > 0) ? 0.5*(ElementV(R,i-1) + ElementV(R,i)) : ElementV(R,i);
761 }
762 for (j=1; j <= k; j++)
763 if (table[j] <= table[j-1]) break;
764 if (j > k) break;
765 }
766
767 if (k <= 0)
768 {
769 dw_free(table);
770 printf("Not enough variation in the posterior draws to form proposal\n");
771 dw_exit(0);
772 }
773
774 elliptical=CreateElliptical_Step(dim,center,scale,table,k);
775 dw_free(table);
776 }
777
778 return elliptical;
779 }
780 /*******************************************************************************/
781 /*******************************************************************************/
782
783
784 /*******************************************************************************/
785 /*********** Create proposal and posterior matrices of log densities ***********/
786 /*******************************************************************************/
787 /*
788 Assumes:
789 ndraws : Number of draws from proposal to create
790 model : Valid pointer to TStateModel structure
791 elliptical : Valid pointer to TElliptical structure
792 alpha : Array of parameters for the independent Dirichlet
793 distributions.
794 dirichlet_dims : integer array of dimensions of the independent Dirichlet
795 distributions.
796
797 Results:
798 Draws theta from the elliptical distribution and q from independent
799 Dirichlet distributions. Computes the log density, properly scaled, of the
800 proposal distribution and stores this in the first column of proposal.
801 Computes the log posterior (likelihood times prior) with the states
802 integerated out, and stores this in the second column of proposal.
803
804 Notes:
805 The integer array dirichlet_dims should be created with the routine
806 CreateDirichletDimensions().
807 */
808 TMatrix CreateProposal(int ndraws, TStateModel* model, TElliptical *elliptical, PRECISION* alpha, int *dirichlet_dims)
809 {
810 TMatrix proposal;
811 PRECISION logdensity, *q=(PRECISION*)NULL, *theta=(PRECISION*)NULL;
812 int i, ntheta, nq, n_dirichlet, period, count;
813
814 if (ndraws <= 0) return (TMatrix)NULL;
815
816 // create proposal
817 proposal=CreateMatrix(ndraws,2);
818
819 // set dimensions and allocate memory
820 ntheta=elliptical ? elliptical->dim : 0;
821 n_dirichlet=dirichlet_dims ? dw_DimA(dirichlet_dims) : 0;
822 for (i=nq=0; i < n_dirichlet; i++) nq+=dirichlet_dims[i]-1;
823 if (ntheta) theta=(PRECISION*)dw_malloc(ntheta*sizeof(PRECISION));
824 if (nq) q=(PRECISION*)dw_malloc(nq*sizeof(PRECISION));
825
826 period=ndraws/50;
827 for (count=period, i=0; i < ndraws; i++)
828 {
829 // draw theta from elliptical and compute log density
830 logdensity=(theta) ? LogDensityElliptical_Radius(DrawElliptical(theta,elliptical),elliptical) : 0.0;
831
832 // draw q from Dirichet and compute log density
833 if (q)
834 {
835 DrawIndependentDirichlet_free(q,alpha,dirichlet_dims,n_dirichlet);
836 logdensity+=LogIndependentDirichlet_pdf(q,alpha,dirichlet_dims,n_dirichlet);
837 }
838
839 // store log density of proposal
840 ElementM(proposal,i,0)=logdensity;
841
842 // force free parameters into model and store log density of posterior
843 if (theta) ConvertFreeParametersToTheta(model,theta);
844 if (q) ConvertFreeParametersToQ(model,q);
845 ElementM(proposal,i,1)=LogPosterior_StatesIntegratedOut(model); //printf("%le\n",ElementM(proposal,i,1));
846
847 // Output status
848 if (i == count)
849 {
850 printf("%d draws out of %d\n",count,ndraws);
851 count+=period;
852 #ifdef OCTAVE_MEX_FILE
853 OCTAVE_QUIT;
854 #elif defined(MATLAB_MEX_FILE)
855 if (utIsInterruptPending())
856 {
857 mexPrintf("\n\n** Ctrl-C detected, quitting...\n");
858 dw_exit(0);
859 }
860 #endif
861 }
862 }
863
864 // clean up
865 if (theta) dw_free(theta);
866 if (q) dw_free(q);
867
868 return proposal;
869 }
870
871 /*
872 Assumes:
873 Posterior file has at least ndraws rows and 2+ntheta+nq columns
874 Column 0 = log posterior density of (theta,q).
875 Column 1 = log likelihood of (theta,q).
876 Columns 2 : 1+ntheta = theta.
877 Columns 2+ntheta : 1+ntheta+nq = q.
878
879 Returns:
880 ndraws x 2 matrix. The first column is the log of the proposal density of the
881 posterior draw and the second column is the log of the posterior density of
882 the posterior draw.
883
884 Notes:
885 The parameters are theta and q. The proposal density is independent across
886 these with independent Dirichlet distributions on q and an elliptical
887 density on theta.
888 */
889 TMatrix CreatePosterior(FILE *f_in, TElliptical *elliptical, PRECISION* alpha, int *dirichlet_dims, int ndraws)
890 {
891 int i, ntheta, nq, n_dirichlet, ntotal;
892 PRECISION logdensity, *x;
893 TMatrix posterior;
894
895 // set dimensions and allocate memory
896 posterior=CreateMatrix(ndraws,2);
897 ntheta=elliptical ? elliptical->dim : 0;
898 n_dirichlet=dirichlet_dims ? dw_DimA(dirichlet_dims) : 0;
899 for (i=nq=0; i < n_dirichlet; i++) nq+=dirichlet_dims[i]-1;
900 ntotal=2+ntheta+nq;
901
902 for (i=0; i < ndraws; i++)
903 {
904 x=dw_ReadDelimitedLine_floating(f_in,' ',REMOVE_EMPTY_FIELDS,MINUS_INFINITY);
905 if (!x || (dw_DimA(x) < ntotal))
906 {
907 printf("Error reading posterior file\n");
908 dw_exit(0);
909 }
910 logdensity=(ntheta > 0) ? LogDensityElliptical_Draw(x+2,elliptical) : 0.0;
911 if (nq > 0) logdensity+=LogIndependentDirichlet_pdf(x+2+ntheta,alpha,dirichlet_dims,n_dirichlet);
912 ElementM(posterior,i,0)=logdensity;
913 ElementM(posterior,i,1)=x[0];
914 dw_FreeArray(x);
915 }
916
917 return posterior;
918 }
919
920 int ModifyUsingSWZ(TMatrix *modified_proposal, TMatrix *modified_posterior, TMatrix proposal, TMatrix posterior, PRECISION cut)
921 {
922 int i, j, count;
923 PRECISION log_p;
924
925 // Number proposal satisfying cut
926 for (count=0, i=RowM(proposal)-1; i >= 0; i--)
927 if (ElementM(proposal,i,1) >= cut) count++;
928
929 // Abort if none satisfy
930 if (count == 0) return 0;
931
932 // Compute log probability of proposal satisfying cut
933 log_p=log((PRECISION)count/(PRECISION)RowM(proposal));
934
935 // Create matrices if necessary
936 if (!(*modified_proposal) || (RowM(*modified_proposal) != count))
937 {
938 if (*modified_proposal) FreeMatrix(*modified_proposal);
939 *modified_proposal=CreateMatrix(count,2);
940 }
941 if (!(*modified_posterior) || (RowM(*modified_posterior) != RowM(posterior)))
942 {
943 if (*modified_posterior) FreeMatrix(*modified_posterior);
944 *modified_posterior=CreateMatrix(RowM(posterior),2);
945 }
946
947 // Set modified posterior
948 for (i=RowM(posterior)-1; i >= 0; i--)
949 {
950 if (ElementM(posterior,i,1) > cut)
951 ElementM(*modified_posterior,i,0)=ElementM(posterior,i,0)-log_p;
952 else
953 ElementM(*modified_posterior,i,0)=MINUS_INFINITY;
954 ElementM(*modified_posterior,i,1)=ElementM(posterior,i,1);
955 }
956
957 // Set modified proposal
958 for (i=j=0; i < RowM(proposal); i++)
959 if (ElementM(proposal,i,1) >= cut)
960 {
961 ElementM(*modified_proposal,j,0)=ElementM(proposal,i,0)-log_p;
962 ElementM(*modified_proposal,j,1)=ElementM(proposal,i,1);
963 }
964
965 // Return number satisfing cut
966 return count;
967 }
968 /*******************************************************************************/
969 /*******************************************************************************/
970 /*******************************************************************************/
971
972
973 /*******************************************************************************/
974 /************************ Setup Dirichlet distributions ************************/
975 /*******************************************************************************/
976 /*
977 Creates integer array that give the size of the Dirichet random variables
978 in q.
979 */
980 static int sv_NumberDirichletDistributions(TMarkovStateVariable *sv)
981 {
982 int i, n_dirichlet;
983 if (sv->n_state_variables > 0)
984 {
985 for (i=n_dirichlet=0; i < sv->n_state_variables; i++)
986 n_dirichlet+=sv_NumberDirichletDistributions(sv->state_variable[i]);
987 return n_dirichlet;
988 }
989 else
990 return dw_DimA(((TDirichletRestrictions*)(sv->info))->DirichletDim);
991 }
992 static int* sv_DirichletDimensions(int *dirichlet_dims, TMarkovStateVariable *sv)
993 {
994 int i, n;
995 if (sv->n_state_variables > 0)
996 for (i=0; i < sv->n_state_variables; i++)
997 dirichlet_dims=sv_DirichletDimensions(dirichlet_dims,sv->state_variable[i]);
998 else
999 {
1000 n=dw_DimA(((TDirichletRestrictions*)(sv->info))->DirichletDim);
1001 memcpy(dirichlet_dims,((TDirichletRestrictions*)(sv->info))->DirichletDim,n*sizeof(int));
1002 dirichlet_dims+=n;
1003 }
1004 return dirichlet_dims;
1005 }
1006 int* CreateDirichletDimensions(TStateModel* model)
1007 {
1008 int n_dirichlet=sv_NumberDirichletDistributions(model->sv);
1009 int *dirichlet_dims=(n_dirichlet > 0) ? dw_CreateArray_int(n_dirichlet) : (int*)NULL;
1010 sv_DirichletDimensions(dirichlet_dims,model->sv);
1011 return dirichlet_dims;
1012 }
1013 /*******************************************************************************/
1014 /*******************************************************************************/
1015 /*******************************************************************************/
1016
1017
1018 /*******************************************************************************/
1019 /****************************** Elliptical plots *******************************/
1020 /*******************************************************************************/
1021 void GraphCummulativeDensities(FILE *f, char* filename, TVector R, TElliptical *elliptical)
1022 {
1023 PRECISION min, max, inc, r;
1024 int d=100, i, j, k=DimV(R), count=50000, n;
1025 TVector v;
1026 FILE *f_out;
1027
1028 if ((f_out=f ? f : fopen(filename,"wt")))
1029 {
1030 SortVectorAscending(R,R);
1031 min=ElementV(R,0);
1032 max=ElementV(R,k-1);
1033 inc=(max-min)/(PRECISION)(d-1);
1034
1035 fprintf(f_out,"radius,posterior,proposal\n");
1036 if (elliptical->cummulative_radius)
1037 for (r=min, i=j=0; j < d; r+=inc, j++)
1038 {
1039 for ( ; i < k; i++)
1040 if (ElementV(R,i) >= r) break;
1041 fprintf(f_out,"%lf,%lf,%lf\n",r,(double)i/(double)k,CummulativeDensityElliptical_Radius(r,elliptical));
1042 }
1043 else
1044 {
1045 // Simulate from elliptical
1046 v=CreateVector(count);
1047 for (i=0; i < count; i++) ElementV(v,i)=DrawElliptical((PRECISION*)NULL,elliptical);
1048 SortVectorAscending(v,v);
1049
1050 for (r=min, n=i=j=0; j < d; r+=inc, j++)
1051 {
1052 for ( ; i < k; i++)
1053 if (ElementV(R,i) >= r) break;
1054 for ( ; n < count; n++)
1055 if (ElementV(v,n) >= r) break;
1056 fprintf(f_out,"%lf,%lf,%lf\n",r,(double)i/(double)k,(double)n/(double)count);
1057 }
1058
1059 FreeVector(v);
1060 }
1061
1062 if (!f) fclose(f_out);
1063 }
1064 else
1065 printf("Unable to open %s\n",filename);
1066 }
1067
1068 /*******************************************************************************/
1069 /*******************************************************************************/
1070 /*******************************************************************************/
1071 /*
1072 Computes marginal data density from posterior draws. Returns one upon success
1073 zero upon failure.
1074
1075 Command line parameters
1076 -t
1077 filename tag
1078 -ft
1079 filename tag -- supersedes -t
1080 -outtag
1081 filename tag -- supersedes -t and -ft
1082 -pf
1083 posterior draws filename (default = simulation_<tag>.out)
1084 -pt
1085 proposal type (1=gaussian, 2=power, 3=truncated power (default), 4=step, 5=truncated gaussian, 6=uniform)
1086 -d
1087 number proposal draws (default = 100,000)
1088 -ndraws
1089 number proposal draws. Superseeds -d. (default = 100,000)
1090 -mode
1091 use posterior mode as center (default = mode)
1092 -mean
1093 use posterior mean as center (default = mode)
1094 -of
1095 output filename (default = mdd_t<proposal type>_<tag>.out)
1096 -l
1097 Lower cutoff for in terms of probability. Used by truncated power, truncated gaussian, step,
1098 and uniform. (default=0.1)
1099 -h
1100 Upper cutoff for in terms of probability. Used by power, truncated power, truncated gaussian
1101 step, and uniform. (default=0.9)
1102 -graph
1103 Produce output suitable for graphing the marginal cummulative densities of the radius of the
1104 posterior and elliptical distributions. The marginal data density is not computed.
1105 -print
1106 Prints the matrices posterior and proposal
1107 -append
1108 Appends proposal draws to those previously made. If the posterior draws have changed in any
1109 way, then this option must not be used. The filename for the proposal draws is
1110 proposal_t<proposal type>_<tag>.out.
1111 -percentage_draws
1112 If between 0 and 1, the first percentage_draws of the posterior draws are used to compute the
1113 center, scale and alpha and the last (1-percentage_draws) of the posterior draws are used to
1114 compute the marginal data density. (default=0.20)
1115 */
1116 int dw_marginal_data_density_command_line(int nargs, char **args, TStateModel *model, int generator_init)
1117 {
1118 TMatrix scale=(TMatrix)NULL, proposal=(TMatrix)NULL, posterior=(TMatrix)NULL, new_proposal, s_proposal, s_posterior;
1119 TVector center=(TVector)NULL, R=(TVector)NULL; /*cuts=(TVector)NULL, cuts1=(TVector)NULL;*/
1120 char *filename=(char*)NULL, *tag, *out_filename, *fmt;
1121 int i, j, ntheta=NumberFreeParametersTheta(model), nq=NumberFreeParametersQ(model), flag, *dirichlet_dims=(int*)NULL,
1122 proposal_type, ndraws_proposal, /*n_cuts=10,*/ in_P1, in_P2, rtrn=0, ndraws_posterior, ndraws_info,
1123 begin_time, end_time, cuts[9]={1000,500,100,50,40,30,20,10,1};
1124 PRECISION alpha_scale=1.5, *alpha=(PRECISION*)NULL, mdd, p_lo, p_hi, **proposal_previous, I, percentage_draws, x;
1125 TElliptical *elliptical=(TElliptical*)NULL;
1126 FILE *f_out, *f_in;
1127
1128 // Initial generator - pass 0 to initialize from clock
1129 dw_initialize_generator(generator_init);
1130
1131 // Get tag from command line
1132 tag=dw_ParseString(nargs,args,'t',"notag");
1133 tag=dw_ParseString_String(nargs,args,"ft",tag);
1134 tag=dw_ParseString_String(nargs,args,"outtag",tag);
1135
1136 // timings
1137 begin_time=time((time_t*)NULL);
1138
1139 // Posterior draws file
1140 printf("Processing posterior draws\n");
1141 if ((filename=dw_ParseString_String(nargs,args,"pf",(char*)NULL)))
1142 {
1143 if (!(f_in=fopen(filename,"rt")))
1144 {
1145 printf("ComputeMarginalDataDensity_command_line(): Unable to open %s\n",filename);
1146 return 0;
1147 }
1148 }
1149 else
1150 {
1151 fmt="simulation_%s.out";
1152 sprintf(filename=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,tag);
1153 if (!(f_in=fopen(filename,"rt")))
1154 {
1155 printf("ComputeMarginalDataDensity_command_line(): Unable to open %s\n",filename);
1156 dw_free(filename);
1157 return 0;
1158 }
1159 dw_free(filename);
1160 }
1161
1162 // Number of posterior draws
1163 ndraws_posterior=dw_NumberLines(f_in,(char*)NULL);
1164
1165 // Get center, scale, and alpha from posterior
1166 flag=(dw_FindArgument_String(nargs,args,"mean") != -1) ? USE_MEAN : USE_MODE;
1167 center=CreateVector(ntheta);
1168 scale=CreateMatrix(ntheta,ntheta);
1169 dirichlet_dims=CreateDirichletDimensions(model);
1170 alpha=(PRECISION*)dw_malloc((nq+dw_DimA(dirichlet_dims))*sizeof(PRECISION));
1171 percentage_draws=dw_ParseFloating_String(nargs,args,"percentage_draws",0.20);
1172 ndraws_info=percentage_draws*ndraws_posterior;
1173 if (ndraws_info > ndraws_posterior) ndraws_info=ndraws_posterior;
1174
1175 // Use first percentage draws of posterior draws to form center and scale
1176 PosteriorDistributionInfo(f_in,flag,center,scale,alpha,dirichlet_dims,alpha_scale,ndraws_info);
1177
1178 // Use first percentage draws of posterior draws to form center and scale
1179 fseek(f_in,0,SEEK_SET);
1180 R=PosteriorRadius(f_in,center,scale,ndraws_info);
1181
1182 // Create proposal distribution
1183 //ProductMS(scale,scale.2.0);
1184 proposal_type=dw_ParseInteger_String(nargs,args,"pt",3);
1185 p_lo=dw_ParseFloating_String(nargs,args,"l",0.1);
1186 p_hi=dw_ParseFloating_String(nargs,args,"h",0.9);
1187 switch (proposal_type)
1188 {
1189 case USE_GAUSSIAN:
1190 printf("Using gaussian proposal\n");
1191 elliptical=CreateEllipticalFromPosterior_Gaussian(R,ntheta,center,scale);
1192 break;
1193 case USE_POWER:
1194 printf("Using power proposal\n");
1195 elliptical=CreateEllipticalFromPosterior_Power(R,ntheta,center,scale,p_hi);
1196 break;
1197 case USE_TRUNCATED_POWER:
1198 printf("Using truncated power proposal\n");
1199 elliptical=CreateEllipticalFromPosterior_TruncatedPower(R,ntheta,center,scale,p_lo,p_hi);
1200 break;
1201 case USE_STEP:
1202 printf("Using step proposal\n");
1203 elliptical=CreateEllipticalFromPosterior_Step(R,ntheta,center,scale,p_lo,p_hi);
1204 break;
1205 case USE_TRUNCATED_GAUSSIAN:
1206 printf("Using truncated proposal\n");
1207 elliptical=CreateEllipticalFromPosterior_TruncatedGaussian(R,ntheta,center,scale,p_lo,p_hi);
1208 break;
1209 case USE_UNIFORM:
1210 printf("Using uniform proposal\n");
1211 elliptical=CreateEllipticalFromPosterior_Uniform(R,ntheta,center,scale,p_lo,p_hi);
1212 break;
1213 default:
1214 printf("\nComputeMarginalDataDensity_command_line(): Unknown proposal density."
1215 "\n Usage: -pt <proposal type>"
1216 "\n 1: gaussian"
1217 "\n 2: power (-h high probability cutoff)"
1218 "\n 3: truncated power (-l or -h low or high probability cutoff)"
1219 "\n 4: step (-l or -h low or high probability cutoff)"
1220 "\n 5: truncated gaussian (-l or -h low or high probability cutoff)"
1221 "\n 6: uniform (-l or -h low or high probability cutoff)"
1222 "\n\n");
1223 goto CLEAN_UP;
1224 break;
1225 }
1226
1227 // Print full elliptical type info and stop
1228 /* PrintEllipticalInfo_full(stdout,elliptical); */
1229 /* dw_exit(0); */
1230
1231 // Open output file
1232 if (tag)
1233 {
1234 fmt="mdd_t%d_%s.out";
1235 sprintf(filename=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,proposal_type,tag);
1236 }
1237 else
1238 {
1239 fmt="mdd_t%d.out";
1240 sprintf(filename=(char*)dw_malloc(strlen(fmt) + 1),fmt,proposal_type);
1241 }
1242 out_filename=dw_ParseString_String(nargs,args,"of",filename);
1243 f_out=fopen(out_filename,"wt");
1244 if (filename) dw_free(filename);
1245
1246 // Plot marginal radius cummulative distribution
1247 if (dw_FindArgument_String(nargs,args,"graph") != -1)
1248 {
1249 printf("Computing cumulative densities\n");
1250 GraphCummulativeDensities(f_out,(char*)NULL,R,elliptical);
1251 fclose(f_out);
1252 rtrn=1;
1253 goto CLEAN_UP;
1254 }
1255
1256 // Compute Proposal and Posterior matrices
1257
1258 // Use last (1.0 - percentage draws) of posterior draws to form posterior matrix, unless percentage_draws == 1, in which case all draws are used
1259 if (ndraws_info == ndraws_posterior)
1260 fseek(f_in,0,SEEK_SET);
1261 else
1262 ndraws_posterior-=ndraws_info;
1263 posterior=CreatePosterior(f_in,elliptical,alpha,dirichlet_dims,ndraws_posterior);
1264
1265 // done with posterior file
1266 fclose(f_in);
1267
1268 // timings
1269 end_time=time((time_t*)NULL);
1270 printf("Elapsed Time: %d seconds\n",end_time - begin_time);
1271
1272 printf("Creating proposal draws\n");
1273 ndraws_proposal=dw_ParseInteger_String(nargs,args,"d",100000);
1274 proposal=CreateProposal(ndraws_proposal,model,elliptical,alpha,dirichlet_dims);
1275 if (dw_FindArgument_String(nargs,args,"append") != -1)
1276 {
1277 if (tag)
1278 {
1279 fmt="proposal_t%d_%s.out";
1280 sprintf(filename=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,proposal_type,tag);
1281 }
1282 else
1283 {
1284 fmt="proposal_t%d.out";
1285 sprintf(filename=(char*)dw_malloc(strlen(fmt) + 1),fmt,proposal_type);
1286 }
1287 proposal_previous=dw_ReadDelimitedFile_floating((FILE*)NULL,filename,' ',REMOVE_EMPTY_FIELDS,-1.0e300);
1288 dw_free(filename);
1289 if (proposal_previous)
1290 {
1291 new_proposal=CreateMatrix((proposal ? RowM(proposal) : 0)+dw_DimA(proposal_previous),2);
1292 for (i=dw_DimA(proposal_previous)-1; i >= 0; i--)
1293 { ElementM(new_proposal,i,0)=proposal_previous[i][0]; ElementM(new_proposal,i,1)=proposal_previous[i][1]; }
1294 if (proposal) InsertSubMatrix(new_proposal,proposal,dw_DimA(proposal_previous),0,0,0,RowM(proposal),2);
1295 dw_FreeArray(proposal_previous);
1296 FreeMatrix(proposal);
1297 proposal=new_proposal;
1298 }
1299 }
1300
1301 // timings
1302 end_time=time((time_t*)NULL);
1303 printf("Elapsed Time: %d seconds\n",end_time - begin_time);
1304
1305 if (!proposal || ! posterior)
1306 {
1307 printf("No proposal or posterior draws\n");
1308 fclose(f_out);
1309 goto CLEAN_UP;
1310 }
1311
1312 // Write proposal information
1313 if (tag) fprintf(f_out,"tag: %s\n",tag);
1314 PrintEllipticalInfo(f_out,elliptical);
1315 fprintf(f_out,"\n");
1316 printf("nproposal = %d nposterior = %d\n",RowM(proposal),RowM(posterior));
1317 fprintf(f_out,"nproposal = %d nposterior = %d\n",RowM(proposal),RowM(posterior));
1318
1319 // Waggoner-Zha
1320 printf("\nWaggoner-Zha\n");
1321 fprintf(f_out,"\nWaggoner-Zha\n");
1322
1323 // No cuts
1324 mdd=ComputeLogMarginalDensity_WaggonerZha(proposal,posterior,MINUS_INFINITY,PLUS_INFINITY,&in_P1,&in_P2,&I);
1325 printf("log(mdd) = %le log(cut) = minus infinity in_proposal = %d in_posterior = %d\n",mdd,in_P1,in_P2);
1326 fprintf(f_out,"log(mdd) = %le log(cut) = minus infinity in_proposal = %d in_posterior = %d\n",mdd,in_P1,in_P2);
1327
1328 s_proposal=SortMatrixRowsDescending((TMatrix)NULL,proposal,1);
1329 s_posterior=SortMatrixRowsDescending((TMatrix)NULL,posterior,1);
1330 if (ElementM(s_proposal,0,1) > ElementM(s_posterior,RowM(s_posterior)-1,1))
1331 if (ElementM(s_proposal,(RowM(s_proposal) > 29) ? 29 : RowM(s_proposal)-1,1) > ElementM(s_posterior,(5*(RowM(s_posterior)-1))/100,1))
1332 {
1333 for (j=40; j >= 5; j-=1)
1334 {
1335 x=ElementM(s_posterior,(j*(RowM(s_posterior)-1))/100,1);
1336 mdd=ComputeLogMarginalDensity_WaggonerZha(proposal,posterior,x,PLUS_INFINITY,&in_P1,&in_P2,&I);
1337 printf("log(mdd) = %le log(cut) = %le in_proposal = %d in_posterior = %d\n",mdd,x,in_P1,in_P2);
1338 fprintf(f_out,"log(mdd) = %le log(cut) = %le in_proposal = %d in_posterior = %d\n",mdd,x,in_P1,in_P2);
1339 }
1340 }
1341 else
1342 {
1343 for (i=0; (i+1 < RowM(s_proposal)) && (ElementM(s_proposal,i+1,1) >= ElementM(s_posterior,RowM(s_posterior)-1,1)); i++);
1344
1345 x=ElementM(s_proposal,i,1);
1346 mdd=ComputeLogMarginalDensity_WaggonerZha(proposal,posterior,x,PLUS_INFINITY,&in_P1,&in_P2,&I);
1347 printf("log(mdd) = %le log(cut) = %le in_proposal = %d in_posterior = %d\n",mdd,x,in_P1,in_P2);
1348 fprintf(f_out,"log(mdd) = %le log(cut) = %le in_proposal = %d in_posterior = %d\n",mdd,x,in_P1,in_P2);
1349 for (j=0; j < 9; j++)
1350 if (i >= cuts[j])
1351 {
1352 x=0.5*(ElementM(s_proposal,cuts[j]-1,1)+ElementM(s_proposal,cuts[j],1));
1353 if (x <= ElementM(s_posterior,0,1))
1354 {
1355 mdd=ComputeLogMarginalDensity_WaggonerZha(proposal,posterior,x,PLUS_INFINITY,&in_P1,&in_P2,&I);
1356 printf("log(mdd) = %le log(cut) = %le in_proposal = %d in_posterior = %d\n",mdd,x,in_P1,in_P2);
1357 fprintf(f_out,"log(mdd) = %le log(cut) = %le in_proposal = %d in_posterior = %d\n",mdd,x,in_P1,in_P2);
1358 }
1359 }
1360 }
1361 else
1362 printf("Unable to compute Waggoner-Zha method for any cutoff value. Try increasing number of proposal draws.\n");
1363
1364 // Compute marginal data density - Muller's method
1365 mdd=ComputeLogMarginalDensity_Mueller(proposal,posterior,&in_P1,&in_P2);
1366 printf("\nMuller log(mdd) = %le\nnproposal = %d nposterior = %d in_P1 = %d in_P2 = %d\n",mdd,RowM(proposal),RowM(posterior),in_P1,in_P2);
1367 fprintf(f_out,"\nMuller log(mdd) = %le\nnproposal = %d nposterior = %d in_P1 = %d in_P2 = %d\n",mdd,RowM(proposal),RowM(posterior),in_P1,in_P2);
1368
1369 // Print explanation of in_P1 and in_P2.
1370 printf("\n in_P1 is the number of proposal draws such that the density of the proposal is greater than"
1371 "\n or equal to the density (properly scaled!) of the posterior. in_P2 is the number of"
1372 "\n posterior draws such that the density (properly scaled!) of the posterior is greater than"
1373 "\n or equal to the density of the proposal. Both numbers should somewhat larger than zero."
1374 "\n Ideally both should also be somewhat less than the maximum possible value, though in"
1375 "\n practice this rarely happens.\n");
1376 fprintf(f_out,"\n in_P1 is the number of proposal draws such that the density of the proposal is greater than"
1377 "\n or equal to the density (properly scaled!) of the posterior. in_P2 is the number of"
1378 "\n posterior draws such that the density (properly scaled!) of the posterior is greater than"
1379 "\n or equal to the density of the proposal. Both numbers should be somewhat larger than zero."
1380 "\n Ideally both should also be somewhat less than the maximum possible value, though in"
1381 "\n practice this rarely happens.\n");
1382
1383 // Compute marginal data density - Bridge method
1384 mdd=ComputeLogMarginalDensity_Bridge(proposal,posterior);
1385 printf("\nBridge log(mdd) = %le\n",mdd);
1386 fprintf(f_out,"\nBridge log(mdd) = %le\n",mdd);
1387
1388 /* // Use Sims, Waggoner, Zha proposal for Mueller and bridge */
1389 /* TMatrix modified_proposal=(TMatrix)NULL, modified_posterior=(TMatrix)NULL; */
1390 /* for (i=0; i < 3*n_cuts; i++) */
1391 /* { */
1392 /* if (!ModifyUsingSWZ(&modified_proposal,&modified_posterior,proposal,posterior,ElementV(cuts,i))) break; */
1393
1394 /* mdd=ComputeLogMarginalDensity_Mueller(modified_proposal,modified_posterior,&in_P1,&in_P2); */
1395 /* printf("\nMuller log(mdd) = %le\nnproposal = %d nposterior = %d in_P1 = %d in_P2 = %d\n",mdd,RowM(modified_proposal),RowM(modified_posterior),in_P1,in_P2); */
1396 /* fprintf(f_out,"\nMuller log(mdd) = %le\nnproposal = %d nposterior = %d in_P1 = %d in_P2 = %d\n",mdd,RowM(modified_proposal),RowM(modified_posterior),in_P1,in_P2); */
1397
1398 /* mdd=ComputeLogMarginalDensity_Bridge(modified_proposal,modified_posterior); */
1399 /* printf("\nBridge log(mdd) = %le\n",mdd); */
1400 /* fprintf(f_out,"\nBridge log(mdd) = %le\n",mdd); */
1401
1402 /* while ((i < 3*n_cuts-1) && (ElementV(cuts,i+1) == ElementV(cuts,i))) i++; */
1403 /* } */
1404 /* FreeMatrix(modified_proposal); */
1405 /* FreeMatrix(modified_posterior); */
1406 /* // clean up */
1407 /* FreeVector(cuts); */
1408
1409 // Close main output file
1410 fclose(f_out);
1411
1412 // Print posterior and proposal
1413 if (dw_FindArgument_String(nargs,args,"print") != -1)
1414 {
1415 if (tag)
1416 {
1417 fmt="posterior_t%d_%s.out";
1418 sprintf(filename=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,proposal_type,tag);
1419 }
1420 else
1421 {
1422 fmt="posterior_t%d.out";
1423 sprintf(filename=(char*)dw_malloc(strlen(fmt) + 1),fmt,proposal_type);
1424 }
1425 f_out=fopen(filename,"wt");
1426 dw_free(filename);
1427 dw_PrintMatrix(f_out,posterior,"%le ");
1428 fclose(f_out);
1429
1430 if (tag)
1431 {
1432 fmt="proposal_t%d_%s.out";
1433 sprintf(filename=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,proposal_type,tag);
1434 }
1435 else
1436 {
1437 fmt="proposal_t%d.out";
1438 sprintf(filename=(char*)dw_malloc(strlen(fmt) + 1),fmt,proposal_type);
1439 }
1440 f_out=fopen(filename,"wt");
1441 dw_free(filename);
1442 dw_PrintMatrix(f_out,proposal,"%le ");
1443 fclose(f_out);
1444 }
1445 else
1446 {
1447 if (tag)
1448 {
1449 fmt="proposal_t%d_%s.out";
1450 sprintf(filename=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,proposal_type,tag);
1451 }
1452 else
1453 {
1454 fmt="proposal_t%d.out";
1455 sprintf(filename=(char*)dw_malloc(strlen(fmt) + 1),fmt,proposal_type);
1456 }
1457 f_out=fopen(filename,"wt");
1458 dw_free(filename);
1459 dw_PrintMatrix(f_out,proposal,"%le ");
1460 fclose(f_out);
1461 }
1462
1463 rtrn=1;
1464
1465 // Cleanup
1466 CLEAN_UP:
1467 FreeMatrix(scale);
1468 FreeMatrix(proposal);
1469 FreeMatrix(posterior);
1470 FreeVector(center);
1471 FreeVector(R);
1472 dw_FreeArray(dirichlet_dims);
1473 if (alpha) dw_free(alpha);
1474 FreeElliptical(elliptical);
1475
1476 // timings
1477 end_time=time((time_t*)NULL);
1478 printf("Elapsed Time: %d seconds\n",end_time - begin_time);
1479
1480 return rtrn;
1481 }
1482 /*******************************************************************************/
1483 /*******************************************************************************/
1484 /*******************************************************************************/
1485
1486
1487 #undef SORTED_LEVEL_CUTS
1488 #undef LINEAR_LEVEL_CUTS
1489 #undef EXP_LEVEL_CUTS
1490 #undef USE_MODE
1491 #undef USE_MEAN
1492
1493 #undef USE_GAUSSIAN
1494 #undef USE_POWER
1495 #undef USE_TRUNCATED_POWER
1496 #undef USE_STEP
1497 #undef USE_TRUNCATED_POWER
1498 #undef USE_UNIFORM