Debian Codegraph @

contrib/ms-sbvar/TZcode/MatlabFiles/imfsim.m

raw
1 function imfsim(xinput)
2 % imfsim(xinput)
3 % Save the simulated pdfs of impulse responses;
4 % Print and save Gelman's measures of B and W for A0's,
5 % only when nstarts (# of starting points) >1.
6 % Ref: Waggoner and Zha "Does Normalization Matter for Inference"
7 % See note Forecast (2)
8 %
9 % xinput{1}: nfp -- total number of free parameters
10 % xinput{2}: nvar -- number of variables
11 % xinput{3}: xhat -- ML estimate of free parameters in A0
12 % xinput{4}: hess -- Hessian of -logLH
13 % xinput{5}:Indxv -- index for selected variables of interest; normall first 2 are of our interest
14 % to select variables, always check idmat0 to make sure
15 % it plots: (1) pdf of 1st v for every buffer, (2) scattered plot of 1st and 2nd for every buffer,
16 % (2) pdf of 1st v for all sequences; (4) scattered plot of 3rd and 4th for all sequences
17 % (5) scattered plot of 1st and 2nd for al sequences.
18 % xinput{6}: IndxGraph - 1: plot graphs; 0: no graphs
19 % xinput{7}: idmat0 -- Index for non-zero elements in A0 with column to equation
20 % xinput{8}: nstarts -- # of starting points in Gibbs sampling
21 % xinput{9}: ndraws1 -- # of 1st loop to be discarded
22 % xinput{10}: ndraws2 -- # of 2nd loop for saving A0 draws
23 % xinput{11}: imndraws=nstarts*ndraws2
24 % xinput{12}: a0indx -- index number for non-zero elements in A0
25 % xinput{13}: tdf -- degrees of freedom for t-distribution
26 % xinput{14}: nbuffer -- interval for printing, plotting, and saving
27 % xinput{15}: Sbd -- nvar-by-nvar S{1}, ..., S{n} -- kind of covariance matrix for each simultaneous equation
28 % Already divided by "fss."
29 % xinput{16}: nSample -- the original sample size including lags
30 % xinput{17}: IndxNmlr -- index for which normalization rule to choose
31 % xinput{18}: IndxGibbs -- index for WZ Gibbs; 1; Gibbs; 0: Metropolis
32 % xinput{19}: scf -- reduction scale factor for Metropolis jumping kernel
33 % xinput{20}: H_sr -- square root of the inverse of the covariance matrix
34 % for free elements in A0 (nfp-by-nfp)
35 % xinput{21}: fss -- effective sample size == nSample-lags+# of dummy observations
36 % xinput{22}: idfile1 -- calls "iden6std." Save stds. of both data and impulse responses in idfile1
37 % xinput{23}: xxhpc -- chol(X'X+inv(H_p_tilde)): upper triangular but its transpose
38 % is lower triagular Choleski
39 % xinput{24}: ImfErr -- if 1, impulse response simulation; if 0, disable this simulation
40 % xinput{25}: ninv -- number of bins pre-specified to put each draw of impulse response
41 % into a proper bin (or small interval)
42 % xinput{26}: imstp -- # of steps for impulse responses
43 % xinput{27}: forep -- forecast periods (# of steps)
44 % xinput{28}: yact -- actual data (in log except R, U, etc.)
45 % xinput{29}: yactqg -- quarterly annualized growth in actual data
46 % xinput{30}: yactCalyg -- calendar annual growth in actual data
47 % xinput{31}: imfml -- imstp-by-nvar^2 ML impulse responses
48 % xinput{32}: forepq -- forecast periods for quarterly growth
49 % xinput{33}: forepy -- forecast periods for annual growth
50 % xinput{34}: ncoef -- k: # of coeffients per equation
51 % xinput{35}: Bhml -- ML reduced form parameter B (nvar-by-k)
52 % xinput{36}: lags -- # of lags
53 %------------------
54 % imfcntmulti: (ninv+2,imstp*nvar^2,nstarts) matrix
55 % cnt: count; for impulse responses; multi (nstarts) sequences
56 % All output is saved in outB_W, including Range5, invc, ninv, and imfcntmulti
57 %
58 % Written by T. Zha 1999
59 %
60 % Copyright (C) 1997-2012 Tao Zha
61 %
62 % This free software: you can redistribute it and/or modify
63 % it under the terms of the GNU General Public License as published by
64 % the Free Software Foundation, either version 3 of the License, or
65 % (at your option) any later version.
66 %
67 % It is distributed in the hope that it will be useful,
68 % but WITHOUT ANY WARRANTY; without even the implied warranty of
69 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
70 % GNU General Public License for more details.
71 %
72 % If you did not received a copy of the GNU General Public License
73 % with this software, see <http://www.gnu.org/licenses/>.
74 %
75
76 nfp=xinput{1}; nvar=xinput{2}; xhat=xinput{3}; hess=xinput{4}; Indxv=xinput{5};
77 IndxGraph=xinput{6}; idmat0=xinput{7}; nstarts=xinput{8}; ndraws1=xinput{9}; ndraws2=xinput{10};
78 imndraws=xinput{11}; a0indx=xinput{12}; tdf=xinput{13}; nbuffer=xinput{14}; Sbd=xinput{15};
79 nSample = xinput{16}; IndxNmlr=xinput{17}; IndxGibbs=xinput{18}; scf=xinput{19}; H_sr=xinput{20};
80 fss=xinput{21}; idfile1=xinput{22}; xxhpc=xinput{23}; ImfErr=xinput{24}; ninv=xinput{25};
81 imstp=xinput{26}; forep=xinput{27}; yact=xinput{28}; yactqg=xinput{29}; yactCalyg=xinput{30};
82 imfml=xinput{31}; forepq=xinput{32}; forepy=xinput{33}; ncoef=xinput{34}; Bhml=xinput{35};
83 lags=xinput{36};
84
85 Avhx_bs = zeros(nfp,1);
86 Avhx_bm = zeros(nfp,1);
87 Avhx_bj = zeros(nfp,1);
88 Avhx_cj = zeros(nfp,1);
89 Avhx_cm = zeros(nfp,1);
90 A0_h = zeros(nvar);
91 A0gbs = A0_h; % drawn A0 in Gibbs sampling
92 Avhxm = zeros(nfp,1);
93 Avhxs = Avhxm;
94 A0xhat = zeros(nvar);
95 A0xhat(a0indx) = xhat;
96 % A0hatw = zeros(nvar^2,nbuffer);
97
98 countJump = zeros(nstarts,1);
99
100 imfmean = zeros(imstp,nvar^2);
101 imfcntmulti = zeros(ninv+2,imstp*nvar^2,nstarts);
102 % cnt: count; for impulse responses; multi (nstarts) sequences
103
104
105 %---------------------------------------------------
106 % Specify the range for counting the empirical distribution
107 %
108 %** load the standard deviations of 6 variables, one for log(y), one for gq, and
109 %** the third one for yg
110 eval(['load ' idfile1 '.prn -ascii']);
111 eval(['ABstd=' idfile1 ';']);
112 Range5 = cell(4,1); % 4: log, qg, yg, and imf
113
114 %@@@ Tony's trick to expand the matrix
115 %
116 %** In order of log(y), qg, and yg for Range5{i} for i=1:3
117 Range5{1} =zeros(forep,nvar,2); % 2: min and max
118 Range5{1}(:,:,1) = repmat(yact(length(yact(:,1)),:)-10*ABstd(1,:),[forep 1]); % min, 30 std.
119 Range5{1}(:,:,2) = repmat(yact(length(yact(:,1)),:)+10*ABstd(1,:),[forep 1]); % max, 30 std.
120 %
121 Range5{2} =zeros(forepq,nvar,2); % 2: min and max
122 Range5{2}(:,:,1) = repmat(yactqg(length(yactqg(:,1)),:)-10*ABstd(2,:),[forepq 1]); % min, 30 std.
123 Range5{2}(:,:,2) = repmat(yactqg(length(yactqg(:,1)),:)+10*ABstd(2,:),[forepq 1]); % max, 30 std.
124 %
125 Range5{3} =zeros(forepy,nvar,2); % 2: min and max
126 Range5{3}(:,:,1) = repmat(yactCalyg(length(yactCalyg(:,1)),:)-10*ABstd(3,:),[forepy 1]); % min, 30 std.
127 Range5{3}(:,:,2) = repmat(yactCalyg(length(yactCalyg(:,1)),:)+10*ABstd(3,:),[forepy 1]); % max, 30 std.
128 %
129 Range5{4} =zeros(imstp,nvar^2,2); % 2: min and max
130 imfscale = repmat(ABstd(4,:),[1 nvar]); % because nvar variables to 1, ..., nvar shocks
131 Range5{4}(:,:,1) = repmat(imfml(1,:)-5*imfscale,[imstp 1]); % min, 5 std.
132 Range5{4}(:,:,2) = repmat(imfml(1,:)+5*imfscale,[imstp 1]); % max, 5 std.
133 % Range5(4)(:,:,1): imstp-by-nvar^2. Column: nvar responses to 1st shock,
134 % nvar responses to 2nd shock, ...
135 %**
136 invc = cell(4,1); % interval length (used for counting later). 1st 3 cells have each
137 % forep-by-nvar, and 4th has imstp-by-nvar^2.
138 for i=1:4
139 invc{i} = Range5{i}(:,:,2) - Range5{i}(:,:,1);
140 end
141 hbin = invc{4} ./ ninv; % bin size for each point of impulse responses kkdf
142 imfloor = Range5{4}(:,:,1);
143
144
145
146 %===================================
147 % Here begins with the big loop
148 %===================================
149 H1 = chol(hess); % upper triangular so that H1' is a lower triangular decomp
150 baseW = H_sr; %inv(H1); %H_sr; % covariance matrix without scaling
151 nswitch=0; %<<>> total number of sign switches
152 A0inxhat = inv(A0xhat); % inverse of ML estimate
153 a0indx0 = find(idmat0==0); % index for all zero's in A0;
154 nn=[nvar lags imstp];
155
156 [cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss);
157
158 tic
159 for starts = 1:nstarts
160 starts
161 if starts == 1
162 A0gbs(a0indx) = xhat; % from "load ..."
163 if ~IndxGibbs % Metropolist
164 Avhx = xhat;
165 hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx);
166 hAvhx = -hAvhx; % converted to logLH
167 end
168 else
169 Avhx = baseW*randn(nfp,1); %H_sr*randn(nfp,1); % D: discarded sequence
170 csq=randn(tdf,1);
171 csq=sum(csq .* csq);
172 Avhx = xhat+Avhx/sqrt(csq/tdf);
173 %** Normalization by the choice of IndxNmlr
174 A0gbs(a0indx) = Avhx;
175 if ~IndxNmlr(5)
176 [A0gbs,jnk] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]);
177 else
178 A0ingbs = inv(A0gbs);
179 [A0gbs,jnk,jnk1] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs);
180 end
181 %
182 if ~IndxGibbs % Metropolist
183 Avhx = A0gbs(a0indx);
184 hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx);
185 hAvhx = -hAvhx; % converted to logLH
186 end
187 end
188 %
189 Avhxmm = zeros(nfp,1);
190 Avhxss = zeros(nfp,1);
191 cJump = 0;
192 imfcnt = zeros(ninv+2,imstp*nvar^2); % cnt: count; for impulse responses
193
194 for draws = 1:ndraws1
195 if IndxGibbs
196 A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf);
197 else % Metropolis
198 [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,...
199 baseW,nfp,Sbd,fss,nvar,a0indx);
200 end
201 end
202
203 wdraws=(starts-1)*ndraws2+0;
204 for draws = 1:ndraws2
205 drawsc = (starts-1)*ndraws2+draws;
206 if IndxGibbs
207 A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf);
208 A0gbs(a0indx0) = 0; % set all zeros in A0gbs clean to avoid possible cumulative round-off errors
209 else % Metropolis
210 [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,...
211 baseW,nfp,Sbd,fss,nvar,a0indx);
212 A0gbs(a0indx) = Avhx;
213 end
214
215 %*** call normalization so that A0_h is normalized
216 if ~IndxNmlr(5)
217 [A0_h,nswitch] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]);
218 A0_hin = inv(A0_h);
219 else
220 A0ingbs = inv(A0gbs);
221 [A0_h,nswitch,A0_hin] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs);
222 end
223 Avhx_norm = A0_h(a0indx);
224
225 %
226 % *** normal draws for posterior Aplus conditional on A0h
227 %
228 %** the mean is Aplushm, and the covariance is inv(xxhp)=Lxxhpc*Lxxhpc'
229 Apindm = randn(ncoef,nvar);
230 %
231 if ~all(all(finite(Bhml)))
232 Aplushm=zeros(ncoef,nvar);
233 for i=1:nvar
234 Aplushm(:,i)=Gb{i}*A0_h(:,i); % see Zha's forecast (1) p.9
235 % Here, Gb is used to compute A+ where A+(i) = Gb(i)*a0(i)
236 end
237 Bh_h = (Aplushm + xxhpc\Apindm)*A0_hin;
238 else
239 Bh_h = Bhml + (xxhpc\Apindm)*A0_hin;
240 end
241
242 if ImfErr
243 swish_h = A0_hin'; % Switching back to the form A0*y(t) = e(t)
244 imf_h = zimpulse(Bh_h,swish_h,nn); % in the form that is congenial to RATS
245 % imf3_h=reshape(imf_h,size(imf_h,1),nvar,nvar);
246 % % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks
247 imfmean = imfmean + imf_h; % posterior mean
248 imfcnt = empdfsort(imfcnt,imf_h,imfloor,hbin,ninv);
249 % sorted counts (prob.) in bins
250 end
251
252 Avhxm = Avhxm + Avhx_norm; % 1st step to overall mean of parameter
253 Avhxs = Avhxs + Avhx_norm.^2; % 1st step to overall 2nd moment of parameter
254
255 %* compute the mean and 2nd moment
256 %** Getting average of variances W and variance of means B/n -- B_n
257 %* see Gelman, p.331, my Shock(0), 12-13, and my Forecast (2), 28-31
258 if (nstarts>1)
259 Avhxmm = Avhxmm + Avhx_norm; % n*(phi_.j)
260 Avhxss = Avhxss + Avhx_norm.^2; % 1st step to (phi_ij) for fixed j
261 end
262
263 % A0hatw(:,drawsc-wdraws) = A0_h(:);
264 if ~mod(draws,nbuffer)
265 starts
266 draws
267 wdraws=drawsc
268 % fwriteid = fopen('outA0.bin','a');
269 % count = fwrite(fwriteid,A0hatw,'double');
270 % status = fclose('all');
271 end
272 end
273 %
274 imfcntmulti(:,:,starts) = imfcnt;
275
276 if ~IndxGibbs
277 countJump(starts,1) = cJump;
278 end
279 %
280 %** Getting average of variances W and variance of means B/n -- B_n
281 %** see Gelman, p.331, my Shock(0), pp.12-13, and my Forecast (2), pp.28-31
282 if (nstarts>1)
283 Avhx_aj = Avhxmm/ndraws2; % (phi_.j)
284 Avhx_bs = Avhx_bs + Avhx_aj.^2; % 1st step to 2nd moment of (phi_.j)
285 Avhx_bm = Avhx_bm + Avhx_aj; % 1st step to (phi_..)
286 %
287 Avhx_bj = Avhxss/ndraws2; % 2nd moment of (phi_ij) for fixed j
288 Avhx_cj = Avhx_bj - Avhx_aj.^2; % ((n-1)/n)*S^2_j
289 Avhx_cm = Avhx_cm + Avhx_cj; % sum of ((n-1)/n)*S^2_j across j
290 end
291 end
292 timend = toc
293 timeminutes=timend/60
294
295 if ~IndxGibbs
296 countJump = countJump/ndraws2
297 end
298
299 Avhxm = Avhxm/(imndraws);
300 Avhxs = Avhxs/(imndraws);
301 Avhxv = Avhxs - Avhxm.^2;
302 Avhxs = sqrt(Avhxv); % stardard deviation
303 A0hm = zeros(nvar);
304 A0hm(a0indx) = Avhxm % mean
305 A0hv = zeros(nvar);
306 A0hv(a0indx) = Avhxv; % varaince matrix
307 A0hs = zeros(nvar);
308 A0hs(a0indx) = Avhxs; % standar deviation
309
310 imfmean = imfmean/(imndraws);
311
312 %**** Getting Within-Sequence W and Between-Sequence B_n
313 % see Gelman, p.331, my Shock(0), pp.12-13, and my Forecast (2), pp.28-31
314 if (nstarts>1)
315 AvhxW = (ndraws2/(ndraws2-1))*Avhx_cm/nstarts;
316 % W: average of j within-sequence variances
317 AvhxB_n = (nstarts/(nstarts-1)) * ( Avhx_bs/nstarts - (Avhx_bm/nstarts).^2 );
318 % B/n: variance of J within-sequence means
319 AvhxB = ndraws2*AvhxB_n; % B
320 %
321 B_W1 = AvhxB ./ AvhxW;
322 B1 = AvhxB;
323 W1 = AvhxW;
324 GR1 = sqrt((ndraws2-1)/ndraws2 + B_W1/ndraws2);
325 % measure of Gelman reduction; need not be 1 to be accurate,
326 % contrary to what Gelman claims
327 save outB_W B_W1 B1 W1 GR1 nstarts ndraws2 imndraws timeminutes Avhxs ...
328 A0xhat A0hm A0hs A0hv IndxGibbs countJump
329 if ImfErr
330 save outB_W nswitch imfml imfmean imfcntmulti Range5 ninv invc imstp nvar -append
331 end
332
333 titstr = ['J ' num2str(nstarts) ' n1 ' num2str(ndraws1) ...
334 ' n2 ' num2str(ndraws2) ' timend minutes ' num2str(timend/60)];
335 disp(' ')
336 disp(titstr)
337 disp('B/W sqrt(B) sqrt(W) Std(A0) GR')
338 format short g
339 [B_W1 sqrt(B1) sqrt(W1) Avhxs GR1]
340 else
341 save outB_W nstarts ndraws1 ndraws2 imndraws timeminutes Avhxs ...
342 A0xhat A0hm A0hs A0hv IndxGibbs countJump
343 if ImfErr
344 save outB_W nswitch imfml imfmean imfcntmulti Range5 ninv invc imstp nvar -append
345 end
346 end