File: McMCDiagnostics.m

package info (click to toggle)
dynare 4.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 40,640 kB
  • sloc: fortran: 82,231; cpp: 72,734; ansic: 28,874; pascal: 13,241; sh: 4,300; objc: 3,281; yacc: 2,833; makefile: 1,288; lex: 1,162; python: 162; lisp: 54; xml: 8
file content (361 lines) | stat: -rw-r--r-- 13,432 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
function McMCDiagnostics(options_, estim_params_, M_)
% function McMCDiagnostics
% Computes convergence tests 
% 
% INPUTS 
%   options_         [structure]
%   estim_params_    [structure]
%   M_               [structure]
%
% OUTPUTS 
%   none  
%
% SPECIAL REQUIREMENTS
%   none
%
% PARALLEL CONTEXT
% See the comment in random_walk_metropolis_hastings.m funtion.

% Copyright (C) 2005-2012 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.

DirectoryName = CheckPath('Output',M_.dname);
MhDirectoryName = CheckPath('metropolis',M_.dname);

TeX = options_.TeX;
nblck = options_.mh_nblck;
% Brooks and Gelman tests need more than one block 
if nblck == 1
    return;
end
npar = estim_params_.nvx;
npar = npar + estim_params_.nvn;
npar = npar + estim_params_.ncx;
npar = npar + estim_params_.ncn;
npar = npar + estim_params_.np ;
MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8);

load([MhDirectoryName '/'  M_.fname '_mh_history.mat'])

NumberOfMcFilesPerBlock = size(dir([MhDirectoryName ,filesep, M_.fname '_mh*_blck1.mat']),1);
for blck = 2:nblck
    tmp = size(dir([MhDirectoryName ,filesep, M_.fname '_mh*_blck' int2str(blck) '.mat']),1);
    if tmp~=NumberOfMcFilesPerBlock
        disp(['McMCDiagnostics:: The number of mh files in chain ' int2str(blck) ' is ' int2str(tmp) ' while'])
        disp(['                  the number of mh files in chain 1 is ' int2str(mcfiles) '!'])
        error('The number of mh files has to be constant across chains!')
    end
end

PastDraws = sum(record.MhDraws,1);
LastFileNumber = PastDraws(2);
LastLineNumber = record.MhDraws(end,3);
NumberOfDraws  = PastDraws(1);

Origin = 1000;
StepSize = ceil((NumberOfDraws-Origin)/100);% So that the computational time does not 
ALPHA = 0.2;                                % increase too much with the number of simulations. 
time = 1:NumberOfDraws;
xx = Origin:StepSize:NumberOfDraws;
NumberOfLines = length(xx);
tmp = zeros(NumberOfDraws*nblck,3);
UDIAG = zeros(NumberOfLines,6,npar);

if NumberOfDraws < Origin
    disp('MCMC Diagnostics :: The number of simulations is to small to compute the MCMC convergence diagnostics.')
    return
end

if TeX
    fidTeX = fopen([DirectoryName '/' M_.fname '_UnivariateDiagnostics.TeX'],'w');
    fprintf(fidTeX,'%% TeX eps-loader file generated by McmcDiagnostics.m (Dynare).\n');
    fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
    fprintf(fidTeX,' \n');
end

disp('MCMC Diagnostics: Univariate convergence diagnostic, Brooks and Gelman (1998):')

% The mandatory variables for local/remote parallel
% computing are stored in localVars struct.

localVars.MhDirectoryName = MhDirectoryName;
localVars.nblck = nblck;
localVars.NumberOfMcFilesPerBlock = NumberOfMcFilesPerBlock;
localVars.Origin = Origin;
localVars.StepSize = StepSize;
localVars.mh_drop = options_.mh_drop;
localVars.NumberOfDraws = NumberOfDraws;
localVars.NumberOfLines = NumberOfLines;
localVars.time = time;
localVars.M_ = M_;


% Like sequential execution!
if isnumeric(options_.parallel),
    fout = McMCDiagnostics_core(localVars,1,npar,0);
    UDIAG = fout.UDIAG;
    clear fout
    % Parallel execution!
else
    ModelName = M_.fname;
    if ~isempty(M_.bvar)
        ModelName = [M_.fname '_bvar'];
    end
    NamFileInput={[M_.dname '/metropolis/'],[ModelName '_mh*_blck*.mat']};
    
    [fout, nBlockPerCPU, totCPU] = masterParallel(options_.parallel, 1, npar,NamFileInput,'McMCDiagnostics_core', localVars, [], options_.parallel_info);
    UDIAG = fout(1).UDIAG;
    for j=2:totCPU,
        UDIAG = cat(3,UDIAG ,fout(j).UDIAG);
    end
end

UDIAG(:,[2 4 6],:) = UDIAG(:,[2 4 6],:)/nblck;
disp(' ')
clear pmet temp moyenne CSUP CINF csup cinf n linea iter tmp;    
pages = floor(npar/3);
k = 0;  
for i = 1:pages
    h=dyn_figure(options_,'Name','MCMC univariate diagnostic (Brooks and Gelman,1998)');
    boxplot = 1;
    for j = 1:3 % Loop over parameters
        k = k+1;
        [nam,namtex] = get_the_name(k,TeX,M_,estim_params_,options_);
        for crit = 1:3% Loop over criteria
            if crit == 1
                plt1 = UDIAG(:,1,k);
                plt2 = UDIAG(:,2,k);
                namnam  = [nam , ' (Interval)']; 
            elseif crit == 2
                plt1 = UDIAG(:,3,k);
                plt2 = UDIAG(:,4,k);
                namnam  = [nam , ' (m2)'];
            elseif crit == 3    
                plt1 = UDIAG(:,5,k);
                plt2 = UDIAG(:,6,k);
                namnam  = [nam , ' (m3)'];
            end
            if TeX
                if j==1
                    NAMES = deblank(namnam);
                    TEXNAMES = deblank(namtex);
                else
                    NAMES = char(NAMES,deblank(namnam));
                    TEXNAMES = char(TEXNAMES,deblank(namtex));
                end
            end
            subplot(3,3,boxplot);
            plot(xx,plt1,'-b');     % Pooled
            hold on;
            plot(xx,plt2,'-r');     % Within (mean)
            hold off;
            xlim([xx(1) xx(NumberOfLines)])
            title(namnam,'Interpreter','none')
            boxplot = boxplot + 1;
        end
    end
    dyn_saveas(h,[DirectoryName '/' M_.fname '_udiag' int2str(i)],options_);
    if TeX
        fprintf(fidTeX,'\\begin{figure}[H]\n');
        for jj = 1:size(NAMES,1)
            fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
        end    
        fprintf(fidTeX,'\\centering \n');
        fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_udiag%s}\n',[DirectoryName '/' M_.fname],int2str(i));
        fprintf(fidTeX,'\\caption{Univariate convergence diagnostics for the Metropolis-Hastings.\n');
        fprintf(fidTeX,'The first, second and third columns are respectively the criteria based on\n');
        fprintf(fidTeX,'the eighty percent interval, the second and third moments.}');
        fprintf(fidTeX,'\\label{Fig:UnivariateDiagnostics:%s}\n',int2str(i));
        fprintf(fidTeX,'\\end{figure}\n');
        fprintf(fidTeX,'\n');
    end
end
reste = npar-k;
if reste
    if reste == 1
        nr = 3;
        nc = 1;
    elseif reste == 2;
        nr = 2;
        nc = 3;
    end
    h = dyn_figure(options_,'Name','MCMC univariate diagnostic (Brooks and Gelman, 1998)');
    boxplot = 1;
    for j = 1:reste
        k = k+1;
        [nam,namtex] = get_the_name(k,TeX,M_,estim_params_,options_);
        for crit = 1:3
            if crit == 1
                plt1 = UDIAG(:,1,k);
                plt2 = UDIAG(:,2,k);
                namnam  = [nam , ' (Interval)']; 
            elseif crit == 2
                plt1 = UDIAG(:,3,k);
                plt2 = UDIAG(:,4,k);
                namnam  = [nam , ' (m2)'];
            elseif crit == 3    
                plt1 = UDIAG(:,5,k);
                plt2 = UDIAG(:,6,k);
                namnam  = [nam , ' (m3)'];
            end
            if TeX
                if j==1
                    NAMES = deblank(namnam);
                    TEXNAMES = deblank(namtex);
                else
                    NAMES = char(NAMES,deblank(namnam));
                    TEXNAMES = char(TEXNAMES,deblank(namtex));
                end
            end
            subplot(nr,nc,boxplot);
            plot(xx,plt1,'-b');                                 % Pooled
            hold on;
            plot(xx,plt2,'-r');                                 % Within (mean)
            hold off;
            xlim([xx(1) xx(NumberOfLines)]);
            title(namnam,'Interpreter','none');
            boxplot = boxplot + 1;
        end
    end
    dyn_saveas(h,[ DirectoryName '/' M_.fname '_udiag' int2str(pages+1)],options_);
    if TeX
        fprintf(fidTeX,'\\begin{figure}[H]\n');
        for jj = 1:size(NAMES,1);
            fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
        end    
        fprintf(fidTeX,'\\centering \n');
        fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_udiag%s}\n',[DirectoryName '/' M_.fname],int2str(pages+1));
        if reste == 2
            fprintf(fidTeX,'\\caption{Univariate convergence diagnostics for the Metropolis-Hastings.\n');
            fprintf(fidTeX,'The first, second and third columns are respectively the criteria based on\n');
            fprintf(fidTeX,'the eighty percent interval, the second and third moments.}');
        elseif reste == 1
            fprintf(fidTeX,'\\caption{Univariate convergence diagnostics for the Metropolis-Hastings.\n');
            fprintf(fidTeX,'The first, second and third rows are respectively the criteria based on\n');
            fprintf(fidTeX,'the eighty percent interval, the second and third moments.}');
        end
        fprintf(fidTeX,'\\label{Fig:UnivariateDiagnostics:%s}\n',int2str(pages+1));
        fprintf(fidTeX,'\\end{figure}\n');
        fprintf(fidTeX,'\n');
        fprintf(fidTeX,'% End Of TeX file.');
        fclose(fidTeX);
    end
end % if reste > 0
clear UDIAG;
%%
%% Multivariate diagnostic.
%%
if TeX
    fidTeX = fopen([DirectoryName '/' M_.fname '_MultivariateDiagnostics.TeX'],'w');
    fprintf(fidTeX,'%% TeX eps-loader file generated by McmcDiagnostics.m (Dynare).\n');
    fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
    fprintf(fidTeX,' \n');
end
tmp = zeros(NumberOfDraws*nblck,3);
MDIAG = zeros(NumberOfLines,6);
for b = 1:nblck
    startline = 0;
    for n = 1:NumberOfMcFilesPerBlock
        %load([MhDirectoryName '/' mcfiles(n,1,b).name],'logpo2');
        load([MhDirectoryName '/' M_.fname '_mh',int2str(n),'_blck' int2str(b) '.mat'],'logpo2');
        nlogpo2 = size(logpo2,1);
        tmp((b-1)*NumberOfDraws+startline+(1:nlogpo2),1) = logpo2;
        startline = startline+nlogpo2;
    end
% $$$   %load([MhDirectoryName '/' mcfiles(NumberOfMcFilesPerBlock,1,b).name],'logpo2');
% $$$   load([MhDirectoryName '/' M_.fname '_mh',int2str(NumberOfMcFilesPerBlock),'_blck' int2str(b) '.mat'],'logpo2');
% $$$   tmp((b-1)*NumberOfDraws+startline+1:(b-1)*NumberOfDraws+ MAX_nruns*(LastFileNumber-1)+LastLineNumber,1) = logpo2;
end
clear logpo2;
tmp(:,2) = kron(transpose(1:nblck),ones(NumberOfDraws,1));
tmp(:,3) = kron(ones(nblck,1),time'); 
tmp = sortrows(tmp,1);
ligne   = 0;
for iter  = Origin:StepSize:NumberOfDraws
    ligne = ligne+1;
    linea = ceil(options_.mh_drop*iter);
    n     = iter-linea+1;
    cinf  = round(n*ALPHA/2);
    csup  = round(n*(1-ALPHA/2));
    CINF  = round(nblck*n*ALPHA/2);
    CSUP  = round(nblck*n*(1-ALPHA/2));
    temp  = tmp(find((tmp(:,3)>=linea) & (tmp(:,3)<=iter)),1:2);
    MDIAG(ligne,1) = temp(CSUP,1)-temp(CINF,1);
    moyenne = mean(temp(:,1));%% Pooled mean.
    MDIAG(ligne,3) = sum((temp(:,1)-moyenne).^2)/(nblck*n-1);
    MDIAG(ligne,5) = sum(abs(temp(:,1)-moyenne).^3)/(nblck*n-1);
    for i=1:nblck
        pmet = temp(find(temp(:,2)==i));
        MDIAG(ligne,2) = MDIAG(ligne,2) + pmet(csup,1)-pmet(cinf,1);
        moyenne = mean(pmet,1); %% Within mean. 
        MDIAG(ligne,4) = MDIAG(ligne,4) + sum((pmet(:,1)-moyenne).^2)/(n-1);
        MDIAG(ligne,6) = MDIAG(ligne,6) + sum(abs(pmet(:,1)-moyenne).^3)/(n-1);
    end
end
MDIAG(:,[2 4 6],:) = MDIAG(:,[2 4 6],:)/nblck;  

h = dyn_figure(options_,'Name','Multivariate diagnostic');
boxplot = 1;
for crit = 1:3
    if crit == 1
        plt1 = MDIAG(:,1);
        plt2 = MDIAG(:,2);
        namnam  = 'Interval'; 
    elseif crit == 2
        plt1 = MDIAG(:,3);
        plt2 = MDIAG(:,4);
        namnam  = 'm2';
    elseif crit == 3    
        plt1 = MDIAG(:,5);
        plt2 = MDIAG(:,6);
        namnam  = 'm3';
    end
    if TeX
        if crit == 1
            NAMES = deblank(namnam);
        else
            NAMES = char(NAMES,deblank(namnam));
        end
    end
    subplot(3,1,boxplot);
    plot(xx,plt1,'-b');  % Pooled
    hold on
    plot(xx,plt2,'-r');  % Within (mean)
    hold off
    xlim([xx(1) xx(NumberOfLines)])
    title(namnam,'Interpreter','none');
    boxplot = boxplot + 1;
end
dyn_saveas(h,[ DirectoryName '/' M_.fname '_mdiag'],options_);

if TeX
    fprintf(fidTeX,'\\begin{figure}[H]\n');
    for jj = 1:3
        fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),' ');
    end    
    fprintf(fidTeX,'\\centering \n');
    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_mdiag}\n',[DirectoryName '/' M_.fname]);
    fprintf(fidTeX,'\\caption{Multivariate convergence diagnostics for the Metropolis-Hastings.\n');
    fprintf(fidTeX,'The first, second and third rows are respectively the criteria based on\n');
    fprintf(fidTeX,'the eighty percent interval, the second and third moments. The different \n');
    fprintf(fidTeX,'parameters are aggregated using the posterior kernel.}');
    fprintf(fidTeX,'\\label{Fig:MultivariateDiagnostics}\n');
    fprintf(fidTeX,'\\end{figure}\n');
    fprintf(fidTeX,'\n');
    fprintf(fidTeX,'% End Of TeX file.');
    fclose(fidTeX);
end