Debian Codegraph @

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

raw
1 /*
2 * Copyright (C) 1996-2012 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_error.h"
23 #include "dw_ascii.h"
24 #include "dw_parse_cmd.h"
25 #include "dw_array.h"
26 #include "dw_metropolis_simulation.h"
27 #include "dw_metropolis_simulation_prior.h"
28 #include "dw_std.h"
29
30 #include <time.h>
31 #include <string.h>
32 #include <ctype.h>
33 #include <stdlib.h>
34 #include <limits.h>
35 #include <math.h>
36
37 #include <time.h>
38
39 /* Undefine to use wall time instead of process time */
40 //#define WALL_TIME
41
42 //=======================
43
44 int SimulatePrior(int burn_in, int draws, int thin, int period, TStateModel *model, FILE *f_out)
45 {
46 #ifdef WALL_TIME
47 time_t time;
48 #else
49 clock_t begin_time;
50 #endif
51 int i, j, check, ntheta, nq;
52 TVector theta, q;
53
54 // Initialization
55 ntheta=NumberFreeParametersTheta(model);
56 nq=NumberFreeParametersQ(model);
57 if (ntheta) theta=CreateVector(ntheta);
58 if (nq) q=CreateVector(nq);
59
60 // Burn-in
61 ResetCounts_metropolis_theta(model->metropolis_theta);
62 ResetMetropolisHastingsCounts_q(model);
63 if (burn_in > 0)
64 {
65 printf("(0 / %d) Beginning burn in.\n",burn_in);
66 #ifdef WALL_TIME
67 begin_time=time((time_t*)NULL);
68 #else
69 begin_time=clock();
70 #endif
71 for (check=period, i=1; i <= burn_in; i++)
72 {
73 draw_prior_all_metropolis(model);
74
75 if (i == check)
76 {
77 check+=period;
78 #ifdef WALL_TIME
79 printf("(%d / %d) Total Elapsed Time: %d seconds\n",i,burn_in,(int)(time((time_t*)NULL) - begin_time));
80 #else
81 printf("(%d / %d) Total Elapsed Time: %lf seconds\n",i,burn_in,((double)(clock() - begin_time))/CLOCKS_PER_SEC);
82 #endif
83 }
84 }
85 #ifdef WALL_TIME
86 printf("(%d / %d) Elapsed Time: %d seconds\n",burn_in,burn_in,(int)(time((time_t*)NULL) - begin_time));
87 #else
88 printf("(%d / %d) Elapsed Time: %lf seconds\n",burn_in,burn_in,((double)(clock() - begin_time))/CLOCKS_PER_SEC);
89 #endif
90 }
91
92
93 // Simulate
94 if (draws > 0)
95 {
96 printf("(0 / %d) Beginning simulation.\n",draws);
97 #ifdef WALL_TIME
98 begin_time=time((time_t*)NULL);
99 #else
100 begin_time=clock();
101 #endif
102 for (check=period, i=1; i <= draws; i++)
103 {
104 for (j=thin; j > 0; j--) draw_prior_all_metropolis(model);
105
106 fprintf(f_out,"%le %le",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model));
107 if (ntheta)
108 {
109 ConvertThetaToFreeParameters(model,pElementV(theta));
110 for (j=0; j < ntheta; j++) fprintf(f_out," %le",ElementV(theta,j));
111 }
112 if (nq)
113 {
114 ConvertQToFreeParameters(model,pElementV(q));
115 for (j=0; j < nq; j++) fprintf(f_out," %le",ElementV(q,j));
116 }
117 fprintf(f_out,"\n");
118
119 if (i == check)
120 {
121 check+=period;
122 #ifdef WALL_TIME
123 printf("(%d / %d) Total Elapsed Time: %d seconds\n",i,draws,(int)(time((time_t*)NULL) - begin_time));
124 #else
125 printf("(%d / %d) Total Elapsed Time: %lf seconds\n",i,draws,((double)(clock() - begin_time))/CLOCKS_PER_SEC);
126 #endif
127 }
128 }
129 #ifdef WALL_TIME
130 printf("(%d / %d) Elapsed Time: %d seconds\n",draws,draws,(int)(time((time_t*)NULL) - begin_time));
131 #else
132 printf("(%d / %d) Elapsed Time: %lf seconds\n",draws,draws,((double)(clock() - begin_time))/CLOCKS_PER_SEC);
133 #endif
134 }
135
136 // Clean up
137 if (ntheta) FreeVector(theta);
138 if (nq) FreeVector(q);
139 return 0;
140 }
141
142 /*
143 Returns 1 if metropolis_theta parameters properly set and 0 otherwise. See dw_simulate_prior_command_line for
144 command line options.
145 */
146 int SetUpMetropolisSimulationPrior(int n_args, char **args, char *tag, TStateModel *model, int default_period)
147 {
148 TMetropolis_theta *metropolis=model->metropolis_theta;
149 FILE *f_in;
150 int i, ndraws, ntheta, nq, period_s, max_period_s, period_a, max_period_a,
151 begin_time, end_time, free_filename_metropolis=0, free_filename_hessian=0;
152 PRECISION center_s, center_a;
153 char *filename_metropolis, *id, *fmt;
154 TMatrix hessian=(TMatrix)NULL, hessian_theta=(TMatrix)NULL, posterior_draws=(TMatrix)NULL,
155 variance=(TMatrix)NULL, X=(TMatrix)NULL;
156 TVector mean=(TVector)NULL, x=(TVector)NULL, theta=(TVector)NULL;
157
158 // Get Sizes
159 ntheta=NumberFreeParametersTheta(model);
160 nq=NumberFreeParametersQ(model);
161
162 // Input/output file name for metropolis_theta info
163 if (!(filename_metropolis=dw_ParseString_String(n_args,args,"af",(char*)NULL)))
164 {
165 if (!tag)
166 {
167 printf("No adaptive filename (-af) or tag (-t) specified\n");
168 return 0;
169 }
170 fmt="metropolis_theta_prior_%s.out";
171 sprintf(filename_metropolis=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,tag);
172 free_filename_metropolis=1;
173 }
174
175 // First try: read info from adpative file if -diagonal is not specified
176 if (dw_FindArgument_String(n_args,args,"diagonal") == -1)
177 if (Read_metropolis_theta((FILE*)NULL,filename_metropolis,(char*)NULL,metropolis))
178 {
179 // Cleanup and return
180 if (free_filename_metropolis) dw_free(filename_metropolis);
181 return READ_METROPOLIS_INFO;
182 }
183 else
184 printf("Unable to open %s. Attempting calibration\n",filename_metropolis);
185 else
186 printf("Starting recalibration\n");
187
188 // Setup calibration parameters
189 center_s=dw_ParseFloating_String(n_args,args,"cs",0.20);
190 //center_a=dw_ParseFloating_String(n_args,args,"ca",0.25);
191 period_s=dw_ParseInteger_String(n_args,args,"ps",default_period);
192 //period_a=dw_ParseInteger_String(n_args,args,"pa",default_period);
193 //max_period_s=dw_ParseInteger_String(n_args,args,"mps",8*period_s);
194 max_period_s=dw_ParseInteger_String(n_args,args,"mps",16*period_s);
195 //max_period_a=dw_ParseInteger_String(n_args,args,"mpa",16*period_a);
196
197 // Second try: Use diagonal
198 // Initializing scale and directions
199 Setup_metropolis_theta_diagonal(metropolis);
200 Setup_metropolis_theta_blocks_full(metropolis);
201
202 // Calibrating
203 begin_time=(int)time((time_t*)NULL);
204 Calibrate_metropolis_theta_prior(model,center_s,period_s,max_period_s,1);
205 //ndraws=Calibrate_metropolis_theta_prior_two_pass(model,center_s,period_s,max_period_s,center_a,period_a,max_period_a,1);
206 end_time=(int)time((time_t*)NULL);
207
208 // Print Metropolis info
209 WriteMetropolisThetaInfo(filename_metropolis,tag,DIAGONAL_CALIBRATION | PRIOR_CALIBRATION,center_s,period_s,max_period_s,
210 center_a,period_a,max_period_a,ndraws,end_time-begin_time,model);
211
212 // Clean up and return
213 if (free_filename_metropolis) dw_free(filename_metropolis);
214 return ((dw_FindArgument_String(n_args,args,"special") != -1) ? SPECIAL_CALIBRATION : DIAGONAL_CALIBRATION) | TWO_PASS;
215 }
216
217 //****************************************************************************//
218 //**************************** Simulation Main *****************************//
219 //****************************************************************************//
220 /*
221 Command line parameters
222
223 General parameters
224 -t : filename tag
225 -ft : filename tag - supersedes -t
226 -outtag : filename tag - supersedes -t and -ft
227
228 Adaptive jump ratio parameters
229 -cs <real> : target acceptance rate for single variable calibrations (default = 0.20)
230 -ca <real> : target acceptance rate for overall calibrations (default = 0.25)
231 -ps <integer> : the initial period for the single variable calibrations (default = 20)
232 -pa <integer> : the initial period for the overall calibrations (default = 20)
233 -mps <integer> : the maximum period for the single variable calibrations (default = 8*ps)
234 -mpa <integer> : the maximum period for the overall calibrations (default = 16*mps)
235 -diagonal : Forces calibration using two-pass diagonal, even if calibration has alread been performed.
236 -af <filename> : file for storing the calibrated metropolis parameters. (default = metropolis_theta_<tag>.out)
237 -hf <filename> : file containing the hessian matrix. (default = outdataout_<tag>.prn)
238
239 Simulation parameters
240 -ndraws : number of draws to save (default = 1000)
241 -burnin : number of burn-in draws (default = 0.1 * ndraws)
242 -thin : thinning factor. Total number of draws made is thin*ndraws + burnin (default = 1)
243 -of <filename> : output filename (default = simulation_prior_<tag>.out)
244
245 Attempts to setup metropolis parameters from command line for simulating theta from the prior. Note if -diagonal
246 is not specified, the default behavior is to first look for calibration file and it is not present to use the
247 two-pass diagonal method.
248 */
249 void dw_simulate_prior_command_line(int n_args, char **args, TStateModel *model, TVector start_value, int generator_init)
250 {
251 FILE *f_out;
252 char *tag, *default_filename, *filename, *fmt;
253 int ndraws, burn_in, thin, default_period=20, n_theta=NumberFreeParametersTheta(model), n_q=NumberFreeParametersQ(model);
254
255 // Initialize generator
256 dw_initialize_generator(generator_init);
257
258 // Get tag from command line
259 tag=dw_ParseString(n_args,args,'t',(char*)NULL);
260 tag=dw_ParseString_String(n_args,args,"ft",tag);
261 tag=dw_ParseString_String(n_args,args,"outtag",tag);
262
263 // Push starting value into model
264 if (start_value)
265 {
266 if (n_theta) ConvertFreeParametersToTheta(model,pElementV(start_value));
267 if (n_q) ConvertFreeParametersToQ(model,pElementV(start_value)+n_theta);
268 }
269
270 if (SetUpMetropolisSimulationPrior(n_args,args,tag,model,default_period))
271 {
272 // simulation parameters
273 ndraws=dw_ParseInteger_String(n_args,args,"ndraws",1000);
274 burn_in=dw_ParseInteger_String(n_args,args,"burnin",ndraws/10);
275 thin=dw_ParseInteger_String(n_args,args,"thin",1);
276
277 // Starting Simulation
278 fmt="simulation_prior_%s.out";
279 sprintf(default_filename=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,tag);
280 filename=dw_ParseString_String(n_args,args,"fo",default_filename);
281 f_out=fopen(filename,"wt");
282 dw_free(default_filename);
283
284 SimulatePrior(burn_in,ndraws,thin,1000,model,f_out);
285
286 if (f_out) fclose(f_out);
287 }
288 else
289 {
290 printf("Error setting up Metropolis adaptive simulation\n");
291 }
292 }