| 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_matrix.h" |
| 19 |
#include "dw_rand.h" |
| 20 |
#include "dw_parse_cmd.h" |
| 21 |
#include "dw_ascii.h" |
| 22 |
#include "dw_error.h" |
| 23 |
#include "VARbase.h" |
| 24 |
#include "VARio.h" |
| 25 |
#include "switch.h" |
| 26 |
#include "switchio.h" |
| 27 |
#include "dw_sbvar_command_line.h" |
| 28 |
#include "dw_std.h" |
| 29 |
|
| 30 |
#include <stdlib.h> |
| 31 |
#include <string.h> |
| 32 |
#include <math.h> |
| 33 |
#include <time.h> |
| 34 |
|
| 35 |
/* |
| 36 |
Returns the largest of the absolute values of the eigenvalues of the companion |
| 37 |
matrix of B |
| 38 |
*/ |
| 39 |
__attribute__((unused)) |
| 40 |
static PRECISION LargestRoot(TMatrix B) |
| 41 |
{ |
| 42 |
TMatrix X; |
| 43 |
TVector re_eig, im_eig; |
| 44 |
int i, k=RowM(B), n=ColM(B); |
| 45 |
PRECISION max, tmp; |
| 46 |
InitializeMatrix(X=CreateMatrix(k,k),0.0); |
| 47 |
for (i=n; i < k; i++) ElementM(X,i-n,i)=1.0; |
| 48 |
InsertSubMatrix(X,B,0,0,0,0,k,n); |
| 49 |
re_eig=CreateVector(k); |
| 50 |
im_eig=CreateVector(k); |
| 51 |
Eigenvalues(re_eig,im_eig,X); |
| 52 |
max=ElementV(re_eig,0)*ElementV(re_eig,0)+ElementV(im_eig,0)*ElementV(im_eig,0); |
| 53 |
for (i=k-1; i > 0; i--) |
| 54 |
if ((tmp=ElementV(re_eig,i)*ElementV(re_eig,i)+ElementV(im_eig,i)*ElementV(im_eig,i)) > max) max=tmp;; |
| 55 |
FreeVector(im_eig); |
| 56 |
FreeVector(re_eig); |
| 57 |
FreeMatrix(X); |
| 58 |
return sqrt(max); |
| 59 |
} |
| 60 |
|
| 61 |
/* |
| 62 |
Computes the matrices A0(s)*Xi(s) and B(s) = Ahat(s) * inverse(A0(s)) |
| 63 |
where Ahat(s) are the first nvars*nlags rows of Aplus(s), for 0 <= s < h. |
| 64 |
The integer h is the number of regimes. Both A0_Xi and B must be matrix |
| 65 |
arrays of length h and each element of A0_Xi and B must be of the proper |
| 66 |
size. |
| 67 |
*/ |
| 68 |
void GetIRMatrices(int h, TMatrix *A0_Xi, TMatrix *B, T_VAR_Parameters *p) |
| 69 |
{ |
| 70 |
TMatrix Aplus; |
| 71 |
int i, j, k; |
| 72 |
PRECISION tmp; |
| 73 |
for (k=h-1; k >= 0; k--) |
| 74 |
{ |
| 75 |
MakeA0(A0_Xi[k],k,p); |
| 76 |
Aplus=MakeAplus((TMatrix)NULL,k,p); |
| 77 |
SubMatrix(B[k],Aplus,0,0,p->nvars*p->nlags,p->nvars); |
| 78 |
FreeMatrix(Aplus); |
| 79 |
ProductInverseMM(B[k],B[k],A0_Xi[k]); |
| 80 |
for (j=p->nvars-1; j >= 0; j--) |
| 81 |
for (tmp=sqrt(p->Zeta[j][p->var_states[j][k]]), i=p->nvars-1; i >= 0; i--) |
| 82 |
ElementM(A0_Xi[k],i,j)*=tmp; |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
/* |
| 88 |
Additional command line parameters |
| 89 |
|
| 90 |
-ndraws <integer> |
| 91 |
Number of draws to save (default value = 1000) |
| 92 |
-burnin <integer> |
| 93 |
Number of burn-in draws (default = 0.1 * thin * ndraws) |
| 94 |
-thin <integer> |
| 95 |
Thinning factor. Total number of draws made is thin*ndraws + burnin (default = 1) |
| 96 |
-no_deg <integer : retry> <integer : cutoff> |
| 97 |
Rejects degenerate draws of regimes. Will redraw regimes up to retry times. In |
| 98 |
order not to be degenerate, there must be at least cutoff observations for each |
| 99 |
state. (default = 1000 1) |
| 100 |
-append |
| 101 |
Append simulation and info to existing files if they exist and use last parameter |
| 102 |
draw as initial value. (default overwrites existing files) |
| 103 |
-mh <integer> |
| 104 |
Tuning period for Metropolis-Hasting draws (default value = 30000) |
| 105 |
-flat |
| 106 |
Produce flat output file and header file (default value = off) |
| 107 |
-nofree |
| 108 |
Do not produce free parameters file (default value = off) |
| 109 |
-nd1 |
| 110 |
Normalize diagonal of A0 to one (flat output only) |
| 111 |
*/ |
| 112 |
//#define DEBUG_1 |
| 113 |
void dw_sbvar_simulate_command_line(int nargs, char **args) |
| 114 |
{ |
| 115 |
TStateModel *model; |
| 116 |
T_VAR_Parameters *p; |
| 117 |
FILE *f_flat, *f_free, *f_info; |
| 118 |
char *filename; |
| 119 |
time_t begin_time, end_time; |
| 120 |
int count, check, period=1000, i, tuning, burnin, ndraws, thin, append, writeflat, writefree, nd1; |
| 121 |
TVARCommandLine *cmd=(TVARCommandLine*)NULL; |
| 122 |
TVector parameters; |
| 123 |
|
| 124 |
// Get tuning peroid, burn-in period, number of iterations, and thinning factor |
| 125 |
ndraws=dw_ParseInteger_String(nargs,args,"ndraws",1000); |
| 126 |
thin=dw_ParseInteger_String(nargs,args,"thin",1); |
| 127 |
burnin=dw_ParseInteger_String(nargs,args,"burnin",(ndraws*thin)/10); |
| 128 |
tuning=dw_ParseInteger_String(nargs,args,"mh",30000); |
| 129 |
|
| 130 |
// Append file |
| 131 |
append=(dw_FindArgument_String(nargs,args,"append") >= 0) ? 1 : 0; |
| 132 |
|
| 133 |
// Get output options |
| 134 |
writeflat=(dw_FindArgument_String(nargs,args,"flat") >= 0) ? 1 : 0; |
| 135 |
writefree=(dw_FindArgument_String(nargs,args,"nofree") >= 0) ? 0 : 1; |
| 136 |
nd1=(dw_FindArgument_String(nargs,args,"nd1") >= 0) ? 1 : 0; |
| 137 |
|
| 138 |
// Setup model and initial parameters |
| 139 |
if (!(cmd=CreateTStateModel_VARCommandLine(nargs,args,(TVARCommandLine*)NULL))) |
| 140 |
dw_Error(MEM_ERR); |
| 141 |
else |
| 142 |
if (!cmd->model) |
| 143 |
dw_UserError("Unable to setup SBVAR from command line parameters"); |
| 144 |
else |
| 145 |
if (!cmd->parameters_filename_actual) |
| 146 |
dw_UserError("Unable to initialize parameters from command line parameters"); |
| 147 |
else |
| 148 |
{ |
| 149 |
model=cmd->model; |
| 150 |
p=(T_VAR_Parameters*)(model->theta); |
| 151 |
|
| 152 |
// Degeneracy behavior |
| 153 |
if ((i=dw_FindArgument_String(nargs,args,"no_deg")) == -1) |
| 154 |
model->reject_degenerate_draws=0; |
| 155 |
else |
| 156 |
{ |
| 157 |
if ((i+1 >= nargs) || ((model->reject_degenerate_draws=atoi(args[i+1])) <= 0)) model->reject_degenerate_draws=100; |
| 158 |
if ((i+2 >= nargs) || ((model->degenerate_draws_cutoff=atoi(args[i+2])) <= 0)) model->degenerate_draws_cutoff=1; |
| 159 |
} |
| 160 |
|
| 161 |
|
| 162 |
// Allocate parameters workspace |
| 163 |
parameters=CreateVector(NumberFreeParametersTheta(model)+NumberFreeParametersQ(model)); |
| 164 |
|
| 165 |
// initialize parameters from previous simulation run if append |
| 166 |
if (append) |
| 167 |
{ |
| 168 |
if (writefree) |
| 169 |
{ |
| 170 |
filename=CreateFilenameFromTag("%ssimulation_%s.out",cmd->out_tag,cmd->out_directory); |
| 171 |
f_free=fopen(filename,"rt"); |
| 172 |
dw_free(filename); |
| 173 |
if (f_free) |
| 174 |
{ |
| 175 |
while (GetPosteriorDraw(f_free,model,F_FREE)); |
| 176 |
fclose(f_free); |
| 177 |
} |
| 178 |
} |
| 179 |
else |
| 180 |
if (writeflat) |
| 181 |
{ |
| 182 |
filename=CreateFilenameFromTag("%sdraws_%s.out",cmd->out_tag,cmd->out_directory); |
| 183 |
f_flat=fopen(filename,"rt"); |
| 184 |
dw_free(filename); |
| 185 |
if (f_flat) |
| 186 |
{ |
| 187 |
while (GetPosteriorDraw(f_flat,model,F_FLAT)); |
| 188 |
fclose(f_flat); |
| 189 |
} |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
// Save initial parameters |
| 194 |
ConvertThetaToFreeParameters(model,pElementV(parameters)); |
| 195 |
ConvertQToFreeParameters(model,pElementV(parameters)+NumberFreeParametersTheta(model)); |
| 196 |
|
| 197 |
// Output tag |
| 198 |
if (!cmd->out_tag) |
| 199 |
cmd->out_tag=dw_DuplicateString(cmd->in_tag ? cmd->in_tag : ""); |
| 200 |
|
| 201 |
// Open header and flat file and print headers |
| 202 |
if (writeflat) |
| 203 |
{ |
| 204 |
filename=CreateFilenameFromTag("%sdraws_header_%s.out",cmd->out_tag,cmd->out_directory); |
| 205 |
if ((f_flat=fopen(filename,"wt"))) |
| 206 |
{ |
| 207 |
dw_free(filename); |
| 208 |
WriteBaseTransitionMatricesFlat_Headers(f_flat,model); |
| 209 |
Write_VAR_ParametersFlat_Headers(f_flat,model); |
| 210 |
fprintf(f_flat,"\n"); |
| 211 |
fclose(f_flat); |
| 212 |
} |
| 213 |
|
| 214 |
filename=CreateFilenameFromTag("%sdraws_%s.out",cmd->out_tag,cmd->out_directory); |
| 215 |
f_flat=fopen(filename,append ? "at" : "wt"); |
| 216 |
dw_free(filename); |
| 217 |
} |
| 218 |
else |
| 219 |
f_flat=(FILE*)NULL; |
| 220 |
|
| 221 |
// Open free file |
| 222 |
if (writefree) |
| 223 |
{ |
| 224 |
filename=CreateFilenameFromTag("%ssimulation_%s.out",cmd->out_tag,cmd->out_directory); |
| 225 |
f_free=fopen(filename,append ? "at" : "wt"); |
| 226 |
dw_free(filename); |
| 227 |
} |
| 228 |
else |
| 229 |
f_free=(FILE*)NULL; |
| 230 |
|
| 231 |
// Begin time |
| 232 |
begin_time=(int)time((time_t*)NULL); |
| 233 |
|
| 234 |
// Open info file and write |
| 235 |
filename=CreateFilenameFromTag("%ssimulation_info_%s.out",cmd->out_tag,cmd->out_directory); |
| 236 |
f_info=fopen(filename,append ? "at" : "wt"); |
| 237 |
dw_free(filename); |
| 238 |
if (f_info) |
| 239 |
{ |
| 240 |
fprintf(f_info,"\nSimulation Run Info\n"); |
| 241 |
fprintf(f_info,"Number saved draws: %d\n",ndraws); |
| 242 |
fprintf(f_info,"Total draws: %d\n",ndraws*thin); |
| 243 |
fprintf(f_info,"Thinning factor: %d\n",thin); |
| 244 |
fprintf(f_info,"Burnin period: %d\n",burnin); |
| 245 |
fprintf(f_info,"Adaptive tuning period: %d\n",tuning); |
| 246 |
fprintf(f_info,"File format: %s\n",f_free ? (f_flat ? "free and flat formats" : "free format") : (f_flat ? "flat format" : "file not written")); |
| 247 |
fprintf(f_info,"Seed: %d\n",dw_ParseInteger_String(nargs,args,"seed",0)); |
| 248 |
fprintf(f_info,"Begin time stamp: %s",ctime(&begin_time)); |
| 249 |
} |
| 250 |
|
| 251 |
// Calibration of jumping parameters |
| 252 |
printf("Calibrating jumping parameters - %d draws\n",tuning); |
| 253 |
AdaptiveMetropolisScale(model,tuning,1000,1,(FILE*)NULL); // tuning iterations - 1000 iterations before updating - verbose |
| 254 |
end_time=(int)time((time_t*)NULL); |
| 255 |
printf("Elapsed Time: %d seconds\n",(int)(end_time - begin_time)); |
| 256 |
|
| 257 |
// Reset initial parameters |
| 258 |
ConvertFreeParametersToTheta(model,pElementV(parameters)); |
| 259 |
ConvertFreeParametersToQ(model,pElementV(parameters)+NumberFreeParametersTheta(model)); |
| 260 |
|
| 261 |
// Reset degeneracy counts |
| 262 |
model->n_degenerate_draws=model->total_degenerate_draws=0; |
| 263 |
|
| 264 |
// Burn-in period |
| 265 |
printf("Burn-in period - %d draws\n",burnin); |
| 266 |
for (check=period, count=1; count <= burnin; count++) |
| 267 |
{ |
| 268 |
DrawAll(model); |
| 269 |
|
| 270 |
if (count == check) |
| 271 |
{ |
| 272 |
check+=period; |
| 273 |
printf("%d iterations completed out of %d\n",count,burnin); |
| 274 |
end_time=(int)time((time_t*)NULL); |
| 275 |
printf("Elapsed Time: %d seconds\n",(int)(end_time - begin_time)); |
| 276 |
} |
| 277 |
} |
| 278 |
end_time=(int)time((time_t*)NULL); |
| 279 |
printf("Elapsed Time: %d seconds\n",(int)(end_time - begin_time)); |
| 280 |
ResetMetropolisInformation(p); |
| 281 |
|
| 282 |
#ifdef DEBUG_1 |
| 283 |
TMatrix *A0_Xi, *B; |
| 284 |
FILE *f_debug; |
| 285 |
|
| 286 |
f_debug=fopen("debug.out","wt"); |
| 287 |
//f_debug=stdout; |
| 288 |
|
| 289 |
A0_Xi=dw_CreateArray_matrix(model->sv->nstates); |
| 290 |
B=dw_CreateArray_matrix(model->sv->nstates); |
| 291 |
for (i=model->sv->nstates-1; i >= 0; i--) |
| 292 |
{ |
| 293 |
A0_Xi[i]=CreateMatrix(p->nvars,p->nvars); |
| 294 |
B[i]=CreateMatrix(p->nvars*p->nlags,p->nvars); |
| 295 |
} |
| 296 |
fprintf(f_debug,"%lf %lf %lf\n",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model),LogPrior(model)); |
| 297 |
/* GetIRMatrices(model->sv->nstates,A0_Xi,B,p); */ |
| 298 |
/* for (i=0; i < model->sv->nstates; i++) */ |
| 299 |
/* fprintf(f_debug," %lf",LargestRoot(B[i])); */ |
| 300 |
/* fprintf(f_debug,"\n"); */ |
| 301 |
DrawStates(model); |
| 302 |
#endif |
| 303 |
|
| 304 |
// Simulation |
| 305 |
printf("Simulating - %d draws\n",ndraws); |
| 306 |
for (check=period, count=1; count <= ndraws; count++) |
| 307 |
{ |
| 308 |
#ifdef DEBUG_1 |
| 309 |
if (f_free) |
| 310 |
{ |
| 311 |
//printf("Previous: %lf %lf %lf\n",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model),LogPrior(model)); |
| 312 |
|
| 313 |
//DrawStates(model); |
| 314 |
//printf("States: %lf %lf %lf\n",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model),LogPrior(model)); |
| 315 |
|
| 316 |
/* DrawTransitionMatrixParameters(model); */ |
| 317 |
/* printf("%lf %lf %lf\n",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model),LogPrior(model)); */ |
| 318 |
|
| 319 |
/* DrawTheta(model); */ |
| 320 |
/* printf("%lf %lf %lf\n",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model),LogPrior(model)); */ |
| 321 |
|
| 322 |
/* DrawZeta_DotProducts(model); */ |
| 323 |
/* ((T_VAR_Parameters*)(model->theta))->valid_parameters=1; */ |
| 324 |
/* ThetaChanged(model); */ |
| 325 |
/* printf("Zeta: %lf %lf %lf\n",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model),LogPrior(model)); */ |
| 326 |
|
| 327 |
/* DrawA0_Metropolis(model); */ |
| 328 |
/* ((T_VAR_Parameters*)(model->theta))->valid_parameters=1; */ |
| 329 |
/* ThetaChanged(model); */ |
| 330 |
/* printf("A0: %lf %lf %lf\n",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model),LogPrior(model)); */ |
| 331 |
|
| 332 |
/* DrawAplus(model); */ |
| 333 |
/* ((T_VAR_Parameters*)(model->theta))->valid_parameters=1; */ |
| 334 |
/* ThetaChanged(model); */ |
| 335 |
/* printf("%lf %lf %lf\n",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model),LogPrior(model)); */ |
| 336 |
|
| 337 |
if (p->Specification & SPEC_SIMS_ZHA) |
| 338 |
{ |
| 339 |
Draw_psi(model); |
| 340 |
Update_bplus_from_lambda_psi(p); |
| 341 |
Update_Aplus_from_bplus_A0(p); |
| 342 |
p->valid_parameters=1; |
| 343 |
ThetaChanged(model); |
| 344 |
fprintf(f_debug,"%lf %lf %lf\n",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model),LogPrior(model)); |
| 345 |
|
| 346 |
/* Draw_lambda(model); */ |
| 347 |
/* Update_bplus_from_lambda_psi(p); */ |
| 348 |
/* Update_Aplus_from_bplus_A0(p); */ |
| 349 |
/* p->valid_parameters=1; */ |
| 350 |
/* ThetaChanged(model); */ |
| 351 |
/* printf("lambda: %lf %lf %lf\n",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model),LogPrior(model)); */ |
| 352 |
} |
| 353 |
else |
| 354 |
{ printf("Not Sim-Zha specification\n"); dw_exit(0); } |
| 355 |
|
| 356 |
// Normalize |
| 357 |
//Normalize_VAR((T_VAR_Parameters*)(model->theta)); |
| 358 |
|
| 359 |
//getchar(); |
| 360 |
|
| 361 |
/* fprintf(f_free,"%lf %lf %lf\n",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model),LogPrior(model)); */ |
| 362 |
/* GetIRMatrices(model->sv->nstates,A0_Xi,B,p); */ |
| 363 |
/* for (i=0; i < model->sv->nstates; i++) */ |
| 364 |
/* fprintf(f_free," %lf",LargestRoot(B[i])); */ |
| 365 |
/* fprintf(f_free,"\n"); */ |
| 366 |
} |
| 367 |
#else |
| 368 |
for (i=thin; i > 0; i--) DrawAll(model); |
| 369 |
|
| 370 |
if (f_flat) |
| 371 |
{ |
| 372 |
WriteBaseTransitionMatricesFlat(f_flat,(char*)NULL,model,"%lf "); |
| 373 |
if (nd1) |
| 374 |
Write_VAR_ParametersFlat_A0_Diagonal_One(f_flat,model,"%lf "); |
| 375 |
else |
| 376 |
Write_VAR_ParametersFlat(f_flat,model,"%lf "); |
| 377 |
fprintf(f_flat,"\n"); |
| 378 |
} |
| 379 |
|
| 380 |
if (f_free) |
| 381 |
{ |
| 382 |
fprintf(f_free,"%le %le ",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model)); |
| 383 |
ConvertThetaToFreeParameters(model,pElementV(parameters)); |
| 384 |
ConvertQToFreeParameters(model,pElementV(parameters)+NumberFreeParametersTheta(model)); |
| 385 |
dw_PrintVector(f_free,parameters,"%le "); |
| 386 |
} |
| 387 |
#endif |
| 388 |
|
| 389 |
if (count == check) |
| 390 |
{ |
| 391 |
check+=period; |
| 392 |
printf("%d * %d iterations completed out of %d * %d\n",count,thin,ndraws,thin); |
| 393 |
end_time=(int)time((time_t*)NULL); |
| 394 |
printf("Elapsed Time: %d seconds\n",(int)(end_time - begin_time)); |
| 395 |
} |
| 396 |
} |
| 397 |
end_time=(int)time((time_t*)NULL); |
| 398 |
printf("Total Elapsed Time: %d seconds\n",(int)(end_time - begin_time)); |
| 399 |
|
| 400 |
if (f_info) |
| 401 |
{ |
| 402 |
fprintf(f_info,"End time stamp: %s\n",ctime(&end_time)); |
| 403 |
fprintf(f_info,"Number degenerate draws of regimes: %d (%d)\n",model->n_degenerate_draws,model->total_degenerate_draws); |
| 404 |
fprintf(f_info,"degenerate draws %s\n",model->reject_degenerate_draws ? "rejected" : "kept"); |
| 405 |
/* fprintf(f_info,"Degenerate draws by regime: "); */ |
| 406 |
/* for (i=0; i < model->sv->nstates; i++) fprintf(f_info,"%d ",model->states_count[i]); */ |
| 407 |
/* fprintf(f_info,"\n"); */ |
| 408 |
} |
| 409 |
|
| 410 |
// clean up |
| 411 |
if (f_flat) fclose(f_flat); |
| 412 |
if (f_free) fclose(f_free); |
| 413 |
if (f_info) fclose(f_info); |
| 414 |
FreeVector(parameters); |
| 415 |
} |
| 416 |
|
| 417 |
// clean up |
| 418 |
Free_VARCommandLine(cmd); |
| 419 |
} |