Debian Codegraph @

contrib/ms-sbvar/switch_dw/state_space/sbvar/sbvar_forecast.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 "VARbase.h"
21 #include "VARio.h"
22 #include "dw_sbvar_command_line.h"
23 #include "dw_matrix_rand.h"
24 #include "dw_parse_cmd.h"
25 #include "dw_ascii.h"
26 #include "dw_error.h"
27 #include "dw_histogram.h"
28 #include "dw_math.h"
29 #include "dw_std.h"
30
31 #include <stdlib.h>
32 #include <string.h>
33
34 TMatrix ForecastHistogramToPercentile(TMatrix F, int data, int horizon, int T, PRECISION percentile, TMatrixHistogram *histogram, TStateModel *model, int flag)
35 {
36 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
37 TMatrix G;
38 int i, j, d=flag ? 1 : 0;
39 if (!F)
40 {
41 if (!(F=CreateMatrix(data+horizon,p->nvars+d))) return (TMatrix)NULL;
42 }
43 else
44 if ((RowM(F) != data+horizon) || (ColM(F) != p->nvars+d))
45 {
46 dw_Error(SIZE_ERR);
47 return (TMatrix)NULL;
48 }
49 MatrixPercentile(G=CreateMatrix(horizon,p->nvars),percentile,histogram);
50 for (i=0; i < data; i++)
51 {
52 if (d) ElementM(F,i,0)=T-data+i+1;
53 for (j=0; j < p->nvars; j++) ElementM(F,i,j+d)=ElementV(p->Y[T-data+i+1],j);
54 }
55 for (i=0; i < horizon; i++)
56 {
57 if (d) ElementM(F,i+data,0)=T+i+1;
58 for (j=0; j < p->nvars; j++) ElementM(F,i+data,j+d)=ElementM(G,i,j);
59 }
60 FreeMatrix(G);
61 return F;
62 }
63
64 /*
65 Assumes
66 f_out : valid FILE pointer
67 percentiles : vector of numbers between 0 and 1 inclusive
68 draws : number of draws of shocks and regimes to make for each posterior draw
69 posterior_file : FILE pointer to file containing posterior draws. If null, current parameters are used.
70 T : last observation to treat as data. Usually equals model->nobs.
71 h : non-negative integer
72 model : point to valid TStateModel structure
73
74 Results:
75 Computes and prints to the file f_out the requested percentiles for forecasts
76 of the observables.
77
78 Returns:
79 One upon success and zero otherwise.
80
81 */
82 TMatrixHistogram* forecast_percentile(int draws, FILE *posterior_file, int thin, int T, int h, TStateModel *model, int flag)
83 {
84 T_VAR_Parameters *p;
85 int done=0, *S, i=0, j, k, m, n=1000;
86 TVector init_prob, prob, *shocks, initial;
87 TMatrix forecast;
88 TMatrixHistogram *histogram;
89
90 // quick check of passed parameters
91 if ((draws <= 0) || (T < 0) || (h <= 0) || !model) return (TMatrixHistogram*)NULL;
92
93 p=(T_VAR_Parameters*)(model->theta);
94
95 if (T > p->nobs) return (TMatrixHistogram*)NULL;
96
97 // allocate memory
98 S=(int*)dw_malloc(h*sizeof(int));
99 forecast=CreateMatrix(h,p->nvars);
100 histogram=CreateMatrixHistogram(h,p->nvars,100,HISTOGRAM_VARIABLE);
101 initial=CreateVector(p->npre);
102 shocks=dw_CreateArray_vector(h);
103 for (i=h-1; i >= 0; i--) shocks[i]=CreateVector(p->nvars);
104 init_prob=CreateVector(p->nstates);
105 prob=CreateVector(p->nstates);
106
107 // Initial value
108 EquateVector(initial,p->X[T]);
109
110 i=0;
111 while (!done)
112 {
113 // Read parameters and push them into model
114 if (!posterior_file)
115 done=1;
116 else
117 {
118 dw_NextLine(posterior_file,thin-1);
119 if (!GetPosteriorDraw(posterior_file,model,flag))
120 {
121 done=2;
122 printf("total posterior draws processed - %d\n",i);
123 }
124 else
125 if (i++ == n)
126 {
127 printf("%d posterior draws processed\n",i);
128 n+=1000;
129 }
130 }
131
132 if (done != 2)
133 {
134 // Get filtered probability at time T
135 for (j=p->nstates-1; j >= 0; j--)
136 ElementV(init_prob,j)=ProbabilityStateConditionalCurrent(j,T,model);
137
138 for (k=draws; k > 0; k--)
139 {
140 // Draw time T regime
141 m=DrawDiscrete(init_prob);
142
143 // Draw regimes from time T+1 through T+h inclusive
144 for (j=0; j < h; j++)
145 {
146 ColumnVector(prob,model->sv->Q,m);
147 S[j]=m=DrawDiscrete(prob);
148 }
149
150 // Draw shocks
151 for (j=h-1; j >= 0; j--) dw_NormalVector(shocks[j]); // InitializeVector(shocks[i],0.0);
152
153 // Compute forecast
154 if (!forecast_base(forecast,h,initial,shocks,S,model))
155 goto ERROR_EXIT;
156
157 // Accumulate impulse response
158 AddMatrixObservation(forecast,histogram);
159 }
160 }
161 }
162
163 ERROR_EXIT:
164 FreeMatrix(forecast);
165 dw_free(S);
166 FreeVector(initial);
167 FreeVector(prob);
168 FreeVector(init_prob);
169 dw_FreeArray(shocks);
170
171 return histogram;
172 }
173
174 /*
175 Assumes
176 f_out : valid FILE pointer
177 percentiles : vector of numbers between 0 and 1 inclusive
178 draws : number of draws of shocks to make for each posterior draw
179 posterior_file : FILE pointer to file containing posterior draws. If null, current parameters are used.
180 s : base state
181 T : last observation to treat as data. Usually equals model->nobs.
182 h : non-negative integer
183 model : point to valid TStateModel/T_MSStateSpace structure
184
185 Results:
186 Computes and prints to the file f_out the requested percentiles for forecasts
187 of the observables.
188
189 Returns:
190 One upon success and zero otherwise.
191
192 Notes:
193 The regime at time T is drawn from the filtered probabilities at time t, and
194 is set to s there after.
195
196 */
197 TMatrixHistogram* forecast_percentile_regime(int draws, FILE *posterior_file, int thin, int s, int T, int h, TStateModel *model, int flag)
198 {
199 T_VAR_Parameters *p;
200 int done=0, *S, i=0, j, k, n=1000;
201 TVector init_prob, prob, *shocks, initial;
202 TMatrix forecast;
203 TMatrixHistogram *histogram;
204
205 // quick check of passed parameters
206 if ((draws <= 0) || (T < 0) || (h <= 0) || !model) return 0;
207
208 p=(T_VAR_Parameters*)(model->theta);
209
210 if (T > p->nobs) return 0;
211
212 // allocate memory
213 S=(int*)dw_malloc(h*sizeof(int));
214 for (i=0; i < h; i++) S[i]=s;
215 forecast=CreateMatrix(h,p->nvars);
216 histogram=CreateMatrixHistogram(h,p->nvars,100,HISTOGRAM_VARIABLE);
217 initial=CreateVector(p->npre);
218 shocks=dw_CreateArray_vector(h);
219 for (i=h-1; i >= 0; i--) shocks[i]=CreateVector(p->nvars);
220 init_prob=CreateVector(p->nstates);
221 prob=CreateVector(p->nstates);
222
223 // Initial value
224 EquateVector(initial,p->X[T]);
225
226 i=0;
227 while (!done)
228 {
229 // Read parameters and push them into model
230 if (!posterior_file)
231 done=1;
232 else
233 {
234 dw_NextLine(posterior_file,thin-1);
235 if (!GetPosteriorDraw(posterior_file,model,flag))
236 {
237 done=2;
238 printf("total posterior draws processed - %d\n",i);
239 }
240 else
241 if (i++ == n)
242 {
243 printf("%d posterior draws processed\n",i);
244 n+=1000;
245 }
246 }
247
248 if (done != 2)
249 {
250 for (k=draws; k > 0; k--)
251 {
252 // Draw shocks
253 for (j=h-1; j >= 0; j--) dw_NormalVector(shocks[j]); // InitializeVector(shocks[i],0.0);
254
255 // Compute forecast
256 if (!forecast_base(forecast,h,initial,shocks,S,model))
257 goto ERROR_EXIT;
258
259 // Accumulate impulse response
260 AddMatrixObservation(forecast,histogram);
261 }
262 }
263 }
264
265 ERROR_EXIT:
266 FreeMatrix(forecast);
267 dw_free(S);
268 FreeVector(initial);
269 FreeVector(prob);
270 FreeVector(init_prob);
271 dw_FreeArray(shocks);
272
273 return histogram;
274 }
275
276
277 /*
278 Additional command line parameters
279
280 -horizon <integer>
281 If this argument exists, then the forecast horizon is given by the passed
282 integer. The default value is 12.
283
284 -data <integer>
285 If this argument exists, then the number of data points included in the
286 output is given by the passed integer. The default value is 0.
287
288 -error_bands
289 Output error bands. (default = off - only median is computed)
290
291 -percentiles n p_1 p_2 ... p_n
292 Percentiles to compute. The first parameter after percentiles must be the
293 number of percentiles and the following values are the actual percentiles.
294 default = 3 0.16 0.50 0.84 if error_bands flag is set
295 = 1 0.50 otherwise
296
297 -parameter_uncertainty
298 Apply parameter uncertainty when computing error bands or median.
299
300 -shocks_per_parameter <integer>
301 Number of shocks and regime paths to draw for each parameter draw. The
302 default value is 1 if parameter_uncertainty is set and 10,000 otherwise.
303
304 -thin
305 Thinning factor. Only 1/thin of the draws in posterior draws file are
306 used. The default value is 1.
307
308 -regimes
309 Produces forecasts as if each regime were permanent. (default = off)
310
311 -regime <integer>
312 Produces forecasts as if regime were permanent. Regime numbers are zero
313 based. (default = off)
314
315 -mean
316 Produces mean forecast. (default = off)
317
318 -flat
319 Assumes that posterior draws is a flat file format. The default is that
320 the posterior draws are in a free file format.
321
322 -nodate
323 If not defined, then the first column of the output is a date number. A
324 date number of one is the first date in the data series, a date number of
325 nobs is the last date in the data series, and date numbers larger than this
326 correspond to forecasts. (default = off)
327
328 */
329 void dw_sbvar_forecast_command_line(int nargs, char **args)
330 {
331 char *post=(char*)NULL, *out_filename, *fmt="%%sforecasts_percentiles_regime_%d_%%s.out", *buffer;
332 TStateModel *model;
333 T_VAR_Parameters *p;
334 TVector percentiles=(TVector)NULL;
335 int dates, type, data, s, horizon, thin, draws, i, j, n, T;
336 FILE *f_out, *posterior_file;
337 TMatrixHistogram *histogram;
338 TMatrix forecast;
339
340 TVARCommandLine *cmd=(TVARCommandLine*)NULL;
341
342 // Setup model and initial parameters
343 if (!(cmd=CreateTStateModel_VARCommandLine(nargs,args,(TVARCommandLine*)NULL)))
344 dw_Error(MEM_ERR);
345 else
346 if (!cmd->model)
347 dw_UserError("Unable to setup SBVAR from command line parameters");
348 else
349 if (!cmd->parameters_filename_actual)
350 dw_UserError("Unable to initialize parameters from command line parameters");
351 else
352 {
353 model=cmd->model;
354 p=(T_VAR_Parameters*)(model->theta);
355
356 // horizon
357 horizon=dw_ParseInteger_String(nargs,args,"horizon",12);
358
359 // Output tag
360 OutTag_VARCommandLine(cmd);
361
362 // Type
363 type=(dw_FindArgument_String(nargs,args,"flat") >= 0) ? F_FLAT : F_FREE;
364
365 // Dates
366 dates=(dw_FindArgument_String(nargs,args,"nodate") >= 0) ? 0 : 1;
367
368 // Data output
369 data=dw_ParseInteger_String(nargs,args,"data",0);
370
371 // Last data point
372 T=p->nobs;
373
374
375 //============================= Compute forecasts =============================
376
377 /* // Mean forecast */
378 /* if (dw_FindArgument_String(nargs,args,"mean") != -1) */
379 /* { */
380 /* fmt="forecasts_mean_%s.prn"; */
381 /* sprintf(out_filename=(char*)dw_malloc(strlen(fmt) + strlen(tag) - 1),fmt,tag); */
382 /* f_out=fopen(out_filename,"wt"); */
383 /* dw_free(out_filename); */
384 /* printf("Constructing mean forecast\n"); */
385 /* if (F=dw_state_space_mean_unconditional_forecast((TVector*)NULL,h,statespace->nobs,model)) */
386 /* for (i=0; i < h; i++) */
387 /* dw_PrintVector(f_out,F[i],"%le "); */
388 /* fclose(f_out); */
389 /* } */
390
391 // Parameter uncertainty
392 if (dw_FindArgument_String(nargs,args,"parameter_uncertainty") != -1)
393 {
394 // Open posterior draws file
395 post=CreateFilenameFromTag((type == F_FREE) ? "%ssimulation_%s.out" : "%sdraws_%s.out",cmd->in_tag ? cmd->in_tag : "notag",cmd->in_directory);
396 if (!(posterior_file=fopen(post,"rt")))
397 {
398 dw_free(post);
399 printf("dw_sbvar_forecast command line(): Unable to open posterior draws file: %s\n",post);
400 return;
401 }
402 else
403 dw_free(post);
404
405 // Get thinning factor from command line
406 if ((thin=dw_ParseInteger_String(nargs,args,"thin",1)) <= 0) thin=1;
407
408 // Get shocks_per_parameter from command line
409 draws=dw_ParseInteger_String(nargs,args,"shocks_per_parameter",1);
410 }
411 else
412 {
413 // Using posterior estimate
414 posterior_file=(FILE*)NULL;
415
416 // thinning factor not used
417 thin=1;
418
419 // Get shocks_per_parameter from command line
420 draws=dw_ParseInteger_String(nargs,args,"shocks_per_parameter",10000);
421 }
422
423 // Setup percentiles
424 if ((i=dw_FindArgument_String(nargs,args,"percentiles")) == -1)
425 if (dw_FindArgument_String(nargs,args,"error_bands") == -1)
426 {
427 percentiles=CreateVector(1);
428 ElementV(percentiles,0)=0.5;
429 }
430 else
431 {
432 percentiles=CreateVector(3);
433 ElementV(percentiles,0)=0.16; ElementV(percentiles,1)=0.5; ElementV(percentiles,2)=0.84;
434 }
435 else
436 if ((i+1 < nargs) && dw_IsInteger(args[i+1]) && ((n=atoi(args[i+1])) > 0) && (i+1+n < nargs))
437 {
438 percentiles=CreateVector(n);
439 for (j=0; j < n; j++)
440 if (!dw_IsFloat(args[i+2+j])|| ((ElementV(percentiles,j)=atof(args[i+2+j])) <= 0.0) || (ElementV(percentiles,j) >= 1.0))
441 break;
442 if (j < n)
443 {
444 FreeVector(percentiles);
445 dw_UserError("dw_sbvar_forecast command line(): Error parsing percentiles\n");
446 return;
447 }
448 }
449 else
450 {
451 dw_UserError("dw_sbvar_forecast command line(): Error parsing percentiles\n");
452 return;
453 }
454
455 if (dw_FindArgument_String(nargs,args,"regimes") != -1)
456 for (s=0; s < p->nstates; s++)
457 {
458 if (posterior_file) rewind(posterior_file);
459 // s must not contain more than 10 digits
460 sprintf(buffer=(char*)dw_malloc(strlen(fmt) + 10),fmt,s);
461 out_filename=CreateFilenameFromTag(buffer,cmd->out_tag,cmd->out_directory);
462 dw_free(buffer);
463 if ((f_out=fopen(out_filename,"wt")))
464 {
465 printf("Constructing percentiles for forecasts - regime %d\n",s);
466 if ((histogram=forecast_percentile_regime(draws,posterior_file,thin,s,T,horizon,model,type)))
467 {
468 for (i=0; i < DimV(percentiles); i++)
469 if ((forecast=ForecastHistogramToPercentile((TMatrix)NULL,data,horizon,T,ElementV(percentiles,i),histogram,model,dates)))
470 {
471 dw_PrintMatrix(f_out,forecast,"%lg ");
472 fprintf(f_out,"\n");
473 FreeMatrix(forecast);
474 }
475 FreeMatrixHistogram(histogram);
476 }
477 fclose(f_out);
478 }
479 dw_free(out_filename);
480 }
481 else
482 if (dw_FindArgument_String(nargs,args,"regime") != -1)
483 if (((s=dw_ParseInteger_String(nargs,args,"regime",-1)) >= 0) && (s < p->nstates))
484 {
485 // s must not contain more than 10 digits
486 sprintf(buffer=(char*)dw_malloc(strlen(fmt) + 10),fmt,s);
487 out_filename=CreateFilenameFromTag(buffer,cmd->out_tag,cmd->out_directory);
488 dw_free(buffer);
489 if ((f_out=fopen(out_filename,"wt")))
490 {
491 printf("Constructing percentiles for forecasts - regime %d\n",s);
492 if ((histogram=forecast_percentile_regime(draws,posterior_file,thin,s,T,horizon,model,type)))
493 {
494 for (i=0; i < DimV(percentiles); i++)
495 if ((forecast=ForecastHistogramToPercentile((TMatrix)NULL,data,horizon,T,ElementV(percentiles,i),histogram,model,dates)))
496 {
497 dw_PrintMatrix(f_out,forecast,"%lg ");
498 fprintf(f_out,"\n");
499 FreeMatrix(forecast);
500 }
501 FreeMatrixHistogram(histogram);
502 }
503 fclose(f_out);
504 }
505 dw_free(out_filename);
506 }
507 else
508 {
509 printf("dw_sbvar_forecast command line(): regime number must be between 0 and %d inclusive\n",p->nstates-1);
510 return;
511 }
512 else
513 {
514 out_filename=CreateFilenameFromTag("%sforecasts_percentiles_%s.out",cmd->out_tag,cmd->out_directory);
515 if ((f_out=fopen(out_filename,"wt")))
516 {
517 printf("Constructing percentiles for forecasts - %d draws of shocks/regimes per posterior value\n",draws);
518 if ((histogram=forecast_percentile(draws,posterior_file,thin,T,horizon,model,type)))
519 {
520 for (i=0; i < DimV(percentiles); i++)
521 if ((forecast=ForecastHistogramToPercentile((TMatrix)NULL,data,horizon,T,ElementV(percentiles,i),histogram,model,dates)))
522 {
523 dw_PrintMatrix(f_out,forecast,"%lg ");
524 fprintf(f_out,"\n");
525 FreeMatrix(forecast);
526 }
527 FreeMatrixHistogram(histogram);
528 }
529 fclose(f_out);
530 }
531 dw_free(out_filename);
532 }
533
534 if (posterior_file) fclose(posterior_file);
535 FreeVector(percentiles);
536 //=============================================================================
537 }
538
539 Free_VARCommandLine(cmd);
540 }