Debian Codegraph @

contrib/ms-sbvar/switch_dw/state_space/dw_state_space_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_MSStateSpace.h"
21 #include "dw_histogram.h"
22 #include "dw_parse_cmd.h"
23 #include "dw_ascii.h"
24 #include "dw_error.h"
25 #include "dw_math.h"
26 #include "dw_std.h"
27
28 #include <stdlib.h>
29 #include <string.h>
30 #include <math.h>
31
32 /*
33 Normalizes variance decomposition. Converts cummulative contributions to the
34 total variance into cummulative percentage contributions.
35 */
36 void NormalizeVarianceDecomposition(TMatrix VD, int nvars)
37 {
38 PRECISION tmp;
39 int nshocks=ColM(VD)/nvars, i, j, t;
40
41 // normalizes to percentages
42 for (t=RowM(VD)-1; t >= 0; t--)
43 for (i=nvars-1; i >= 0; i--)
44 {
45 for (tmp=0.0, j=nshocks-1; j >= 0; j--) tmp+=ElementM(VD,t,j+i*nshocks);
46 if (tmp > 0)
47 for (tmp=1.0/tmp, j=nshocks-1; j >= 0; j--) ElementM(VD,t,j+i*nshocks)*=tmp;
48 }
49 }
50
51 /*
52 Assumes
53 draws : number of draws of the regime path to make for each posterior draw
54 posterior_file : FILE pointer to file containing posterior draws. If null,
55 current parameters are used.
56 thin : thinning factor to use if posterior_file is not null.
57 horizon : non-negative integer
58 ergodic : if non-zero, uses the ergodic distribution to draw the initial
59 regime, otherwise uses the filtered probabilities at time nobs.
60 model : point to valid TStateModel structure
61 flag : equal to IR_STATES or IR_OBSERVABLES
62
63 Results:
64 Creates matrix containing the mean variance decompositions.
65
66 Returns:
67 Pointer to matrix upon success and null pointer on failure.
68
69 Notes:
70 The element in position (t,j+i*nshocks) of returned matrix is the
71 cummulative contribution of the jth shock to the total variance of ith
72 variable to the at horizon t. Horizon zero is the contemporaneous
73 contribution.
74
75 If flag is equal to IR_STATES then the variables are the state variables and
76 the shocks are the fundamental shocks. If flag is equal to IR_OBSERVABLES
77 then the variables are the observables and the shocks are both the
78 fundamental shocks and the measurement error. The fundamental shocks are
79 ordered first.
80 */
81 TMatrix state_space_variance_decomposition_mean(int draws, FILE *posterior_file, int thin, int ergodic, int horizon, TStateModel *model, int flag)
82 {
83 T_MSStateSpace *statespace=(T_MSStateSpace*)(model->theta);
84 int done=0, *S, i, j, k, m, n=1000, T=model->nobs, count=0, nvars, nshocks;
85 TMatrix vd, tvd;
86 TVector init_prob, prob;
87
88 // set sizes
89 if (flag & IR_STATES)
90 {
91 nvars=statespace->nz;
92 nshocks=statespace->nepsilon;
93 }
94 else
95 {
96 nvars=statespace->ny;
97 nshocks=statespace->nepsilon + statespace->nu;
98 }
99
100 // allocate memory
101 S=(int*)dw_malloc(horizon*sizeof(int));
102 vd=CreateMatrix(horizon,nvars*nshocks);
103 InitializeMatrix(tvd=CreateMatrix(horizon,nvars*nshocks),0.0);
104 init_prob=CreateVector(model->sv->nbasestates);
105 prob=CreateVector(model->sv->nbasestates);
106
107 i=0;
108 while (!done)
109 {
110 // Read parameters and push them into model
111 if (!posterior_file)
112 done=1;
113 else
114 {
115 dw_NextLine(posterior_file,thin-1);
116 if (!dw_ReadPosteriorDraw(posterior_file,model))
117 {
118 done=2;
119 printf("total posterior draws processed - %d\n",i);
120 }
121 else
122 if (i++ == n)
123 {
124 printf("%d posterior draws processed\n",i);
125 n+=1000;
126 }
127 }
128
129 if (done != 2)
130 {
131 // Use ergodic initial probability or filtered probability at time T
132 if (ergodic)
133 Ergodic(init_prob,model->sv->baseQ);
134 else
135 for (j=model->sv->nstates-1; j >= 0; j--)
136 ElementV(init_prob,j)=ProbabilityBaseStateConditionalCurrent(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 < horizon; j++)
145 {
146 ColumnVector(prob,model->sv->baseQ,m);
147 S[j]=m=DrawDiscrete(prob);
148 }
149
150 // Compute variance decomposition contributions
151 dw_state_space_variance_decomposition(vd,S,model,flag);
152
153 // Accumulate variance decomposition contributions
154 AddMM(tvd,tvd,vd);
155
156 count++;
157 }
158 }
159 }
160
161 FreeMatrix(vd);
162 dw_free(S);
163 FreeVector(prob);
164 FreeVector(init_prob);
165
166 ProductMS(tvd,tvd,1.0/(PRECISION)count);
167 return tvd;
168 }
169
170 /*
171 Assumes
172 posterior_file : FILE pointer to file containing posterior draws. If null,
173 current parameters are used.
174 thin : thinning factor to use if posterior_file is not null.
175 s : fixed regime
176 horizon : non-negative integer
177 model : point to valid TStateModel structure
178 flag : determines the type of posterior draws file passed.
179
180 Results:
181 Creates matrix containing the mean variance decompositions.
182
183 Returns:
184 Pointer to matrix upon success and null pointer on failure.
185
186 Notes:
187 The element in position (k,i+j*nvars) of tvd is the cummulative contributions
188 to the total variance of ith variable to the jth shock at horizon k. Horizon
189 zero is the contemporaneous contribution.
190 */
191 TMatrix state_space_variance_decomposition_mean_regime(FILE *posterior_file, int thin, int s, int horizon, TStateModel *model, int flag)
192 {
193 T_MSStateSpace *statespace=(T_MSStateSpace*)(model->theta);
194 int done=0, *S, i, n=1000, count=0, nvars, nshocks;
195 TMatrix tvd, vd;
196
197 // set sizes
198 if (flag & IR_STATES)
199 {
200 nvars=statespace->nz;
201 nshocks=statespace->nepsilon;
202 }
203 else
204 {
205 nvars=statespace->ny;
206 nshocks=statespace->nepsilon + statespace->nu;
207 }
208
209 // allocate memory
210 S=(int*)dw_malloc(horizon*sizeof(int));
211 for (i=0; i < horizon; i++) S[i]=s;
212 vd=CreateMatrix(horizon,nvars*nshocks);
213 InitializeMatrix(tvd=CreateMatrix(horizon,nvars*nshocks),0.0);
214
215 i=0;
216 while (!done)
217 {
218 // Read parameters and push them into model
219 if (!posterior_file)
220 done=1;
221 else
222 {
223 dw_NextLine(posterior_file,thin-1);
224 if (!dw_ReadPosteriorDraw(posterior_file,model))
225 {
226 done=2;
227 printf("total posterior draws processed - %d\n",i);
228 }
229 else
230 if (i++ == n)
231 {
232 printf("%d posterior draws processed\n",i);
233 n+=1000;
234 }
235 }
236
237 if (done != 2)
238 {
239 // Compute variance decomposition contributions
240 dw_state_space_variance_decomposition(vd,S,model,flag);
241
242 // Accumulate variance decomposition contributions
243 AddMM(tvd,tvd,vd);
244
245 count++;
246 }
247 }
248
249 FreeMatrix(vd);
250 dw_free(S);
251
252 ProductMS(tvd,tvd,1.0/(PRECISION)count);
253 return tvd;
254 }
255
256 /*
257 Assumes
258 draws : number of draws of the regime path to make for each posterior draw
259 posterior_file : FILE pointer to file containing posterior draws. If null,
260 current parameters are used.
261 thin : thinning factor to use if posterior_file is not null.
262 horizon : non-negative integer
263 ergodic : if non-zero, uses the ergodic distribution to draw the initial
264 regime, otherwise uses the filtered probabilities at time nobs.
265 model : point to valid TStateModel structure
266 flag : determines the type of posterior draws file passed.
267
268 Results:
269 Creates matrix histogram containing the cummulative percentage contributions
270 to the total variance.
271
272 Returns:
273 Pointer to histogram upon success and null pointer on failure.
274
275 Notes:
276 The element in position (k,i+j*nvars) is the cummulative contribution to the
277 total variance of ith variable to the jth shock at horizon k. Horizon zero
278 is the contemporaneous contribution.
279 */
280 TMatrixHistogram *state_space_variance_decomposition_percentiles(int draws, FILE *posterior_file, int thin, int ergodic, int horizon, TStateModel *model, int flag)
281 {
282 T_MSStateSpace *statespace=(T_MSStateSpace*)(model->theta);
283 int done=0, *S, i, j, k, m, n=1000, T=model->nobs, nvars, nshocks;
284 TMatrix vd;
285 TVector init_prob, prob;
286 TMatrixHistogram *histogram;
287
288 // set sizes
289 if (flag & IR_STATES)
290 {
291 nvars=statespace->nz;
292 nshocks=statespace->nepsilon;
293 }
294 else
295 {
296 nvars=statespace->ny;
297 nshocks=statespace->nepsilon + statespace->nu;
298 }
299
300 // allocate memory
301 S=(int*)dw_malloc(horizon*sizeof(int));
302 vd=CreateMatrix(horizon,nvars*nshocks);
303 histogram=CreateMatrixHistogram(horizon,nvars*nshocks,100,HISTOGRAM_VARIABLE);
304 init_prob=CreateVector(model->sv->nbasestates);
305 prob=CreateVector(model->sv->nbasestates);
306
307 i=0;
308 while (!done)
309 {
310 // Read parameters and push them into model
311 if (!posterior_file)
312 done=1;
313 else
314 {
315 dw_NextLine(posterior_file,thin-1);
316 if (!dw_ReadPosteriorDraw(posterior_file,model))
317 {
318 done=2;
319 printf("total posterior draws processed - %d\n",i);
320 }
321 else
322 if (i++ == n)
323 {
324 printf("%d posterior draws processed\n",i);
325 n+=1000;
326 }
327 }
328
329 if (done != 2)
330 {
331 // Use ergodic initial probability or filtered probability at time T
332 if (ergodic)
333 Ergodic(init_prob,model->sv->baseQ);
334 else
335 for (j=model->sv->nstates-1; j >= 0; j--)
336 ElementV(init_prob,j)=ProbabilityBaseStateConditionalCurrent(j,T,model);
337
338 for (k=draws; k > 0; k--)
339 {
340 // Draw time T regime
341 m=DrawDiscrete(init_prob);
342
343 // Draw regimes from time T+1 through T+h inclusive
344 for (j=0; j < horizon; j++)
345 {
346 ColumnVector(prob,model->sv->baseQ,m);
347 S[j]=m=DrawDiscrete(prob);
348 }
349
350 // Compute variance decomposition contributions
351 dw_state_space_variance_decomposition(vd,S,model,flag);
352
353 // Convert to percentages
354 NormalizeVarianceDecomposition(vd,nvars);
355
356 // Accumulate variance decomposition percentages
357 AddMatrixObservation(vd,histogram);
358 }
359 }
360 }
361
362 FreeMatrix(vd);
363 dw_free(S);
364 FreeVector(prob);
365 FreeVector(init_prob);
366
367 return histogram;
368 }
369
370 /*
371 Assumes
372 posterior_file : FILE pointer to file containing posterior draws. If null,
373 current parameters are used.
374 thin : thinning factor to use if posterior_file is not null.
375 s : fixed regime
376 horizon : non-negative integer
377 model : point to valid TStateModel structure
378 flag : determines the type of posterior draws file passed.
379
380 Results:
381 Creates matrix histogram containing the cummulative percentage contributions
382 to the total variance.
383
384 Returns:
385 Pointer to histogram upon success and null pointer on failure.
386
387 Notes:
388 The element in position (k,i+j*nvars) is the cummulative contribution to the
389 total variance of ith variable to the jth shock at horizon k. Horizon zero
390 is the contemporaneous contribution.
391 */
392 TMatrixHistogram *state_space_variance_decomposition_percentiles_regime(FILE *posterior_file, int thin, int s, int horizon, TStateModel *model, int flag)
393 {
394 T_MSStateSpace *statespace=(T_MSStateSpace*)(model->theta);
395 int nvars, nshocks, done=0, *S, i, n=1000;
396 TMatrix vd;
397 TMatrixHistogram *histogram;
398
399 // set sizes
400 if (flag & IR_STATES)
401 {
402 nvars=statespace->nz;
403 nshocks=statespace->nepsilon;
404 }
405 else
406 {
407 nvars=statespace->ny;
408 nshocks=statespace->nepsilon + statespace->nu;
409 }
410
411 // allocate memory
412 S=(int*)dw_malloc(horizon*sizeof(int));
413 for (i=0; i < horizon; i++) S[i]=s;
414 vd=CreateMatrix(horizon,nvars*nshocks);
415 histogram=CreateMatrixHistogram(horizon,nvars*nshocks,100,HISTOGRAM_VARIABLE);
416
417 i=0;
418 while (!done)
419 {
420 // Read parameters and push them into model
421 if (!posterior_file)
422 done=1;
423 else
424 {
425 dw_NextLine(posterior_file,thin-1);
426 if (!dw_ReadPosteriorDraw(posterior_file,model))
427 {
428 done=2;
429 printf("total posterior draws processed - %d\n",i);
430 }
431 else
432 if (i++ == n)
433 {
434 printf("%d posterior draws processed\n",i);
435 n+=1000;
436 }
437 }
438
439 if (done != 2)
440 {
441 // Compute variance decomposition contributions
442 dw_state_space_variance_decomposition(vd,S,model,flag);
443
444 // Convert to percentages
445 NormalizeVarianceDecomposition(vd,nvars);
446
447 // Accumulate variance decomposition percentages
448 AddMatrixObservation(vd,histogram);
449 }
450 }
451
452 FreeMatrix(vd);
453 dw_free(S);
454
455 return histogram;
456 }