Debian Codegraph @

contrib/ms-sbvar/switch_dw/state_space/sbvar/sbvar_variance_decomposition.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_histogram.h"
21 #include "VARio.h"
22 #include "VARbase.h"
23 #include "dw_sbvar_command_line.h"
24 #include "dw_parse_cmd.h"
25 #include "dw_ascii.h"
26 #include "dw_error.h"
27 #include "dw_math.h"
28 #include "dw_std.h"
29 #include "sbvar_impulse_responses.h"
30
31 #include <stdlib.h>
32 #include <string.h>
33 #include <math.h>
34
35 /*
36 Assumes
37 vd : horizon x nvar*nvar matrix
38 S : integer array of length horizon
39 A0_Xi : nvar x nvar matrix equal to A0[S[0]]*Xi[S[0]]
40 B : h dimensional array of nvar x nvar*nlags matrices or null pointer.
41 See GetIRMatrices() for a description of B. A null pointer implies
42 that nlags is zero.
43
44 Notes:
45 The element in position (k,i+j*nvars) of vd is the cummulative contributions
46 to the total variance of ith variable to the jth shock at horizon k. Horizon
47 zero is the contemporaneous contribution.
48 */
49 void variance_decomposition(TMatrix vd, int *S, TMatrix A0_Xi, TMatrix* B)
50 {
51 int horizon=RowM(vd), t, j;
52 PRECISION tmp;
53
54 impulse_response(vd,S,A0_Xi,B);
55
56 for (j=ColM(vd)-1; j >= 0; j--)
57 ElementM(vd,0,j)*=ElementM(vd,0,j);
58
59 for (t=1; t < horizon; t++)
60 for (j=ColM(vd)-1; j >= 0; j--)
61 {
62 tmp=ElementM(vd,t,j);
63 ElementM(vd,t,j)=tmp*tmp+ElementM(vd,t-1,j);
64 }
65 }
66
67
68
69 /*
70 Normalizes variance decomposition. Converts cummulative contributions to the
71 total variance into cummulative percentage contributions. This routine must
72 be called before ReorderVarianceDecomposition().
73 */
74 void NormalizeVarianceDecomposition(TMatrix vd, T_VAR_Parameters *p)
75 {
76 PRECISION tmp;
77 int n=p->nvars, i, j, t;
78
79 // normalizes to percentages
80 for (t=RowM(vd)-1; t >= 0; t--)
81 for (i=0; i < n; i++)
82 {
83 for (tmp=0.0, j=0; j < n; j++) tmp+=ElementM(vd,t,j*n+i);
84 for (tmp=1.0/tmp, j=0; j < n; j++) ElementM(vd,t,j*n+i)*=tmp;
85 }
86 }
87
88 /*
89 Reorders variance decomposition. Reorders the matrix so that the element in
90 position (k,i+j*nvars) of tvd is moved to position (k,j+i*nvars). If called
91 after NormalizeVarianceDecomposition(), the element in position (k,j_i*vnars)
92 is the cummulative percentage contributions to the total variance of ith
93 variable to the jth shock at horizon k.
94 */
95 void ReorderVarianceDecomposition(TMatrix vd, T_VAR_Parameters *p)
96 {
97 PRECISION tmp;
98 int n=p->nvars, i, j, t;
99
100 // reorders columns
101 for (t=RowM(vd)-1; t >= 0; t--)
102 for (i=0; i < n; i++)
103 for (j=i+1; j < n; j++)
104 {
105 tmp=ElementM(vd,t,i*n+j);
106 ElementM(vd,t,i*n+j)=ElementM(vd,t,j*n+i);
107 ElementM(vd,t,j*n+i)=tmp;
108 }
109 }
110
111 /*
112 Assumes
113 draws : number of draws of the regime path to make for each posterior draw
114 posterior_file : FILE pointer to file containing posterior draws. If null,
115 current parameters are used.
116 thin : thinning factor to use if posterior_file is not null.
117 horizon : non-negative integer
118 ergodic : if non-zero, uses the ergodic distribution to draw the initial
119 regime, otherwise uses the filtered probabilities at time nobs.
120 model : point to valid TStateModel structure
121 flag : determines the type of posterior draws file passed.
122
123 Results:
124 Creates matrix containing the mean variance decompositions.
125
126 Returns:
127 Pointer to matrix upon success and null pointer on failure.
128
129 Notes:
130 The element in position (k,i+j*nvars) of tvd is the cummulative contributions
131 to the total variance of ith variable to the jth shock at horizon k. Horizon
132 zero is the contemporaneous contribution.
133 */
134 TMatrix variance_decomposition_mean(int draws, FILE *posterior_file, int thin, int ergodic, int horizon, TStateModel *model, int flag)
135 {
136 T_VAR_Parameters *p;
137 int done=0, *S, i, j, k, m, n=1000, T=model->nobs, count=0;
138 TMatrix vd, tvd, *A0_Xi, *B;
139 TVector init_prob, prob;
140
141 // quick check of passed parameters
142 if ((horizon <= 0) || !model) return 0;
143
144 p=(T_VAR_Parameters*)(model->theta);
145
146 // allocate memory
147 S=(int*)dw_malloc(horizon*sizeof(int));
148 vd=CreateMatrix(horizon,p->nvars*p->nvars);
149 InitializeMatrix(tvd=CreateMatrix(horizon,p->nvars*p->nvars),0.0);
150 A0_Xi=dw_CreateArray_matrix(model->sv->nstates);
151 B=dw_CreateArray_matrix(model->sv->nstates);
152 for (i=model->sv->nstates-1; i >= 0; i--)
153 {
154 A0_Xi[i]=CreateMatrix(p->nvars,p->nvars);
155 B[i]=CreateMatrix(p->nvars*p->nlags,p->nvars);
156 }
157 init_prob=CreateVector(p->nstates);
158 prob=CreateVector(p->nstates);
159
160 i=0;
161 while (!done)
162 {
163 // Read parameters and push them into model
164 if (!posterior_file)
165 done=1;
166 else
167 {
168 dw_NextLine(posterior_file,thin-1);
169 if (!GetPosteriorDraw(posterior_file,model,flag))
170 {
171 done=2;
172 printf("total posterior draws processed - %d\n",i);
173 }
174 else
175 if (i++ == n)
176 {
177 printf("%d posterior draws processed\n",i);
178 n+=1000;
179 }
180 }
181
182 if (done != 2)
183 {
184 // Compute A0_Xi and B
185 GetIRMatrices(model->sv->nstates,A0_Xi,B,p);
186
187 // Use ergodic initial probability or filtered probability at time T
188 if (ergodic)
189 Ergodic(init_prob,model->sv->Q);
190 else
191 for (j=p->nstates-1; j >= 0; j--)
192 ElementV(init_prob,j)=ProbabilityStateConditionalCurrent(j,T,model);
193
194 for (k=draws; k > 0; k--)
195 {
196 // Draw time T regime
197 m=DrawDiscrete(init_prob);
198
199 // Draw regimes from time T+1 through T+h inclusive
200 for (j=0; j < horizon; j++)
201 {
202 ColumnVector(prob,model->sv->Q,m);
203 S[j]=m=DrawDiscrete(prob);
204 }
205
206 // Compute variance decomposition contributions
207 variance_decomposition(vd,S,A0_Xi[S[0]],B);
208
209 // Accumulate variance decomposition contributions
210 AddMM(tvd,tvd,vd);
211
212 count++;
213 }
214 }
215 }
216
217 FreeMatrix(vd);
218 dw_free(S);
219 dw_FreeArray(A0_Xi);
220 dw_FreeArray(B);
221 FreeVector(prob);
222 FreeVector(init_prob);
223
224 ProductMS(tvd,tvd,1.0/(PRECISION)count);
225 return tvd;
226 }
227
228 /*
229 Assumes
230 posterior_file : FILE pointer to file containing posterior draws. If null,
231 current parameters are used.
232 thin : thinning factor to use if posterior_file is not null.
233 s : fixed regime
234 horizon : non-negative integer
235 model : point to valid TStateModel structure
236 flag : determines the type of posterior draws file passed.
237
238 Results:
239 Creates matrix containing the mean variance decompositions.
240
241 Returns:
242 Pointer to matrix upon success and null pointer on failure.
243
244 Notes:
245 The element in position (k,i+j*nvars) of tvd is the cummulative contributions
246 to the total variance of ith variable to the jth shock at horizon k. Horizon
247 zero is the contemporaneous contribution.
248 */
249 TMatrix variance_decomposition_mean_regime(FILE *posterior_file, int thin, int s, int horizon, TStateModel *model, int flag)
250 {
251 T_VAR_Parameters *p;
252 int done=0, *S, i, n=1000, count=0;
253 TMatrix tvd, vd, *A0_Xi, *B;
254
255 // quick check of passed parameters
256 if ((horizon <= 0) || !model) return 0;
257
258 p=(T_VAR_Parameters*)(model->theta);
259
260 // allocate memory
261 S=(int*)dw_malloc(horizon*sizeof(int));
262 for (i=0; i < horizon; i++) S[i]=s;
263 vd=CreateMatrix(horizon,p->nvars*p->nvars);
264 InitializeMatrix(tvd=CreateMatrix(horizon,p->nvars*p->nvars),0.0);
265 A0_Xi=dw_CreateArray_matrix(model->sv->nstates);
266 B=dw_CreateArray_matrix(model->sv->nstates);
267 for (i=model->sv->nstates-1; i >= 0; i--)
268 {
269 A0_Xi[i]=CreateMatrix(p->nvars,p->nvars);
270 B[i]=CreateMatrix(p->nvars*p->nlags,p->nvars);
271 }
272
273 i=0;
274 while (!done)
275 {
276 // Read parameters and push them into model
277 if (!posterior_file)
278 done=1;
279 else
280 {
281 dw_NextLine(posterior_file,thin-1);
282 if (!GetPosteriorDraw(posterior_file,model,flag))
283 {
284 done=2;
285 printf("total posterior draws processed - %d\n",i);
286 }
287 else
288 if (i++ == n)
289 {
290 printf("%d posterior draws processed\n",i);
291 n+=1000;
292 }
293 }
294
295 if (done != 2)
296 {
297 // Compute A0_Xi and B
298 GetIRMatrices(model->sv->nstates,A0_Xi,B,p);
299
300 // Compute variance decomposition contributions
301 variance_decomposition(vd,S,A0_Xi[s],B);
302
303 // Accumulate variance decomposition contributions
304 AddMM(tvd,tvd,vd);
305
306 count++;
307 }
308 }
309
310 FreeMatrix(vd);
311 dw_free(S);
312 dw_FreeArray(A0_Xi);
313 dw_FreeArray(B);
314
315 ProductMS(tvd,tvd,1.0/(PRECISION)count);
316 return tvd;
317 }
318
319 /*
320 Assumes
321 draws : number of draws of the regime path to make for each posterior draw
322 posterior_file : FILE pointer to file containing posterior draws. If null,
323 current parameters are used.
324 thin : thinning factor to use if posterior_file is not null.
325 horizon : non-negative integer
326 ergodic : if non-zero, uses the ergodic distribution to draw the initial
327 regime, otherwise uses the filtered probabilities at time nobs.
328 model : point to valid TStateModel structure
329 flag : determines the type of posterior draws file passed.
330
331 Results:
332 Creates matrix histogram containing the cummulative percentage contributions
333 to the total variance.
334
335 Returns:
336 Pointer to histogram upon success and null pointer on failure.
337
338 Notes:
339 The element in position (k,i+j*nvars) is the cummulative contribution to the
340 total variance of ith variable to the jth shock at horizon k. Horizon zero
341 is the contemporaneous contribution.
342 */
343 TMatrixHistogram *variance_decomposition_percentiles(int draws, FILE *posterior_file, int thin, int ergodic, int horizon, TStateModel *model, int flag)
344 {
345 T_VAR_Parameters *p;
346 int done=0, *S, i, j, k, m, n=1000, T=model->nobs;
347 TMatrix vd, *A0_Xi, *B;
348 TVector init_prob, prob;
349 TMatrixHistogram *histogram;
350
351 // quick check of passed parameters
352 if ((horizon <= 0) || !model) return (TMatrixHistogram*)NULL;
353
354 p=(T_VAR_Parameters*)(model->theta);
355
356 // allocate memory
357 S=(int*)dw_malloc(horizon*sizeof(int));
358 vd=CreateMatrix(horizon,p->nvars*p->nvars);
359 histogram=CreateMatrixHistogram(horizon,p->nvars*p->nvars,100,HISTOGRAM_VARIABLE);
360 A0_Xi=dw_CreateArray_matrix(model->sv->nstates);
361 B=dw_CreateArray_matrix(model->sv->nstates);
362 for (i=model->sv->nstates-1; i >= 0; i--)
363 {
364 A0_Xi[i]=CreateMatrix(p->nvars,p->nvars);
365 B[i]=CreateMatrix(p->nvars*p->nlags,p->nvars);
366 }
367 init_prob=CreateVector(p->nstates);
368 prob=CreateVector(p->nstates);
369
370 i=0;
371 while (!done)
372 {
373 // Read parameters and push them into model
374 if (!posterior_file)
375 done=1;
376 else
377 {
378 dw_NextLine(posterior_file,thin-1);
379 if (!GetPosteriorDraw(posterior_file,model,flag))
380 {
381 done=2;
382 printf("total posterior draws processed - %d\n",i);
383 }
384 else
385 if (i++ == n)
386 {
387 printf("%d posterior draws processed\n",i);
388 n+=1000;
389 }
390 }
391
392 if (done != 2)
393 {
394 // Compute A0_Xi and B
395 GetIRMatrices(model->sv->nstates,A0_Xi,B,p);
396
397 // Use ergodic initial probability or filtered probability at time T
398 if (ergodic)
399 Ergodic(init_prob,model->sv->Q);
400 else
401 for (j=p->nstates-1; j >= 0; j--)
402 ElementV(init_prob,j)=ProbabilityStateConditionalCurrent(j,T,model);
403
404 for (k=draws; k > 0; k--)
405 {
406 // Draw time T regime
407 m=DrawDiscrete(init_prob);
408
409 // Draw regimes from time T+1 through T+h inclusive
410 for (j=0; j < horizon; j++)
411 {
412 ColumnVector(prob,model->sv->Q,m);
413 S[j]=m=DrawDiscrete(prob);
414 }
415
416 // Compute variance decomposition contributions
417 variance_decomposition(vd,S,A0_Xi[S[0]],B);
418
419 // Convert to percentages
420 NormalizeVarianceDecomposition(vd,p);
421
422 // Accumulate variance decomposition percentages
423 AddMatrixObservation(vd,histogram);
424 }
425 }
426 }
427
428 FreeMatrix(vd);
429 dw_free(S);
430 dw_FreeArray(A0_Xi);
431 dw_FreeArray(B);
432 FreeVector(prob);
433 FreeVector(init_prob);
434
435 return histogram;
436 }
437
438 /*
439 Assumes
440 posterior_file : FILE pointer to file containing posterior draws. If null,
441 current parameters are used.
442 thin : thinning factor to use if posterior_file is not null.
443 s : fixed regime
444 horizon : non-negative integer
445 model : point to valid TStateModel structure
446 flag : determines the type of posterior draws file passed.
447
448 Results:
449 Creates matrix histogram containing the cummulative percentage contributions
450 to the total variance.
451
452 Returns:
453 Pointer to histogram upon success and null pointer on failure.
454
455 Notes:
456 The element in position (k,i+j*nvars) is the cummulative contribution to the
457 total variance of ith variable to the jth shock at horizon k. Horizon zero
458 is the contemporaneous contribution.
459 */
460 TMatrixHistogram *variance_decomposition_percentiles_regime(FILE *posterior_file, int thin, int s, int horizon, TStateModel *model, int flag)
461 {
462 T_VAR_Parameters *p;
463 int done=0, *S, i, n=1000;
464 TMatrix vd, *A0_Xi, *B;
465 TMatrixHistogram *histogram;
466
467 // quick check of passed parameters
468 if ((horizon <= 0) || !model) return 0;
469
470 p=(T_VAR_Parameters*)(model->theta);
471
472 // allocate memory
473 S=(int*)dw_malloc(horizon*sizeof(int));
474 for (i=0; i < horizon; i++) S[i]=s;
475 vd=CreateMatrix(horizon,p->nvars*p->nvars);
476 histogram=CreateMatrixHistogram(horizon,p->nvars*p->nvars,100,HISTOGRAM_VARIABLE);
477 A0_Xi=dw_CreateArray_matrix(model->sv->nstates);
478 B=dw_CreateArray_matrix(model->sv->nstates);
479 for (i=model->sv->nstates-1; i >= 0; i--)
480 {
481 A0_Xi[i]=CreateMatrix(p->nvars,p->nvars);
482 B[i]=CreateMatrix(p->nvars*p->nlags,p->nvars);
483 }
484
485 i=0;
486 while (!done)
487 {
488 // Read parameters and push them into model
489 if (!posterior_file)
490 done=1;
491 else
492 {
493 dw_NextLine(posterior_file,thin-1);
494 if (!GetPosteriorDraw(posterior_file,model,flag))
495 {
496 done=2;
497 printf("total posterior draws processed - %d\n",i);
498 }
499 else
500 if (i++ == n)
501 {
502 printf("%d posterior draws processed\n",i);
503 n+=1000;
504 }
505 }
506
507 if (done != 2)
508 {
509 // Compute A0_Xi and B
510 GetIRMatrices(model->sv->nstates,A0_Xi,B,p);
511
512 // Compute variance decomposition contributions
513 variance_decomposition(vd,S,A0_Xi[S[0]],B);
514
515 // Convert to percentages
516 NormalizeVarianceDecomposition(vd,p);
517
518 // Accumulate variance decomposition percentages
519 AddMatrixObservation(vd,histogram);
520 }
521 }
522
523 FreeMatrix(vd);
524 dw_free(S);
525 dw_FreeArray(A0_Xi);
526 dw_FreeArray(B);
527
528 return histogram;
529 }
530
531
532
533 /*
534 Additional command line parameters
535
536 -horrizon <integer>
537 If this argument exists, then the forecast horizon is given by the passed
538 integer. The default value is 12.
539
540 -filtered
541 Uses filtered probabilities at the end of the sample as initial conditions
542 for regime probabilities. The default behavior is to us the erogdic
543 distribution for the initial conditions. This flag only applies if neither
544 -regimes nor -regime is specified.
545
546 -parameter_uncertainty
547 Apply parameter uncertainty.
548
549 -shocks_per_parameter <integer>
550 Number of regime paths to draw for each parameter draw. The default value
551 is 1 if parameter_uncertainty is set and 10,000 otherwise.
552
553 -error_bands
554 Output percentile error bands. (default = off - mean is computed)
555
556 -percentiles n p_1 p_2 ... p_n
557 Percentiles to compute. The first parameter after percentiles must be the
558 number of percentiles and the following values are the actual percentiles.
559 (default = 3 0.16 0.50 0.84 - only meaningful if -error_bands is set)
560
561 -thin
562 Thinning factor. Only 1/thin of the draws in posterior draws file are
563 used. The default value is 1.
564
565 -regimes
566 Produces forecasts as if each regime were permanent. (default = off)
567
568 -regime <integer>
569 Produces forecasts as if the given regime were permanent. Regime numbers
570 are zero based. (default = off)
571
572 -flat
573 Assumes that posterior draws is a flat file format. The default is that
574 the posterior draws are in a free file format.
575
576 */
577 void dw_sbvar_variance_decomposition_command_line(int nargs, char **args)
578 {
579 char *post=(char*)NULL, *out_filename, *fmt="%%svar_decomp_mean_regime_%d_%%s.out", *buffer;
580 TStateModel *model;
581 T_VAR_Parameters *p;
582 int ergodic, type, s, horizon, thin, draws, i, j, n;
583 FILE *f_out, *posterior_file=(FILE*)NULL;
584 TMatrix tvd;
585 TVector percentiles=(TVector)NULL;
586 TMatrixHistogram *histogram;
587
588 TVARCommandLine *cmd=(TVARCommandLine*)NULL;
589
590 // Setup model and initial parameters
591 if (!(cmd=CreateTStateModel_VARCommandLine(nargs,args,(TVARCommandLine*)NULL)))
592 dw_Error(MEM_ERR);
593 else
594 if (!cmd->model)
595 dw_UserError("Unable to setup SBVAR from command line parameters");
596 else
597 if (!cmd->parameters_filename_actual)
598 dw_UserError("Unable to initialize parameters from command line parameters");
599 else
600 {
601 model=cmd->model;
602 p=(T_VAR_Parameters*)(model->theta);
603
604 // horizon
605 horizon=dw_ParseInteger_String(nargs,args,"horizon",12);
606
607 // Output tag
608 OutTag_VARCommandLine(cmd);
609
610 // Type
611 type=(dw_FindArgument_String(nargs,args,"flat") >= 0) ? F_FLAT : F_FREE;
612
613 // Ergodic distribution for initial value of shocks
614 ergodic=(dw_FindArgument_String(nargs,args,"filtered") >= 0) ? 0 : 1;
615
616 // Error bands and percentiles
617 if ((i=dw_FindArgument_String(nargs,args,"percentiles")) != -1)
618 {
619 if ((i+1 < nargs) && dw_IsInteger(args[i+1]) && ((n=atoi(args[i+1])) > 0) && (i+1+n < nargs))
620 {
621 percentiles=CreateVector(n);
622 for (j=0; j < n; j++)
623 if (!dw_IsFloat(args[i+2+j])|| ((ElementV(percentiles,j)=atof(args[i+2+j])) <= 0.0) || (ElementV(percentiles,j) >= 1.0))
624 break;
625 if (j < n)
626 {
627 dw_UserError("sbvar_variance_decomposition_command_line(): Error parsing percentiles\n");
628 goto ERROR_EXIT;
629 }
630 }
631 else
632 {
633 dw_UserError("sbvar_variance_decomposition_command_line(): Error parsing percentiles\n");
634 goto ERROR_EXIT;
635 }
636 }
637 else
638 if (dw_FindArgument_String(nargs,args,"error_bands") != -1)
639 {
640 percentiles=CreateVector(3);
641 ElementV(percentiles,0)=0.16; ElementV(percentiles,1)=0.5; ElementV(percentiles,2)=0.84;
642 }
643
644 // Parameter uncertainty
645 if (dw_FindArgument_String(nargs,args,"parameter_uncertainty") != -1)
646 {
647 // Open posterior draws file
648 post=CreateFilenameFromTag((type == F_FREE) ? "%ssimulation_%s.out" : "%sdraws_%s.out",cmd->in_tag ? cmd->in_tag : "notag",cmd->in_directory);
649 if (!(posterior_file=fopen(post,"rt")))
650 {
651 printf("dw_sbvar_variance_decomposition_command line(): Unable to open posterior draws file: %s\n",post);
652 goto ERROR_EXIT;
653 }
654
655 // Get thinning factor from command line
656 thin=dw_ParseInteger_String(nargs,args,"thin",1);
657 if (thin <= 0) thin=1;
658
659 // Get shocks_per_parameter from command line
660 draws=dw_ParseInteger_String(nargs,args,"shocks_per_parameter",1);
661 }
662 else
663 {
664 // thinning factor not used
665 thin=1;
666
667 // Get shocks_per_parameter from command line
668 draws=dw_ParseInteger_String(nargs,args,"shocks_per_parameter",10000);
669 }
670
671 fmt=percentiles ? "%%svar_decomp_percentiles_regime_%d_%%s.out" : "%%svar_decomp_mean_regime_%d_%%s.out";
672 if (dw_FindArgument_String(nargs,args,"regimes") != -1)
673 for (s=0; s < p->nstates; s++)
674 {
675 if (posterior_file) rewind(posterior_file);
676 // s must not contain more than 10 digits
677 sprintf(buffer=(char*)dw_malloc(strlen(fmt) + 10),fmt,s);
678 out_filename=CreateFilenameFromTag(buffer,cmd->out_tag,cmd->out_directory);
679 dw_free(buffer);
680 if ((f_out=fopen(out_filename,"wt")))
681 {
682 printf("Constructing variance decomposition - regime %d\n",s);
683 if (percentiles)
684 {
685 if ((histogram=variance_decomposition_percentiles_regime(posterior_file,thin,s,horizon,model,type)))
686 {
687 tvd=CreateMatrix(horizon,p->nvars*p->nvars);
688 for (i=0; i < DimV(percentiles); i++)
689 {
690 MatrixPercentile(tvd,ElementV(percentiles,i),histogram);
691 ReorderVarianceDecomposition(tvd,p);
692 dw_PrintMatrix(f_out,tvd,"%lg ");
693 fprintf(f_out,"\n");
694 }
695 FreeMatrix(tvd);
696 FreeMatrixHistogram(histogram);
697 }
698 }
699 else
700 {
701 if ((tvd=variance_decomposition_mean_regime(posterior_file,thin,s,horizon,model,type)))
702 {
703 NormalizeVarianceDecomposition(tvd,p);
704 ReorderVarianceDecomposition(tvd,p);
705 dw_PrintMatrix(f_out,tvd,"%lg ");
706 FreeMatrix(tvd);
707 }
708 }
709 fclose(f_out);
710 }
711 dw_free(out_filename);
712 }
713 else
714 if (dw_FindArgument_String(nargs,args,"regime") != -1)
715 if (((s=dw_ParseInteger_String(nargs,args,"regime",-1)) >= 0) && (s < p->nstates))
716 {
717 // s must not contain more than 10 digits
718 sprintf(buffer=(char*)dw_malloc(strlen(fmt) + 10),fmt,s);
719 out_filename=CreateFilenameFromTag(buffer,cmd->out_tag,cmd->out_directory);
720 dw_free(buffer);
721 if ((f_out=fopen(out_filename,"wt")))
722 {
723 printf("Constructing variance decomposition - regime %d\n",s);
724 if (percentiles)
725 {
726 if ((histogram=variance_decomposition_percentiles_regime(posterior_file,thin,s,horizon,model,type)))
727 {
728 tvd=CreateMatrix(horizon,p->nvars*p->nvars);
729 for (i=0; i < DimV(percentiles); i++)
730 {
731 MatrixPercentile(tvd,ElementV(percentiles,i),histogram);
732 ReorderVarianceDecomposition(tvd,p);
733 dw_PrintMatrix(f_out,tvd,"%lg ");
734 fprintf(f_out,"\n");
735 }
736 FreeMatrix(tvd);
737 FreeMatrixHistogram(histogram);
738 }
739 }
740 else
741 {
742 if ((tvd=variance_decomposition_mean_regime(posterior_file,thin,s,horizon,model,type)))
743 {
744 NormalizeVarianceDecomposition(tvd,p);
745 ReorderVarianceDecomposition(tvd,p);
746 dw_PrintMatrix(f_out,tvd,"%lg ");
747 FreeMatrix(tvd);
748 }
749 }
750 fclose(f_out);
751 }
752 dw_free(out_filename);
753 }
754 else
755 {
756 printf("dw_sbvar_variance_decomposition_command line(): regime number must be between 0 and %d inclusive\n",p->nstates-1);
757 return;
758 }
759 else
760 {
761 if (percentiles)
762 if (ergodic)
763 fmt="%svar_decomp_percentiles_ergodic_%s.out";
764 else
765 fmt="%svar_decomp_percentiles_filtered_%s.out";
766 else
767 if (ergodic)
768 fmt="%svar_decomp_mean_ergodic_%s.out";
769 else
770 fmt="%svar_decomp_mean_filtered_%s.out";
771 out_filename=CreateFilenameFromTag(fmt,cmd->out_tag,cmd->out_directory);
772 if ((f_out=fopen(out_filename,"wt")))
773 {
774 printf("Constructing variance decomposition - %d draws of regimes per posterior value\n",draws);
775 if (percentiles)
776 {
777 if ((histogram=variance_decomposition_percentiles(draws,posterior_file,thin,ergodic,horizon,model,type)))
778 {
779 tvd=CreateMatrix(horizon,p->nvars*p->nvars);
780 for (i=0; i < DimV(percentiles); i++)
781 {
782 MatrixPercentile(tvd,ElementV(percentiles,i),histogram);
783 ReorderVarianceDecomposition(tvd,p);
784 dw_PrintMatrix(f_out,tvd,"%lg ");
785 fprintf(f_out,"\n");
786 }
787 FreeMatrix(tvd);
788 FreeMatrixHistogram(histogram);
789 }
790 }
791 else
792 {
793 if ((tvd=variance_decomposition_mean(draws,posterior_file,thin,ergodic,horizon,model,type)))
794 {
795 NormalizeVarianceDecomposition(tvd,p);
796 ReorderVarianceDecomposition(tvd,p);
797 dw_PrintMatrix(f_out,tvd,"%lg ");
798 FreeMatrix(tvd);
799 }
800 }
801 fclose(f_out);
802 }
803 dw_free(out_filename);
804 }
805 }
806
807 ERROR_EXIT:
808 if (post) dw_free(post);
809 if (posterior_file) fclose(posterior_file);
810 Free_VARCommandLine(cmd);
811 }