Debian Codegraph @

contrib/ms-sbvar/switch_dw/switching/dw_switch_sim.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_switch.h"
19 #include "dw_switchio.h"
20 #include "dw_metropolis_theta.h"
21 #include "dw_rand.h"
22 #include "dw_matrix_rand.h"
23 #include "dw_error.h"
24 #include "dw_ascii.h"
25 #include "dw_parse_cmd.h"
26 #include "dw_array.h"
27 #include "dw_matrix_array.h"
28 #include "dw_switch_sim.h"
29 #include "dw_std.h"
30
31 #include <string.h>
32 #include <ctype.h>
33 #include <stdlib.h>
34 #include <limits.h>
35 #include <stdlib.h>
36 #include <memory.h>
37 #include <math.h>
38 #include <time.h>
39
40 /******************************************************************************/
41 /******************************************************************************/
42 /******************************************************************************/
43 /*
44 The file contains 2 + nparameters columns which are to be interpreted as
45
46 Column 0 : 0 = log posterior density
47 Column 1 : 1 = log likelihood
48 Columns 2 : 1 + nparameters = parameters
49
50 The file is a delimited ascii file and the delimiter is a space (' ').
51
52 Creates and returns a m x (2 + nparameters) matrix containing the data in the
53 file.
54
55 Fields that are empty or do not parse into valid floating point numbers are
56 ignored.
57
58 Rows that do not contain 2 + nparameter valid fields are ignored.
59
60 One of f_in, filename or tag must not be null. If f_in is not null, this file
61 is read, starting at the current pointer. Otherwise, if filename is not null
62 then it is opened and read. If both f_in and filename are null, then the file
63 simulation_<tag>.out is opened and read.
64
65 */
66 TMatrix dw_ReadPosteriorDraws(FILE *f_in, char *filename, char *tag, int nparameters)
67 {
68 char *fmt="simulation_%s.out", delimiter=' ';
69 TMatrix posterior_draws=(TMatrix)NULL;
70 int free_filename=0, m=0, cols=2+nparameters, i, j, k;
71 double** Y;
72
73 // setup filename
74 if (!f_in && !filename)
75 if (!tag)
76 {
77 printf("dw_ReadPosterior(): Must specify FILE pointer, filename or tag\n");
78 return (TMatrix)NULL;
79 }
80 else
81 {
82 sprintf(filename=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,tag);
83 free_filename=1;
84 }
85
86 // Get matrix
87 if (Y=dw_ReadDelimitedFile_double(f_in,filename,delimiter,REMOVE_EMPTY_FIELDS,0.0))
88 {
89 for (k=dw_DimA(Y)-1; k >= 0; k--)
90 if (dw_DimA(Y[k]) == cols) m++;
91 if ((m > 0) && (posterior_draws=CreateMatrix(m,cols)))
92 {
93 for (k=i=0; k < dw_DimA(Y); k++)
94 if (dw_DimA(Y[k]) == cols)
95 {
96 for (j=cols-1; j >= 0; j--) ElementM(posterior_draws,i,j)=Y[k][j];
97 i++;
98 }
99 }
100 dw_FreeArray(Y);
101 }
102
103 // Clean up
104 if (free_filename) dw_free(filename);
105
106 // Return
107 return posterior_draws;
108 }
109
110 /*******************************************************************************/
111 /*******************************************************************************/
112 /*******************************************************************************/
113
114
115
116 /*******************************************************************************/
117 /*******************************************************************************/
118 /*******************************************************************************/
119 /*
120 Assumes
121 model : pointer to valid TStateModel structure
122 center_s : target acceptance rate for each direction invidually
123 peroid_s : initial length of sub-runs to calibrate scale for each direction individually
124 max_period_s : maximum length of sub-runs to calibrate scale for each direction individually
125 center_a : target acceptance rate for each block
126 peroid_a : initial length of sub-runs to calibrate scales for each block
127 max_period_a : maximum length of sub-runs to calibrate scales for each block
128 verbose : non-zero for output to stdout
129
130 Returns
131 The total number of theta draws made.
132
133 Results
134 The values of model->metropolis_scale_theta are calibrated to obtain the
135 desired acceptance ratio.
136 */
137 int calibrate_metropolis_theta_two_pass(TStateModel *model, PRECISION center_s, int period_s, int max_period_s,
138 PRECISION center_a, int period_a, int max_period_a)
139 {
140 int n_draws=0, i, j, n_theta=NumberFreeParametersTheta(model), n_q=NumberFreeParametersQ(model);
141 TVector initial_theta=(TVector)NULL, initial_q=(TVector)NULL;
142 int *dims, n_blocks;
143
144 // Save initial value
145 if (n_theta) ConvertThetaToFreeParameters(model,pElementV(initial_theta=CreateVector(n_theta)));
146 if (n_q) ConvertQToFreeParameters(model,pElementV(initial_q=CreateVector(n_q)));
147
148 // Individual direction run
149 if (period_s > 0)
150 {
151 // Save old blocks
152 n_blocks=model->metropolis_theta->n_blocks;
153 memcpy(dims=(int*)dw_malloc(n_blocks*sizeof(int)),model->metropolis_theta->block_dims,n_blocks*sizeof(int));
154
155 // Setup one-dimensional blocks
156 Setup_metropolis_theta_blocks_full(model->metropolis_theta);
157
158 // Calibrate
159 AdaptiveScale_metropolis_theta(model,center_s,period_s,max_period_s,1);
160
161 // Number theta draws
162 for (j=0; j < model->metropolis_theta->n_blocks; j++)
163 n_draws+=model->metropolis_theta->draws[j];
164
165 // Reset blocks
166 Setup_metropolis_theta_blocks(model->metropolis_theta,n_blocks,dims);
167 dw_free(dims);
168
169 // Reset initial value
170 if (n_theta) ConvertFreeParametersToTheta(model,pElementV(initial_theta));
171 if (n_q) ConvertFreeParametersToQ(model,pElementV(initial_q));
172 }
173
174 // Final run
175 if (period_a > 0)
176 {
177 AdaptiveScale_metropolis_theta(model,center_a,period_a,max_period_a,2);
178
179 for (j=0; j < model->metropolis_theta->n_blocks; j++)
180 n_draws+=model->metropolis_theta->draws[0];
181
182 // Reset initial value
183 if (n_theta) ConvertFreeParametersToTheta(model,pElementV(initial_theta));
184 if (n_q) ConvertFreeParametersToQ(model,pElementV(initial_q));
185 }
186
187 if (n_theta) FreeVector(initial_theta);
188 if (n_q) FreeVector(initial_q);
189
190 return n_draws;
191 }
192
193 /* Undefine to use wall time instead of process time */
194 #define WALL_TIME
195
196 //=== Static declarations
197 static int Simulate(int burn_in, int draws, int thin, int period, TStateModel *model, FILE *f_out);
198 static int WriteMetropolisThetaInfo(char *filename, char *tag, int type, PRECISION center_s, int period_s, int max_period_s,
199 PRECISION center_a, int period_a, int max_period_a, int ndraws, int elapsed_time,
200 TStateModel *model);
201 static int SetUpMetropolisSimulation(int n_args, char **args, char *tag, TStateModel *model, int default_period);
202 //=======================
203
204 static int Simulate(int burn_in, int draws, int thin, int period, TStateModel *model, FILE *f_out)
205 {
206 PRECISION logposterior;
207 #ifdef WALL_TIME
208 time_t begin_time;
209 #else
210 clock_t begin_time;
211 #endif
212 int i, j, check, ntheta, nq;
213 TVector theta, q;
214
215 // Initialization
216 ntheta=NumberFreeParametersTheta(model);
217 nq=NumberFreeParametersQ(model);
218 if (ntheta) theta=CreateVector(ntheta);
219 if (nq) q=CreateVector(nq);
220
221 // Initial log posterior
222 logposterior=LogPosterior_StatesIntegratedOut(model);
223
224 // Burn-in
225 ResetCounts_metropolis_theta(model->metropolis_theta);
226 ResetMetropolisHastingsCounts_q(model);
227 if (burn_in > 0)
228 {
229 printf("(0 / %d) Beginning burn in.\n",burn_in);
230 #ifdef WALL_TIME
231 begin_time=time((time_t*)NULL);
232 #else
233 begin_time=clock();
234 #endif
235 for (check=period, i=1; i <= burn_in; i++)
236 {
237 logposterior=draw_metropolis(model,logposterior);
238
239 if (i == check)
240 {
241 check+=period;
242 #ifdef WALL_TIME
243 printf("(%d / %d) Total Elapsed Time: %d seconds\n",i,burn_in,(int)(time((time_t*)NULL) - begin_time));
244 #else
245 printf("(%d / %d) Total Elapsed Time: %lf seconds\n",i,burn_in,((double)(clock() - begin_time))/CLOCKS_PER_SEC);
246 #endif
247 }
248 }
249 #ifdef WALL_TIME
250 printf("(%d / %d) Elapsed Time: %d seconds\n",burn_in,burn_in,(int)(time((time_t*)NULL) - begin_time));
251 #else
252 printf("(%d / %d) Elapsed Time: %lf seconds\n",burn_in,burn_in,((double)(clock() - begin_time))/CLOCKS_PER_SEC);
253 #endif
254 }
255
256 // Simulate
257 if (draws > 0)
258 {
259 printf("(0 / %d) Beginning simulation.\n",draws);
260 #ifdef WALL_TIME
261 begin_time=time((time_t*)NULL);
262 #else
263 begin_time=clock();
264 #endif
265 for (check=period, i=1; i <= draws; i++)
266 {
267 for (j=thin; j > 0; j--) logposterior=draw_metropolis(model,logposterior);
268
269 fprintf(f_out,"%.14le %.14le",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model));
270 if (ntheta)
271 {
272 ConvertThetaToFreeParameters(model,pElementV(theta));
273 for (j=0; j < ntheta; j++) fprintf(f_out," %.14le",ElementV(theta,j));
274 }
275 if (nq)
276 {
277 ConvertQToFreeParameters(model,pElementV(q));
278 for (j=0; j < nq; j++) fprintf(f_out," %.14le",ElementV(q,j));
279 }
280 fprintf(f_out,"\n");
281
282 if (i == check)
283 {
284 check+=period;
285 #ifdef WALL_TIME
286 printf("(%d / %d) Total Elapsed Time: %d seconds\n",i,draws,(int)(time((time_t*)NULL) - begin_time));
287 #else
288 printf("(%d / %d) Total Elapsed Time: %lf seconds\n",i,draws,((double)(clock() - begin_time))/CLOCKS_PER_SEC);
289 #endif
290 }
291 }
292 #ifdef WALL_TIME
293 printf("(%d / %d) Elapsed Time: %d seconds\n",draws,draws,(int)(time((time_t*)NULL) - begin_time));
294 #else
295 printf("(%d / %d) Elapsed Time: %lf seconds\n",draws,draws,((double)(clock() - begin_time))/CLOCKS_PER_SEC);
296 #endif
297 }
298
299 // Clean up
300 if (ntheta) FreeVector(theta);
301 if (nq) FreeVector(q);
302 return 0;
303 }
304
305 #define READ_METROPOLIS_INFO 1
306 #define DIAGONAL_CALIBRATION 4
307 #define TWO_PASS 8
308 #define VARIANCE_CALIBRATION 32
309 static int WriteMetropolisThetaInfo(char *filename, char *tag, int type, PRECISION center_s, int period_s, int max_period_s,
310 PRECISION center_a, int period_a, int max_period_a, int ndraws, int elapsed_time,
311 TStateModel *model)
312 {
313 FILE *f_out;
314 time_t ltime=time((time_t*)NULL);
315 int i, j;
316 PRECISION accept;
317
318 if (!(f_out=fopen(filename,"wt")))
319 {
320 printf("Unable to create %s for output\n",filename);
321 return 0;
322 }
323
324 fprintf(f_out,"//== Calibration info ==//\n");
325
326 switch(type)
327 {
328 case DIAGONAL_CALIBRATION | TWO_PASS: fprintf(f_out,"type - diagonal two pass calibration\n"); break;
329 case VARIANCE_CALIBRATION | TWO_PASS: fprintf(f_out,"type - variance two pass calibration\n"); break;
330 default: fprintf(f_out,"type - unknown\n"); break;
331 }
332
333 if (type & TWO_PASS)
334 {
335 fprintf(f_out,"target acceptance rate single variable - %lf\n",center_s);
336 fprintf(f_out,"initial period single variable - %d\n",period_s);
337 fprintf(f_out,"maximum period single variable - %d\n",max_period_s);
338 fprintf(f_out,"target acceptance rate overall - %lf\n",center_a);
339 fprintf(f_out,"initial period overall - %d\n",period_a);
340 fprintf(f_out,"maximum period overall - %d\n",max_period_a);
341 }
342 else
343 {
344 fprintf(f_out,"target acceptance rate - %lf\n",center_a);
345 fprintf(f_out,"initial period - %d\n",period_a);
346 fprintf(f_out,"maximum period - %d\n",max_period_a);
347 }
348
349 fprintf(f_out,"acceptance rates final run\n");
350 for (j=0; j < model->metropolis_theta->n_blocks; j++)
351 {
352 accept=model->metropolis_theta->draws[j] ? (PRECISION)(model->metropolis_theta->jumps[j])/(PRECISION)(model->metropolis_theta->draws[j]) : -1.0;
353 fprintf(f_out,"block[%d] = %lf\n",j,accept);
354 }
355
356 fprintf(f_out,"total draws - %d\n",ndraws);
357 fprintf(f_out,"elapsed time - %d seconds\n",elapsed_time);
358 fprintf(f_out,"date - %s\n",ctime(&ltime));
359 if (tag)
360 fprintf(f_out,"file tag - %s\n",tag);
361 else
362 fprintf(f_out,"No file tag\n");
363
364
365 fprintf(f_out,"\n");
366
367 Write_metropolis_theta(f_out,(char*)NULL,(char*)NULL,model->metropolis_theta);
368
369 fclose(f_out);
370
371 return 1;
372 }
373
374 /*
375 Returns 1 if metropolis_theta parameters properly set and 0 otherwise. See dw_Simulate() for
376 command line options.
377 */
378 static int SetUpMetropolisSimulation(int n_args, char **args, char *tag, TStateModel *model, int default_period)
379 {
380 FILE *f_in, *f_out;
381 int i, k, ndraws, ntheta, nq, period_s, max_period_s, period_a, max_period_a, type,
382 begin_time, end_time, free_filename_metropolis=0;
383 PRECISION center_s, center_a;
384 char *filename_variance, *filename_hessian, *filename_metropolis, *id, *fmt, *header;
385 TMatrix posterior_draws=(TMatrix)NULL, variance=(TMatrix)NULL, X=(TMatrix)NULL;
386 TVector mean=(TVector)NULL, x=(TVector)NULL, theta=(TVector)NULL;
387
388 // Get Sizes
389 ntheta=NumberFreeParametersTheta(model);
390 nq=NumberFreeParametersQ(model);
391
392 // Input/output file name for metropolis_theta info
393 if (!(filename_metropolis=dw_ParseString_String(n_args,args,"af",(char*)NULL)))
394 {
395 if (!tag)
396 {
397 printf("No adaptive filename (-af) or tag (-t) specified\n");
398 return 0;
399 }
400 fmt="metropolis_theta_%s.prn";
401 sprintf(filename_metropolis=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,tag);
402 free_filename_metropolis=1;
403 }
404
405 // First try: read info from adpative file if -diagonal and -variance are not specified
406 if ((dw_FindArgument_String(n_args,args,"diagonal") == -1) && (dw_FindArgument_String(n_args,args,"variance") == -1))
407 if (Read_metropolis_theta((FILE*)NULL,filename_metropolis,(char*)NULL,model->metropolis_theta))
408 {
409 // Cleanup and return
410 if (free_filename_metropolis) dw_free(filename_metropolis);
411 return READ_METROPOLIS_INFO;
412 }
413 else
414 printf("Unable to open %s. Attempting calibration\n",filename_metropolis);
415 else
416 printf("Starting recalibration\n");
417
418 // Setup calibration parameters
419 center_s=dw_ParseFloating_String(n_args,args,"cs",0.20);
420 center_a=dw_ParseFloating_String(n_args,args,"ca",0.25);
421 period_s=dw_ParseInteger_String(n_args,args,"ps",default_period);
422 period_a=dw_ParseInteger_String(n_args,args,"pa",default_period);
423 max_period_s=dw_ParseInteger_String(n_args,args,"mps",8*period_s);
424 max_period_a=dw_ParseInteger_String(n_args,args,"mpa",16*period_a);
425
426 // Second try: Read parameter draws and calibrate using variance directions if -variance is specified
427 if (filename_variance=dw_ParseString_String(n_args,args,"variance",(char*)NULL))
428 {
429 if (!(posterior_draws=dw_ReadPosteriorDraws((FILE*)NULL,filename_variance,(char*)NULL,ntheta+nq)))
430 {
431 printf("Unable to read posterior draws file - %s.\n",filename_variance);
432 return 0;
433 }
434 InitializeMatrix(variance=CreateMatrix(ntheta,ntheta),0.0);
435 X=CreateMatrix(ntheta,ntheta);
436 InitializeVector(mean=CreateVector(ntheta),0.0);
437 x=CreateVector(ntheta+nq+2);
438 theta=CreateVector(ntheta);
439 for (i=RowM(posterior_draws)-1; i >= 0; i--)
440 {
441 RowVector(x,posterior_draws,i);
442 SubVector(theta,x,2,ntheta);
443 AddVV(mean,mean,theta);
444 OuterProduct(X,theta,theta);
445 AddMM(variance,variance,X);
446 }
447 ProductVS(mean,mean,1.0/(PRECISION)RowM(posterior_draws));
448 ProductMS(variance,variance,1.0/(PRECISION)RowM(posterior_draws));
449 SubtractMM(variance,variance,OuterProduct(X,mean,mean));
450 FreeMatrix(X);
451
452 // Initializing scale and directions using variance
453 Setup_metropolis_theta_variance(model->metropolis_theta,variance);
454 if (model->metropolis_theta->n_blocks <= 0)
455 Setup_metropolis_theta_blocks_single(model->metropolis_theta);
456
457 // Calibrating
458 begin_time=(int)time((time_t*)NULL);
459 ndraws=calibrate_metropolis_theta_two_pass(model,center_s,period_s,max_period_s,center_a,period_a,max_period_a);
460 end_time=(int)time((time_t*)NULL);
461
462 // Print Metropolis info
463 WriteMetropolisThetaInfo(filename_metropolis,tag,VARIANCE_CALIBRATION | TWO_PASS,center_s,period_s,max_period_s,
464 center_a,period_a,max_period_a,ndraws,end_time-begin_time,model);
465
466 // Clean up and return
467 FreeMatrix(posterior_draws);
468 FreeMatrix(variance);
469 FreeVector(x);
470 FreeVector(mean);
471 FreeVector(theta);
472 if (free_filename_metropolis) dw_free(filename_metropolis);
473 return VARIANCE_CALIBRATION | TWO_PASS;
474 }
475
476 // Last try: Use diagonal
477 // Initializing scale and directions
478 Setup_metropolis_theta_diagonal(model->metropolis_theta);
479 if (model->metropolis_theta->n_blocks <= 0)
480 Setup_metropolis_theta_blocks_single(model->metropolis_theta);
481
482 // Calibrating
483 begin_time=(int)time((time_t*)NULL);
484 ndraws=calibrate_metropolis_theta_two_pass(model,center_s,period_s,max_period_s,center_a,period_a,max_period_a);
485 end_time=(int)time((time_t*)NULL);
486
487 // Print Metropolis info
488 WriteMetropolisThetaInfo(filename_metropolis,tag,DIAGONAL_CALIBRATION | TWO_PASS,center_s,period_s,max_period_s,
489 center_a,period_a,max_period_a,ndraws,end_time-begin_time,model);
490
491 // Clean up and return
492 if (free_filename_metropolis) dw_free(filename_metropolis);
493 return DIAGONAL_CALIBRATION | TWO_PASS;
494 }
495
496
497
498 //****************************************************************************//
499 //**************************** Simulation Main *****************************//
500 //****************************************************************************//
501 /*
502 Command line parameters
503
504 General parameters
505 -outtag : filename tag
506
507 Adaptive jump ratio parameters
508 -cs <real>: target acceptance rate for single variable calibrations (default = 0.20)
509 -ca <real> : target acceptance rate for overall calibrations (default = 0.25)
510 -ps <integer> : the initial period for the single variable calibrations (default = 20)
511 -pa <integer> : the initial period for the overall calibrations (default = 20)
512 -mps <integer> : the maximum period for the single variable calibrations (default = 8*ps)
513 -mpa <integer> : the maximum period for the overall calibrations (default = 16*mps)
514 -diagonal : Forces calibration using two-pass diagonal, even if calibration has alread been performed.
515 This is the default option.
516 -variance <filename> : Forces calibration using two-pass variance, even if calibration has already
517 been performed. Reads draws from filename.
518 -af <filename> : file for storing the calibrated metropolis parameters. (default = metropolis_theta_<tag>.prn)
519 -database : write to the database instead of a file.
520
521 Simulation parameters
522 -ndraws : number of draws to save (default = 1000)
523 -burnin : number of burn-in draws (default = 0.1 * ndraws)
524 -thin : thinning factor. Total number of draws made is thin*ndraws + burnin (default = 1)
525 -of <filename> : output filename (default = simulation_<tag>.out)
526 -random <filename> : Reads previous simulation output and randomly selects a starting value.
527
528 Attempts to setup metropolis parameters from command line for simulating theta. Note if neither -diagonal,
529 or -variance are specified, the default behavior is to first look for calibration file and if is
530 not present to use the two-pass diagonal method.
531 */
532 void dw_simulate_command_line(int n_args, char **args, TStateModel *model, TVector start_value, int generator_init)
533 {
534 FILE *f_out, *f_start;
535 char *tag, *default_filename, *filename, *fmt;
536 int j, row, ndraws, burn_in, thin, default_period=20, n_theta=NumberFreeParametersTheta(model), n_q=NumberFreeParametersQ(model);
537 TMatrix draws;
538 TVector draw;
539 PRECISION logposterior, loglikelihood;
540
541 // Initialize generator
542 dw_initialize_generator(generator_init);
543
544 // Get tag from command line
545 tag=dw_ParseString(n_args,args,'t',(char*)NULL);
546 tag=dw_ParseString_String(n_args,args,"ft",tag);
547 tag=dw_ParseString_String(n_args,args,"outtag",tag);
548
549 // Set maximum posterior and write initial value
550 model->max_log_posterior=logposterior=LogPosterior_StatesIntegratedOut(model);
551 loglikelihood=LogLikelihood_StatesIntegratedOut(model);
552 if (model->max_posterior_theta) ConvertThetaToFreeParameters(model,pElementV(model->max_posterior_theta));
553 if (model->max_posterior_q) ConvertQToFreeParameters(model,pElementV(model->max_posterior_q));
554 fmt="simulation_startmax_%s.out";
555 sprintf(filename=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,tag);
556 if (!(f_start=fopen(filename,"wt")))
557 printf("Unable to open %s\n",filename);
558 else
559 {
560 fprintf(f_start,"%.14le %.14le",logposterior,loglikelihood);
561 if (model->max_posterior_theta)
562 for (j=0; j < n_theta; j++) fprintf(f_start," %.14le",ElementV(model->max_posterior_theta,j));
563 if (model->max_posterior_q)
564 dw_PrintVector(f_start,model->max_posterior_q," %.14le");
565 else
566 fprintf(f_start,"\n");
567 }
568 dw_free(filename);
569
570 // Push starting value into model
571 if (start_value)
572 {
573 if (n_theta) ConvertFreeParametersToTheta(model,pElementV(start_value));
574 if (n_q) ConvertFreeParametersToQ(model,pElementV(start_value)+n_theta);
575 logposterior=LogPosterior_StatesIntegratedOut(model);
576 loglikelihood=LogLikelihood_StatesIntegratedOut(model);
577 if (f_start)
578 {
579 fprintf(f_start,"%.14le %.14le",logposterior,loglikelihood);
580 dw_PrintVector(f_start,start_value," %.14le");
581 }
582 if (logposterior > model->max_log_posterior)
583 {
584 model->max_log_posterior=logposterior;
585 if (model->max_posterior_theta) ConvertThetaToFreeParameters(model,pElementV(model->max_posterior_theta));
586 if (model->max_posterior_q) ConvertQToFreeParameters(model,pElementV(model->max_posterior_q));
587 }
588 }
589
590 // Random starting values
591 if (filename=dw_ParseString_String(n_args,args,"random",(char*)NULL))
592 if (draws=dw_ReadPosteriorDraws((FILE*)NULL,filename,(char*)NULL,n_theta+n_q))
593 {
594 row=(int)floor(dw_uniform_rnd()*RowM(draws));
595 if (row >= RowM(draws)) row=RowM(draws);
596 draw=RowVector((TVector)NULL,draws,row);
597 if (n_theta) ConvertFreeParametersToTheta(model,pElementV(draw)+2);
598 if (n_q) ConvertFreeParametersToQ(model,pElementV(draw)+2+n_theta);
599 printf("Using row %d as random starting value from %s\n",row,filename);
600 printf("initial log posterior = %le - %le\n",logposterior=LogPosterior_StatesIntegratedOut(model),ElementV(draw,0));
601 printf("initial log likelihood = %le - %le\n",loglikelihood=LogLikelihood_StatesIntegratedOut(model),ElementV(draw,1));
602 ElementV(draw,0)=logposterior;
603 ElementV(draw,1)=loglikelihood;
604 if (f_start) dw_PrintVector(f_start,draw," %.14le");
605 if (logposterior > model->max_log_posterior)
606 {
607 model->max_log_posterior=logposterior;
608 if (model->max_posterior_theta) ConvertThetaToFreeParameters(model,pElementV(model->max_posterior_theta));
609 if (model->max_posterior_q) ConvertQToFreeParameters(model,pElementV(model->max_posterior_q));
610 }
611 FreeVector(draw);
612 FreeMatrix(draws);
613 }
614 else
615 {
616 printf("Unable to open %s\n",filename);
617 dw_exit(0);
618 }
619 else
620 {
621 printf("initial log posterior = %le\n",logposterior);
622 printf("initial log likelihood = %le\n",loglikelihood);
623 }
624
625 if (SetUpMetropolisSimulation(n_args,args,tag,model,default_period))
626 {
627 // simulation parameters
628 ndraws=dw_ParseInteger_String(n_args,args,"ndraws",1000);
629 burn_in=dw_ParseInteger_String(n_args,args,"burnin",ndraws/10);
630 thin=dw_ParseInteger_String(n_args,args,"thin",1);
631
632 // Starting Simulation
633 if (dw_FindArgument_String(n_args,args,"database") == -1)
634 {
635 // output filename
636 if (tag)
637 {
638 fmt="simulation_%s.out";
639 sprintf(default_filename=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,tag);
640 filename=dw_ParseString_String(n_args,args,"fo",default_filename);
641 f_out=fopen(filename,"wt");
642 dw_free(default_filename);
643 }
644 else
645 f_out=fopen(filename=dw_ParseString_String(n_args,args,"fo","simulation.out"),"wt");
646 if (!f_out)
647 {
648 printf("Unable to open output file.\n");
649 dw_exit(0);
650 }
651 }
652 else
653 {
654 f_out=(FILE*)NULL;
655 // initialize sdsm
656 //sdsm_init(1001,100,100,1,0,1,1);
657 printf("-database not yet supported\n");
658 dw_exit(0);
659 }
660
661 Simulate(burn_in,ndraws,thin,1000,model,f_out);
662
663 if (f_start)
664 {
665 fprintf(f_start,"%.14le %.14le",model->max_log_posterior,loglikelihood);
666 if (model->max_posterior_theta)
667 for (j=0; j < n_theta; j++) fprintf(f_start," %.14le",ElementV(model->max_posterior_theta,j));
668 if (model->max_posterior_q)
669 dw_PrintVector(f_start,model->max_posterior_q," %.14le");
670 else
671 fprintf(f_start,"\n");
672 fclose(f_start);
673 }
674
675 if (f_out) fclose(f_out);
676 }
677 else
678 {
679 printf("Error setting up Metropolis adaptive simulation\n");
680 if (f_start) fclose(f_start);
681 }
682 }