Fixed indentation of matlab files.
parent
3d91cf9716
commit
5417b27ac7
|
@ -26,107 +26,107 @@ function [AHess, DLIK, LIK] = AHessian(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,ka
|
|||
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
k = size(DT,3); % number of structural parameters
|
||||
smpl = size(Y,2); % Sample size.
|
||||
pp = size(Y,1); % Maximum number of observed variables.
|
||||
mm = size(T,2); % Number of state variables.
|
||||
a = zeros(mm,1); % State vector.
|
||||
Om = R*Q*transpose(R); % Variance of R times the vector of structural innovations.
|
||||
t = 0; % Initialization of the time index.
|
||||
oldK = 0;
|
||||
notsteady = 1; % Steady state flag.
|
||||
F_singular = 1;
|
||||
k = size(DT,3); % number of structural parameters
|
||||
smpl = size(Y,2); % Sample size.
|
||||
pp = size(Y,1); % Maximum number of observed variables.
|
||||
mm = size(T,2); % Number of state variables.
|
||||
a = zeros(mm,1); % State vector.
|
||||
Om = R*Q*transpose(R); % Variance of R times the vector of structural innovations.
|
||||
t = 0; % Initialization of the time index.
|
||||
oldK = 0;
|
||||
notsteady = 1; % Steady state flag.
|
||||
F_singular = 1;
|
||||
|
||||
lik = zeros(smpl,1); % Initialization of the vector gathering the densities.
|
||||
LIK = Inf; % Default value of the log likelihood.
|
||||
if nargout > 1
|
||||
DLIK = zeros(k,1); % Initialization of the score.
|
||||
end
|
||||
AHess = zeros(k,k); % Initialization of the Hessian
|
||||
Da = zeros(mm,k); % State vector.
|
||||
Dv = zeros(length(mf),k);
|
||||
|
||||
AHess = zeros(k,k); % Initialization of the Hessian
|
||||
Da = zeros(mm,k); % State vector.
|
||||
Dv = zeros(length(mf),k);
|
||||
|
||||
% for ii = 1:k
|
||||
% DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii));
|
||||
% DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii));
|
||||
% end
|
||||
|
||||
while notsteady && t<smpl
|
||||
t = t+1;
|
||||
v = Y(:,t)-a(mf);
|
||||
F = P(mf,mf) + H;
|
||||
if rcond(F) < kalman_tol
|
||||
if ~all(abs(F(:))<kalman_tol)
|
||||
return
|
||||
else
|
||||
a = T*a;
|
||||
P = T*P*transpose(T)+Om;
|
||||
end
|
||||
|
||||
while notsteady && t<smpl
|
||||
t = t+1;
|
||||
v = Y(:,t)-a(mf);
|
||||
F = P(mf,mf) + H;
|
||||
if rcond(F) < kalman_tol
|
||||
if ~all(abs(F(:))<kalman_tol)
|
||||
return
|
||||
else
|
||||
F_singular = 0;
|
||||
iF = inv(F);
|
||||
K = P(:,mf)*iF;
|
||||
lik(t) = log(det(F))+transpose(v)*iF*v;
|
||||
|
||||
[DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K);
|
||||
|
||||
for ii = 1:k
|
||||
Dv(:,ii) = -Da(mf,ii) - DYss(mf,ii);
|
||||
Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
|
||||
if t>=start && nargout > 1
|
||||
DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
|
||||
end
|
||||
end
|
||||
vecDPmf = reshape(DP(mf,mf,:),[],k);
|
||||
% iPmf = inv(P(mf,mf));
|
||||
if t>=start
|
||||
AHess = AHess + Dv'*iF*Dv + .5*(vecDPmf' * kron(iF,iF) * vecDPmf);
|
||||
end
|
||||
a = T*(a+K*v);
|
||||
P = T*(P-K*P(mf,:))*transpose(T)+Om;
|
||||
DP = DP1;
|
||||
a = T*a;
|
||||
P = T*P*transpose(T)+Om;
|
||||
end
|
||||
notsteady = max(max(abs(K-oldK))) > riccati_tol;
|
||||
oldK = K;
|
||||
end
|
||||
else
|
||||
F_singular = 0;
|
||||
iF = inv(F);
|
||||
K = P(:,mf)*iF;
|
||||
lik(t) = log(det(F))+transpose(v)*iF*v;
|
||||
|
||||
if F_singular
|
||||
error('The variance of the forecast error remains singular until the end of the sample')
|
||||
end
|
||||
[DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K);
|
||||
|
||||
|
||||
if t < smpl
|
||||
t0 = t+1;
|
||||
while t < smpl
|
||||
t = t+1;
|
||||
v = Y(:,t)-a(mf);
|
||||
for ii = 1:k
|
||||
Dv(:,ii) = -Da(mf,ii)-DYss(mf,ii);
|
||||
Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
|
||||
if t>=start && nargout >1
|
||||
DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
|
||||
end
|
||||
end
|
||||
if t>=start
|
||||
AHess = AHess + Dv'*iF*Dv;
|
||||
end
|
||||
a = T*(a+K*v);
|
||||
lik(t) = transpose(v)*iF*v;
|
||||
end
|
||||
AHess = AHess + .5*(smpl-t0+1)*(vecDPmf' * kron(iF,iF) * vecDPmf);
|
||||
if nargout > 1
|
||||
for ii = 1:k
|
||||
% DLIK(ii,1) = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) );
|
||||
Dv(:,ii) = -Da(mf,ii) - DYss(mf,ii);
|
||||
Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
|
||||
if t>=start && nargout > 1
|
||||
DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
|
||||
end
|
||||
end
|
||||
vecDPmf = reshape(DP(mf,mf,:),[],k);
|
||||
% iPmf = inv(P(mf,mf));
|
||||
if t>=start
|
||||
AHess = AHess + Dv'*iF*Dv + .5*(vecDPmf' * kron(iF,iF) * vecDPmf);
|
||||
end
|
||||
lik(t0:smpl) = lik(t0:smpl) + log(det(F));
|
||||
% for ii = 1:k;
|
||||
% for jj = 1:ii
|
||||
% H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)'));
|
||||
% end
|
||||
% end
|
||||
end
|
||||
|
||||
AHess = -AHess;
|
||||
a = T*(a+K*v);
|
||||
P = T*(P-K*P(mf,:))*transpose(T)+Om;
|
||||
DP = DP1;
|
||||
end
|
||||
notsteady = max(max(abs(K-oldK))) > riccati_tol;
|
||||
oldK = K;
|
||||
end
|
||||
|
||||
if F_singular
|
||||
error('The variance of the forecast error remains singular until the end of the sample')
|
||||
end
|
||||
|
||||
|
||||
if t < smpl
|
||||
t0 = t+1;
|
||||
while t < smpl
|
||||
t = t+1;
|
||||
v = Y(:,t)-a(mf);
|
||||
for ii = 1:k
|
||||
Dv(:,ii) = -Da(mf,ii)-DYss(mf,ii);
|
||||
Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
|
||||
if t>=start && nargout >1
|
||||
DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
|
||||
end
|
||||
end
|
||||
if t>=start
|
||||
AHess = AHess + Dv'*iF*Dv;
|
||||
end
|
||||
a = T*(a+K*v);
|
||||
lik(t) = transpose(v)*iF*v;
|
||||
end
|
||||
AHess = AHess + .5*(smpl-t0+1)*(vecDPmf' * kron(iF,iF) * vecDPmf);
|
||||
if nargout > 1
|
||||
for ii = 1:k
|
||||
% DLIK(ii,1) = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) );
|
||||
end
|
||||
end
|
||||
lik(t0:smpl) = lik(t0:smpl) + log(det(F));
|
||||
% for ii = 1:k;
|
||||
% for jj = 1:ii
|
||||
% H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)'));
|
||||
% end
|
||||
% end
|
||||
end
|
||||
|
||||
AHess = -AHess;
|
||||
if nargout > 1
|
||||
DLIK = DLIK/2;
|
||||
end
|
||||
|
@ -134,15 +134,15 @@ end
|
|||
lik = (lik + pp*log(2*pi))/2;
|
||||
|
||||
LIK = sum(lik(start:end)); % Minus the log-likelihood.
|
||||
% end of main function
|
||||
|
||||
% end of main function
|
||||
|
||||
function [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K)
|
||||
|
||||
k = size(DT,3);
|
||||
tmp = P-K*P(mf,:);
|
||||
k = size(DT,3);
|
||||
tmp = P-K*P(mf,:);
|
||||
|
||||
for ii = 1:k
|
||||
DF(:,:,ii) = DP(mf,mf,ii) + DH(:,:,ii);
|
||||
DF(:,:,ii) = DP(mf,mf,ii) + DH(:,:,ii);
|
||||
DiF(:,:,ii) = -iF*DF(:,:,ii)*iF;
|
||||
DK(:,:,ii) = DP(:,mf,ii)*iF + P(:,mf)*DiF(:,:,ii);
|
||||
Dtmp = DP(:,:,ii) - DK(:,:,ii)*P(mf,:) - K*DP(mf,:,ii);
|
||||
|
@ -150,6 +150,3 @@ for ii = 1:k
|
|||
end
|
||||
|
||||
% end of computeDKalman
|
||||
|
||||
|
||||
|
|
@ -29,7 +29,7 @@ function e = SPAimerr(c)
|
|||
% Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
|
||||
% pages 472-489
|
||||
|
||||
if(c==1) e='Aim: unique solution.';
|
||||
if(c==1) e='Aim: unique solution.';
|
||||
elseif(c==2) e='Aim: roots not correctly computed by real_schur.';
|
||||
elseif(c==3) e='Aim: too many big roots.';
|
||||
elseif(c==35) e='Aim: too many big roots, and q(:,right) is singular.';
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
|
||||
SPAmalg(h,neq,nlag,nlead,condn,uprbnd)
|
||||
SPAmalg(h,neq,nlag,nlead,condn,uprbnd)
|
||||
% [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
|
||||
% SPAmalg(h,neq,nlag,nlead,condn,uprbnd)
|
||||
%
|
||||
|
@ -8,9 +8,9 @@ function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
|
|||
% roots. This procedure will fail if the companion matrix is
|
||||
% defective and does not have a linearly independent set of
|
||||
% eigenvectors associated with the big roots.
|
||||
%
|
||||
%
|
||||
% Input arguments:
|
||||
%
|
||||
%
|
||||
% h Structural coefficient matrix (neq,neq*(nlag+1+nlead)).
|
||||
% neq Number of equations.
|
||||
% nlag Number of lags.
|
||||
|
@ -19,9 +19,9 @@ function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
|
|||
% by numeric_shift and reduced_form.
|
||||
% uprbnd Inclusive upper bound for the modulus of roots
|
||||
% allowed in the reduced form.
|
||||
%
|
||||
%
|
||||
% Output arguments:
|
||||
%
|
||||
%
|
||||
% b Reduced form coefficient matrix (neq,neq*nlag).
|
||||
% rts Roots returned by eig.
|
||||
% ia Dimension of companion matrix (number of non-trivial
|
||||
|
@ -57,7 +57,7 @@ function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
|
|||
% pages 472-489
|
||||
|
||||
b=[];rts=[];ia=[];nexact=[];nnumeric=[];lgroots=[];aimcode=[];
|
||||
if(nlag<1 || nlead<1)
|
||||
if(nlag<1 || nlead<1)
|
||||
error('Aim_eig: model must have at least one lag and one lead');
|
||||
end
|
||||
% Initialization.
|
||||
|
@ -75,17 +75,17 @@ if (iq>qrows)
|
|||
end
|
||||
[a,ia,js] = SPBuild_a(h,qcols,neq);
|
||||
if (ia ~= 0)
|
||||
if any(any(isnan(a))) || any(any(isinf(a)))
|
||||
if any(any(isnan(a))) || any(any(isinf(a)))
|
||||
disp('A is NAN or INF')
|
||||
aimcode=63;
|
||||
return
|
||||
end
|
||||
aimcode=63;
|
||||
return
|
||||
end
|
||||
[w,rts,lgroots,flag_trouble]=SPEigensystem(a,uprbnd,min(length(js),qrows-iq+1));
|
||||
if flag_trouble==1
|
||||
disp('Problem in SPEIG');
|
||||
disp('Problem in SPEIG');
|
||||
aimcode=64;
|
||||
return
|
||||
end
|
||||
end
|
||||
q = SPCopy_w(q,w,js,iq,qrows);
|
||||
end
|
||||
test=nexact+nnumeric+lgroots;
|
||||
|
|
|
@ -41,9 +41,9 @@ hs(:,left) = -hs(:,right)\hs(:,left);
|
|||
a = zeros(qcols,qcols);
|
||||
|
||||
if(qcols > neq)
|
||||
eyerows = 1:qcols-neq;
|
||||
eyecols = neq+1:qcols;
|
||||
a(eyerows,eyecols) = eye(qcols-neq);
|
||||
eyerows = 1:qcols-neq;
|
||||
eyecols = neq+1:qcols;
|
||||
a(eyerows,eyecols) = eye(qcols-neq);
|
||||
end
|
||||
hrows = qcols-neq+1:qcols;
|
||||
a(hrows,:) = hs(:,left);
|
||||
|
@ -51,14 +51,14 @@ a(hrows,:) = hs(:,left);
|
|||
% Delete inessential lags and build index array js. js indexes the
|
||||
% columns in the big transition matrix that correspond to the
|
||||
% essential lags in the model. They are the columns of q that will
|
||||
% get the unstable left eigenvectors.
|
||||
% get the unstable left eigenvectors.
|
||||
|
||||
js = 1:qcols;
|
||||
zerocols = sum(abs(a)) == 0;
|
||||
while( any(zerocols) )
|
||||
a(:,zerocols) = [];
|
||||
a(zerocols,:) = [];
|
||||
js(zerocols) = [];
|
||||
zerocols = sum(abs(a)) == 0;
|
||||
a(:,zerocols) = [];
|
||||
a(zerocols,:) = [];
|
||||
js(zerocols) = [];
|
||||
zerocols = sum(abs(a)) == 0;
|
||||
end
|
||||
ia = length(js);
|
||||
|
|
|
@ -2,7 +2,7 @@ function q = SPCopy_w(q,w,js,iq,qrows)
|
|||
% q = SPCopy_w(q,w,js,iq,qrows)
|
||||
%
|
||||
% Copy the eigenvectors corresponding to the largest roots into the
|
||||
% remaining empty rows and columns js of q
|
||||
% remaining empty rows and columns js of q
|
||||
|
||||
% Author: Gary Anderson
|
||||
% Original file downloaded from:
|
||||
|
@ -30,7 +30,7 @@ function q = SPCopy_w(q,w,js,iq,qrows)
|
|||
|
||||
|
||||
if(iq < qrows)
|
||||
lastrows = iq+1:qrows;
|
||||
wrows = 1:length(lastrows);
|
||||
q(lastrows,js) = w(:,wrows)';
|
||||
lastrows = iq+1:qrows;
|
||||
wrows = 1:length(lastrows);
|
||||
q(lastrows,js) = w(:,wrows)';
|
||||
end
|
||||
|
|
|
@ -30,7 +30,7 @@ function [w,rts,lgroots,flag_trouble] = SPEigensystem(a,uprbnd,rowsLeft)
|
|||
% Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
|
||||
% pages 472-489
|
||||
|
||||
opts.disp=0;
|
||||
opts.disp=0;
|
||||
% next block is commented out because eigs() intermitently returns different rts
|
||||
%try
|
||||
% [w,d] = eigs(a',rowsLeft,'LM',opts);
|
||||
|
@ -39,24 +39,24 @@ opts.disp=0;
|
|||
% [mag,k] = sort(-mag);
|
||||
% rts = rts(k);
|
||||
%catch
|
||||
%disp('Catch in SPE');
|
||||
%pause(0.5);
|
||||
%aStr=datestr(clock);
|
||||
%eval(['save ' regexprep(aStr,' ','') ' a']);
|
||||
try
|
||||
[w,d]=eig(a');
|
||||
catch
|
||||
lasterr
|
||||
w=[];rts=[];lgroots=[];
|
||||
flag_trouble=1;
|
||||
return
|
||||
end
|
||||
rts = diag(d);
|
||||
mag = abs(rts);
|
||||
[mag,k] = sort(-mag);
|
||||
rts = rts(k);
|
||||
%disp('Catch in SPE');
|
||||
%pause(0.5);
|
||||
%aStr=datestr(clock);
|
||||
%eval(['save ' regexprep(aStr,' ','') ' a']);
|
||||
try
|
||||
[w,d]=eig(a');
|
||||
catch
|
||||
lasterr
|
||||
w=[];rts=[];lgroots=[];
|
||||
flag_trouble=1;
|
||||
return
|
||||
end
|
||||
rts = diag(d);
|
||||
mag = abs(rts);
|
||||
[mag,k] = sort(-mag);
|
||||
rts = rts(k);
|
||||
%end
|
||||
flag_trouble=0;
|
||||
flag_trouble=0;
|
||||
|
||||
%ws=SPSparse(w);
|
||||
ws=sparse(w);
|
||||
|
@ -65,7 +65,7 @@ ws = ws(:,k);
|
|||
% Given a complex conjugate pair of vectors W = [w1,w2], there is a
|
||||
% nonsingular matrix D such that W*D = real(W) + imag(W). That is to
|
||||
% say, W and real(W)+imag(W) span the same subspace, which is all
|
||||
% that aim cares about.
|
||||
% that aim cares about.
|
||||
|
||||
ws = real(ws) + imag(ws);
|
||||
|
||||
|
|
|
@ -36,12 +36,11 @@ right = qcols+1:qcols+neq;
|
|||
zerorows = find( sum(abs( hs(:,right)' ))==0 );
|
||||
|
||||
while( any(zerorows) && iq <= qrows )
|
||||
nz = length(zerorows);
|
||||
q(iq+1:iq+nz,:) = hs(zerorows,left);
|
||||
hs(zerorows,:) = SPShiftright(hs(zerorows,:),neq);
|
||||
iq = iq + nz;
|
||||
nexact = nexact + nz;
|
||||
zerorows = find( sum(abs( hs(:,right)' ))==0 );
|
||||
nz = length(zerorows);
|
||||
q(iq+1:iq+nz,:) = hs(zerorows,left);
|
||||
hs(zerorows,:) = SPShiftright(hs(zerorows,:),neq);
|
||||
iq = iq + nz;
|
||||
nexact = nexact + nz;
|
||||
zerorows = find( sum(abs( hs(:,right)' ))==0 );
|
||||
end
|
||||
h=full(hs);
|
||||
|
||||
|
|
|
@ -37,14 +37,14 @@ right = qcols+1:qcols+neq;
|
|||
zerorows = find( abs(diag(R)) <= condn );
|
||||
|
||||
while( any(zerorows) && iq <= qrows )
|
||||
h=sparse(h);
|
||||
Q=sparse(Q);
|
||||
h = Q'*h;
|
||||
nz = length(zerorows);
|
||||
q(iq+1:iq+nz,:) = h(zerorows,left);
|
||||
h(zerorows,:) = SPShiftright( h(zerorows,:), neq );
|
||||
iq = iq + nz;
|
||||
nnumeric = nnumeric + nz;
|
||||
[Q,R,E] = qr( full(h(:,right)) );
|
||||
zerorows = find( abs(diag(R)) <= condn );
|
||||
h=sparse(h);
|
||||
Q=sparse(Q);
|
||||
h = Q'*h;
|
||||
nz = length(zerorows);
|
||||
q(iq+1:iq+nz,:) = h(zerorows,left);
|
||||
h(zerorows,:) = SPShiftright( h(zerorows,:), neq );
|
||||
iq = iq + nz;
|
||||
nnumeric = nnumeric + nz;
|
||||
[Q,R,E] = qr( full(h(:,right)) );
|
||||
zerorows = find( abs(diag(R)) <= condn );
|
||||
end
|
||||
|
|
|
@ -2,7 +2,7 @@ function scof = SPObstruct(cof,cofb,neq,nlag,nlead)
|
|||
% scof = SPObstruct(cof,cofb,neq,nlag,nlead)
|
||||
%
|
||||
% Construct the coefficients in the observable structure.
|
||||
%
|
||||
%
|
||||
% Input arguments:
|
||||
%
|
||||
% cof structural coefficients
|
||||
|
@ -51,17 +51,17 @@ qs=sparse(q);
|
|||
qs(1:rc,1:cc) = sparse(cofb);
|
||||
qcols = neq*(nlag+nlead);
|
||||
|
||||
if( nlead > 1 )
|
||||
for i = 1:nlead-1
|
||||
rows = i*neq + (1:neq);
|
||||
qs(rows,:) = SPShiftright( qs((rows-neq),:), neq );
|
||||
end
|
||||
if( nlead > 1 )
|
||||
for i = 1:nlead-1
|
||||
rows = i*neq + (1:neq);
|
||||
qs(rows,:) = SPShiftright( qs((rows-neq),:), neq );
|
||||
end
|
||||
end
|
||||
|
||||
l = (1: neq*nlag);
|
||||
r = (neq*nlag+1: neq*(nlag+nlead));
|
||||
|
||||
qs(:,l) = - qs(:,r) \ qs(:,l);
|
||||
qs(:,l) = - qs(:,r) \ qs(:,l);
|
||||
|
||||
minus = 1: neq*(nlag+1);
|
||||
plus = neq*(nlag+1)+1: neq*(nlag+1+nlead);
|
||||
|
|
|
@ -38,7 +38,7 @@ if(nonsing)
|
|||
b = qs(1:neq,1:bcols);
|
||||
b = full(b);
|
||||
else %rescale by dividing row by maximal qr element
|
||||
%'inverse condition number small, rescaling '
|
||||
%'inverse condition number small, rescaling '
|
||||
themax=max(abs(qs(:,right)),[],2);
|
||||
oneover = diag(1 ./ themax);
|
||||
nonsing = rcond(full(oneover *qs(:,right))) > condn;
|
||||
|
@ -48,4 +48,3 @@ else %rescale by dividing row by maximal qr element
|
|||
b = full(b);
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@ function [y] = SPShiftright(x,n)
|
|||
% [y] = shiftright(x,n)
|
||||
%
|
||||
% Shift the rows of x to the right by n columns, leaving zeros in the
|
||||
% first n columns.
|
||||
% first n columns.
|
||||
|
||||
% Original author: Gary Anderson
|
||||
% Original file downloaded from:
|
||||
|
|
|
@ -1,20 +1,20 @@
|
|||
function [dr,aimcode,rts]=dynAIMsolver1(jacobia_,M_,dr)
|
||||
% function [dr,aimcode]=dynAIMsolver1(jacobia_,M_,dr)
|
||||
% Maps Dynare jacobia to AIM 1st order model solver designed and developed by Gary ANderson
|
||||
% Maps Dynare jacobia to AIM 1st order model solver designed and developed by Gary ANderson
|
||||
% and derives the solution for gy=dr.hgx and gu=dr.hgu from the AIM outputs
|
||||
% AIM System is given as a sum:
|
||||
% i.e. for i=-$...+& SUM(Hi*xt+i)= £*zt, t = 0, . . . ,?
|
||||
% AIM System is given as a sum:
|
||||
% i.e. for i=-$...+& SUM(Hi*xt+i)= £*zt, t = 0, . . . ,?
|
||||
% and its input as single array of matrices: [H-$... Hi ... H+&]
|
||||
% and its solution as xt=SUM( Bi*xt+i) + @*£*zt for i=-$...-1
|
||||
% with the output in form bb=[B-$... Bi ... B-1] and @=inv(Ho+H1*B-1)
|
||||
% Dynare jacobian = [fy'-$... fy'i ... fy'+& fu']
|
||||
% where [fy'-$... fy'i ... fy'+&]=[H-$... Hi ... H+&] and fu'= £
|
||||
% and its solution as xt=SUM( Bi*xt+i) + @*£*zt for i=-$...-1
|
||||
% with the output in form bb=[B-$... Bi ... B-1] and @=inv(Ho+H1*B-1)
|
||||
% Dynare jacobian = [fy'-$... fy'i ... fy'+& fu']
|
||||
% where [fy'-$... fy'i ... fy'+&]=[H-$... Hi ... H+&] and fu'= £
|
||||
%
|
||||
% INPUTS
|
||||
% jacobia_ [matrix] 1st order derivative of the model
|
||||
% jacobia_ [matrix] 1st order derivative of the model
|
||||
% dr [matlab structure] Decision rules for stochastic simulations.
|
||||
% M_ [matlab structure] Definition of the model.
|
||||
%
|
||||
% M_ [matlab structure] Definition of the model.
|
||||
%
|
||||
% OUTPUTS
|
||||
% dr [matlab structure] Decision rules for stochastic simulations.
|
||||
% aimcode [integer] 1: the model defines variables uniquely
|
||||
|
@ -31,20 +31,20 @@ function [dr,aimcode,rts]=dynAIMsolver1(jacobia_,M_,dr)
|
|||
% (c==63) e='Aim: A is NAN or INF.';
|
||||
% (c==64) e='Aim: Problem in SPEIG.';
|
||||
% else e='Aimerr: return code not properly specified';
|
||||
%
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% Dynare use:
|
||||
% Dynare use:
|
||||
% 1) the lognormal block in DR1 is being invoked for some models and changing
|
||||
% values of ghx and ghy. We need to return the AIM output
|
||||
% values before that block and run the block with the current returned values
|
||||
% of gy (i.e. dr.ghx) and gu (dr.ghu) if it is needed even when the AIM is used
|
||||
% of gy (i.e. dr.ghx) and gu (dr.ghu) if it is needed even when the AIM is used
|
||||
% (it does not depend on mjdgges output).
|
||||
%
|
||||
% 2) passing in aa={Q'|1}*jacobia_ can produce ~ one order closer
|
||||
% results to the Dynare solutiion then when if plain jacobia_ is passed,
|
||||
% i.e. diff < e-14 for aa and diff < *e-13 for jacobia_ if Q' is used.
|
||||
%
|
||||
% GP July 2008
|
||||
% 2) passing in aa={Q'|1}*jacobia_ can produce ~ one order closer
|
||||
% results to the Dynare solutiion then when if plain jacobia_ is passed,
|
||||
% i.e. diff < e-14 for aa and diff < *e-13 for jacobia_ if Q' is used.
|
||||
%
|
||||
% GP July 2008
|
||||
|
||||
% Copyright (C) 2008-2012 Dynare Team
|
||||
%
|
||||
|
@ -69,8 +69,8 @@ lags=M_.maximum_endo_lag; % no of lags and leads
|
|||
leads=M_.maximum_endo_lead;
|
||||
klen=(leads+lags+1); % total lenght
|
||||
theAIM_H=zeros(neq, neq*klen); % alloc space
|
||||
lli=M_.lead_lag_incidence';
|
||||
% "sparse" the compact jacobia into AIM H aray of matrices
|
||||
lli=M_.lead_lag_incidence';
|
||||
% "sparse" the compact jacobia into AIM H aray of matrices
|
||||
% without exogenous shoc
|
||||
theAIM_H(:,find(lli(:)))=jacobia_(:,nonzeros(lli(:)));
|
||||
condn = 1.e-10;%SPAmalg uses this in zero tests
|
||||
|
@ -102,7 +102,7 @@ if aimcode==1 %if OK
|
|||
col_order=[((i-1)*neq)+dr.order_var' col_order];
|
||||
end
|
||||
bb_ord= bb(dr.order_var,col_order); % derive ordered gy
|
||||
|
||||
|
||||
% variables are present in the state space at the lag at which they
|
||||
% appear and at all smaller lags. The are ordered from smaller to
|
||||
% higher lag (reversed order of M_.lead_lag_incidence rows for lagged
|
||||
|
@ -117,7 +117,7 @@ if aimcode==1 %if OK
|
|||
%theH0= theAIM_H (:,lags*neq+1: (lags+1)*neq);
|
||||
% theHP= theAIM_H (:,(M_.maximum_endo_lag+1)*neq+1: (M_.maximum_endo_lag+2)*neq);
|
||||
%theHP= theAIM_H (:,(lags+1)*neq+1: (lags+2)*neq);
|
||||
theAIM_Psi= - jacobia_(:, size(nonzeros(lli(:)))+1:end);%
|
||||
theAIM_Psi= - jacobia_(:, size(nonzeros(lli(:)))+1:end);%
|
||||
%? = inv(H0 + H1B1)
|
||||
%phi= (theH0+theHP*sparse(bb(:,(lags-1)*neq+1:end)))\eye( neq);
|
||||
%AIM_ghu=phi*theAIM_Psi;
|
||||
|
@ -137,8 +137,8 @@ else
|
|||
if aimcode < 1 || aimcode > 5 % too big exception, use mjdgges
|
||||
error('Error in AIM: aimcode=%d ; %s', aimcode, err);
|
||||
end
|
||||
% if aimcode > 5
|
||||
% if aimcode > 5
|
||||
% disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]);
|
||||
% aimcode=5;
|
||||
% end
|
||||
% end
|
||||
end
|
||||
|
|
|
@ -67,35 +67,34 @@ function [dr,info]=AIM_first_order_solver(jacobia,M,dr,qz_criterium)
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
info = 0;
|
||||
|
||||
[dr,aimcode]=dynAIMsolver1(jacobia,M,dr);
|
||||
|
||||
if aimcode ~=1
|
||||
info(1) = convertAimCodeToInfo(aimCode); %convert to be in the 100 range
|
||||
info(2) = 1.0e+8;
|
||||
return
|
||||
info = 0;
|
||||
|
||||
[dr,aimcode]=dynAIMsolver1(jacobia,M,dr);
|
||||
|
||||
if aimcode ~=1
|
||||
info(1) = convertAimCodeToInfo(aimCode); %convert to be in the 100 range
|
||||
info(2) = 1.0e+8;
|
||||
return
|
||||
end
|
||||
A = kalman_transition_matrix(dr,M.nstatic+(1:M.nspred), 1:M.nspred,...
|
||||
M.exo_nbr);
|
||||
dr.eigval = eig(A);
|
||||
disp(dr.eigval)
|
||||
nd = size(dr.kstate,1);
|
||||
nba = nd-sum( abs(dr.eigval) < qz_criterium );
|
||||
|
||||
nsfwrd = M.nsfwrd;
|
||||
|
||||
if nba ~= nsfwrd
|
||||
temp = sort(abs(dr.eigval));
|
||||
if nba > nsfwrd
|
||||
temp = temp(nd-nba+1:nd-nsfwrd)-1-qz_criterium;
|
||||
info(1) = 3;
|
||||
elseif nba < nsfwrd
|
||||
temp = temp(nd-nsfwrd+1:nd-nba)-1-qz_criterium;
|
||||
info(1) = 4;
|
||||
end
|
||||
A = kalman_transition_matrix(dr,M.nstatic+(1:M.nspred), 1:M.nspred,...
|
||||
M.exo_nbr);
|
||||
dr.eigval = eig(A);
|
||||
disp(dr.eigval)
|
||||
nd = size(dr.kstate,1);
|
||||
nba = nd-sum( abs(dr.eigval) < qz_criterium );
|
||||
|
||||
nsfwrd = M.nsfwrd;
|
||||
|
||||
if nba ~= nsfwrd
|
||||
temp = sort(abs(dr.eigval));
|
||||
if nba > nsfwrd
|
||||
temp = temp(nd-nba+1:nd-nsfwrd)-1-qz_criterium;
|
||||
info(1) = 3;
|
||||
elseif nba < nsfwrd
|
||||
temp = temp(nd-nsfwrd+1:nd-nba)-1-qz_criterium;
|
||||
info(1) = 4;
|
||||
end
|
||||
info(2) = temp'*temp;
|
||||
return
|
||||
end
|
||||
|
||||
info(2) = temp'*temp;
|
||||
return
|
||||
end
|
||||
|
|
|
@ -2,7 +2,7 @@ function [DirectoryName, info] = CheckPath(type,dname)
|
|||
% Creates the subfolder "./M_.dname/type" if it does not exist yet.
|
||||
%
|
||||
% INPUTS
|
||||
% type [string] Name of the subfolder.
|
||||
% type [string] Name of the subfolder.
|
||||
% dname [string] Name of the directory
|
||||
%
|
||||
% OUTPUTS
|
||||
|
|
|
@ -66,7 +66,7 @@ if (TotalNumberOfMhFiles-1)-(FirstMhFile+1)+1 > 0
|
|||
elseif TotalNumberOfMhFiles == 1
|
||||
record.KeepedDraws.Distribution = [];
|
||||
elseif TotalNumberOfMhFiles == 2 && FirstMhFile > 1
|
||||
record.KeepedDraws.Distribution = [MAX_nruns-FirstLine+1 ; record.MhDraws(end,3)];
|
||||
record.KeepedDraws.Distribution = [MAX_nruns-FirstLine+1 ; record.MhDraws(end,3)];
|
||||
end
|
||||
|
||||
% Save updated mh-history file.
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,decomp,trend_addition,state_uncertainty,M_,oo_,options_,bayestopt_] = DsgeSmoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_)
|
||||
% Estimation of the smoothed variables and innovations.
|
||||
%
|
||||
% INPUTS
|
||||
% o xparam1 [double] (p*1) vector of (estimated) parameters.
|
||||
% Estimation of the smoothed variables and innovations.
|
||||
%
|
||||
% INPUTS
|
||||
% o xparam1 [double] (p*1) vector of (estimated) parameters.
|
||||
% o gend [integer] scalar specifying the number of observations ==> varargin{1}.
|
||||
% o data [double] (n*T) matrix of data.
|
||||
% o data_index [cell] 1*smpl cell of column vectors of indices.
|
||||
|
@ -12,7 +12,7 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,de
|
|||
% o options_ [structure] describing the options
|
||||
% o bayestopt_ [structure] describing the priors
|
||||
% o estim_params_ [structure] characterizing parameters to be estimated
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% o alphahat [double] (m*T) matrix, smoothed endogenous variables (a_{t|T}) (decision-rule order)
|
||||
% o etahat [double] (r*T) matrix, smoothed structural shocks (r>=n is the number of shocks).
|
||||
|
@ -29,31 +29,31 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,de
|
|||
% matrices (meaningless for periods 1:d) (decision-rule order)
|
||||
% o decomp (K*m*r*(T+K)) 4D array of shock decomposition of k-step ahead
|
||||
% filtered variables (decision-rule order)
|
||||
% o trend_addition [double] (n*T) pure trend component; stored in options_.varobs order
|
||||
% o trend_addition [double] (n*T) pure trend component; stored in options_.varobs order
|
||||
% o state_uncertainty [double] (K,K,T) array, storing the uncertainty
|
||||
% about the smoothed state (decision-rule order)
|
||||
% o M_ [structure] decribing the model
|
||||
% o oo_ [structure] storing the results
|
||||
% o options_ [structure] describing the options
|
||||
% o bayestopt_ [structure] describing the priors
|
||||
%
|
||||
%
|
||||
% Notes:
|
||||
% m: number of endogenous variables (M_.endo_nbr)
|
||||
% T: number of Time periods (options_.nobs)
|
||||
% r: number of strucural shocks (M_.exo_nbr)
|
||||
% n: number of observables (length(options_.varobs))
|
||||
% K: maximum forecast horizon (max(options_.nk))
|
||||
%
|
||||
%
|
||||
% To get variables that are stored in decision rule order in order of declaration
|
||||
% as in M_.endo_names, ones needs code along the lines of:
|
||||
% variables_declaration_order(dr.order_var,:) = alphahat
|
||||
%
|
||||
% Defines bayestopt_.mf = bayestopt_.smoother_mf (positions of observed variables
|
||||
% and requested smoothed variables in decision rules (decision rule order)) and
|
||||
%
|
||||
% Defines bayestopt_.mf = bayestopt_.smoother_mf (positions of observed variables
|
||||
% and requested smoothed variables in decision rules (decision rule order)) and
|
||||
% passes it back via global variable
|
||||
%
|
||||
% ALGORITHM
|
||||
% Diffuse Kalman filter (Durbin and Koopman)
|
||||
%
|
||||
% ALGORITHM
|
||||
% Diffuse Kalman filter (Durbin and Koopman)
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% None
|
||||
|
@ -97,7 +97,7 @@ end
|
|||
%------------------------------------------------------------------------------
|
||||
% 2. call model setup & reduction program
|
||||
%------------------------------------------------------------------------------
|
||||
oldoo.restrict_var_list = oo_.dr.restrict_var_list;
|
||||
oldoo.restrict_var_list = oo_.dr.restrict_var_list;
|
||||
oldoo.restrict_columns = oo_.dr.restrict_columns;
|
||||
oo_.dr.restrict_var_list = bayestopt_.smoother_var_list;
|
||||
oo_.dr.restrict_columns = bayestopt_.smoother_restrict_columns;
|
||||
|
@ -133,8 +133,8 @@ mf = bayestopt_.mf;
|
|||
% ------------------------------------------------------------------------------
|
||||
% 3. Initial condition of the Kalman filter
|
||||
% ------------------------------------------------------------------------------
|
||||
%
|
||||
% Here, Pinf and Pstar are determined. If the model is stationary, determine
|
||||
%
|
||||
% Here, Pinf and Pstar are determined. If the model is stationary, determine
|
||||
% Pstar as the solution of the Lyapunov equation and set Pinf=[] (Notation follows
|
||||
% Koopman/Durbin (2003), Journal of Time Series Analysis 24(1))
|
||||
%
|
||||
|
@ -169,7 +169,7 @@ elseif options_.lik_init == 3 % Diffuse Kalman filter
|
|||
kalman_algo = 3;
|
||||
else
|
||||
if ~all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
|
||||
%Augment state vector (follows Section 6.4.3 of DK (2012))
|
||||
%Augment state vector (follows Section 6.4.3 of DK (2012))
|
||||
expanded_state_vector_for_univariate_filter=1;
|
||||
T = blkdiag(T,zeros(vobs));
|
||||
np = size(T,1);
|
||||
|
@ -240,32 +240,32 @@ if kalman_algo == 1 || kalman_algo == 3
|
|||
end
|
||||
|
||||
if kalman_algo == 2 || kalman_algo == 4
|
||||
if ~all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
|
||||
if ~expanded_state_vector_for_univariate_filter
|
||||
%Augment state vector (follows Section 6.4.3 of DK (2012))
|
||||
expanded_state_vector_for_univariate_filter=1;
|
||||
Z = [Z, eye(vobs)];
|
||||
ST = blkdiag(ST,zeros(vobs));
|
||||
np = size(ST,1);
|
||||
Q = blkdiag(Q,H);
|
||||
R1 = blkdiag(R,eye(vobs));
|
||||
if kalman_algo == 4
|
||||
%recompute Schur state space transformation with
|
||||
%expanded state space
|
||||
[Pstar,Pinf] = compute_Pinf_Pstar(mf,ST,R1,Q,options_.qz_criterium);
|
||||
else
|
||||
Pstar = blkdiag(Pstar,H);
|
||||
if ~isempty(Pinf)
|
||||
Pinf = blkdiag(Pinf,zeros(vobs));
|
||||
end
|
||||
end
|
||||
%now reset H to 0
|
||||
H = zeros(vobs,vobs);
|
||||
if ~all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
|
||||
if ~expanded_state_vector_for_univariate_filter
|
||||
%Augment state vector (follows Section 6.4.3 of DK (2012))
|
||||
expanded_state_vector_for_univariate_filter=1;
|
||||
Z = [Z, eye(vobs)];
|
||||
ST = blkdiag(ST,zeros(vobs));
|
||||
np = size(ST,1);
|
||||
Q = blkdiag(Q,H);
|
||||
R1 = blkdiag(R,eye(vobs));
|
||||
if kalman_algo == 4
|
||||
%recompute Schur state space transformation with
|
||||
%expanded state space
|
||||
[Pstar,Pinf] = compute_Pinf_Pstar(mf,ST,R1,Q,options_.qz_criterium);
|
||||
else
|
||||
%do nothing, state vector was already expanded
|
||||
Pstar = blkdiag(Pstar,H);
|
||||
if ~isempty(Pinf)
|
||||
Pinf = blkdiag(Pinf,zeros(vobs));
|
||||
end
|
||||
end
|
||||
%now reset H to 0
|
||||
H = zeros(vobs,vobs);
|
||||
else
|
||||
%do nothing, state vector was already expanded
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,decomp,state_uncertainty] = missing_DiffuseKalmanSmootherH3_Z(ST, ...
|
||||
Z,R1,Q,diag(H), ...
|
||||
Pinf,Pstar,data1,vobs,np,smpl,data_index, ...
|
||||
|
@ -282,7 +282,7 @@ if expanded_state_vector_for_univariate_filter && (kalman_algo == 2 || kalman_al
|
|||
ahat = ahat(k,:);
|
||||
aK = aK(:,k,:,:);
|
||||
epsilonhat=etahat(end-vobs+1:end,:);
|
||||
etahat=etahat(1:end-vobs,:);
|
||||
etahat=etahat(1:end-vobs,:);
|
||||
if ~isempty(PK)
|
||||
PK = PK(:,k,k,:);
|
||||
end
|
||||
|
|
|
@ -5,14 +5,14 @@ function Draws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumbe
|
|||
%
|
||||
% INPUTS
|
||||
% column: column
|
||||
% FirstMhFile: first mh file
|
||||
% FirstMhFile: first mh file
|
||||
% FirstLine: first line
|
||||
% TotalNumberOfMhFile: total number of mh file
|
||||
% TotalNumberOfMhFile: total number of mh file
|
||||
% NumberOfDraws: number of draws
|
||||
|
||||
% OUTPUTS
|
||||
% Draws: draws from posterior distribution
|
||||
%
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% none
|
||||
|
||||
|
@ -55,7 +55,7 @@ if nblck>1 && nargin<6
|
|||
iline = 1;
|
||||
end
|
||||
end
|
||||
else
|
||||
else
|
||||
for blck = 1:nblck
|
||||
iline=iline0;
|
||||
for file = FirstMhFile:TotalNumberOfMhFile
|
||||
|
|
|
@ -5,11 +5,11 @@ function [xparams, logpost] = GetOneDraw(type)
|
|||
% INPUTS
|
||||
% type: [string] 'posterior': draw from MCMC draws
|
||||
% 'prior': draw from prior
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% xparams: vector of estimated parameters (drawn from posterior or prior distribution)
|
||||
% logpost: log of the posterior density of this parameter vector
|
||||
%
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% none
|
||||
|
||||
|
|
|
@ -16,38 +16,38 @@ function [mean,variance] = GetPosteriorMeanVariance(M,drop)
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
MetropolisFolder = CheckPath('metropolis',M.dname);
|
||||
FileName = M.fname;
|
||||
BaseName = [MetropolisFolder filesep FileName];
|
||||
load_last_mh_history_file(MetropolisFolder, FileName);
|
||||
NbrDraws = sum(record.MhDraws(:,1));
|
||||
NbrFiles = sum(record.MhDraws(:,2));
|
||||
NbrBlocks = record.Nblck;
|
||||
mean = 0;
|
||||
variance = 0;
|
||||
|
||||
NbrKeptDraws = 0;
|
||||
for i=1:NbrBlocks
|
||||
NbrDrawsCurrentBlock = 0;
|
||||
for j=1:NbrFiles
|
||||
o = load([BaseName '_mh' int2str(j) '_blck' int2str(i),'.mat']);
|
||||
NbrDrawsCurrentFile = size(o.x2,1);
|
||||
if NbrDrawsCurrentBlock + NbrDrawsCurrentFile <= drop*NbrDraws
|
||||
NbrDrawsCurrentBlock = NbrDrawsCurrentBlock + NbrDrawsCurrentFile;
|
||||
continue
|
||||
elseif NbrDrawsCurrentBlock < drop*NbrDraws
|
||||
FirstDraw = ceil(drop*NbrDraws - NbrDrawsCurrentBlock + 1);
|
||||
x2 = o.x2(FirstDraw:end,:);
|
||||
else
|
||||
x2 = o.x2;
|
||||
end
|
||||
NbrKeptDrawsCurrentFile = size(x2,1);
|
||||
%recursively compute mean and variance
|
||||
mean = (NbrKeptDraws*mean + sum(x2)')/(NbrKeptDraws+NbrKeptDrawsCurrentFile);
|
||||
x2Demeaned = bsxfun(@minus,x2,mean');
|
||||
variance = (NbrKeptDraws*variance + x2Demeaned'*x2Demeaned)/(NbrKeptDraws+NbrKeptDrawsCurrentFile);
|
||||
|
||||
MetropolisFolder = CheckPath('metropolis',M.dname);
|
||||
FileName = M.fname;
|
||||
BaseName = [MetropolisFolder filesep FileName];
|
||||
load_last_mh_history_file(MetropolisFolder, FileName);
|
||||
NbrDraws = sum(record.MhDraws(:,1));
|
||||
NbrFiles = sum(record.MhDraws(:,2));
|
||||
NbrBlocks = record.Nblck;
|
||||
mean = 0;
|
||||
variance = 0;
|
||||
|
||||
NbrKeptDraws = 0;
|
||||
for i=1:NbrBlocks
|
||||
NbrDrawsCurrentBlock = 0;
|
||||
for j=1:NbrFiles
|
||||
o = load([BaseName '_mh' int2str(j) '_blck' int2str(i),'.mat']);
|
||||
NbrDrawsCurrentFile = size(o.x2,1);
|
||||
if NbrDrawsCurrentBlock + NbrDrawsCurrentFile <= drop*NbrDraws
|
||||
NbrDrawsCurrentBlock = NbrDrawsCurrentBlock + NbrDrawsCurrentFile;
|
||||
NbrKeptDraws = NbrKeptDraws + NbrKeptDrawsCurrentFile;
|
||||
continue
|
||||
elseif NbrDrawsCurrentBlock < drop*NbrDraws
|
||||
FirstDraw = ceil(drop*NbrDraws - NbrDrawsCurrentBlock + 1);
|
||||
x2 = o.x2(FirstDraw:end,:);
|
||||
else
|
||||
x2 = o.x2;
|
||||
end
|
||||
NbrKeptDrawsCurrentFile = size(x2,1);
|
||||
%recursively compute mean and variance
|
||||
mean = (NbrKeptDraws*mean + sum(x2)')/(NbrKeptDraws+NbrKeptDrawsCurrentFile);
|
||||
x2Demeaned = bsxfun(@minus,x2,mean');
|
||||
variance = (NbrKeptDraws*variance + x2Demeaned'*x2Demeaned)/(NbrKeptDraws+NbrKeptDrawsCurrentFile);
|
||||
NbrDrawsCurrentBlock = NbrDrawsCurrentBlock + NbrDrawsCurrentFile;
|
||||
NbrKeptDraws = NbrKeptDraws + NbrKeptDrawsCurrentFile;
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,17 +1,17 @@
|
|||
function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bayestopt_, oo_, pnames)
|
||||
% This function prints and saves posterior estimates after the mcmc
|
||||
% (+updates of oo_ & TeX output).
|
||||
%
|
||||
% INPUTS
|
||||
% estim_params_ [structure]
|
||||
% (+updates of oo_ & TeX output).
|
||||
%
|
||||
% INPUTS
|
||||
% estim_params_ [structure]
|
||||
% M_ [structure]
|
||||
% options_ [structure]
|
||||
% bayestopt_ [structure]
|
||||
% oo_ [structure]
|
||||
% pnames [char] Array of char, names of the prior shapes available
|
||||
%
|
||||
% OUTPUTS
|
||||
% oo_ [structure]
|
||||
%
|
||||
% OUTPUTS
|
||||
% oo_ [structure]
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% None.
|
||||
|
@ -34,7 +34,7 @@ function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bay
|
|||
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
%if ~options_.mh_replic && options_.load_mh_file
|
||||
% load([M_.fname '_results.mat'],'oo_');
|
||||
% load([M_.fname '_results.mat'],'oo_');
|
||||
%end
|
||||
|
||||
TeX = options_.TeX;
|
||||
|
@ -48,7 +48,7 @@ nx = nvx+nvn+ncx+ncn+np;
|
|||
|
||||
MetropolisFolder = CheckPath('metropolis',M_.dname);
|
||||
OutputFolder = CheckPath('Output',M_.dname);
|
||||
FileName = M_.fname;
|
||||
FileName = M_.fname;
|
||||
|
||||
load_last_mh_history_file(MetropolisFolder,FileName);
|
||||
|
||||
|
@ -108,14 +108,14 @@ if np
|
|||
[post_mean, post_median, post_var, hpd_interval, post_deciles, ...
|
||||
density] = posterior_moments(Draws,1,options_.mh_conf_sig);
|
||||
name = bayestopt_.name{ip};
|
||||
oo_ = Filloo(oo_,name,type,post_mean,hpd_interval,post_median,post_var,post_deciles,density);
|
||||
oo_ = Filloo(oo_,name,type,post_mean,hpd_interval,post_median,post_var,post_deciles,density);
|
||||
end
|
||||
end
|
||||
disp(sprintf(pformat,header_width,name,bayestopt_.p1(ip),...
|
||||
post_mean, ...
|
||||
hpd_interval, ...
|
||||
pnames(bayestopt_.pshape(ip)+1,:), ...
|
||||
bayestopt_.p2(ip)));
|
||||
bayestopt_.p2(ip)));
|
||||
if TeX
|
||||
k = estim_params_.param_vals(i,1);
|
||||
name = deblank(M_.param_names_tex(k,:));
|
||||
|
@ -171,7 +171,7 @@ if nvx
|
|||
ip = ip+1;
|
||||
end
|
||||
if TeX
|
||||
TeXEnd(fid,2,'standard deviation of structural shocks');
|
||||
TeXEnd(fid,2,'standard deviation of structural shocks');
|
||||
end
|
||||
end
|
||||
if nvn
|
||||
|
@ -213,7 +213,7 @@ if nvn
|
|||
ip = ip+1;
|
||||
end
|
||||
if TeX
|
||||
TeXEnd(fid,3,'standard deviation of measurement errors');
|
||||
TeXEnd(fid,3,'standard deviation of measurement errors');
|
||||
end
|
||||
end
|
||||
if ncx
|
||||
|
@ -314,12 +314,12 @@ if ncn
|
|||
if TeX
|
||||
name = ['(',deblank(M_.endo_names_tex(k1,:)) ',' deblank(M_.endo_names_tex(k2,:)),')'];
|
||||
TeXCore(fid,name,deblank(pnames(bayestopt_.pshape(ip)+1,:)),bayestopt_.p1(ip),...
|
||||
bayestopt_.p2(ip),post_mean,sqrt(post_var),hpd_interval);
|
||||
bayestopt_.p2(ip),post_mean,sqrt(post_var),hpd_interval);
|
||||
end
|
||||
ip = ip+1;
|
||||
end
|
||||
if TeX
|
||||
TeXEnd(fid,5,'correlation of measurement errors');
|
||||
TeXEnd(fid,5,'correlation of measurement errors');
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -359,7 +359,7 @@ fid = fidTeX;
|
|||
|
||||
|
||||
function TeXCore(fid,name,shape,priormean,priorstd,postmean,poststd,hpd)
|
||||
fprintf(fid,['$%s$ & %s & %7.3f & %6.4f & %7.3f& %6.4f & %7.4f & %7.4f \\\\ \n'],...
|
||||
fprintf(fid,['$%s$ & %s & %7.3f & %6.4f & %7.3f& %6.4f & %7.4f & %7.4f \\\\ \n'],...
|
||||
name,...
|
||||
shape,...
|
||||
priormean,...
|
||||
|
@ -371,7 +371,7 @@ fprintf(fid,['$%s$ & %s & %7.3f & %6.4f & %7.3f& %6.4f & %7.4f & %7.4f \\\\ \n']
|
|||
|
||||
|
||||
function TeXEnd(fid,fnum,title)
|
||||
fprintf(fid,'\\end{longtable}\n ');
|
||||
fprintf(fid,'\\end{longtable}\n ');
|
||||
fprintf(fid,'\\end{center}\n');
|
||||
fprintf(fid,'%% End of TeX file.\n');
|
||||
fclose(fid);
|
||||
|
|
|
@ -19,11 +19,11 @@ function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info)
|
|||
|
||||
global M_ options_
|
||||
|
||||
FigHandle = figure('Name',FigureProperties.Name);
|
||||
FigHandle = figure('Name',FigureProperties.Name);
|
||||
|
||||
NAMES = cell(NumberOfPlots,1);
|
||||
if options_.TeX
|
||||
TeXNAMES = cell(NumberOfPlots,1);
|
||||
TeXNAMES = cell(NumberOfPlots,1);
|
||||
end
|
||||
|
||||
if NumberOfPlots == 9
|
||||
|
@ -53,7 +53,7 @@ elseif NumberOfPlots == 2
|
|||
elseif NumberOfPlots == 1
|
||||
nr = 1;
|
||||
nc = 1;
|
||||
end
|
||||
end
|
||||
|
||||
for plt = 1:NumberOfPlots
|
||||
eval(['NumberOfCurves = Info.Box' int2str(plt) '.Number;'])
|
||||
|
@ -138,7 +138,7 @@ for plt = 1:NumberOfPlots
|
|||
set(hh,'Color','r','LineStyle','-','LineWidth',2)
|
||||
%
|
||||
%
|
||||
end
|
||||
end
|
||||
end
|
||||
axis([xmin xmax ymin ymax])
|
||||
title(NAMES{plt})
|
||||
|
@ -150,14 +150,14 @@ if Info.SaveFormat.Eps
|
|||
if isempty(Info.SaveFormat.Name)
|
||||
eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.eps']);
|
||||
else
|
||||
eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.eps']);
|
||||
eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.eps']);
|
||||
end
|
||||
end
|
||||
if Info.SaveFormat.Pdf && ~isoctave
|
||||
if isempty(Info.SaveFormat.Name)
|
||||
eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number)]);
|
||||
else
|
||||
eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name]);
|
||||
eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name]);
|
||||
end
|
||||
end
|
||||
if Info.SaveFormat.Fig && ~isoctave
|
||||
|
|
|
@ -4,15 +4,15 @@ function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt
|
|||
% plots posterior distributions
|
||||
%
|
||||
% INPUTS
|
||||
% estim_params_ [structure]
|
||||
% estim_params_ [structure]
|
||||
% M_ [structure]
|
||||
% options_ [structure]
|
||||
% options_ [structure]
|
||||
% bayestopt_ [structure]
|
||||
% oo_ [structure]
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% oo_ [structure]
|
||||
%
|
||||
% oo_ [structure]
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% none
|
||||
|
||||
|
@ -49,7 +49,7 @@ nn = sqrt(MaxNumberOfPlotPerFigure);
|
|||
|
||||
figurename = 'Priors and posteriors';
|
||||
|
||||
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
||||
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
||||
fidTeX = fopen([OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors.tex'],'w');
|
||||
fprintf(fidTeX,'%% TeX eps-loader file generated by PlotPosteriorDistributions.m (Dynare).\n');
|
||||
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
|
||||
|
@ -78,9 +78,9 @@ for i=1:npar
|
|||
end
|
||||
end
|
||||
[x2,f2,abscissa,dens,binf2,bsup2] = draw_prior_density(i,bayestopt_);
|
||||
top2 = max(f2);
|
||||
top2 = max(f2);
|
||||
if i <= nvx
|
||||
name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:));
|
||||
name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:));
|
||||
x1 = oo_.posterior_density.shocks_std.(name)(:,1);
|
||||
f1 = oo_.posterior_density.shocks_std.(name)(:,2);
|
||||
oo_.prior_density.shocks_std.(name)(:,1) = x2;
|
||||
|
@ -96,18 +96,18 @@ for i=1:npar
|
|||
oo_.prior_density.measurement_errors_std.(name)(:,2) = f2;
|
||||
if ~options_.mh_posterior_mode_estimation
|
||||
pmod = oo_.posterior_mode.measurement_errors_std.(name);
|
||||
end
|
||||
end
|
||||
elseif i <= nvx+nvn+ncx
|
||||
j = i - (nvx+nvn);
|
||||
k1 = estim_params_.corrx(j,1);
|
||||
k2 = estim_params_.corrx(j,2);
|
||||
name = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))];
|
||||
name = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))];
|
||||
x1 = oo_.posterior_density.shocks_corr.(name)(:,1);
|
||||
f1 = oo_.posterior_density.shocks_corr.(name)(:,2);
|
||||
oo_.prior_density.shocks_corr.(name)(:,1) = x2;
|
||||
oo_.prior_density.shocks_corr.(name)(:,2) = f2;
|
||||
if ~options_.mh_posterior_mode_estimation
|
||||
pmod = oo_.posterior_mode.shocks_corr.(name);
|
||||
pmod = oo_.posterior_mode.shocks_corr.(name);
|
||||
end
|
||||
elseif i <= nvx+nvn+ncx+ncn
|
||||
j = i - (nvx+nvn+ncx);
|
||||
|
@ -157,7 +157,7 @@ for i=1:npar
|
|||
fprintf(fidTeX,'\\begin{figure}[H]\n');
|
||||
for j = 1:size(NAMES,1)
|
||||
fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(j,:)),deblank(TeXNAMES(j,:)));
|
||||
end
|
||||
end
|
||||
fprintf(fidTeX,'\\centering\n');
|
||||
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s/%s_PriorsAndPosteriors%s}\n',options_.figures.textwidth*min(subplotnum/nn,1),OutputDirectoryName,M_.fname,int2str(figunumber));
|
||||
fprintf(fidTeX,'\\caption{Priors and posteriors.}');
|
||||
|
|
|
@ -368,101 +368,101 @@ end
|
|||
% PosteriorIRF_core2.m function.
|
||||
|
||||
if ~options_.nograph && ~options_.no_graph.posterior
|
||||
% Save the local variables.
|
||||
localVars=[];
|
||||
% Save the local variables.
|
||||
localVars=[];
|
||||
|
||||
Check=options_.TeX;
|
||||
if (Check)
|
||||
localVars.varlist_TeX=varlist_TeX;
|
||||
end
|
||||
|
||||
|
||||
localVars.nvar=nvar;
|
||||
localVars.MeanIRF=MeanIRF;
|
||||
localVars.tit=tit;
|
||||
localVars.nn=nn;
|
||||
localVars.MAX_nirfs_dsgevar=MAX_nirfs_dsgevar;
|
||||
localVars.HPDIRF=HPDIRF;
|
||||
localVars.varlist=varlist;
|
||||
localVars.MaxNumberOfPlotPerFigure=MaxNumberOfPlotPerFigure;
|
||||
if options_.dsge_var
|
||||
localVars.HPDIRFdsgevar=HPDIRFdsgevar;
|
||||
localVars.MeanIRFdsgevar = MeanIRFdsgevar;
|
||||
end
|
||||
|
||||
% The files .TeX are genereted in sequential way always!
|
||||
|
||||
% The files .TeX are generated in sequential way always!
|
||||
subplotnum = 0;
|
||||
tit_TeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex;
|
||||
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
||||
fidTeX = fopen([DirectoryName filesep M_.fname '_BayesianIRF.tex'],'w');
|
||||
fprintf(fidTeX,'%% TeX eps-loader file generated by PosteriorIRF.m (Dynare).\n');
|
||||
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
|
||||
fprintf(fidTeX,' \n');
|
||||
titTeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex;
|
||||
|
||||
for ii=irf_shocks_indx
|
||||
figunumber = 0;
|
||||
|
||||
for jj=1:nvar
|
||||
if max(abs(MeanIRF(:,jj,ii))) >= options_.impulse_responses.plot_threshold
|
||||
subplotnum = subplotnum+1;
|
||||
|
||||
if subplotnum == 1
|
||||
fprintf(fidTeX,'\\begin{figure}[H]\n');
|
||||
end
|
||||
name = deblank(varlist(jj,:));
|
||||
texname = deblank(varlist_TeX(jj,:));
|
||||
fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],name,['$' texname '$']);
|
||||
end
|
||||
if subplotnum == MaxNumberOfPlotPerFigure || (jj == nvar && subplotnum> 0)
|
||||
figunumber = figunumber+1;
|
||||
|
||||
fprintf(fidTeX,'\\centering \n');
|
||||
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s/%s_Bayesian_IRF_%s_%d}\n',options_.figures.textwidth*min(subplotnum/nn,1),DirectoryName,M_.fname,deblank(tit(ii,:)),figunumber);
|
||||
if options_.relative_irf
|
||||
fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']);
|
||||
else
|
||||
fprintf(fidTeX,'\\caption{Bayesian IRF: Orthogonalized shock to $%s$.}\n',deblank(tit_TeX(ii,:)));
|
||||
end
|
||||
fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%d}\n',deblank(tit(ii,:)),figunumber);
|
||||
fprintf(fidTeX,'\\end{figure}\n');
|
||||
fprintf(fidTeX,' \n');
|
||||
|
||||
subplotnum = 0;
|
||||
end
|
||||
end
|
||||
Check=options_.TeX;
|
||||
if (Check)
|
||||
localVars.varlist_TeX=varlist_TeX;
|
||||
end
|
||||
fprintf(fidTeX,'%% End of TeX file.\n');
|
||||
fclose(fidTeX);
|
||||
end
|
||||
|
||||
% The others file format are generated in parallel by PosteriorIRF_core2!
|
||||
|
||||
|
||||
% Comment for testing!
|
||||
if ~isoctave
|
||||
if isnumeric(options_.parallel) || (M_.exo_nbr*ceil(size(varlist,1)/MaxNumberOfPlotPerFigure))<8
|
||||
[fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0);
|
||||
else
|
||||
isRemoteOctave = 0;
|
||||
for indPC=1:length(options_.parallel)
|
||||
isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave'));
|
||||
localVars.nvar=nvar;
|
||||
localVars.MeanIRF=MeanIRF;
|
||||
localVars.tit=tit;
|
||||
localVars.nn=nn;
|
||||
localVars.MAX_nirfs_dsgevar=MAX_nirfs_dsgevar;
|
||||
localVars.HPDIRF=HPDIRF;
|
||||
localVars.varlist=varlist;
|
||||
localVars.MaxNumberOfPlotPerFigure=MaxNumberOfPlotPerFigure;
|
||||
if options_.dsge_var
|
||||
localVars.HPDIRFdsgevar=HPDIRFdsgevar;
|
||||
localVars.MeanIRFdsgevar = MeanIRFdsgevar;
|
||||
end
|
||||
|
||||
% The files .TeX are genereted in sequential way always!
|
||||
|
||||
% The files .TeX are generated in sequential way always!
|
||||
subplotnum = 0;
|
||||
tit_TeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex;
|
||||
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
||||
fidTeX = fopen([DirectoryName filesep M_.fname '_BayesianIRF.tex'],'w');
|
||||
fprintf(fidTeX,'%% TeX eps-loader file generated by PosteriorIRF.m (Dynare).\n');
|
||||
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
|
||||
fprintf(fidTeX,' \n');
|
||||
titTeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex;
|
||||
|
||||
for ii=irf_shocks_indx
|
||||
figunumber = 0;
|
||||
|
||||
for jj=1:nvar
|
||||
if max(abs(MeanIRF(:,jj,ii))) >= options_.impulse_responses.plot_threshold
|
||||
subplotnum = subplotnum+1;
|
||||
|
||||
if subplotnum == 1
|
||||
fprintf(fidTeX,'\\begin{figure}[H]\n');
|
||||
end
|
||||
name = deblank(varlist(jj,:));
|
||||
texname = deblank(varlist_TeX(jj,:));
|
||||
fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],name,['$' texname '$']);
|
||||
end
|
||||
if subplotnum == MaxNumberOfPlotPerFigure || (jj == nvar && subplotnum> 0)
|
||||
figunumber = figunumber+1;
|
||||
|
||||
fprintf(fidTeX,'\\centering \n');
|
||||
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s/%s_Bayesian_IRF_%s_%d}\n',options_.figures.textwidth*min(subplotnum/nn,1),DirectoryName,M_.fname,deblank(tit(ii,:)),figunumber);
|
||||
if options_.relative_irf
|
||||
fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']);
|
||||
else
|
||||
fprintf(fidTeX,'\\caption{Bayesian IRF: Orthogonalized shock to $%s$.}\n',deblank(tit_TeX(ii,:)));
|
||||
end
|
||||
fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%d}\n',deblank(tit(ii,:)),figunumber);
|
||||
fprintf(fidTeX,'\\end{figure}\n');
|
||||
fprintf(fidTeX,' \n');
|
||||
|
||||
subplotnum = 0;
|
||||
end
|
||||
end
|
||||
end
|
||||
if isRemoteOctave
|
||||
fprintf(fidTeX,'%% End of TeX file.\n');
|
||||
fclose(fidTeX);
|
||||
end
|
||||
|
||||
% The others file format are generated in parallel by PosteriorIRF_core2!
|
||||
|
||||
|
||||
% Comment for testing!
|
||||
if ~isoctave
|
||||
if isnumeric(options_.parallel) || (M_.exo_nbr*ceil(size(varlist,1)/MaxNumberOfPlotPerFigure))<8
|
||||
[fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0);
|
||||
else
|
||||
globalVars = struct('M_',M_, ...
|
||||
'options_', options_);
|
||||
isRemoteOctave = 0;
|
||||
for indPC=1:length(options_.parallel)
|
||||
isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave'));
|
||||
end
|
||||
if isRemoteOctave
|
||||
[fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0);
|
||||
else
|
||||
globalVars = struct('M_',M_, ...
|
||||
'options_', options_);
|
||||
|
||||
[fout] = masterParallel(options_.parallel, 1, M_.exo_nbr,NamFileInput,'PosteriorIRF_core2', localVars, globalVars, options_.parallel_info);
|
||||
[fout] = masterParallel(options_.parallel, 1, M_.exo_nbr,NamFileInput,'PosteriorIRF_core2', localVars, globalVars, options_.parallel_info);
|
||||
end
|
||||
end
|
||||
else
|
||||
[fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0);
|
||||
end
|
||||
else
|
||||
[fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0);
|
||||
end
|
||||
% END parallel code!
|
||||
% END parallel code!
|
||||
|
||||
end
|
||||
|
||||
|
|
|
@ -2,10 +2,10 @@ function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam,ThisMatlab)
|
|||
% function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam, ThisMatlab)
|
||||
% Generates the Posterior IRFs plot from the IRFs generated in
|
||||
% PosteriorIRF_core1
|
||||
%
|
||||
%
|
||||
% PARALLEL CONTEXT
|
||||
% Performs in parallel execution a portion of the PosteriorIRF.m code.
|
||||
% For more information, see the comment in posterior_sampler_core.m
|
||||
% For more information, see the comment in posterior_sampler_core.m
|
||||
% function.
|
||||
%
|
||||
% INPUTS
|
||||
|
@ -135,7 +135,7 @@ for i=fpar:npar
|
|||
plot(1:options_.irf,HPDIRFdsgevar(:,1,j,i),'--k','linewidth',1)
|
||||
plot(1:options_.irf,HPDIRFdsgevar(:,2,j,i),'--k','linewidth',1)
|
||||
end
|
||||
% plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
|
||||
% plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
|
||||
box on
|
||||
axis tight
|
||||
xlim([1 options_.irf]);
|
||||
|
@ -162,7 +162,7 @@ for i=fpar:npar
|
|||
if whoiam
|
||||
fprintf('Done! \n');
|
||||
waitbarString = [ 'Exog. shocks ' int2str(i) '/' int2str(npar) ' done.'];
|
||||
% fMessageStatus((i-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
|
||||
% fMessageStatus((i-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
|
||||
dyn_waitbar((i-fpar+1)/(npar-fpar+1),[],waitbarString);
|
||||
end
|
||||
end% loop over exo_var
|
||||
|
|
|
@ -18,9 +18,9 @@ function ReshapeMatFiles(type, type2)
|
|||
% posterior
|
||||
% gsa
|
||||
% prior
|
||||
%
|
||||
%
|
||||
% OUTPUTS:
|
||||
% none
|
||||
% none
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% none
|
||||
|
@ -61,17 +61,17 @@ else
|
|||
end
|
||||
else
|
||||
MhDirectoryName = [CheckPath('prior',M_.dname) filesep ];
|
||||
end
|
||||
end
|
||||
end
|
||||
switch type
|
||||
case 'irf_dsge'
|
||||
CAPtype = 'IRF_DSGE';
|
||||
TYPEsize = [ options_.irf , size(options_.varlist,1) , M_.exo_nbr ];
|
||||
TYPEarray = 4;
|
||||
TYPEarray = 4;
|
||||
case 'irf_bvardsge'
|
||||
CAPtype = 'IRF_BVARDSGE';
|
||||
TYPEsize = [ options_.irf , length(options_.varobs) , M_.exo_nbr ];
|
||||
TYPEarray = 4;
|
||||
TYPEarray = 4;
|
||||
case 'smooth'
|
||||
CAPtype = 'SMOOTH';
|
||||
TYPEsize = [ M_.endo_nbr , options_.nobs ];
|
||||
|
@ -134,7 +134,7 @@ switch TYPEarray
|
|||
eval(['idx = idx + size(stock_' type ',4);'])
|
||||
end
|
||||
%eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);'])
|
||||
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles-foffset+1) '.mat'],['STOCK_' CAPtype]);
|
||||
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles-foffset+1) '.mat'],['STOCK_' CAPtype]);
|
||||
end
|
||||
else
|
||||
load([MhDirectoryName M_.fname '_' type '1.mat']);
|
||||
|
@ -176,7 +176,7 @@ switch TYPEarray
|
|||
load([MhDirectoryName M_.fname '_' type '1.mat']);
|
||||
%eval(['STOCK_' CAPtype ' = sort(stock_' type ',3);'])
|
||||
eval(['STOCK_' CAPtype ' = stock_' type ';'])
|
||||
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]);
|
||||
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]);
|
||||
end
|
||||
% Original file format may be useful in some cases...
|
||||
% for file = 1:NumberOfTYPEfiles
|
||||
|
|
|
@ -3,15 +3,15 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff] = TaRB_optimiz
|
|||
% Wrapper function for target function used in TaRB algorithm; reassembles
|
||||
% full parameter vector before calling target function
|
||||
%
|
||||
% INPUTS
|
||||
% o optpar [double] (p_opt*1) vector of subset of parameters to be considered
|
||||
% o par_vector [double] (p*1) full vector of parameters
|
||||
% INPUTS
|
||||
% o optpar [double] (p_opt*1) vector of subset of parameters to be considered
|
||||
% o par_vector [double] (p*1) full vector of parameters
|
||||
% o parameterindices [double] (p_opt*1) index of optpar entries in
|
||||
% par_vector
|
||||
% o TargetFun [char] string specifying the name of the objective
|
||||
% function (posterior kernel).
|
||||
% o varargin [structure] other inputs of target function
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% o fval [scalar] value of (minus) the likelihood.
|
||||
% o info [double] (p*2) error code vector
|
||||
|
@ -20,7 +20,7 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff] = TaRB_optimiz
|
|||
% o Hess [double] (p*p) asymptotic Hessian matrix.
|
||||
% o SteadyState [double] Vector of doubles, steady state level for the endogenous variables.
|
||||
% o trend_coeff [double] Matrix of doubles, coefficients of the deterministic trend in the measurement equation
|
||||
%
|
||||
%
|
||||
% Copyright (C) 2015-16 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -40,4 +40,3 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff] = TaRB_optimiz
|
|||
|
||||
par_vector(parameterindices,:)=optpar; %reassemble parameter
|
||||
[fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff] = feval(TargetFun,par_vector,varargin{:}); %call target function
|
||||
|
||||
|
|
|
@ -2,15 +2,15 @@ function [] = Tracing()
|
|||
% DESCRIPTION
|
||||
% This function is used to test the correct execution of a matlab section
|
||||
% on remote machine.
|
||||
%
|
||||
%
|
||||
% If no error happen the function simply create a file.
|
||||
%
|
||||
% INPUTS
|
||||
% ...
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% ...
|
||||
%
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% none
|
||||
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
function [oo_] = UnivariateSpectralDensity(M_,oo_,options_,var_list)
|
||||
% This function computes the theoretical spectral density of each
|
||||
% endogenous variable declared in var_list. Results are stored in
|
||||
% oo_.SpectralDensity and may be plotted. Plots are saved into the
|
||||
% graphs-folder.
|
||||
%
|
||||
% endogenous variable declared in var_list. Results are stored in
|
||||
% oo_.SpectralDensity and may be plotted. Plots are saved into the
|
||||
% graphs-folder.
|
||||
%
|
||||
% INPUTS
|
||||
% M_ [structure] Dynare's model structure
|
||||
% oo_ [structure] Dynare's results structure
|
||||
% options_ [structure] Dynare's options structure
|
||||
% var_list [integer] Vector of indices for a subset of variables.
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% oo_ [structure] Dynare's results structure,
|
||||
% containing the subfield
|
||||
|
@ -17,7 +17,7 @@ function [oo_] = UnivariateSpectralDensity(M_,oo_,options_,var_list)
|
|||
% and density, which are of size nvar*ngrid.
|
||||
%
|
||||
|
||||
% Adapted from th_autocovariances.m.
|
||||
% Adapted from th_autocovariances.m.
|
||||
|
||||
% Copyright (C) 2006-2017 Dynare Team
|
||||
%
|
||||
|
@ -38,7 +38,7 @@ function [oo_] = UnivariateSpectralDensity(M_,oo_,options_,var_list)
|
|||
|
||||
|
||||
if options_.order > 1
|
||||
disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density')
|
||||
disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density')
|
||||
disp('with a second order approximation of the DSGE model!')
|
||||
disp('Please set order = 1. I abort')
|
||||
return
|
||||
|
@ -102,7 +102,7 @@ if ~isempty(u)
|
|||
ivar = oo_.dr.order_var(iky);
|
||||
end
|
||||
|
||||
iky = iv(ivar);
|
||||
iky = iv(ivar);
|
||||
aa = ghx(iky,:);
|
||||
bb = ghu(iky,:);
|
||||
ngrid = options_.hp_ngrid; %number of grid points
|
||||
|
@ -112,7 +112,7 @@ tneg = exp(-sqrt(-1)*freqs); %negative frequencies
|
|||
if options_.one_sided_hp_filter
|
||||
error('UnivariateSpectralDensity:: spectral density estimate not available with one-sided HP filter')
|
||||
elseif options_.hp_filter == 0 && ~options_.bandpass.indicator %do not filter
|
||||
filter_gain=ones(ngrid,1);
|
||||
filter_gain=ones(ngrid,1);
|
||||
elseif ~(options_.hp_filter == 0 && ~options_.bandpass.indicator) && options_.bandpass.indicator %filter with bandpass
|
||||
filter_gain = zeros(1,ngrid);
|
||||
lowest_periodicity=options_.bandpass.passband(2);
|
||||
|
@ -122,7 +122,7 @@ elseif ~(options_.hp_filter == 0 && ~options_.bandpass.indicator) && options_.ba
|
|||
filter_gain(freqs<=-2*pi/lowest_periodicity+2*pi & freqs>=-2*pi/highest_periodicity+2*pi)=1;
|
||||
elseif ~(options_.hp_filter == 0 && ~options_.bandpass.indicator) && ~options_.bandpass.indicator %filter with HP-filter
|
||||
lambda = options_.hp_filter;
|
||||
filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2);
|
||||
filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2);
|
||||
end
|
||||
|
||||
mathp_col = NaN(ngrid,length(ivar)^2);
|
||||
|
@ -139,7 +139,7 @@ end
|
|||
f = zeros(nvar,ngrid);
|
||||
for i=1:nvar
|
||||
f(i,:) = real(mathp_col(:,(i-1)*nvar+i)); %read out spectral density
|
||||
end
|
||||
end
|
||||
|
||||
oo_.SpectralDensity.freqs=freqs;
|
||||
oo_.SpectralDensity.density=f;
|
||||
|
@ -164,7 +164,7 @@ if options_.nograph == 0
|
|||
xlabel('0 \leq \omega \leq \pi')
|
||||
ylabel('f(\omega)')
|
||||
box on
|
||||
axis tight
|
||||
axis tight
|
||||
dyn_saveas(hh,[M_.fname ,filesep,'graphs', filesep, 'SpectralDensity_' deblank(M_.endo_names(ivar(i),:))],options_.nodisplay,options_.graph_format)
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
function WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions,opts_decomp)
|
||||
%function WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions)
|
||||
% Saves the results from the shock_decomposition command to xls
|
||||
%
|
||||
%
|
||||
% Inputs
|
||||
% z [n_var*(nshock+2)*nperiods] shock decomposition array, see shock_decomposition.m for details
|
||||
% shock_names [endo_nbr*string length] shock names from M_.exo_names
|
||||
|
@ -48,8 +48,8 @@ if nargin==8
|
|||
end
|
||||
if isfield(opts_decomp,'fig_mode') && ~isempty(opts_decomp.fig_mode)
|
||||
fig_mode = opts_decomp.fig_mode;
|
||||
fig_mode1 = ['_' fig_mode];
|
||||
fig_mode = [fig_mode '_'];
|
||||
fig_mode1 = ['_' fig_mode];
|
||||
fig_mode = [fig_mode '_'];
|
||||
end
|
||||
if isfield(opts_decomp,'screen_shocks')
|
||||
if use_shock_groups
|
||||
|
@ -60,15 +60,15 @@ if nargin==8
|
|||
end
|
||||
if isfield(opts_decomp,'fig_name')
|
||||
fig_name = opts_decomp.fig_name;
|
||||
% fig_name = ['_' fig_name];
|
||||
fig_name1 = [fig_name];
|
||||
fig_name = [fig_name '_'];
|
||||
% fig_name = ['_' fig_name];
|
||||
fig_name1 = [fig_name];
|
||||
fig_name = [fig_name '_'];
|
||||
end
|
||||
if screen_shocks
|
||||
fig_name1 = [fig_name1 '_screen'];
|
||||
fig_name = [fig_name 'screen_'];
|
||||
fig_name1 = [fig_name1 '_screen'];
|
||||
fig_name = [fig_name 'screen_'];
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
gend = size(z,3);
|
||||
|
@ -99,7 +99,7 @@ for j=1:nvar
|
|||
z1 = [z1(isort(1:16),:); zres; z1(comp_nbr0:end,:)];
|
||||
comp_nbr=18;
|
||||
end
|
||||
|
||||
|
||||
d0(1,:)=[{'Decomposition'} cellstr(labels(1:comp_nbr,:))' {'Smoot Var'}];
|
||||
d0=[d0; num2cell([x' z1'])];
|
||||
LastRow=size(d0,1);
|
||||
|
@ -112,7 +112,7 @@ for j=1:nvar
|
|||
d0(LastRow+2+ic,2:1+length(group_members))=group_members;
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
warning off
|
||||
if ~ismac
|
||||
[STATUS,MESSAGE] = xlswrite([DynareModel.fname,'_shock_decomposition',fig_mode,fig_name1],d0,deblank(endo_names(i_var(j),:)));
|
||||
|
@ -122,6 +122,5 @@ for j=1:nvar
|
|||
warning on
|
||||
|
||||
clear d0
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
function title=add_filter_subtitle(title,options_)
|
||||
|
||||
if ~options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpass.indicator %do not filter
|
||||
%nothing to add here
|
||||
%nothing to add here
|
||||
elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && options_.bandpass.indicator
|
||||
title = [title ' (Bandpass filter, (' ...
|
||||
num2str(options_.bandpass.passband(1)),' ',num2str(options_.bandpass.passband(2)), '))'];
|
||||
|
@ -10,6 +10,6 @@ elseif options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpas
|
|||
num2str(options_.hp_filter) ')'];
|
||||
elseif ~options_.hp_filter && options_.one_sided_hp_filter && ~options_.bandpass.indicator
|
||||
title = [title ' (One-sided HP filter, lambda = ' ...
|
||||
num2str(options_.one_sided_hp_filter) ')'];
|
||||
num2str(options_.one_sided_hp_filter) ')'];
|
||||
end
|
||||
end
|
|
@ -1,5 +1,5 @@
|
|||
function mexpath = add_path_to_mex_files(dynareroot, modifypath)
|
||||
|
||||
|
||||
% Copyright (C) 2015-2017 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -20,7 +20,7 @@ function mexpath = add_path_to_mex_files(dynareroot, modifypath)
|
|||
if nargin<2
|
||||
modifypath = true;
|
||||
end
|
||||
|
||||
|
||||
if exist('OCTAVE_VERSION')
|
||||
if ispc() && strcmpi(computer(), 'i686-w64-mingw32')
|
||||
mexpath = {[dynareroot '../mex/octave32/']};
|
||||
|
|
|
@ -1,28 +1,28 @@
|
|||
function [z, endo_names, endo_names_tex, steady_state, i_var, oo_] = annualized_shock_decomposition(oo_, M_, options_, i_var, t0, t1, realtime_, vintage_, steady_state, q2a, cumfix)
|
||||
% function oo_ = annualized_shock_decomposition(oo_,t0,options_.nobs);
|
||||
% Computes annualized shocks contribution to a simulated trajectory. The fields set are
|
||||
% oo_.annualized_shock_decomposition, oo_.annualized_realtime_shock_decomposition,
|
||||
% oo_.annualized_realtime_conditional_shock_decomposition and oo_.annualized_realtime_forecast_shock_decomposition.
|
||||
% oo_.annualized_shock_decomposition, oo_.annualized_realtime_shock_decomposition,
|
||||
% oo_.annualized_realtime_conditional_shock_decomposition and oo_.annualized_realtime_forecast_shock_decomposition.
|
||||
% Subfields are arrays n_var by nshock+2 by nperiods. The
|
||||
% first nshock columns store the respective shock contributions, column n+1
|
||||
% stores the role of the initial conditions, while column n+2 stores the
|
||||
% value of the smoothed variables. Both the variables and shocks are stored
|
||||
% value of the smoothed variables. Both the variables and shocks are stored
|
||||
% in the order of endo_names and M_.exo_names, respectively.
|
||||
%
|
||||
% INPUTS
|
||||
% oo_: [structure] Storage of results
|
||||
% M_: [structure] Storage of model
|
||||
% opts: [structure] options for shock decomp
|
||||
% opts: [structure] options for shock decomp
|
||||
% i_var: [array] index of vars
|
||||
% t0: [integer] first period
|
||||
% t1: [integer] last period
|
||||
% realtime_: [integer]
|
||||
% realtime_: [integer]
|
||||
% vintage_: [integer]
|
||||
% steady_state: [array] steady state value of quarterly (log-) level vars
|
||||
% q2a: [structure] info on q2a
|
||||
%
|
||||
% OUTPUTS
|
||||
% z: [matrix] shock decomp to plot
|
||||
% z: [matrix] shock decomp to plot
|
||||
% endo_names: [char] updated var names
|
||||
% endo_names_tex: [char] updated TeX var names
|
||||
% steady_state: [array] updated stady state of vars
|
||||
|
@ -57,13 +57,13 @@ islog = q2a.islog;
|
|||
aux = q2a.aux;
|
||||
aux0 = aux;
|
||||
cumfix = q2a.cumfix;
|
||||
% usual shock decomp
|
||||
% usual shock decomp
|
||||
if isstruct(oo_)
|
||||
% z = oo_.shock_decomposition;
|
||||
myopts=options_;
|
||||
myopts.plot_shock_decomp.type='qoq';
|
||||
myopts.plot_shock_decomp.realtime=0;
|
||||
[z, junk] = plot_shock_decomposition(M_,oo_,myopts,[]);
|
||||
% z = oo_.shock_decomposition;
|
||||
myopts=options_;
|
||||
myopts.plot_shock_decomp.type='qoq';
|
||||
myopts.plot_shock_decomp.realtime=0;
|
||||
[z, junk] = plot_shock_decomposition(M_,oo_,myopts,[]);
|
||||
else
|
||||
z = oo_;
|
||||
end
|
||||
|
@ -177,147 +177,147 @@ end
|
|||
|
||||
% realtime
|
||||
if realtime_ && isstruct(oo_) && isfield(oo_, 'realtime_shock_decomposition')
|
||||
init=1;
|
||||
for i=t0:4:t1
|
||||
yr=floor(i/4);
|
||||
za=[];
|
||||
gza=[];
|
||||
init=1;
|
||||
for i=t0:4:t1
|
||||
yr=floor(i/4);
|
||||
za=[];
|
||||
gza=[];
|
||||
myopts=options_;
|
||||
myopts.plot_shock_decomp.type='qoq';
|
||||
myopts.plot_shock_decomp.realtime=1;
|
||||
myopts.plot_shock_decomp.vintage=i;
|
||||
[z, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,[]);
|
||||
z = z(i_var,:,:);
|
||||
if isstruct(aux)
|
||||
if ischar(aux0.y)
|
||||
[y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux0.y);
|
||||
aux.y=y_aux;
|
||||
aux.yss=steady_state_aux;
|
||||
end
|
||||
yaux=aux.y;
|
||||
end
|
||||
nterms = size(z,2);
|
||||
|
||||
% z = oo_.realtime_shock_decomposition.(['time_' int2str(i)]);
|
||||
% z = z(i_var,:,:);
|
||||
|
||||
for j=1:nvar
|
||||
for k =nterms:-1:1
|
||||
% if k<nterms
|
||||
% ztmp = squeeze(sum(z(j,[1:k-1,k+1:end-1],t0-4:end)));
|
||||
% else
|
||||
ztmp = squeeze(z(j,k,min((t0-3):-4:1):end));
|
||||
% end
|
||||
if isstruct(aux)
|
||||
aux.y = squeeze(yaux(j,k,min((t0-3):-4:1):end));
|
||||
if isstruct(aux)
|
||||
if ischar(aux0.y)
|
||||
[y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux0.y);
|
||||
aux.y=y_aux;
|
||||
aux.yss=steady_state_aux;
|
||||
end
|
||||
[za(j,k,:), steady_state_a(j,1), gza(j,k,:), steady_state_ga(j,1)] = ...
|
||||
quarterly2annual(ztmp,steady_state(j),GYTREND0,var_type,islog,aux);
|
||||
% if k<nterms
|
||||
% za(j,k,:) = za(j,end,:) - za(j,k,:);
|
||||
% gza(j,k,:) = gza(j,end,:) - gza(j,k,:);
|
||||
% end
|
||||
|
||||
yaux=aux.y;
|
||||
end
|
||||
|
||||
ztmp=squeeze(za(j,:,:));
|
||||
nterms = size(z,2);
|
||||
|
||||
if cumfix==0
|
||||
zscale = sum(ztmp(1:end-1,:))./ztmp(end,:);
|
||||
ztmp(1:end-1,:) = ztmp(1:end-1,:)./repmat(zscale,[nterms-1,1]);
|
||||
else
|
||||
zres = ztmp(end,:)-sum(ztmp(1:end-1,:));
|
||||
ztmp(end-1,:) = ztmp(end-1,:) + zres;
|
||||
% z = oo_.realtime_shock_decomposition.(['time_' int2str(i)]);
|
||||
% z = z(i_var,:,:);
|
||||
|
||||
for j=1:nvar
|
||||
for k =nterms:-1:1
|
||||
% if k<nterms
|
||||
% ztmp = squeeze(sum(z(j,[1:k-1,k+1:end-1],t0-4:end)));
|
||||
% else
|
||||
ztmp = squeeze(z(j,k,min((t0-3):-4:1):end));
|
||||
% end
|
||||
if isstruct(aux)
|
||||
aux.y = squeeze(yaux(j,k,min((t0-3):-4:1):end));
|
||||
end
|
||||
[za(j,k,:), steady_state_a(j,1), gza(j,k,:), steady_state_ga(j,1)] = ...
|
||||
quarterly2annual(ztmp,steady_state(j),GYTREND0,var_type,islog,aux);
|
||||
% if k<nterms
|
||||
% za(j,k,:) = za(j,end,:) - za(j,k,:);
|
||||
% gza(j,k,:) = gza(j,end,:) - gza(j,k,:);
|
||||
% end
|
||||
|
||||
end
|
||||
|
||||
ztmp=squeeze(za(j,:,:));
|
||||
|
||||
if cumfix==0
|
||||
zscale = sum(ztmp(1:end-1,:))./ztmp(end,:);
|
||||
ztmp(1:end-1,:) = ztmp(1:end-1,:)./repmat(zscale,[nterms-1,1]);
|
||||
else
|
||||
zres = ztmp(end,:)-sum(ztmp(1:end-1,:));
|
||||
ztmp(end-1,:) = ztmp(end-1,:) + zres;
|
||||
end
|
||||
|
||||
gztmp=squeeze(gza(j,:,:));
|
||||
if cumfix==0
|
||||
gscale = sum(gztmp(1:end-1,:))./ gztmp(end,:);
|
||||
gztmp(1:end-1,:) = gztmp(1:end-1,:)./repmat(gscale,[nterms-1,1]);
|
||||
else
|
||||
gres = gztmp(end,:) - sum(gztmp(1:end-1,:));
|
||||
gztmp(end-1,:) = gztmp(end-1,:)+gres;
|
||||
end
|
||||
|
||||
za(j,:,:) = ztmp;
|
||||
gza(j,:,:) = gztmp;
|
||||
end
|
||||
|
||||
gztmp=squeeze(gza(j,:,:));
|
||||
if cumfix==0
|
||||
gscale = sum(gztmp(1:end-1,:))./ gztmp(end,:);
|
||||
gztmp(1:end-1,:) = gztmp(1:end-1,:)./repmat(gscale,[nterms-1,1]);
|
||||
|
||||
if q2a.plot ==1
|
||||
z=gza;
|
||||
elseif q2a.plot == 2
|
||||
z=za;
|
||||
else
|
||||
gres = gztmp(end,:) - sum(gztmp(1:end-1,:));
|
||||
gztmp(end-1,:) = gztmp(end-1,:)+gres;
|
||||
z=cat(1,za,gza);
|
||||
end
|
||||
|
||||
za(j,:,:) = ztmp;
|
||||
gza(j,:,:) = gztmp;
|
||||
end
|
||||
|
||||
if q2a.plot ==1
|
||||
z=gza;
|
||||
elseif q2a.plot == 2
|
||||
z=za;
|
||||
else
|
||||
z=cat(1,za,gza);
|
||||
end
|
||||
|
||||
if init==1
|
||||
oo_.annualized_realtime_shock_decomposition.pool = z;
|
||||
else
|
||||
oo_.annualized_realtime_shock_decomposition.pool(:,:,yr) = z(:,:,end-nfrcst);
|
||||
end
|
||||
oo_.annualized_realtime_shock_decomposition.(['yr_' int2str(yr)]) = z;
|
||||
|
||||
if opts.forecast
|
||||
oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr)]) = z(:,:,end-nfrcst:end);
|
||||
if init>nfrcst
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)]) = ...
|
||||
oo_.annualized_realtime_shock_decomposition.pool(:,:,yr-nfrcst:end) - ...
|
||||
oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-nfrcst)]);
|
||||
% fix others
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end-1,:) = ...
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end-1,:) + ...
|
||||
oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end,:);
|
||||
% fix total
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end,:) = ...
|
||||
oo_.annualized_realtime_shock_decomposition.pool(:,end,yr-nfrcst:end);
|
||||
if i==t1
|
||||
for my_forecast_=(nfrcst-1):-1:1
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)]) = ...
|
||||
oo_.annualized_realtime_shock_decomposition.pool(:,:,yr-my_forecast_:yr) - ...
|
||||
oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,:,1:my_forecast_+1);
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end-1,:) = ...
|
||||
oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end,1:my_forecast_+1);
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end,:) = ...
|
||||
oo_.annualized_realtime_shock_decomposition.pool(:,end,yr-my_forecast_:yr);
|
||||
|
||||
if init==1
|
||||
oo_.annualized_realtime_shock_decomposition.pool = z;
|
||||
else
|
||||
oo_.annualized_realtime_shock_decomposition.pool(:,:,yr) = z(:,:,end-nfrcst);
|
||||
end
|
||||
oo_.annualized_realtime_shock_decomposition.(['yr_' int2str(yr)]) = z;
|
||||
|
||||
if opts.forecast
|
||||
oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr)]) = z(:,:,end-nfrcst:end);
|
||||
if init>nfrcst
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)]) = ...
|
||||
oo_.annualized_realtime_shock_decomposition.pool(:,:,yr-nfrcst:end) - ...
|
||||
oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-nfrcst)]);
|
||||
% fix others
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end-1,:) = ...
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end-1,:) + ...
|
||||
oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end,:);
|
||||
% fix total
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end,:) = ...
|
||||
oo_.annualized_realtime_shock_decomposition.pool(:,end,yr-nfrcst:end);
|
||||
if i==t1
|
||||
for my_forecast_=(nfrcst-1):-1:1
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)]) = ...
|
||||
oo_.annualized_realtime_shock_decomposition.pool(:,:,yr-my_forecast_:yr) - ...
|
||||
oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,:,1:my_forecast_+1);
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end-1,:) = ...
|
||||
oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end,1:my_forecast_+1);
|
||||
oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end,:) = ...
|
||||
oo_.annualized_realtime_shock_decomposition.pool(:,end,yr-my_forecast_:yr);
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
% ztmp=oo_.realtime_shock_decomposition.pool(:,:,21:29)-oo_.realtime_forecast_shock_decomposition.time_21;
|
||||
|
||||
|
||||
|
||||
init=init+1;
|
||||
end
|
||||
% ztmp=oo_.realtime_shock_decomposition.pool(:,:,21:29)-oo_.realtime_forecast_shock_decomposition.time_21;
|
||||
|
||||
|
||||
switch realtime_
|
||||
|
||||
init=init+1;
|
||||
end
|
||||
|
||||
|
||||
switch realtime_
|
||||
|
||||
case 0
|
||||
case 0
|
||||
z = oo_.annualized_shock_decomposition;
|
||||
|
||||
case 1 % realtime
|
||||
|
||||
case 1 % realtime
|
||||
if vintage_
|
||||
z = oo_.annualized_realtime_shock_decomposition.(['yr_' int2str(floor(vintage_/4))]);
|
||||
else
|
||||
z = oo_.annualized_realtime_shock_decomposition.pool;
|
||||
end
|
||||
|
||||
case 2 % conditional
|
||||
|
||||
case 2 % conditional
|
||||
if vintage_
|
||||
z = oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(floor(vintage_/4))]);
|
||||
else
|
||||
error();
|
||||
end
|
||||
|
||||
case 3 % forecast
|
||||
|
||||
case 3 % forecast
|
||||
if vintage_
|
||||
z = oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(floor(vintage_/4))]);
|
||||
else
|
||||
error()
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if q2a.plot ==0
|
||||
|
@ -331,4 +331,3 @@ else
|
|||
steady_state = steady_state_a;
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -2,43 +2,43 @@ function [InnovationVariance,AutoregressiveParameters] = autoregressive_process_
|
|||
% This function computes the parameters of an AR(p) process from the variance and the autocorrelation function
|
||||
% (the first p terms) of this process.
|
||||
%
|
||||
% INPUTS
|
||||
% INPUTS
|
||||
% [1] Variance [double] scalar, variance of the variable.
|
||||
% [2] Rho [double] p*1 vector, the autocorelation function: \rho(1), \rho(2), ..., \rho(p).
|
||||
% [3] p [double] scalar, the number of lags in the AR process.
|
||||
%
|
||||
% OUTPUTS
|
||||
% OUTPUTS
|
||||
% [1] InnovationVariance [double] scalar, the variance of the innovation.
|
||||
% [2] AutoregressiveParameters [double] p*1 vector of autoregressive parameters.
|
||||
%
|
||||
% NOTES
|
||||
% NOTES
|
||||
%
|
||||
% The AR(p) model for {y_t} is:
|
||||
%
|
||||
% y_t = \phi_1 * y_{t-1} + \phi_2 * y_{t-2} + ... + \phi_p * y_{t-p} + e_t
|
||||
%
|
||||
% y_t = \phi_1 * y_{t-1} + \phi_2 * y_{t-2} + ... + \phi_p * y_{t-p} + e_t
|
||||
%
|
||||
% Let \gamma(0) and \rho(1), ..., \rho(2) be the variance and the autocorrelation function of {y_t}. This function
|
||||
% compute the variance of {e_t} and the \phi_i (i=1,...,p) from the variance and the autocorrelation function of {y_t}.
|
||||
% compute the variance of {e_t} and the \phi_i (i=1,...,p) from the variance and the autocorrelation function of {y_t}.
|
||||
% We know that:
|
||||
%
|
||||
%
|
||||
% \gamma(0) = \phi_1 \gamma(1) + ... + \phi_p \gamma(p) + \sigma^2
|
||||
%
|
||||
% where \sigma^2 is the variance of {e_t}. Equivalently we have:
|
||||
%
|
||||
% \sigma^2 = \gamma(0) (1-\rho(1)\phi_1 - ... - \rho(p)\phi_p)
|
||||
% \sigma^2 = \gamma(0) (1-\rho(1)\phi_1 - ... - \rho(p)\phi_p)
|
||||
%
|
||||
% We also have for any integer h>0:
|
||||
%
|
||||
%
|
||||
% \rho(h) = \phi_1 \rho(h-1) + ... + \phi_p \rho(h-p)
|
||||
%
|
||||
% We can write the equations for \rho(1), ..., \rho(p) using matrices. Let R be the p*p autocorelation
|
||||
% matrix and v be the p*1 vector gathering the first p terms of the autocorrelation function. We have:
|
||||
% matrix and v be the p*1 vector gathering the first p terms of the autocorrelation function. We have:
|
||||
%
|
||||
% v = R*PHI
|
||||
%
|
||||
%
|
||||
% where PHI is a p*1 vector with the autoregressive parameters of the AR(p) process. We can recover the autoregressive
|
||||
% parameters by inverting the autocorrelation matrix: PHI = inv(R)*v.
|
||||
%
|
||||
%
|
||||
% This function first computes the vector PHI by inverting R and computes the variance of the innovation by evaluating
|
||||
%
|
||||
% \sigma^2 = \gamma(0)*(1-PHI'*v)
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
function [endogenousvariables, exogenousvariables] = backward_model_inversion(constraints, exogenousvariables, initialconditions, endo_names, exo_names, freeinnovations, DynareModel, DynareOptions, DynareOutput)
|
||||
|
||||
% INPUTS
|
||||
% INPUTS
|
||||
% - constraints [dseries] with N constrained endogenous variables from t1 to t2.
|
||||
% - exogenousvariables [dseries] with Q exogenous variables.
|
||||
% - initialconditions [dseries] with M endogenous variables starting before t1 (M initialcond must contain at least the state variables).
|
||||
|
@ -8,11 +8,11 @@ function [endogenousvariables, exogenousvariables] = backward_model_inversion(co
|
|||
% - exo_names [cell] list of exogenous variable names.
|
||||
% - freeinstruments [cell] list of exogenous variable names used to control the constrained endogenous variables.
|
||||
%
|
||||
% OUTPUTS
|
||||
% OUTPUTS
|
||||
% - endogenous [dseries]
|
||||
% - exogenous [dseries]
|
||||
%
|
||||
% REMARKS
|
||||
% REMARKS
|
||||
|
||||
% Copyright (C) 2017 Dynare Team
|
||||
%
|
||||
|
|
|
@ -31,60 +31,60 @@ function plan = basic_plan(plan, exogenous, expectation_type, date, value)
|
|||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
if ~ischar(expectation_type) || size(expectation_type,1) ~= 1
|
||||
error(['in basic_plan the third argument should be a string containing the simulation type (''perfect_foresight'' or ''surprise'')']);
|
||||
end
|
||||
exogenous = strtrim(exogenous);
|
||||
ix = find(strcmp(exogenous, plan.exo_names));
|
||||
if isempty(ix)
|
||||
error(['in basic_plan the second argument ' exogenous ' is not an exogenous variable']);
|
||||
end
|
||||
sdate = length(date);
|
||||
if sdate > 1
|
||||
if date(1) < plan.date(1) || date(end) > plan.date(end)
|
||||
error(['in basic_plan the fourth argument (date=' date ') must lay inside the plan.date ' plan.date]);
|
||||
end
|
||||
else
|
||||
if date < plan.date(1) || date > plan.date(end)
|
||||
error(['in basic_plan the fourth argument (date=' date ') must lay iside the plan.date ' plan.date]);
|
||||
end
|
||||
end
|
||||
if length(date) ~= length(value)
|
||||
error(['in basic_plan the number of dates (' int2str(length(date)) ') is not equal to the numbers of shock (' int2str(length(value)) ') for exogenous variable ' exogenous]);
|
||||
end
|
||||
if ~isempty(plan.options_cond_fcst_.controlled_varexo)
|
||||
common_var = find(ix == plan.options_cond_fcst_.controlled_varexo);
|
||||
if ~isempty(common_var)
|
||||
common_date = intersect(date, plan.constrained_date_{common_var});
|
||||
if ~isempty(common_date)
|
||||
[date_, i_date] = setdiff(date, common_date);
|
||||
value = value(i_date);
|
||||
if common_date.length > 1
|
||||
the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))];
|
||||
else
|
||||
the_dates = cell2mat(strings(common_date));
|
||||
end
|
||||
warning(['Impossible case: ' plan.exo_names{plan.options_cond_fcst_.controlled_varexo(common_var)} ' is used both as a shock and as an endogenous variable to control the path of ' plan.endo_names{plan.constrained_vars_(common_var)} ' at the dates ' the_dates]);
|
||||
warning('This shock will not be considered');
|
||||
end
|
||||
end
|
||||
end
|
||||
if isempty(plan.shock_vars_)
|
||||
plan.shock_vars_ = ix;
|
||||
if strcmp(expectation_type, 'perfect_foresight')
|
||||
plan.shock_perfect_foresight_ = 1;
|
||||
else
|
||||
plan.shock_perfect_foresight_ = 0;
|
||||
end
|
||||
else
|
||||
plan.shock_vars_ = [plan.shock_vars_ ; ix];
|
||||
if strcmp(expectation_type, 'perfect_foresight')
|
||||
plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 1];
|
||||
else
|
||||
plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 0];
|
||||
end
|
||||
end
|
||||
plan.shock_date_{length(plan.shock_date_) + 1} = date;
|
||||
plan.shock_str_date_{length(plan.shock_str_date_) + 1} = strings(date);
|
||||
plan.shock_int_date_{length(plan.shock_int_date_) + 1} = date - plan.date(1) + 1;
|
||||
plan.shock_paths_{length(plan.shock_paths_) + 1} = value;
|
||||
if ~ischar(expectation_type) || size(expectation_type,1) ~= 1
|
||||
error(['in basic_plan the third argument should be a string containing the simulation type (''perfect_foresight'' or ''surprise'')']);
|
||||
end
|
||||
exogenous = strtrim(exogenous);
|
||||
ix = find(strcmp(exogenous, plan.exo_names));
|
||||
if isempty(ix)
|
||||
error(['in basic_plan the second argument ' exogenous ' is not an exogenous variable']);
|
||||
end
|
||||
sdate = length(date);
|
||||
if sdate > 1
|
||||
if date(1) < plan.date(1) || date(end) > plan.date(end)
|
||||
error(['in basic_plan the fourth argument (date=' date ') must lay inside the plan.date ' plan.date]);
|
||||
end
|
||||
else
|
||||
if date < plan.date(1) || date > plan.date(end)
|
||||
error(['in basic_plan the fourth argument (date=' date ') must lay iside the plan.date ' plan.date]);
|
||||
end
|
||||
end
|
||||
if length(date) ~= length(value)
|
||||
error(['in basic_plan the number of dates (' int2str(length(date)) ') is not equal to the numbers of shock (' int2str(length(value)) ') for exogenous variable ' exogenous]);
|
||||
end
|
||||
if ~isempty(plan.options_cond_fcst_.controlled_varexo)
|
||||
common_var = find(ix == plan.options_cond_fcst_.controlled_varexo);
|
||||
if ~isempty(common_var)
|
||||
common_date = intersect(date, plan.constrained_date_{common_var});
|
||||
if ~isempty(common_date)
|
||||
[date_, i_date] = setdiff(date, common_date);
|
||||
value = value(i_date);
|
||||
if common_date.length > 1
|
||||
the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))];
|
||||
else
|
||||
the_dates = cell2mat(strings(common_date));
|
||||
end
|
||||
warning(['Impossible case: ' plan.exo_names{plan.options_cond_fcst_.controlled_varexo(common_var)} ' is used both as a shock and as an endogenous variable to control the path of ' plan.endo_names{plan.constrained_vars_(common_var)} ' at the dates ' the_dates]);
|
||||
warning('This shock will not be considered');
|
||||
end
|
||||
end
|
||||
end
|
||||
if isempty(plan.shock_vars_)
|
||||
plan.shock_vars_ = ix;
|
||||
if strcmp(expectation_type, 'perfect_foresight')
|
||||
plan.shock_perfect_foresight_ = 1;
|
||||
else
|
||||
plan.shock_perfect_foresight_ = 0;
|
||||
end
|
||||
else
|
||||
plan.shock_vars_ = [plan.shock_vars_ ; ix];
|
||||
if strcmp(expectation_type, 'perfect_foresight')
|
||||
plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 1];
|
||||
else
|
||||
plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 0];
|
||||
end
|
||||
end
|
||||
plan.shock_date_{length(plan.shock_date_) + 1} = date;
|
||||
plan.shock_str_date_{length(plan.shock_str_date_) + 1} = strings(date);
|
||||
plan.shock_int_date_{length(plan.shock_int_date_) + 1} = date - plan.date(1) + 1;
|
||||
plan.shock_paths_{length(plan.shock_paths_) + 1} = value;
|
||||
|
|
|
@ -4,7 +4,7 @@ function d = bksup0(c,ny,jcf,iyf,icf,periods)
|
|||
% INPUTS
|
||||
% ny: number of endogenous variables
|
||||
% jcf: variables index forward
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% d: vector of backsubstitution results
|
||||
%
|
||||
|
|
|
@ -5,7 +5,7 @@ function d = bksup1(c,ny,jcf,iyf,periods)
|
|||
% INPUTS
|
||||
% ny: number of endogenous variables
|
||||
% jcf: variables index forward
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% d: vector of backsubstitution results
|
||||
%
|
||||
|
@ -40,4 +40,3 @@ for i = 2:periods
|
|||
end
|
||||
|
||||
d = c(:,jcf) ;
|
||||
|
||||
|
|
|
@ -68,7 +68,7 @@ while i <= options_.periods
|
|||
c = fread(fid,[jcf,ny],'float64')' ;
|
||||
|
||||
d1(ir) = c(:,jcf)-c(:,icf)*d1(irf) ;
|
||||
ir = ir-ny ;
|
||||
ir = ir-ny ;
|
||||
irf = irf-ny ;
|
||||
i = i+1;
|
||||
end
|
||||
|
|
|
@ -33,16 +33,15 @@ for im = 1:m
|
|||
for i = 1:min(length(key),length(temp))
|
||||
if temp(i) > key(i)
|
||||
h = mid - 1 ;
|
||||
break
|
||||
break
|
||||
else
|
||||
l = mid + 1 ;
|
||||
break
|
||||
break
|
||||
end
|
||||
end
|
||||
else
|
||||
x(im) = mid ;
|
||||
break
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -37,16 +37,16 @@ for nlags = 1:maxnlags
|
|||
[ny, nx, posterior, prior] = bvar_toolbox(nlags);
|
||||
oo_.bvar.posterior{nlags}=posterior;
|
||||
oo_.bvar.prior{nlags}=prior;
|
||||
|
||||
|
||||
posterior_int = matrictint(posterior.S, posterior.df, posterior.XXi);
|
||||
prior_int = matrictint(prior.S, prior.df, prior.XXi);
|
||||
|
||||
|
||||
lik_nobs = posterior.df - prior.df;
|
||||
|
||||
|
||||
log_dnsty = posterior_int - prior_int - 0.5*ny*lik_nobs*log(2*pi);
|
||||
|
||||
|
||||
oo_.bvar.log_marginal_data_density(nlags)=log_dnsty;
|
||||
|
||||
|
||||
skipline()
|
||||
fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ...
|
||||
nlags, log_dnsty);
|
||||
|
@ -61,7 +61,7 @@ function w = matrictint(S, df, XXi)
|
|||
% S: parameter of inverse-Wishart distribution
|
||||
% df: number of degrees of freedom of inverse-Wishart distribution
|
||||
% XXi: first component of VCV matrix of matrix-normal distribution
|
||||
%
|
||||
%
|
||||
% Computes the integral over (Phi, Sigma) of:
|
||||
%
|
||||
% det(Sigma)^(-k/2)*exp(-0.5*Tr((Phi-PhiHat)'*(XXi)^(-1)*(Phi-PhiHat)*Sigma^(-1)))*
|
||||
|
|
|
@ -54,7 +54,7 @@ p = 0;
|
|||
% Loop counter initialization
|
||||
d = 0;
|
||||
while d <= options_.bvar_replic
|
||||
|
||||
|
||||
Sigma = rand_inverse_wishart(ny, posterior.df, S_inv_upper_chol);
|
||||
|
||||
% Option 'lower' of chol() not available in old versions of
|
||||
|
@ -62,15 +62,15 @@ while d <= options_.bvar_replic
|
|||
Sigma_lower_chol = chol(Sigma)';
|
||||
|
||||
Phi = rand_matrix_normal(k, ny, posterior.PhiHat, Sigma_lower_chol, XXi_lower_chol);
|
||||
|
||||
|
||||
% All the eigenvalues of the companion matrix have to be on or inside the unit circle
|
||||
Companion_matrix(1:ny,:) = Phi(1:ny*nlags,:)';
|
||||
Companion_matrix(1:ny,:) = Phi(1:ny*nlags,:)';
|
||||
test = (abs(eig(Companion_matrix)));
|
||||
if any(test>1.0000000000001)
|
||||
p = p+1;
|
||||
end
|
||||
d = d+1;
|
||||
|
||||
|
||||
% Without shocks
|
||||
lags_data = forecast_data.initval;
|
||||
for t = 1:options_.forecast
|
||||
|
@ -80,7 +80,7 @@ while d <= options_.bvar_replic
|
|||
lags_data(end,:) = y;
|
||||
sims_no_shock(t, :, d) = y;
|
||||
end
|
||||
|
||||
|
||||
% With shocks
|
||||
lags_data = forecast_data.initval;
|
||||
for t = 1:options_.forecast
|
||||
|
@ -120,9 +120,9 @@ dyn_graph=dynare_graph_init(sprintf('BVAR forecasts (nlags = %d)', nlags), ny, {
|
|||
|
||||
for i = 1:ny
|
||||
dyn_graph=dynare_graph(dyn_graph,[ sims_no_shock_median(:, i) ...
|
||||
sims_no_shock_up_conf(:, i) sims_no_shock_down_conf(:, i) ...
|
||||
sims_with_shocks_up_conf(:, i) sims_with_shocks_down_conf(:, i) ], ...
|
||||
options_.varobs{i});
|
||||
sims_no_shock_up_conf(:, i) sims_no_shock_down_conf(:, i) ...
|
||||
sims_with_shocks_up_conf(:, i) sims_with_shocks_down_conf(:, i) ], ...
|
||||
options_.varobs{i});
|
||||
end
|
||||
|
||||
dyn_saveas(dyn_graph.fh,[OutputDirectoryName '/' M_.fname '_BVAR_forecast_',num2str(nlags)],options_.nodisplay,options_.graph_format)
|
||||
|
@ -130,9 +130,9 @@ dyn_saveas(dyn_graph.fh,[OutputDirectoryName '/' M_.fname '_BVAR_forecast_',num2
|
|||
% Compute RMSE
|
||||
|
||||
if ~isempty(forecast_data.realized_val)
|
||||
|
||||
|
||||
sq_err_cumul = zeros(1, ny);
|
||||
|
||||
|
||||
lags_data = forecast_data.initval;
|
||||
for t = 1:size(forecast_data.realized_val, 1)
|
||||
X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.realized_xdata(t, :) ];
|
||||
|
@ -141,14 +141,14 @@ if ~isempty(forecast_data.realized_val)
|
|||
lags_data(end,:) = y;
|
||||
sq_err_cumul = sq_err_cumul + (y - forecast_data.realized_val(t, :)) .^ 2;
|
||||
end
|
||||
|
||||
|
||||
rmse = sqrt(sq_err_cumul / size(forecast_data.realized_val, 1));
|
||||
|
||||
|
||||
fprintf('RMSE of BVAR(%d):\n', nlags);
|
||||
|
||||
|
||||
for i = 1:length(options_.varobs)
|
||||
fprintf('%s: %10.4f\n', options_.varobs{i}, rmse(i));
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
% Store results
|
||||
|
|
|
@ -54,7 +54,7 @@ p = 0;
|
|||
sampled_irfs = NaN(ny, ny, options_.irf, options_.bvar_replic);
|
||||
|
||||
for draw=1:options_.bvar_replic
|
||||
|
||||
|
||||
% Get a covariance matrix from an inverted Wishart distribution.
|
||||
Sigma = rand_inverse_wishart(ny, posterior.df, S_inv_upper_chol);
|
||||
Sigma_upper_chol = chol(Sigma);
|
||||
|
@ -62,10 +62,10 @@ for draw=1:options_.bvar_replic
|
|||
|
||||
% Get the Autoregressive matrices from a matrix variate distribution.
|
||||
Phi = rand_matrix_normal(k, ny, posterior.PhiHat, Sigma_lower_chol, XXi_lower_chol);
|
||||
|
||||
|
||||
% Form the companion matrix.
|
||||
Companion_matrix(1:ny,:) = transpose(Phi(1:ny*nlags,:));
|
||||
|
||||
Companion_matrix(1:ny,:) = transpose(Phi(1:ny*nlags,:));
|
||||
|
||||
% All the eigenvalues of the companion matrix have to be on or
|
||||
% inside the unit circle to rule out explosive time series.
|
||||
test = (abs(eig(Companion_matrix)));
|
||||
|
@ -78,7 +78,7 @@ for draw=1:options_.bvar_replic
|
|||
elseif strcmpi(identification,'SquareRoot')
|
||||
StructuralMat = sqrtm(Sigma);
|
||||
end
|
||||
|
||||
|
||||
% Build the IRFs...
|
||||
lags_data = zeros(ny,ny*nlags) ;
|
||||
sampled_irfs(:,:,1,draw) = Sigma_lower_chol ;
|
||||
|
@ -88,7 +88,7 @@ for draw=1:options_.bvar_replic
|
|||
lags_data(:,ny+1:end) = lags_data(:,1:end-ny) ;
|
||||
lags_data(:,1:ny) = sampled_irfs(:,:,t,draw) ;
|
||||
end
|
||||
|
||||
|
||||
end
|
||||
|
||||
if p > 0
|
||||
|
@ -106,7 +106,7 @@ sort_idx = round((0.5 + [-options_.bvar.conf_sig, options_.bvar.conf_sig, .0]/2)
|
|||
|
||||
posterior_down_conf_irfs = sorted_irfs(:,:,:,sort_idx(1));
|
||||
posterior_up_conf_irfs = sorted_irfs(:,:,:,sort_idx(2));
|
||||
posterior_median_irfs = sorted_irfs(:,:,:,sort_idx(3));
|
||||
posterior_median_irfs = sorted_irfs(:,:,:,sort_idx(3));
|
||||
|
||||
number_of_columns = fix(sqrt(ny));
|
||||
number_of_rows = ceil(ny / number_of_columns) ;
|
||||
|
|
|
@ -29,7 +29,7 @@ function [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags)
|
|||
% forecasting, of size options_.forecast*nx (actually only
|
||||
% contains "1" values for the constant term if nx ~= 0)
|
||||
% - realized_val: only non-empty if options_.nobs doesn't point
|
||||
% to the end of sample
|
||||
% to the end of sample
|
||||
% In that case, contains values of endogenous variables after
|
||||
% options_.nobs and up to the end of the sample
|
||||
% - realized_xdata: contains values of exogenous variables after
|
||||
|
@ -67,7 +67,7 @@ options_ = set_default_option(options_, 'nobs', size(dataset,1)-options_.first_o
|
|||
|
||||
if (options_.first_obs+options_.nobs-1)> size(dataset,1)
|
||||
fprintf('Incorrect or missing specification of the number of observations. nobs can be at most %4u\n',size(dataset,1)-options_.first_obs+1);
|
||||
error('Inconsistent number of observations.')
|
||||
error('Inconsistent number of observations.')
|
||||
end
|
||||
|
||||
% Parameters for prior
|
||||
|
@ -160,7 +160,7 @@ function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior)
|
|||
%function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior)
|
||||
% ydum, xdum: dummy observation data that implement the prior
|
||||
% breaks: vector of points in the dummy data after which new dummy obs's start
|
||||
% Set breaks=T+[0;breaks], ydata=[ydata;ydum], xdum=[xdata;xdum], where
|
||||
% Set breaks=T+[0;breaks], ydata=[ydata;ydum], xdum=[xdata;xdum], where
|
||||
% actual data matrix has T rows, in preparing input for rfvar3
|
||||
% nv,nx,lags: VAR dimensions
|
||||
% mnprior.tight:Overall tightness of Minnesota prior
|
||||
|
@ -175,8 +175,8 @@ function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior)
|
|||
% taken to include the sum-of-coefficients and co-persistence components
|
||||
% that are implemented directly in rfvar3.m. The diagonal prior on v, combined
|
||||
% with sum-of-coefficients and co-persistence components and with the unit own-first-lag
|
||||
% prior mean generates larger prior variances for own than for cross-effects even in
|
||||
% this formulation, but here there is no way to shrink toward a set of unconstrained
|
||||
% prior mean generates larger prior variances for own than for cross-effects even in
|
||||
% this formulation, but here there is no way to shrink toward a set of unconstrained
|
||||
% univariate AR's.
|
||||
|
||||
% Original file downloaded from:
|
||||
|
@ -228,9 +228,9 @@ function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)
|
|||
% discontinuities in the data (e.g. war years) and for the possibility of
|
||||
% adding dummy observations to implement a prior. This must be a column vector.
|
||||
% Note that a single dummy observation becomes lags+1 rows of the data matrix,
|
||||
% with a break separating it from the rest of the data. The function treats the
|
||||
% with a break separating it from the rest of the data. The function treats the
|
||||
% first lags observations at the top and after each "break" in ydata and xdata as
|
||||
% initial conditions.
|
||||
% initial conditions.
|
||||
% lambda: weight on "co-persistence" prior dummy observations. This expresses
|
||||
% belief that when data on *all* y's are stable at their initial levels, they will
|
||||
% tend to persist at that level. lambda=5 is a reasonable first try. With lambda<0,
|
||||
|
@ -243,7 +243,7 @@ function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)
|
|||
% one of these for each variable. A reasonable first guess is mu=2.
|
||||
% The program assumes that the first lags rows of ydata and xdata are real data, not dummies.
|
||||
% Dummy observations should go at the end, if any. If pre-sample x's are not available,
|
||||
% repeating the initial xdata(lags+1,:) row or copying xdata(lags+1:2*lags,:) into
|
||||
% repeating the initial xdata(lags+1,:) row or copying xdata(lags+1:2*lags,:) into
|
||||
% xdata(1:lags,:) are reasonable subsititutes. These values are used in forming the
|
||||
% persistence priors.
|
||||
|
||||
|
@ -280,7 +280,7 @@ for is = 1:length(smpl)
|
|||
end
|
||||
X = [X(:,:) xdata(smpl,:)];
|
||||
y = ydata(smpl,:);
|
||||
% Everything now set up with input data for y=Xb+e
|
||||
% Everything now set up with input data for y=Xb+e
|
||||
|
||||
% Add persistence dummies
|
||||
if lambda ~= 0 || mu > 0
|
||||
|
|
|
@ -5,7 +5,7 @@ function cprod = cartesian_product_of_sets(varargin)
|
|||
%! @deftypefn {Function File} {@var{cprod} =} cartesian_product_of_sets (@var{a},@var{b}, ...)
|
||||
%! @anchor{cartesian_product_of_sets}
|
||||
%! @sp 1
|
||||
%! Computes A_1 * A_2 * .... * A_n with a generic set A_i = {e_1,e_2,e_3,...} where e_i is a string
|
||||
%! Computes A_1 * A_2 * .... * A_n with a generic set A_i = {e_1,e_2,e_3,...} where e_i is a string
|
||||
%! or a number. It is assumed that each element e_i is unique in set A_i.
|
||||
%! @sp 2
|
||||
%! @strong{Inputs}
|
||||
|
|
|
@ -2,11 +2,11 @@ function cellofchar2mfile(fname, c, cname)
|
|||
|
||||
% Write a cell of char in a matlab script.
|
||||
%
|
||||
% INPUTS
|
||||
% INPUTS
|
||||
% - fname [string] name of the file where c is to be saved.
|
||||
% - c [cell] a two dimensional cell of char.
|
||||
%
|
||||
% OUTPUTS
|
||||
% OUTPUTS
|
||||
% None.
|
||||
|
||||
% Copyright (C) 2015 Dynare Team
|
||||
|
|
|
@ -42,7 +42,7 @@ calibrated_covariance_pos=covariance_pos(~ismember(covariance_pos,correlation_po
|
|||
if any(calibrated_covariance_pos)
|
||||
[rows, columns]=ind2sub(size(M.Sigma_e),calibrated_covariance_pos); %find linear indices of lower triangular covariance entries
|
||||
estim_params.calibrated_covariances.position=[calibrated_covariance_pos;sub2ind(size(M.Sigma_e),columns,rows)]; %get linear entries of upper triangular parts
|
||||
estim_params.calibrated_covariances.cov_value=Sigma_e_calibrated(estim_params.calibrated_covariances.position);
|
||||
estim_params.calibrated_covariances.cov_value=Sigma_e_calibrated(estim_params.calibrated_covariances.position);
|
||||
end
|
||||
|
||||
correlation_pos_ME=find(tril(M.Correlation_matrix_ME,-1)); %off-diagonal elements set by correlations after accounting for estimation
|
||||
|
@ -50,6 +50,5 @@ calibrated_covariance_pos_ME=covariance_pos_ME(~ismember(covariance_pos_ME,corre
|
|||
if any(calibrated_covariance_pos_ME)
|
||||
[rows, columns]=ind2sub(size(M.H),calibrated_covariance_pos_ME); %find linear indices of lower triangular covariance entries
|
||||
estim_params.calibrated_covariances_ME.position=[calibrated_covariance_pos_ME;sub2ind(size(M.H),columns,rows)]; %get linear entries of upper triangular parts
|
||||
estim_params.calibrated_covariances_ME.cov_value=H_calibrated(estim_params.calibrated_covariances_ME.position);
|
||||
estim_params.calibrated_covariances_ME.cov_value=H_calibrated(estim_params.calibrated_covariances_ME.position);
|
||||
end
|
||||
|
||||
|
|
|
@ -1,17 +1,17 @@
|
|||
function varlist = check_list_of_variables(options_, M_, varlist)
|
||||
% This function defines, if necessary, the list of endogenous variables
|
||||
% for which the posterior statistics have to be computed.
|
||||
%
|
||||
% for which the posterior statistics have to be computed.
|
||||
%
|
||||
% INPUTS
|
||||
%
|
||||
% INPUTS
|
||||
%
|
||||
% options_ [structure] Dynare structure.
|
||||
% M_ [structure] Dynare structure (related to model definition).
|
||||
% varlist [string] Array of strings with name of the endogenous variables.
|
||||
%
|
||||
% OUTPUTS
|
||||
% varlist [string]
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% varlist [string]
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
|
||||
% Copyright (C) 2003-2017 Dynare Team
|
||||
|
@ -63,7 +63,7 @@ if ~isempty(varlist) && ~isempty(options_.endo_vars_for_moment_computations_in_e
|
|||
error('You cannot use the consider_all_endogenous or consider_all_observed options when listing variables after the estimation command')
|
||||
elseif isempty(varlist) && ~isempty(options_.endo_vars_for_moment_computations_in_estimation)
|
||||
if strcmp(options_.endo_vars_for_moment_computations_in_estimation,'all_endogenous_variables')
|
||||
varlist = M_.endo_names(1:M_.orig_endo_nbr, :);
|
||||
varlist = M_.endo_names(1:M_.orig_endo_nbr, :);
|
||||
elseif strcmp(options_.endo_vars_for_moment_computations_in_estimation,'only_observed_variables')
|
||||
varlist = char(options_.varobs');
|
||||
else
|
||||
|
@ -106,7 +106,7 @@ elseif isempty(varlist) && isempty(options_.endo_vars_for_moment_computations_in
|
|||
end
|
||||
if ~isempty(cas)
|
||||
string = [ cas , ' will be computed for the ' num2str(M_.endo_nbr) ' endogenous variables'];
|
||||
string = [ string ' of your model, this can be very long....'];
|
||||
string = [ string ' of your model, this can be very long....'];
|
||||
format_text(string, 10)
|
||||
if options_.nointeractive
|
||||
% Default behaviour is to consider all the endogenous variables.
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
function check_matlab_path(change_path_flag)
|
||||
|
||||
|
||||
% Copyright (C) 2015-2016 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -82,7 +82,7 @@ else
|
|||
warning(msg);
|
||||
skipline()
|
||||
rmpath(DYNARE_PATH)
|
||||
addpath(DYNARE_PATH)
|
||||
addpath(DYNARE_PATH)
|
||||
end
|
||||
warning on backtrace
|
||||
end
|
||||
|
@ -90,7 +90,7 @@ else
|
|||
else
|
||||
% Check that the user did not put all the subfolders in the path.
|
||||
% => If DYNARE_PATH/qz is in the path while mjdgges dll is available
|
||||
% it most likely means that user wrongly put all subfolders in the
|
||||
% it most likely means that user wrongly put all subfolders in the
|
||||
% matlab's path!
|
||||
mexpath = add_path_to_mex_files([DYNARE_PATH filesep], false);
|
||||
MATLAB_PATH = path2cell(MATLAB_PATH);
|
||||
|
@ -107,40 +107,40 @@ else
|
|||
end
|
||||
|
||||
function q = path2cell(p)
|
||||
% Converts the output of path() to a cell
|
||||
s = strfind(p,pathsep);
|
||||
n = length(s)+1;
|
||||
q = cell(n,1);
|
||||
q(1) = {p(1:s(1)-1)};
|
||||
q(n) = {p(s(end)+1:end)};
|
||||
for i=2:n-1
|
||||
q(i) = {p(s(i-1)+1:s(i)-1)};
|
||||
end
|
||||
|
||||
% Converts the output of path() to a cell
|
||||
s = strfind(p,pathsep);
|
||||
n = length(s)+1;
|
||||
q = cell(n,1);
|
||||
q(1) = {p(1:s(1)-1)};
|
||||
q(n) = {p(s(end)+1:end)};
|
||||
for i=2:n-1
|
||||
q(i) = {p(s(i-1)+1:s(i)-1)};
|
||||
end
|
||||
|
||||
function flist = getallroutinenames(p, excludedsubfolders)
|
||||
if nargin<2
|
||||
excludedsubfolders = {};
|
||||
end
|
||||
flist={};
|
||||
%get m-files in this directory
|
||||
dd = dir([p,filesep '*.m']);
|
||||
temp=struct2cell(dd);
|
||||
flist=[flist temp(1,:)];
|
||||
%deal with subdirectories
|
||||
dlist=getalldirectories(p,excludedsubfolders); %first call with excluded directories
|
||||
for ii=1:length(dlist)
|
||||
flist=[flist getallroutinenames([ p filesep dlist{ii}])]; %recursive calls without subfolders
|
||||
end
|
||||
|
||||
if nargin<2
|
||||
excludedsubfolders = {};
|
||||
end
|
||||
flist={};
|
||||
%get m-files in this directory
|
||||
dd = dir([p,filesep '*.m']);
|
||||
temp=struct2cell(dd);
|
||||
flist=[flist temp(1,:)];
|
||||
%deal with subdirectories
|
||||
dlist=getalldirectories(p,excludedsubfolders); %first call with excluded directories
|
||||
for ii=1:length(dlist)
|
||||
flist=[flist getallroutinenames([ p filesep dlist{ii}])]; %recursive calls without subfolders
|
||||
end
|
||||
|
||||
|
||||
function dlist = getalldirectories(p,excluded_directories)
|
||||
if nargin<2
|
||||
excluded_directories = {};
|
||||
end
|
||||
dd = dir(p);
|
||||
dir_result=struct2cell(dd);
|
||||
directory_indicator=cell2mat(dir_result(4,:));
|
||||
dlist = dir_result(1,directory_indicator==1 & ~strcmp('.',dir_result(1,:)) & ~strcmp('..',dir_result(1,:)) & ~ismember(dir_result(1,:),excluded_directories));
|
||||
if nargin<2
|
||||
excluded_directories = {};
|
||||
end
|
||||
dd = dir(p);
|
||||
dir_result=struct2cell(dd);
|
||||
directory_indicator=cell2mat(dir_result(4,:));
|
||||
dlist = dir_result(1,directory_indicator==1 & ~strcmp('.',dir_result(1,:)) & ~strcmp('..',dir_result(1,:)) & ~ismember(dir_result(1,:),excluded_directories));
|
||||
|
||||
function n = position(i, currentpath)
|
||||
n = length(strfind(currentpath(1:i), pathsep));
|
||||
n = length(strfind(currentpath(1:i), pathsep));
|
|
@ -1,13 +1,13 @@
|
|||
function [info,description] = check_posterior_analysis_data(type,M_)
|
||||
% function [info,description] = check_posterior_analysis_data(type,M_)
|
||||
% Checks the status of posterior analysis and in particular if files need to be
|
||||
% Checks the status of posterior analysis and in particular if files need to be
|
||||
% created or updated; called by posterior_analysis.m
|
||||
%
|
||||
%
|
||||
% Inputs:
|
||||
% type [string] name of the posterior moment considered
|
||||
% M_ [structure] Dynare model structure
|
||||
%
|
||||
% Outputs:
|
||||
%
|
||||
% Outputs:
|
||||
% info [scalar] return code
|
||||
% info = 1; % select_posterior_draws has to be called first.
|
||||
% info = 2; % _posterior_draws files have to be updated.
|
||||
|
@ -99,7 +99,7 @@ else
|
|||
number_of_the_last_post_data_file = length(pdfinfo);
|
||||
name_of_the_last_post_data_file = ...
|
||||
[ pwd filesep MetropolisFolder filesep ...
|
||||
M_.fname '_' ...
|
||||
M_.fname '_' ...
|
||||
generic_post_data_file_name ...
|
||||
int2str(number_of_the_last_post_data_file) ...
|
||||
'.mat' ];
|
||||
|
@ -108,7 +108,7 @@ else
|
|||
info = 5; % posterior data files have to be updated.
|
||||
if nargout>1
|
||||
description = 'posterior data files have to be updated.';
|
||||
end
|
||||
end
|
||||
else
|
||||
info = 6; % Ok (nothing to do ;-)
|
||||
if nargout>1
|
||||
|
|
|
@ -40,339 +40,339 @@ if init
|
|||
% set default options and user defined options
|
||||
posterior_sampler_options.posterior_sampling_method = options_.posterior_sampler_options.posterior_sampling_method;
|
||||
posterior_sampler_options.bounds = bounds;
|
||||
|
||||
|
||||
switch posterior_sampler_options.posterior_sampling_method
|
||||
|
||||
case 'random_walk_metropolis_hastings'
|
||||
posterior_sampler_options.parallel_bar_refresh_rate=50;
|
||||
posterior_sampler_options.serial_bar_refresh_rate=3;
|
||||
posterior_sampler_options.parallel_bar_title='RWMH';
|
||||
posterior_sampler_options.serial_bar_title='RW Metropolis-Hastings';
|
||||
|
||||
% default options
|
||||
posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.rwmh);
|
||||
|
||||
% user defined options
|
||||
if ~isempty(options_.posterior_sampler_options.sampling_opt)
|
||||
options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
|
||||
for i=1:rows(options_list)
|
||||
switch options_list{i,1}
|
||||
|
||||
case 'proposal_distribution'
|
||||
if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
|
||||
strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
|
||||
error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
|
||||
'rand_multivariate_student or rand_multivariate_normal as options']);
|
||||
else
|
||||
posterior_sampler_options.proposal_distribution=options_list{i,2};
|
||||
end
|
||||
|
||||
|
||||
case 'student_degrees_of_freedom'
|
||||
if options_list{i,2} <= 0
|
||||
error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
|
||||
else
|
||||
posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
|
||||
end
|
||||
|
||||
case 'use_mh_covariance_matrix'
|
||||
% indicates to use the covariance matrix from previous iterations to
|
||||
% define the covariance of the proposal distribution
|
||||
% default = 0
|
||||
posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
|
||||
options_.use_mh_covariance_matrix = options_list{i,2};
|
||||
case 'scale_file'
|
||||
% load optimal_mh_scale parameter if previous run was with mode_compute=6
|
||||
% will overwrite jscale from set_prior.m
|
||||
if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file')
|
||||
tmp = load(options_list{i,2},'Scale');
|
||||
global bayestopt_
|
||||
bayestopt_.mh_jscale = tmp.Scale;
|
||||
options_.mh_jscale = tmp.Scale;
|
||||
bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale;
|
||||
% options_.mh_init_scale = 2*options_.mh_jscale;
|
||||
else
|
||||
error('initial_estimation_checks:: The specified mh_scale_file does not exist.')
|
||||
end
|
||||
case 'save_tmp_file'
|
||||
posterior_sampler_options.save_tmp_file = options_list{i,2};
|
||||
otherwise
|
||||
warning(['rwmh_sampler: Unknown option (' options_list{i,1} ')!'])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
case 'tailored_random_block_metropolis_hastings'
|
||||
posterior_sampler_options.parallel_bar_refresh_rate=5;
|
||||
posterior_sampler_options.serial_bar_refresh_rate=1;
|
||||
posterior_sampler_options.parallel_bar_title='TaRB-MH';
|
||||
posterior_sampler_options.serial_bar_title='TaRB Metropolis-Hastings';
|
||||
|
||||
% default options
|
||||
posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.tarb);
|
||||
|
||||
% user defined options
|
||||
if ~isempty(options_.posterior_sampler_options.sampling_opt)
|
||||
options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
|
||||
for i=1:rows(options_list)
|
||||
|
||||
switch options_list{i,1}
|
||||
|
||||
case 'proposal_distribution'
|
||||
if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
|
||||
strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
|
||||
error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
|
||||
'rand_multivariate_student or rand_multivariate_normal as options']);
|
||||
else
|
||||
posterior_sampler_options.proposal_distribution=options_list{i,2};
|
||||
end
|
||||
|
||||
|
||||
case 'student_degrees_of_freedom'
|
||||
if options_list{i,2} <= 0
|
||||
error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
|
||||
else
|
||||
posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
|
||||
end
|
||||
|
||||
case 'mode_compute'
|
||||
posterior_sampler_options.mode_compute=options_list{i,2};
|
||||
|
||||
case 'optim'
|
||||
posterior_sampler_options.optim_opt=options_list{i,2};
|
||||
|
||||
case 'new_block_probability'
|
||||
if options_list{i,2}<0 || options_list{i,2}>1
|
||||
error('check_posterior_sampler_options:: The tarb new_block_probability must be between 0 and 1!')
|
||||
else
|
||||
posterior_sampler_options.new_block_probability=options_list{i,2};
|
||||
end
|
||||
case 'scale_file'
|
||||
% load optimal_mh_scale parameter if previous run was with mode_compute=6
|
||||
% will overwrite jscale from set_prior.m
|
||||
if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file')
|
||||
tmp = load(options_list{i,2},'Scale');
|
||||
global bayestopt_
|
||||
bayestopt_.mh_jscale = tmp.Scale;
|
||||
options_.mh_jscale = tmp.Scale;
|
||||
bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale;
|
||||
% options_.mh_init_scale = 2*options_.mh_jscale;
|
||||
else
|
||||
error('initial_estimation_checks:: The specified scale_file does not exist.')
|
||||
end
|
||||
case 'save_tmp_file'
|
||||
posterior_sampler_options.save_tmp_file = options_list{i,2};
|
||||
|
||||
otherwise
|
||||
warning(['tarb_sampler: Unknown option (' options_list{i,1} ')!'])
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
case 'independent_metropolis_hastings'
|
||||
posterior_sampler_options.parallel_bar_refresh_rate=50;
|
||||
posterior_sampler_options.serial_bar_refresh_rate=3;
|
||||
posterior_sampler_options.parallel_bar_title='IMH';
|
||||
posterior_sampler_options.serial_bar_title='Ind. Metropolis-Hastings';
|
||||
|
||||
% default options
|
||||
posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.imh);
|
||||
|
||||
% user defined options
|
||||
if ~isempty(options_.posterior_sampler_options.sampling_opt)
|
||||
options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
|
||||
for i=1:rows(options_list)
|
||||
switch options_list{i,1}
|
||||
|
||||
case 'proposal_distribution'
|
||||
if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
|
||||
strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
|
||||
error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
|
||||
'rand_multivariate_student or rand_multivariate_normal as options']);
|
||||
else
|
||||
posterior_sampler_options.proposal_distribution=options_list{i,2};
|
||||
end
|
||||
|
||||
|
||||
case 'student_degrees_of_freedom'
|
||||
if options_list{i,2} <= 0
|
||||
error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
|
||||
else
|
||||
posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
|
||||
end
|
||||
|
||||
case 'use_mh_covariance_matrix'
|
||||
% indicates to use the covariance matrix from previous iterations to
|
||||
% define the covariance of the proposal distribution
|
||||
% default = 0
|
||||
posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
|
||||
options_.use_mh_covariance_matrix = options_list{i,2};
|
||||
|
||||
case 'save_tmp_file'
|
||||
posterior_sampler_options.save_tmp_file = options_list{i,2};
|
||||
case 'random_walk_metropolis_hastings'
|
||||
posterior_sampler_options.parallel_bar_refresh_rate=50;
|
||||
posterior_sampler_options.serial_bar_refresh_rate=3;
|
||||
posterior_sampler_options.parallel_bar_title='RWMH';
|
||||
posterior_sampler_options.serial_bar_title='RW Metropolis-Hastings';
|
||||
|
||||
otherwise
|
||||
warning(['imh_sampler: Unknown option (' options_list{i,1} ')!'])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
case 'slice'
|
||||
posterior_sampler_options.parallel_bar_refresh_rate=1;
|
||||
posterior_sampler_options.serial_bar_refresh_rate=1;
|
||||
posterior_sampler_options.parallel_bar_title='SLICE';
|
||||
posterior_sampler_options.serial_bar_title='SLICE';
|
||||
|
||||
% default options
|
||||
posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.slice);
|
||||
|
||||
% user defined options
|
||||
if ~isempty(options_.posterior_sampler_options.sampling_opt)
|
||||
options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
|
||||
for i=1:rows(options_list)
|
||||
switch options_list{i,1}
|
||||
case 'rotated'
|
||||
% triggers rotated slice iterations using a covariance
|
||||
% matrix from initial burn-in iterations
|
||||
% must be associated with:
|
||||
% <use_mh_covariance_matrix> or <slice_initialize_with_mode>
|
||||
% default = 0
|
||||
posterior_sampler_options.rotated = options_list{i,2};
|
||||
|
||||
case 'mode'
|
||||
% for multimodal posteriors, provide the list of modes as a
|
||||
% matrix, ordered by column, i.e. [x1 x2 x3] for three
|
||||
% modes x1 x2 x3
|
||||
% MR note: not sure this is possible with the
|
||||
% read_key_value_string ???
|
||||
% if this is not possible <mode_files> does to job in any case
|
||||
% This will automatically trigger <rotated>
|
||||
% default = []
|
||||
tmp_mode = options_list{i,2};
|
||||
for j=1:size(tmp_mode,2)
|
||||
posterior_sampler_options.mode(j).m = tmp_mode(:,j);
|
||||
end
|
||||
|
||||
case 'mode_files'
|
||||
% for multimodal posteriors provide the name of
|
||||
% a file containing a variable array xparams = [nparam * nmodes]
|
||||
% one column per mode. With this info, the code will automatically
|
||||
% set the <mode> option.
|
||||
% This will automatically trigger <rotated>
|
||||
% default = []
|
||||
posterior_sampler_options.mode_files = options_list{i,2};
|
||||
|
||||
case 'slice_initialize_with_mode'
|
||||
% the default for slice is to set mode_compute = 0 in the
|
||||
% preprocessor and start the chain(s) from a random location in the prior.
|
||||
% This option first runs the optimizer and then starts the
|
||||
% chain from the mode. Associated with optios <rotated>, it will
|
||||
% use invhess from the mode to perform rotated slice
|
||||
% iterations.
|
||||
% default = 0
|
||||
posterior_sampler_options.slice_initialize_with_mode = options_list{i,2};
|
||||
|
||||
case 'initial_step_size'
|
||||
% sets the initial size of the interval in the STEPPING-OUT PROCEDURE
|
||||
% the initial_step_size must be a real number in [0, 1],
|
||||
% and it sets the size as a proportion of the prior bounds,
|
||||
% i.e. the size will be initial_step_size*(UB-LB)
|
||||
% slice sampler requires prior_truncation > 0!
|
||||
% default = 0.8
|
||||
if options_list{i,2}<=0 || options_list{i,2}>=1
|
||||
error('check_posterior_sampler_options:: slice initial_step_size must be between 0 and 1')
|
||||
else
|
||||
posterior_sampler_options.initial_step_size=options_list{i,2};
|
||||
end
|
||||
case 'use_mh_covariance_matrix'
|
||||
% in association with <rotated> indicates to use the
|
||||
% covariance matrix from previous iterations to define the
|
||||
% rotated slice
|
||||
% default = 0
|
||||
posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
|
||||
options_.use_mh_covariance_matrix = options_list{i,2};
|
||||
% default options
|
||||
posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.rwmh);
|
||||
|
||||
case 'save_tmp_file'
|
||||
posterior_sampler_options.save_tmp_file = options_list{i,2};
|
||||
|
||||
otherwise
|
||||
warning(['slice_sampler: Unknown option (' options_list{i,1} ')!'])
|
||||
% user defined options
|
||||
if ~isempty(options_.posterior_sampler_options.sampling_opt)
|
||||
options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
|
||||
for i=1:rows(options_list)
|
||||
switch options_list{i,1}
|
||||
|
||||
case 'proposal_distribution'
|
||||
if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
|
||||
strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
|
||||
error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
|
||||
'rand_multivariate_student or rand_multivariate_normal as options']);
|
||||
else
|
||||
posterior_sampler_options.proposal_distribution=options_list{i,2};
|
||||
end
|
||||
|
||||
|
||||
case 'student_degrees_of_freedom'
|
||||
if options_list{i,2} <= 0
|
||||
error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
|
||||
else
|
||||
posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
|
||||
end
|
||||
|
||||
case 'use_mh_covariance_matrix'
|
||||
% indicates to use the covariance matrix from previous iterations to
|
||||
% define the covariance of the proposal distribution
|
||||
% default = 0
|
||||
posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
|
||||
options_.use_mh_covariance_matrix = options_list{i,2};
|
||||
case 'scale_file'
|
||||
% load optimal_mh_scale parameter if previous run was with mode_compute=6
|
||||
% will overwrite jscale from set_prior.m
|
||||
if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file')
|
||||
tmp = load(options_list{i,2},'Scale');
|
||||
global bayestopt_
|
||||
bayestopt_.mh_jscale = tmp.Scale;
|
||||
options_.mh_jscale = tmp.Scale;
|
||||
bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale;
|
||||
% options_.mh_init_scale = 2*options_.mh_jscale;
|
||||
else
|
||||
error('initial_estimation_checks:: The specified mh_scale_file does not exist.')
|
||||
end
|
||||
case 'save_tmp_file'
|
||||
posterior_sampler_options.save_tmp_file = options_list{i,2};
|
||||
otherwise
|
||||
warning(['rwmh_sampler: Unknown option (' options_list{i,1} ')!'])
|
||||
end
|
||||
end
|
||||
|
||||
% slice posterior sampler does not require mode or hessian to run
|
||||
% needs to be set to 1 to skip parts in dynare_estimation_1.m
|
||||
% requiring posterior maximization/calibrated smoother before MCMC
|
||||
options_.mh_posterior_mode_estimation=1;
|
||||
|
||||
if ~ posterior_sampler_options.slice_initialize_with_mode
|
||||
end
|
||||
|
||||
case 'tailored_random_block_metropolis_hastings'
|
||||
posterior_sampler_options.parallel_bar_refresh_rate=5;
|
||||
posterior_sampler_options.serial_bar_refresh_rate=1;
|
||||
posterior_sampler_options.parallel_bar_title='TaRB-MH';
|
||||
posterior_sampler_options.serial_bar_title='TaRB Metropolis-Hastings';
|
||||
|
||||
% default options
|
||||
posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.tarb);
|
||||
|
||||
% user defined options
|
||||
if ~isempty(options_.posterior_sampler_options.sampling_opt)
|
||||
options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
|
||||
for i=1:rows(options_list)
|
||||
|
||||
switch options_list{i,1}
|
||||
|
||||
case 'proposal_distribution'
|
||||
if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
|
||||
strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
|
||||
error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
|
||||
'rand_multivariate_student or rand_multivariate_normal as options']);
|
||||
else
|
||||
posterior_sampler_options.proposal_distribution=options_list{i,2};
|
||||
end
|
||||
|
||||
|
||||
case 'student_degrees_of_freedom'
|
||||
if options_list{i,2} <= 0
|
||||
error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
|
||||
else
|
||||
posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
|
||||
end
|
||||
|
||||
case 'mode_compute'
|
||||
posterior_sampler_options.mode_compute=options_list{i,2};
|
||||
|
||||
case 'optim'
|
||||
posterior_sampler_options.optim_opt=options_list{i,2};
|
||||
|
||||
case 'new_block_probability'
|
||||
if options_list{i,2}<0 || options_list{i,2}>1
|
||||
error('check_posterior_sampler_options:: The tarb new_block_probability must be between 0 and 1!')
|
||||
else
|
||||
posterior_sampler_options.new_block_probability=options_list{i,2};
|
||||
end
|
||||
case 'scale_file'
|
||||
% load optimal_mh_scale parameter if previous run was with mode_compute=6
|
||||
% will overwrite jscale from set_prior.m
|
||||
if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file')
|
||||
tmp = load(options_list{i,2},'Scale');
|
||||
global bayestopt_
|
||||
bayestopt_.mh_jscale = tmp.Scale;
|
||||
options_.mh_jscale = tmp.Scale;
|
||||
bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale;
|
||||
% options_.mh_init_scale = 2*options_.mh_jscale;
|
||||
else
|
||||
error('initial_estimation_checks:: The specified scale_file does not exist.')
|
||||
end
|
||||
case 'save_tmp_file'
|
||||
posterior_sampler_options.save_tmp_file = options_list{i,2};
|
||||
|
||||
otherwise
|
||||
warning(['tarb_sampler: Unknown option (' options_list{i,1} ')!'])
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
case 'independent_metropolis_hastings'
|
||||
posterior_sampler_options.parallel_bar_refresh_rate=50;
|
||||
posterior_sampler_options.serial_bar_refresh_rate=3;
|
||||
posterior_sampler_options.parallel_bar_title='IMH';
|
||||
posterior_sampler_options.serial_bar_title='Ind. Metropolis-Hastings';
|
||||
|
||||
% default options
|
||||
posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.imh);
|
||||
|
||||
% user defined options
|
||||
if ~isempty(options_.posterior_sampler_options.sampling_opt)
|
||||
options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
|
||||
for i=1:rows(options_list)
|
||||
switch options_list{i,1}
|
||||
|
||||
case 'proposal_distribution'
|
||||
if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
|
||||
strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
|
||||
error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
|
||||
'rand_multivariate_student or rand_multivariate_normal as options']);
|
||||
else
|
||||
posterior_sampler_options.proposal_distribution=options_list{i,2};
|
||||
end
|
||||
|
||||
|
||||
case 'student_degrees_of_freedom'
|
||||
if options_list{i,2} <= 0
|
||||
error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
|
||||
else
|
||||
posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
|
||||
end
|
||||
|
||||
case 'use_mh_covariance_matrix'
|
||||
% indicates to use the covariance matrix from previous iterations to
|
||||
% define the covariance of the proposal distribution
|
||||
% default = 0
|
||||
posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
|
||||
options_.use_mh_covariance_matrix = options_list{i,2};
|
||||
|
||||
case 'save_tmp_file'
|
||||
posterior_sampler_options.save_tmp_file = options_list{i,2};
|
||||
|
||||
otherwise
|
||||
warning(['imh_sampler: Unknown option (' options_list{i,1} ')!'])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
case 'slice'
|
||||
posterior_sampler_options.parallel_bar_refresh_rate=1;
|
||||
posterior_sampler_options.serial_bar_refresh_rate=1;
|
||||
posterior_sampler_options.parallel_bar_title='SLICE';
|
||||
posterior_sampler_options.serial_bar_title='SLICE';
|
||||
|
||||
% default options
|
||||
posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.slice);
|
||||
|
||||
% user defined options
|
||||
if ~isempty(options_.posterior_sampler_options.sampling_opt)
|
||||
options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
|
||||
for i=1:rows(options_list)
|
||||
switch options_list{i,1}
|
||||
case 'rotated'
|
||||
% triggers rotated slice iterations using a covariance
|
||||
% matrix from initial burn-in iterations
|
||||
% must be associated with:
|
||||
% <use_mh_covariance_matrix> or <slice_initialize_with_mode>
|
||||
% default = 0
|
||||
posterior_sampler_options.rotated = options_list{i,2};
|
||||
|
||||
case 'mode'
|
||||
% for multimodal posteriors, provide the list of modes as a
|
||||
% matrix, ordered by column, i.e. [x1 x2 x3] for three
|
||||
% modes x1 x2 x3
|
||||
% MR note: not sure this is possible with the
|
||||
% read_key_value_string ???
|
||||
% if this is not possible <mode_files> does to job in any case
|
||||
% This will automatically trigger <rotated>
|
||||
% default = []
|
||||
tmp_mode = options_list{i,2};
|
||||
for j=1:size(tmp_mode,2)
|
||||
posterior_sampler_options.mode(j).m = tmp_mode(:,j);
|
||||
end
|
||||
|
||||
case 'mode_files'
|
||||
% for multimodal posteriors provide the name of
|
||||
% a file containing a variable array xparams = [nparam * nmodes]
|
||||
% one column per mode. With this info, the code will automatically
|
||||
% set the <mode> option.
|
||||
% This will automatically trigger <rotated>
|
||||
% default = []
|
||||
posterior_sampler_options.mode_files = options_list{i,2};
|
||||
|
||||
case 'slice_initialize_with_mode'
|
||||
% the default for slice is to set mode_compute = 0 in the
|
||||
% preprocessor and start the chain(s) from a random location in the prior.
|
||||
% This option first runs the optimizer and then starts the
|
||||
% chain from the mode. Associated with optios <rotated>, it will
|
||||
% use invhess from the mode to perform rotated slice
|
||||
% iterations.
|
||||
% default = 0
|
||||
posterior_sampler_options.slice_initialize_with_mode = options_list{i,2};
|
||||
|
||||
case 'initial_step_size'
|
||||
% sets the initial size of the interval in the STEPPING-OUT PROCEDURE
|
||||
% the initial_step_size must be a real number in [0, 1],
|
||||
% and it sets the size as a proportion of the prior bounds,
|
||||
% i.e. the size will be initial_step_size*(UB-LB)
|
||||
% slice sampler requires prior_truncation > 0!
|
||||
% default = 0.8
|
||||
if options_list{i,2}<=0 || options_list{i,2}>=1
|
||||
error('check_posterior_sampler_options:: slice initial_step_size must be between 0 and 1')
|
||||
else
|
||||
posterior_sampler_options.initial_step_size=options_list{i,2};
|
||||
end
|
||||
case 'use_mh_covariance_matrix'
|
||||
% in association with <rotated> indicates to use the
|
||||
% covariance matrix from previous iterations to define the
|
||||
% rotated slice
|
||||
% default = 0
|
||||
posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
|
||||
options_.use_mh_covariance_matrix = options_list{i,2};
|
||||
|
||||
case 'save_tmp_file'
|
||||
posterior_sampler_options.save_tmp_file = options_list{i,2};
|
||||
|
||||
otherwise
|
||||
warning(['slice_sampler: Unknown option (' options_list{i,1} ')!'])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
% slice posterior sampler does not require mode or hessian to run
|
||||
% needs to be set to 1 to skip parts in dynare_estimation_1.m
|
||||
% requiring posterior maximization/calibrated smoother before MCMC
|
||||
options_.mh_posterior_mode_estimation=1;
|
||||
|
||||
if ~ posterior_sampler_options.slice_initialize_with_mode
|
||||
% by default, slice sampler should trigger
|
||||
% mode_compute=0 and
|
||||
% mh_replic=100 (much smaller than the default mh_replic=20000 of RWMH)
|
||||
options_.mode_compute = 0;
|
||||
options_.cova_compute = 0;
|
||||
else
|
||||
if (isequal(options_.mode_compute,0) && isempty(options_.mode_file) )
|
||||
skipline()
|
||||
disp('check_posterior_sampler_options:: You have specified the option "slice_initialize_with_mode"')
|
||||
disp('check_posterior_sampler_options:: to initialize the slice sampler using mode information')
|
||||
disp('check_posterior_sampler_options:: but no mode file nor posterior maximization is selected,')
|
||||
error('check_posterior_sampler_options:: The option "slice_initialize_with_mode" is inconsistent with mode_compute=0 or empty mode_file.')
|
||||
else
|
||||
options_.mh_posterior_mode_estimation=0;
|
||||
end
|
||||
end
|
||||
|
||||
if any(isinf(bounds.lb)) || any(isinf(bounds.ub))
|
||||
options_.mode_compute = 0;
|
||||
options_.cova_compute = 0;
|
||||
else
|
||||
if (isequal(options_.mode_compute,0) && isempty(options_.mode_file) )
|
||||
skipline()
|
||||
disp('some priors are unbounded and prior_trunc is set to zero')
|
||||
error('The option "slice" is inconsistent with prior_trunc=0.')
|
||||
end
|
||||
|
||||
% moreover slice must be associated to:
|
||||
% options_.mh_posterior_mode_estimation = 0;
|
||||
% this is done below, but perhaps preprocessing should do this?
|
||||
|
||||
if ~isempty(posterior_sampler_options.mode)
|
||||
% multimodal case
|
||||
posterior_sampler_options.rotated = 1;
|
||||
posterior_sampler_options.WR=[];
|
||||
end
|
||||
% posterior_sampler_options = set_default_option(posterior_sampler_options,'mode_files',[]);
|
||||
|
||||
|
||||
posterior_sampler_options.W1=posterior_sampler_options.initial_step_size*(bounds.ub-bounds.lb);
|
||||
if options_.load_mh_file
|
||||
posterior_sampler_options.slice_initialize_with_mode = 0;
|
||||
disp('check_posterior_sampler_options:: You have specified the option "slice_initialize_with_mode"')
|
||||
disp('check_posterior_sampler_options:: to initialize the slice sampler using mode information')
|
||||
disp('check_posterior_sampler_options:: but no mode file nor posterior maximization is selected,')
|
||||
error('check_posterior_sampler_options:: The option "slice_initialize_with_mode" is inconsistent with mode_compute=0 or empty mode_file.')
|
||||
else
|
||||
if ~posterior_sampler_options.slice_initialize_with_mode
|
||||
posterior_sampler_options.invhess=[];
|
||||
end
|
||||
options_.mh_posterior_mode_estimation=0;
|
||||
end
|
||||
|
||||
if ~isempty(posterior_sampler_options.mode_files) % multimodal case
|
||||
modes = posterior_sampler_options.mode_files; % these can be also mean files from previous parallel slice chains
|
||||
load(modes, 'xparams')
|
||||
if size(xparams,2)<2
|
||||
error(['check_posterior_sampler_options:: Variable xparams loaded in file <' modes '> has size [' int2str(size(xparams,1)) 'x' int2str(size(xparams,2)) ']: it must contain at least two columns, to allow multi-modal sampling.'])
|
||||
end
|
||||
for j=1:size(xparams,2)
|
||||
mode(j).m=xparams(:,j);
|
||||
end
|
||||
posterior_sampler_options.mode = mode;
|
||||
posterior_sampler_options.rotated = 1;
|
||||
posterior_sampler_options.WR=[];
|
||||
end
|
||||
|
||||
if any(isinf(bounds.lb)) || any(isinf(bounds.ub))
|
||||
skipline()
|
||||
disp('some priors are unbounded and prior_trunc is set to zero')
|
||||
error('The option "slice" is inconsistent with prior_trunc=0.')
|
||||
end
|
||||
|
||||
% moreover slice must be associated to:
|
||||
% options_.mh_posterior_mode_estimation = 0;
|
||||
% this is done below, but perhaps preprocessing should do this?
|
||||
|
||||
if ~isempty(posterior_sampler_options.mode)
|
||||
% multimodal case
|
||||
posterior_sampler_options.rotated = 1;
|
||||
posterior_sampler_options.WR=[];
|
||||
end
|
||||
% posterior_sampler_options = set_default_option(posterior_sampler_options,'mode_files',[]);
|
||||
|
||||
|
||||
posterior_sampler_options.W1=posterior_sampler_options.initial_step_size*(bounds.ub-bounds.lb);
|
||||
if options_.load_mh_file
|
||||
posterior_sampler_options.slice_initialize_with_mode = 0;
|
||||
else
|
||||
if ~posterior_sampler_options.slice_initialize_with_mode
|
||||
posterior_sampler_options.invhess=[];
|
||||
end
|
||||
|
||||
otherwise
|
||||
error('check_posterior_sampler_options:: Unknown posterior_sampling_method option %s ',posterior_sampler_options.posterior_sampling_method);
|
||||
end
|
||||
|
||||
if ~isempty(posterior_sampler_options.mode_files) % multimodal case
|
||||
modes = posterior_sampler_options.mode_files; % these can be also mean files from previous parallel slice chains
|
||||
load(modes, 'xparams')
|
||||
if size(xparams,2)<2
|
||||
error(['check_posterior_sampler_options:: Variable xparams loaded in file <' modes '> has size [' int2str(size(xparams,1)) 'x' int2str(size(xparams,2)) ']: it must contain at least two columns, to allow multi-modal sampling.'])
|
||||
end
|
||||
for j=1:size(xparams,2)
|
||||
mode(j).m=xparams(:,j);
|
||||
end
|
||||
posterior_sampler_options.mode = mode;
|
||||
posterior_sampler_options.rotated = 1;
|
||||
posterior_sampler_options.WR=[];
|
||||
end
|
||||
|
||||
otherwise
|
||||
error('check_posterior_sampler_options:: Unknown posterior_sampling_method option %s ',posterior_sampler_options.posterior_sampling_method);
|
||||
end
|
||||
|
||||
|
||||
return
|
||||
end
|
||||
|
||||
|
@ -434,6 +434,3 @@ fnam = fieldnames(sampler_options);
|
|||
for j=1:length(fnam)
|
||||
posterior_sampler_options.(fnam{j}) = sampler_options.(fnam{j});
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -1,13 +1,13 @@
|
|||
function [info,description] = check_prior_analysis_data(type,M_)
|
||||
% function [info,description] = check_prior_analysis_data(type,M_)
|
||||
% Checks the status of prior analysis and in particular if files need to be
|
||||
% Checks the status of prior analysis and in particular if files need to be
|
||||
% created or updated; called by prior_analysis.m
|
||||
%
|
||||
%
|
||||
% Inputs:
|
||||
% type [string] name of the posterior moment considered
|
||||
% M_ [structure] Dynare model structure
|
||||
%
|
||||
% Outputs:
|
||||
%
|
||||
% Outputs:
|
||||
% info [scalar] return code
|
||||
% info = 1; % prior_sampler has to be called first.
|
||||
% info = 2; % _prior_draws files have to be updated.
|
||||
|
@ -40,7 +40,7 @@ if nargout>1
|
|||
description = '';
|
||||
end
|
||||
|
||||
%% Get informations about prior draws files.
|
||||
%% Get informations about prior draws files.
|
||||
if ~exist([ M_.dname '/prior/draws'],'dir')
|
||||
disp('check_prior_analysis_data:: Can''t find any prior draws file!')
|
||||
return
|
||||
|
@ -65,7 +65,7 @@ else
|
|||
end
|
||||
return
|
||||
else
|
||||
info = 3; % Nothing to do!
|
||||
info = 3; % Nothing to do!
|
||||
if nargout>1
|
||||
description = 'prior draws files are up to date.';
|
||||
end
|
||||
|
@ -98,9 +98,9 @@ else
|
|||
name_of_the_last_prior_data_file = pdinfo(end).name;
|
||||
pdfdate = pdinfo(end).datenum;
|
||||
% /!\ REMARK /!\
|
||||
% The user can change the model or the value of a calibrated
|
||||
% parameter without changing the prior. In this case the (prior)
|
||||
% moments should be computed. But this case cannot be detected!!!
|
||||
% The user can change the model or the value of a calibrated
|
||||
% parameter without changing the prior. In this case the (prior)
|
||||
% moments should be computed. But this case cannot be detected!!!
|
||||
if pdfdate<date_of_the_last_prior_draw_file
|
||||
info = 5; % prior data files have to be updated.
|
||||
if nargout>1
|
||||
|
|
|
@ -5,7 +5,7 @@ function check_prior_bounds(xparam1,bounds,M_,estim_params_,options_,bayestopt_)
|
|||
% -xparam1 [double] vector of parameters to be estimated (initial values)
|
||||
% -bounds [vector] vector containing the lower and upper
|
||||
% bounds
|
||||
% -M_ [structure] characterizing the model.
|
||||
% -M_ [structure] characterizing the model.
|
||||
% -estim_params_ [structure] characterizing parameters to be estimated
|
||||
% -options_ [structure] characterizing the options
|
||||
% -bayestopt_ [structure] characterizing priors
|
||||
|
|
|
@ -1,17 +1,17 @@
|
|||
function [R,indef, E, P]=chol_SE(A,pivoting)
|
||||
% [R,indef, E, P]=chol_SE(A,pivoting)
|
||||
% Performs a (modified) Cholesky factorization of the form
|
||||
%
|
||||
% Performs a (modified) Cholesky factorization of the form
|
||||
%
|
||||
% P'*A*P + E = R'*R
|
||||
%
|
||||
%
|
||||
% As detailed in Schnabel/Eskow (1990), the factorization has 2 phases:
|
||||
% Phase 1: While A can still be positive definite, pivot on the maximum diagonal element.
|
||||
% Check that the standard Cholesky update would result in a positive diagonal
|
||||
% at the current iteration. If so, continue with the normal Cholesky update.
|
||||
% Otherwise switch to phase 2.
|
||||
% If A is safely positive definite, stage 1 is never left, resulting in
|
||||
% the standard Cholesky decomposition.
|
||||
%
|
||||
% at the current iteration. If so, continue with the normal Cholesky update.
|
||||
% Otherwise switch to phase 2.
|
||||
% If A is safely positive definite, stage 1 is never left, resulting in
|
||||
% the standard Cholesky decomposition.
|
||||
%
|
||||
% Phase 2: Pivot on the minimum of the negatives of the lower Gershgorin bound
|
||||
% estimates. To prevent negative diagonals, compute the amount to add to the
|
||||
% pivot element and add this. Then, do the Cholesky update and update the estimates of the
|
||||
|
@ -21,18 +21,18 @@ function [R,indef, E, P]=chol_SE(A,pivoting)
|
|||
% - During factorization, L=R' is stored in the lower triangle of the original matrix A,
|
||||
% miminizing the memory requirements
|
||||
% - Conforming with the original Schnabel/Eskow (1990) algorithm:
|
||||
% - at each iteration the updated Gershgorin bounds are estimated instead of recomputed,
|
||||
% - at each iteration the updated Gershgorin bounds are estimated instead of recomputed,
|
||||
% reducing the computational requirements from o(n^3) to o (n^2)
|
||||
% - For the last 2 by 2 submatrix, an eigenvalue-based decomposition is used
|
||||
% - While pivoting is not necessary, it improves the size of E, the add-on on to the diagonal. But this comes at
|
||||
% - While pivoting is not necessary, it improves the size of E, the add-on on to the diagonal. But this comes at
|
||||
% the cost of introduding a permutation.
|
||||
%
|
||||
%
|
||||
% Inputs
|
||||
%
|
||||
% Inputs
|
||||
% A [n*n] Matrix to be factorized
|
||||
% pivoting [scalar] dummy whether pivoting is used
|
||||
%
|
||||
% Outputs
|
||||
%
|
||||
% Outputs
|
||||
% R [n*n] originally stored in lower triangular portion of A, including the main diagonal
|
||||
%
|
||||
% E [n*1] Elements added to the diagonal of A
|
||||
|
@ -40,18 +40,18 @@ function [R,indef, E, P]=chol_SE(A,pivoting)
|
|||
% performing the decomposition
|
||||
%
|
||||
% REFERENCES:
|
||||
% This implementation is based on
|
||||
% This implementation is based on
|
||||
%
|
||||
% Robert B. Schnabel and Elizabeth Eskow. 1990. "A New Modified Cholesky
|
||||
% Factorization," SIAM Journal of Scientific Statistical Computating,
|
||||
% 11, 6: 1136-58.
|
||||
%
|
||||
%
|
||||
% Elizabeth Eskow and Robert B. Schnabel 1991. "Algorithm 695 - Software for a New Modified Cholesky
|
||||
% Factorization," ACM Transactions on Mathematical Software, Vol 17, No 3: 306-312
|
||||
%
|
||||
%
|
||||
%
|
||||
%
|
||||
% Author: Johannes Pfeifer based on Eskow/Schnabel (1991)
|
||||
%
|
||||
%
|
||||
% Copyright (C) 2015 Johannes Pfeifer
|
||||
% Copyright (C) 2015 Dynare Team
|
||||
% This file is part of Dynare.
|
||||
|
@ -148,7 +148,7 @@ for j = 1:n-1
|
|||
% Swap elements of the permutation vector
|
||||
itemp = P(j);
|
||||
P(j) = P(imaxd);
|
||||
P(imaxd) = itemp;
|
||||
P(imaxd) = itemp;
|
||||
end
|
||||
end
|
||||
% check to see whether the normal Cholesky update for this
|
||||
|
@ -183,13 +183,13 @@ for j = 1:n-1
|
|||
g=gersh_nested(A,j,n);
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
% PHASE 2
|
||||
if ~phase1
|
||||
if j ~= n-1
|
||||
if pivoting
|
||||
% Find the minimum negative Gershgorin bound
|
||||
[tmp,iming] = min(g(j:n));
|
||||
[tmp,iming] = min(g(j:n));
|
||||
iming=iming+j-1;
|
||||
% Pivot to the top the row and column with the
|
||||
% minimum negative Gershgorin bound
|
||||
|
@ -229,9 +229,9 @@ for j = 1:n-1
|
|||
end
|
||||
% Calculate delta and add to the diagonal. delta=max{0,-A(j,j) + max{normj,taugam},delta_previous}
|
||||
% where normj=sum of |A(i,j)|,for i=1,n, delta_previous is the delta computed at the previous iter and taugam is tau1*gamma.
|
||||
|
||||
|
||||
normj=sum(abs(A(j+1:n,j)));
|
||||
|
||||
|
||||
delta = max([0;delta;-A(j,j)+normj;-A(j,j)+taugam]); % get adjustment based on formula on bottom of p. 309 of Eskow/Schnabel (1991)
|
||||
|
||||
E(j) = delta;
|
||||
|
@ -259,9 +259,9 @@ for j = 1:n-1
|
|||
% Find eigenvalues of final 2 by 2 submatrix
|
||||
% Find delta such that:
|
||||
% 1. the l2 condition number of the final 2X2 submatrix + delta*I <= tau2
|
||||
% 2. delta >= previous delta,
|
||||
% 2. delta >= previous delta,
|
||||
% 3. min(eigvals) + delta >= tau2 * gamma, where min(eigvals) is the smallest eigenvalue of the final 2X2 submatrix
|
||||
|
||||
|
||||
A(n-1,n)=A(n,n-1); %set value above diagonal for computation of eigenvalues
|
||||
eigvals = eig(A(n-1:n,n-1:n));
|
||||
delta = max([ 0 ; delta ; -min(eigvals)+tau2*max((max(eigvals)-min(eigvals))/(1-tau1),gammma) ]); %Formula 5.3.2 of Schnabel/Eskow (1990)
|
||||
|
@ -272,7 +272,7 @@ for j = 1:n-1
|
|||
E(n-1) = delta;
|
||||
E(n) = delta;
|
||||
end
|
||||
|
||||
|
||||
% Final update
|
||||
A(n-1,n-1) = sqrt(A(n-1,n-1));
|
||||
A(n,n-1) = A(n,n-1)/A(n-1,n-1);
|
||||
|
@ -306,4 +306,3 @@ for ii = j:n
|
|||
g(ii) = sum_up_to_i + sum_after_i- A(ii,ii);
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -58,5 +58,5 @@ if writelistofroutinestobecleared
|
|||
return
|
||||
end
|
||||
|
||||
list_of_functions_to_be_cleared;
|
||||
list_of_functions_to_be_cleared;
|
||||
clear(list_of_functions{:});
|
|
@ -42,7 +42,7 @@ if isempty(varargin) || ( isequal(length(varargin), 1) && isequal(varargin{1},'h
|
|||
return
|
||||
end
|
||||
|
||||
global options_ M_ estim_params_ bayestopt_ oo_
|
||||
global options_ M_ estim_params_ bayestopt_ oo_
|
||||
|
||||
donesomething = false;
|
||||
|
||||
|
@ -53,11 +53,11 @@ end
|
|||
|
||||
if (size(estim_params_.var_endo,1) || size(estim_params_.corrn,1))
|
||||
% Prior over measurement errors are defined...
|
||||
if ((isfield(options_,'varobs') && isempty(options_.varobs)) || ~isfield(options_,'varobs'))
|
||||
% ... But the list of observed variabled is not yet defined.
|
||||
warning('Prior detected on measurement erros, but no list of observed variables (varobs is missing)!')
|
||||
return
|
||||
end
|
||||
if ((isfield(options_,'varobs') && isempty(options_.varobs)) || ~isfield(options_,'varobs'))
|
||||
% ... But the list of observed variabled is not yet defined.
|
||||
warning('Prior detected on measurement erros, but no list of observed variables (varobs is missing)!')
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
% Fill or update bayestopt_ structure
|
||||
|
@ -114,7 +114,7 @@ if ismember('optimize', varargin) % Prior optimization.
|
|||
end
|
||||
|
||||
if ismember('moments', varargin) % Prior simulations (2nd order moments).
|
||||
% Set estimated parameters to the prior mode...
|
||||
% Set estimated parameters to the prior mode...
|
||||
xparam1 = BayesOptions.p5;
|
||||
% ... Except for uniform priors (use the prior mean)!
|
||||
k = find(isnan(xparam1));
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
function collect_latex_files
|
||||
% function collect_LaTeX_Files;
|
||||
% Creates TeX-File embedding all eps-loaders created for current mod-file
|
||||
%
|
||||
%
|
||||
% Inputs: none
|
||||
%
|
||||
% Notes:
|
||||
%
|
||||
% Notes:
|
||||
% - The packages loaded enable pdflatex to run
|
||||
% - The _dynamic and _static TeX-model files are not included as they are standalone TeX-files
|
||||
|
||||
|
@ -45,11 +45,11 @@ TeX_Files=dir([M_.fname,'*.tex']);
|
|||
for ii=1:length(TeX_Files)
|
||||
[pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
|
||||
if ~strcmp(TeX_Files(ii).name,f_name_binder) && ...
|
||||
~strcmp(TeX_Files(ii).name,[M_.fname,'_dynamic.tex']) && ...
|
||||
~strcmp(TeX_Files(ii).name,[M_.fname,'_static.tex']) && ...
|
||||
~strcmp(TeX_Files(ii).name,[M_.fname,'_original.tex']) && ...
|
||||
~strcmp(TeX_Files(ii).name,[M_.fname,'_TeX_binder.tex'])
|
||||
fprintf(fid,'%s \n',['\include{',f_name,'}']);
|
||||
~strcmp(TeX_Files(ii).name,[M_.fname,'_dynamic.tex']) && ...
|
||||
~strcmp(TeX_Files(ii).name,[M_.fname,'_static.tex']) && ...
|
||||
~strcmp(TeX_Files(ii).name,[M_.fname,'_original.tex']) && ...
|
||||
~strcmp(TeX_Files(ii).name,[M_.fname,'_TeX_binder.tex'])
|
||||
fprintf(fid,'%s \n',['\include{',f_name,'}']);
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -58,7 +58,7 @@ TeX_Files=dir([M_.dname filesep 'Output' filesep M_.fname '*.tex']);
|
|||
for ii=1:length(TeX_Files)
|
||||
[pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
|
||||
if ~strcmp(TeX_Files(ii).name,f_name_binder)
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/Output' '/',f_name,'}']);
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/Output' '/',f_name,'}']);
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -67,7 +67,7 @@ TeX_Files=dir([M_.dname filesep 'graphs' filesep M_.fname '*.tex']);
|
|||
for ii=1:length(TeX_Files)
|
||||
[pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
|
||||
if ~strcmp(TeX_Files(ii).name,f_name_binder)
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/graphs' '/',f_name,'}']);
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/graphs' '/',f_name,'}']);
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -76,7 +76,7 @@ TeX_Files=dir([M_.dname filesep 'identification' filesep M_.fname '*.tex']);
|
|||
for ii=1:length(TeX_Files)
|
||||
[pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
|
||||
if ~strcmp(TeX_Files(ii).name,f_name_binder)
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/identification' '/',f_name,'}']);
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/identification' '/',f_name,'}']);
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -86,7 +86,7 @@ TeX_Files=dir([M_.dname filesep 'identification' filesep 'Output' filesep M_.fna
|
|||
for ii=1:length(TeX_Files)
|
||||
[pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
|
||||
if ~strcmp(TeX_Files(ii).name,f_name_binder)
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/identification/Output' '/',f_name,'}']);
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/identification/Output' '/',f_name,'}']);
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -95,7 +95,7 @@ TeX_Files=dir([M_.dname filesep 'gsa' filesep M_.fname '*.tex']);
|
|||
for ii=1:length(TeX_Files)
|
||||
[pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
|
||||
if ~strcmp(TeX_Files(ii).name,f_name_binder)
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/gsa' '/',f_name,'}']);
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/gsa' '/',f_name,'}']);
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -104,7 +104,7 @@ TeX_Files=dir([M_.dname filesep 'gsa' filesep 'Output' filesep M_.fname '*.tex'
|
|||
for ii=1:length(TeX_Files)
|
||||
[pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
|
||||
if ~strcmp(TeX_Files(ii).name,f_name_binder)
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/gsa/Output' '/',f_name,'}']);
|
||||
fprintf(fid,'%s \n',['\include{', M_.dname '/gsa/Output' '/',f_name,'}']);
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -1,30 +1,30 @@
|
|||
function [Pstar,Pinf] = compute_Pinf_Pstar(mf,T,R,Q,qz_criterium, restrict_columns)
|
||||
% function [Z,ST,QT,R1,Pstar,Pinf] = schur_statespace_transformation(mf,T,R,Q,qz_criterium, restrict_columns)
|
||||
% Kitagawa transformation of state space system with a quasi-triangular
|
||||
% transition matrix with unit roots at the top, but excluding zero columns of the transition matrix.
|
||||
% transition matrix with unit roots at the top, but excluding zero columns of the transition matrix.
|
||||
% Computation of Pstar and Pinf for Durbin and Koopman Diffuse filter
|
||||
%
|
||||
% The transformed state space is
|
||||
% The transformed state space is
|
||||
% y = [ss; z; x];
|
||||
% s = static variables (zero columns of T)
|
||||
% z = unit roots
|
||||
% x = stable roots
|
||||
% ss = s - z = stationarized static variables
|
||||
%
|
||||
% INPUTS
|
||||
%
|
||||
% INPUTS
|
||||
% mf [integer] vector of indices of observed variables in
|
||||
% state vector
|
||||
% T [double] matrix of transition
|
||||
% R [double] matrix of structural shock effects
|
||||
% Q [double] matrix of covariance of structural shocks
|
||||
% qz_criterium [double] numerical criterium for unit roots
|
||||
%
|
||||
% OUTPUTS
|
||||
% qz_criterium [double] numerical criterium for unit roots
|
||||
%
|
||||
% OUTPUTS
|
||||
% Pstar [double] matrix of covariance of stationary part
|
||||
% Pinf [double] matrix of covariance initialization for
|
||||
% nonstationary part
|
||||
%
|
||||
% ALGORITHM
|
||||
% nonstationary part
|
||||
%
|
||||
% ALGORITHM
|
||||
% Real Schur transformation of transition equation
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
|
@ -49,7 +49,7 @@ function [Pstar,Pinf] = compute_Pinf_Pstar(mf,T,R,Q,qz_criterium, restrict_colum
|
|||
|
||||
np = size(T,1);
|
||||
|
||||
% perform Kitagawa transformation
|
||||
% perform Kitagawa transformation
|
||||
[QT,ST] = schur(T);
|
||||
e1 = abs(ordeig(ST)) > 2-qz_criterium;
|
||||
[QT,ST] = ordschur(QT,ST,e1);
|
||||
|
@ -112,4 +112,3 @@ end
|
|||
|
||||
Pinf = QT*Pinf*QT';
|
||||
Pstar = QT*Pstar*QT';
|
||||
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
function [posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at_the_mode] = compute_mh_covariance_matrix()
|
||||
% Estimation of the posterior covariance matrix, posterior mean, posterior mode and evaluation of the posterior kernel at the
|
||||
% estimated mode, using the draws from a metropolis-hastings. The estimated posterior mode and covariance matrix are saved in
|
||||
% a file <M_.fname>_mh_mode.mat.
|
||||
%
|
||||
% INPUTS
|
||||
% a file <M_.fname>_mh_mode.mat.
|
||||
%
|
||||
% INPUTS
|
||||
% None.
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% o posterior_mean [double] (n*1) vector, posterior expectation of the parameters.
|
||||
% o posterior_covariance [double] (n*n) matrix, posterior covariance of the parameters (computed from previous metropolis hastings).
|
||||
% o posterior_mode [double] (n*1) vector, posterior mode of the parameters.
|
||||
% o posterior_mode [double] (n*1) vector, posterior mode of the parameters.
|
||||
% o posterior_kernel_at_the_mode [double] scalar.
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
|
@ -62,7 +62,7 @@ offset = 0;
|
|||
for b=1:nblck
|
||||
first_line = FirstLine;
|
||||
for n = FirstMhFile:TotalNumberOfMhFiles
|
||||
load([ BaseName '_mh' int2str(n) '_blck' int2str(b) '.mat'],'x2','logpo2');
|
||||
load([ BaseName '_mh' int2str(n) '_blck' int2str(b) '.mat'],'x2','logpo2');
|
||||
[tmp,idx] = max(logpo2);
|
||||
if tmp>posterior_kernel_at_the_mode
|
||||
posterior_kernel_at_the_mode = tmp;
|
||||
|
|
|
@ -4,10 +4,10 @@ function moments=compute_model_moments(dr,M_,options_)
|
|||
% dr: structure describing model solution
|
||||
% M_: structure of Dynare options
|
||||
% options_
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% moments: a cell array containing requested moments
|
||||
%
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% none
|
||||
|
||||
|
|
|
@ -2,14 +2,14 @@ function oo_ = compute_moments_varendo(type,options_,M_,oo_,var_list_)
|
|||
% Computes the second order moments (autocorrelation function, covariance
|
||||
% matrix and variance decomposition) distributions for all the endogenous variables selected in
|
||||
% var_list_. The results are saved in oo_
|
||||
%
|
||||
%
|
||||
% INPUTS:
|
||||
% type [string] 'posterior' or 'prior'
|
||||
% options_ [structure] Dynare structure.
|
||||
% M_ [structure] Dynare structure (related to model definition).
|
||||
% oo_ [structure] Dynare structure (results).
|
||||
% var_list_ [string] Array of string with endogenous variable names.
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% oo_ [structure] Dynare structure (results).
|
||||
%
|
||||
|
@ -31,7 +31,7 @@ function oo_ = compute_moments_varendo(type,options_,M_,oo_,var_list_)
|
|||
% 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/>.
|
||||
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
fprintf('Estimation::compute_moments_varendo: I''m computing endogenous moments (this may take a while)... ');
|
||||
|
@ -129,7 +129,7 @@ if M_.exo_nbr > 1
|
|||
headers = char(' ',headers);
|
||||
lh = size(deblank(var_list_),2)+2;
|
||||
dyntable(options_,title,headers,deblank(var_list_),100* ...
|
||||
temp,lh,8,2);
|
||||
temp,lh,8,2);
|
||||
if options_.TeX
|
||||
headers=M_.exo_names_tex;
|
||||
headers = char(' ',headers);
|
||||
|
@ -166,7 +166,7 @@ if M_.exo_nbr > 1
|
|||
headers = char(' ',headers);
|
||||
lh = size(deblank(var_list_),2)+2;
|
||||
dyntable(options_,title_print,headers,deblank(var_list_),100* ...
|
||||
temp(:,:,step_iter),lh,8,2);
|
||||
temp(:,:,step_iter),lh,8,2);
|
||||
if options_.TeX
|
||||
headers=M_.exo_names_tex;
|
||||
headers = char(' ',headers);
|
||||
|
|
|
@ -16,7 +16,7 @@ function overallacceptanceratio = compute_overall_acceptance_ratio(MetropolisFol
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
BaseName = [MetropolisFolder filesep ModelName];
|
||||
mh_history_files = dir([BaseName '_mh_history_*.mat']);
|
||||
|
||||
|
@ -24,12 +24,12 @@ n = length(mh_history_files);
|
|||
|
||||
load([BaseName '_mh_history_' num2str(0)]);
|
||||
TotalNumberOfDraws = record.MhDraws(end,1);
|
||||
TotalNumberOfAcceptedProposals = record.AcceptanceRatio*record.MhDraws(end,1);
|
||||
TotalNumberOfAcceptedProposals = record.AcceptanceRatio*record.MhDraws(end,1);
|
||||
|
||||
for i=2:n
|
||||
load([BaseName '_mh_history_' num2str(i-1)]);
|
||||
TotalNumberOfDraws = TotalNumberOfDraws + record.MhDraws(end,1);
|
||||
TotalNumberOfAcceptedProposals = TotalNumberOfAcceptedProposals + record.AcceptanceRatio*record.MhDraws(end,1);
|
||||
TotalNumberOfAcceptedProposals = TotalNumberOfAcceptedProposals + record.AcceptanceRatio*record.MhDraws(end,1);
|
||||
end
|
||||
|
||||
overallacceptanceratio = TotalNumberOfAcceptedProposals/TotalNumberOfDraws;
|
|
@ -1,14 +1,14 @@
|
|||
function ConditionalVarianceDecomposition = conditional_variance_decomposition(StateSpaceModel, Steps, SubsetOfVariables,sigma_e_is_diagonal)
|
||||
% This function computes the conditional variance decomposition of a given state space model
|
||||
% for a subset of endogenous variables.
|
||||
%
|
||||
% INPUTS
|
||||
%
|
||||
% INPUTS
|
||||
% StateSpaceModel [structure] Specification of the state space model.
|
||||
% Steps [integer] 1*h vector of dates.
|
||||
% SubsetOfVariables [integer] 1*q vector of indices.
|
||||
%
|
||||
% OUTPUTS
|
||||
% ConditionalVarianceDecomposition [double] [n h p] array, where
|
||||
%
|
||||
% OUTPUTS
|
||||
% ConditionalVarianceDecomposition [double] [n h p] array, where
|
||||
% n is equal to length(SubsetOfVariables)
|
||||
% h is the number of Steps
|
||||
% p is the number of state innovations and
|
||||
|
@ -77,7 +77,7 @@ for h = 1:length(Steps)
|
|||
SumOfVariances(:,h) = sum(ConditionalVariance(:,h,:),3);
|
||||
end
|
||||
|
||||
ConditionalVarianceDecomposition = zeros(NumberOfVariables,length(Steps),number_of_state_innovations);
|
||||
ConditionalVarianceDecomposition = zeros(NumberOfVariables,length(Steps),number_of_state_innovations);
|
||||
for i=1:number_of_state_innovations
|
||||
for h = 1:length(Steps)
|
||||
ConditionalVarianceDecomposition(:,h,i) = squeeze(ConditionalVariance(:,h,i))./SumOfVariances(:,h);
|
||||
|
|
|
@ -9,7 +9,7 @@ function oo_ = ...
|
|||
% dname [string] directory name where to save
|
||||
% fname [string] name of the mod-file
|
||||
% Steps [integers] horizons at which to conduct decomposition
|
||||
% exonames [string] (n_exo*char_length) character array with names of exogenous variables
|
||||
% exonames [string] (n_exo*char_length) character array with names of exogenous variables
|
||||
% exo [string] name of current exogenous
|
||||
% variable
|
||||
% var_list [string] (n_endo*char_length) character array with name
|
||||
|
@ -106,7 +106,7 @@ for i=1:length(Steps)
|
|||
p_density(:,:,i) = pp_density;
|
||||
else
|
||||
[pp_mean, pp_median, pp_var, hpd_interval, pp_deciles] = ...
|
||||
posterior_moments(tmp(:,i),0,mh_conf_sig);
|
||||
posterior_moments(tmp(:,i),0,mh_conf_sig);
|
||||
end
|
||||
p_mean(i) = pp_mean;
|
||||
p_median(i) = pp_median;
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
function oo_ = McMCDiagnostics(options_, estim_params_, M_, oo_)
|
||||
% function McMCDiagnostics
|
||||
% Computes convergence tests
|
||||
%
|
||||
% INPUTS
|
||||
% Computes convergence tests
|
||||
%
|
||||
% INPUTS
|
||||
% options_ [structure]
|
||||
% estim_params_ [structure]
|
||||
% M_ [structure]
|
||||
%
|
||||
% OUTPUTS
|
||||
% oo_ [structure]
|
||||
% OUTPUTS
|
||||
% oo_ [structure]
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% none
|
||||
|
@ -82,12 +82,12 @@ param_name_tex=[];
|
|||
for jj=1:npar
|
||||
if options_.TeX
|
||||
[par_name_temp,par_name_tex_temp]=get_the_name(jj,options_.TeX,M_,estim_params_,options_);
|
||||
param_name = strvcat(param_name,par_name_temp);
|
||||
param_name = strvcat(param_name,par_name_temp);
|
||||
par_name_tex_temp = strrep(par_name_tex_temp,'$','');
|
||||
param_name_tex = strvcat(param_name_tex,par_name_tex_temp);
|
||||
else
|
||||
[par_name_temp]=get_the_name(jj,options_.TeX,M_,estim_params_,options_);
|
||||
param_name = strvcat(param_name,par_name_temp);
|
||||
param_name = strvcat(param_name,par_name_temp);
|
||||
end
|
||||
Draws = GetAllPosteriorDraws(jj,FirstMhFile,FirstLine,TotalNumberOfMhFiles,NumberOfDraws);
|
||||
Draws = reshape(Draws,[NumberOfDraws nblck]);
|
||||
|
@ -130,7 +130,7 @@ end
|
|||
if nblck == 1 % Brooks and Gelman tests need more than one block
|
||||
convergence_diagnostics_geweke=zeros(npar,4+2*length(options_.convergence.geweke.taper_steps));
|
||||
if any(options_.convergence.geweke.geweke_interval<0) || any(options_.convergence.geweke.geweke_interval>1) || length(options_.convergence.geweke.geweke_interval)~=2 ...
|
||||
|| (options_.convergence.geweke.geweke_interval(2)-options_.convergence.geweke.geweke_interval(1)<0)
|
||||
|| (options_.convergence.geweke.geweke_interval(2)-options_.convergence.geweke.geweke_interval(1)<0)
|
||||
fprintf('\nCONVERGENCE DIAGNOSTICS: Invalid option for geweke_interval. Using the default of [0.2 0.5].\n')
|
||||
options_.convergence.geweke.geweke_interval=[0.2 0.5];
|
||||
end
|
||||
|
@ -139,9 +139,9 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
|
|||
first_obs_end_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(2)*NumberOfDraws*(1-options_.mh_drop));
|
||||
param_name=[];
|
||||
if options_.TeX
|
||||
param_name_tex=[];
|
||||
param_name_tex=[];
|
||||
end
|
||||
for jj=1:npar
|
||||
for jj=1:npar
|
||||
if options_.TeX
|
||||
[param_name_temp, param_name_tex_temp]= get_the_name(jj,options_.TeX,M_,estim_params_,options_);
|
||||
param_name_tex = strvcat(param_name_tex,strrep(param_name_tex_temp,'$',''));
|
||||
|
@ -152,7 +152,7 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
|
|||
end
|
||||
end
|
||||
fprintf('\nGeweke (1992) Convergence Tests, based on means of draws %d to %d vs %d to %d.\n',first_obs_begin_sample,last_obs_begin_sample,first_obs_end_sample,NumberOfDraws);
|
||||
fprintf('p-values are for Chi2-test for equality of means.\n');
|
||||
fprintf('p-values are for Chi2-test for equality of means.\n');
|
||||
Geweke_header=char('Parameter', 'Post. Mean', 'Post. Std', 'p-val No Taper');
|
||||
for ii=1:length(options_.convergence.geweke.taper_steps)
|
||||
Geweke_header=char(Geweke_header,['p-val ' num2str(options_.convergence.geweke.taper_steps(ii)),'% Taper']);
|
||||
|
@ -168,12 +168,12 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
|
|||
end
|
||||
[results_vec, results_struct] = geweke_moments(param_draws,options_);
|
||||
convergence_diagnostics_geweke(jj,:)=results_vec;
|
||||
|
||||
|
||||
param_draws1 = param_draws(first_obs_begin_sample:last_obs_begin_sample,:);
|
||||
param_draws2 = param_draws(first_obs_end_sample:end,:);
|
||||
[results_vec1] = geweke_moments(param_draws1,options_);
|
||||
[results_vec2] = geweke_moments(param_draws2,options_);
|
||||
|
||||
|
||||
results_struct = geweke_chi2_test(results_vec1,results_vec2,results_struct,options_);
|
||||
eval(['oo_.convergence.geweke.',param_name(jj,:),'=results_struct;'])
|
||||
datamat(jj,:)=[results_struct.posteriormean,results_struct.posteriorstd,results_struct.prob_chi2_test];
|
||||
|
@ -183,29 +183,29 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
|
|||
if options_.TeX
|
||||
Geweke_tex_header=char('Parameter', 'Mean', 'Std', 'No\ Taper');
|
||||
additional_header={[' & \multicolumn{2}{c}{Posterior} & \multicolumn{',num2str(1+length(options_.convergence.geweke.taper_steps)),'}{c}{p-values} \\'],
|
||||
['\cmidrule(r{.75em}){2-3} \cmidrule(r{.75em}){4-',num2str(4+length(options_.convergence.geweke.taper_steps)),'}']};
|
||||
['\cmidrule(r{.75em}){2-3} \cmidrule(r{.75em}){4-',num2str(4+length(options_.convergence.geweke.taper_steps)),'}']};
|
||||
for ii=1:length(options_.convergence.geweke.taper_steps)
|
||||
Geweke_tex_header=char(Geweke_tex_header,[num2str(options_.convergence.geweke.taper_steps(ii)),'\%%\ Taper']);
|
||||
end
|
||||
headers = char(Geweke_tex_header);
|
||||
lh = size(param_name_tex,2)+2;
|
||||
my_title=sprintf('Geweke (1992) Convergence Tests, based on means of draws %d to %d vs %d to %d. p-values are for $\\\\chi^2$-test for equality of means.',first_obs_begin_sample,last_obs_begin_sample,first_obs_end_sample,NumberOfDraws);
|
||||
dyn_latex_table(M_,options_,my_title,'geweke',headers,param_name_tex,datamat,lh,12,4,additional_header);
|
||||
dyn_latex_table(M_,options_,my_title,'geweke',headers,param_name_tex,datamat,lh,12,4,additional_header);
|
||||
end
|
||||
skipline(2);
|
||||
|
||||
|
||||
if options_.convergence.rafterylewis.indicator
|
||||
if any(options_.convergence.rafterylewis.qrs<0) || any(options_.convergence.rafterylewis.qrs>1) || length(options_.convergence.rafterylewis.qrs)~=3 ...
|
||||
|| (options_.convergence.rafterylewis.qrs(1)-options_.convergence.rafterylewis.qrs(2)<=0)
|
||||
|| (options_.convergence.rafterylewis.qrs(1)-options_.convergence.rafterylewis.qrs(2)<=0)
|
||||
fprintf('\nCONVERGENCE DIAGNOSTICS: Invalid option for raftery_lewis_qrs. Using the default of [0.025 0.005 0.95].\n')
|
||||
options_.convergence.rafterylewis.qrs=[0.025 0.005 0.95];
|
||||
end
|
||||
end
|
||||
Raftery_Lewis_q=options_.convergence.rafterylewis.qrs(1);
|
||||
Raftery_Lewis_r=options_.convergence.rafterylewis.qrs(2);
|
||||
Raftery_Lewis_s=options_.convergence.rafterylewis.qrs(3);
|
||||
oo_.Raftery_Lewis = raftery_lewis(x2,Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s);
|
||||
oo_.Raftery_Lewis.parameter_names=param_name;
|
||||
my_title=sprintf('Raftery/Lewis (1992) Convergence Diagnostics, based on quantile q=%4.3f with precision r=%4.3f with probability s=%4.3f.',Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s);
|
||||
my_title=sprintf('Raftery/Lewis (1992) Convergence Diagnostics, based on quantile q=%4.3f with precision r=%4.3f with probability s=%4.3f.',Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s);
|
||||
headers = char('Variables','M (burn-in)','N (req. draws)','N+M (total draws)','k (thinning)');
|
||||
|
||||
raftery_data_mat=[oo_.Raftery_Lewis.M_burn,oo_.Raftery_Lewis.N_prec,oo_.Raftery_Lewis.N_total,oo_.Raftery_Lewis.k_thin];
|
||||
|
@ -217,15 +217,15 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
|
|||
labels_Raftery_Lewis_tex=char(param_name_tex,'Maximum');
|
||||
lh = size(labels_Raftery_Lewis_tex,2)+2;
|
||||
dyn_latex_table(M_,options_,my_title,'raftery_lewis',headers,labels_Raftery_Lewis_tex,raftery_data_mat,lh,10,0);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
return
|
||||
end
|
||||
|
||||
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.
|
||||
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);
|
||||
|
@ -273,7 +273,7 @@ else
|
|||
ModelName = [ModelName '_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
|
||||
|
@ -283,9 +283,9 @@ end
|
|||
|
||||
UDIAG(:,[2 4 6],:) = UDIAG(:,[2 4 6],:)/nblck;
|
||||
skipline()
|
||||
clear pmet temp moyenne CSUP CINF csup cinf n linea iter tmp;
|
||||
clear pmet temp moyenne CSUP CINF csup cinf n linea iter tmp;
|
||||
pages = floor(npar/3);
|
||||
k = 0;
|
||||
k = 0;
|
||||
for i = 1:pages
|
||||
h=dyn_figure(options_.nodisplay,'Name','MCMC univariate convergence diagnostic (Brooks and Gelman,1998)');
|
||||
boxplot = 1;
|
||||
|
@ -296,12 +296,12 @@ for i = 1:pages
|
|||
if crit == 1
|
||||
plt1 = UDIAG(:,1,k);
|
||||
plt2 = UDIAG(:,2,k);
|
||||
namnam = [nam , ' (Interval)'];
|
||||
namnam = [nam , ' (Interval)'];
|
||||
elseif crit == 2
|
||||
plt1 = UDIAG(:,3,k);
|
||||
plt2 = UDIAG(:,4,k);
|
||||
namnam = [nam , ' (m2)'];
|
||||
elseif crit == 3
|
||||
elseif crit == 3
|
||||
plt1 = UDIAG(:,5,k);
|
||||
plt2 = UDIAG(:,6,k);
|
||||
namnam = [nam , ' (m3)'];
|
||||
|
@ -330,7 +330,7 @@ for i = 1:pages
|
|||
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
|
||||
end
|
||||
fprintf(fidTeX,'\\centering \n');
|
||||
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_udiag%s}\n',options_.figures.textwidth*min((boxplot-1)/3,1),[OutputFolder '/' ModelName],int2str(i));
|
||||
fprintf(fidTeX,'\\caption{Univariate convergence diagnostics for the Metropolis-Hastings.\n');
|
||||
|
@ -359,12 +359,12 @@ if reste
|
|||
if crit == 1
|
||||
plt1 = UDIAG(:,1,k);
|
||||
plt2 = UDIAG(:,2,k);
|
||||
namnam = [nam , ' (Interval)'];
|
||||
namnam = [nam , ' (Interval)'];
|
||||
elseif crit == 2
|
||||
plt1 = UDIAG(:,3,k);
|
||||
plt2 = UDIAG(:,4,k);
|
||||
namnam = [nam , ' (m2)'];
|
||||
elseif crit == 3
|
||||
elseif crit == 3
|
||||
plt1 = UDIAG(:,5,k);
|
||||
plt2 = UDIAG(:,6,k);
|
||||
namnam = [nam , ' (m3)'];
|
||||
|
@ -393,7 +393,7 @@ if reste
|
|||
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
|
||||
end
|
||||
fprintf(fidTeX,'\\centering \n');
|
||||
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_udiag%s}\n',options_.figures.textwidth*min((boxplot-1)/nc,1),[OutputFolder '/' ModelName],int2str(pages+1));
|
||||
if reste == 2
|
||||
|
@ -435,7 +435,7 @@ for b = 1:nblck
|
|||
end
|
||||
clear logpo2;
|
||||
tmp(:,2) = kron(transpose(1:nblck),ones(NumberOfDraws,1));
|
||||
tmp(:,3) = kron(ones(nblck,1),time');
|
||||
tmp(:,3) = kron(ones(nblck,1),time');
|
||||
tmp = sortrows(tmp,1);
|
||||
ligne = 0;
|
||||
for iter = Origin:StepSize:NumberOfDraws
|
||||
|
@ -454,12 +454,12 @@ for iter = Origin:StepSize:NumberOfDraws
|
|||
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.
|
||||
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;
|
||||
MDIAG(:,[2 4 6],:) = MDIAG(:,[2 4 6],:)/nblck;
|
||||
|
||||
h = dyn_figure(options_.nodisplay,'Name','Multivariate convergence diagnostic');
|
||||
boxplot = 1;
|
||||
|
@ -467,12 +467,12 @@ for crit = 1:3
|
|||
if crit == 1
|
||||
plt1 = MDIAG(:,1);
|
||||
plt2 = MDIAG(:,2);
|
||||
namnam = 'Interval';
|
||||
namnam = 'Interval';
|
||||
elseif crit == 2
|
||||
plt1 = MDIAG(:,3);
|
||||
plt2 = MDIAG(:,4);
|
||||
namnam = 'm2';
|
||||
elseif crit == 3
|
||||
elseif crit == 3
|
||||
plt1 = MDIAG(:,5);
|
||||
plt2 = MDIAG(:,6);
|
||||
namnam = 'm3';
|
||||
|
@ -499,7 +499,7 @@ if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
|||
fprintf(fidTeX,'\\begin{figure}[H]\n');
|
||||
for jj = 1:3
|
||||
fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),' ');
|
||||
end
|
||||
end
|
||||
fprintf(fidTeX,'\\centering \n');
|
||||
fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s_mdiag}\n',[OutputFolder '/' ModelName]);
|
||||
fprintf(fidTeX,'\\caption{Multivariate convergence diagnostics for the Metropolis-Hastings.\n');
|
||||
|
@ -512,4 +512,3 @@ if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
|||
fprintf(fidTeX,'%% End Of TeX file.');
|
||||
fclose(fidTeX);
|
||||
end
|
||||
|
||||
|
|
|
@ -2,12 +2,12 @@ function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab)
|
|||
% function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab)
|
||||
% Computes the Brooks/Gelman (1998) convergence diagnostics, both the
|
||||
% parameteric and the non-parameteric versions
|
||||
%
|
||||
%
|
||||
% PARALLEL CONTEXT
|
||||
% Core functionality for MCMC Diagnostics, which can be parallelized.
|
||||
% See also the comment in posterior_sampler_core.m funtion.
|
||||
%
|
||||
%
|
||||
%
|
||||
%
|
||||
% INPUTS
|
||||
% See See the comment in posterior_sampler_core.m funtion.
|
||||
|
||||
|
@ -25,10 +25,10 @@ function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab)
|
|||
%
|
||||
% ALGORITHM
|
||||
% Computes part of the convergence diagnostics, the rest is computed in McMCDiagnostics.m .
|
||||
% The methodology and terminology is based on: Brooks/Gelman (1998): General
|
||||
% Methods for Monitoring Convergence of Iterative Simulations, Journal of Computational
|
||||
% The methodology and terminology is based on: Brooks/Gelman (1998): General
|
||||
% Methods for Monitoring Convergence of Iterative Simulations, Journal of Computational
|
||||
% and Graphical Statistics, Volume 7, Number 4, Pages 434-455
|
||||
%
|
||||
%
|
||||
%
|
||||
% SPECIAL REQUIREMENTS.
|
||||
% None.
|
||||
|
|
|
@ -2,7 +2,7 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti
|
|||
% results_struct = geweke_chi2_test(results1,results2,results_struct,options)
|
||||
% PURPOSE: computes Geweke's chi-squared test for two sets of MCMC sample draws
|
||||
%
|
||||
% INPUTS
|
||||
% INPUTS
|
||||
% results1 [1 by (4+n_taper*2) vector] vector with post. mean,
|
||||
% std, NSE_iid, RNE_iid, and tapered NSE and RNE
|
||||
% for chain part 1
|
||||
|
@ -12,7 +12,7 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti
|
|||
% results_struct [structure] results structure generated by geweke_moments
|
||||
% Dynareoptions [structure]
|
||||
%
|
||||
% OUTPUTS
|
||||
% OUTPUTS
|
||||
% results_struct [structure] containing the following fields:
|
||||
% pooled_mean Pooled mean of the chain parts, weighted
|
||||
% with precision
|
||||
|
@ -49,26 +49,25 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti
|
|||
% J.M. Bernardo, A.P. Dawid, and A.F.M. Smith (eds.) Proceedings of
|
||||
% the Fourth Valencia International Meeting on Bayesian Statistics,
|
||||
% pp. 169-194, Oxford University Press
|
||||
% Geweke (1999): `Using simulation methods for Bayesian econometric models:
|
||||
% Geweke (1999): `Using simulation methods for Bayesian econometric models:
|
||||
% Inference, development and communication', Econometric Reviews, 18(1),
|
||||
% 1-73
|
||||
|
||||
% written by: Johannes Pfeifer,
|
||||
% based on code by James P. LeSage, who in turn
|
||||
% drew on MATLAB programs written by Siddartha Chib
|
||||
% written by: Johannes Pfeifer,
|
||||
% based on code by James P. LeSage, who in turn
|
||||
% drew on MATLAB programs written by Siddartha Chib
|
||||
|
||||
for k=1:length(options.convergence.geweke.taper_steps)+1
|
||||
NSE=[results1(:,3+(k-1)*2) results2(:,3+(k-1)*2)];
|
||||
means=[results1(:,1) results2(:,1)];
|
||||
diff_Means=means(:,1)-means(:,2);
|
||||
sum_of_weights=sum(1./(NSE.^2),2);
|
||||
pooled_mean=sum(means./(NSE.^2),2)./sum_of_weights;
|
||||
pooled_NSE=1./sqrt(sum_of_weights);
|
||||
NSE=[results1(:,3+(k-1)*2) results2(:,3+(k-1)*2)];
|
||||
means=[results1(:,1) results2(:,1)];
|
||||
diff_Means=means(:,1)-means(:,2);
|
||||
sum_of_weights=sum(1./(NSE.^2),2);
|
||||
pooled_mean=sum(means./(NSE.^2),2)./sum_of_weights;
|
||||
pooled_NSE=1./sqrt(sum_of_weights);
|
||||
|
||||
test_stat=diff_Means.^2./sum(NSE.^2,2);
|
||||
p = 1-chi2cdf(test_stat,1);
|
||||
results_struct.pooled_mean(:,k) = pooled_mean;
|
||||
results_struct.pooled_nse(:,k) = pooled_NSE;
|
||||
results_struct.prob_chi2_test(:,k) = p;
|
||||
test_stat=diff_Means.^2./sum(NSE.^2,2);
|
||||
p = 1-chi2cdf(test_stat,1);
|
||||
results_struct.pooled_mean(:,k) = pooled_mean;
|
||||
results_struct.pooled_nse(:,k) = pooled_NSE;
|
||||
results_struct.prob_chi2_test(:,k) = p;
|
||||
end
|
||||
|
||||
|
|
|
@ -1,13 +1,13 @@
|
|||
function [results_vec, results_struct] = geweke_moments(draws,Dynareoptions)
|
||||
%[results_vec, results_struct] = geweke_moments(draws,Dynareoptions)
|
||||
% PURPOSE: computes Gewke's convergence diagnostics NSE and RNE
|
||||
% PURPOSE: computes Gewke's convergence diagnostics NSE and RNE
|
||||
% (numerical std error and relative numerical efficiencies)
|
||||
|
||||
% INPUTS
|
||||
% draws [ndraws by 1 vector]
|
||||
% INPUTS
|
||||
% draws [ndraws by 1 vector]
|
||||
% Dynareoptions [structure]
|
||||
%
|
||||
% OUTPUTS
|
||||
%
|
||||
% OUTPUTS
|
||||
% results_vec
|
||||
% results_struct [structure] containing the following fields:
|
||||
% posteriormean= posterior parameter mean
|
||||
|
@ -44,16 +44,16 @@ function [results_vec, results_struct] = geweke_moments(draws,Dynareoptions)
|
|||
% J.M. Bernardo, A.P. Dawid, and A.F.M. Smith (eds.) Proceedings of
|
||||
% the Fourth Valencia International Meeting on Bayesian Statistics,
|
||||
% pp. 169-194, Oxford University Press
|
||||
% Geweke (1999): `Using simulation methods for Bayesian econometric models:
|
||||
% Geweke (1999): `Using simulation methods for Bayesian econometric models:
|
||||
% Inference, development and communication', Econometric Reviews, 18(1),
|
||||
% 1-73
|
||||
% -----------------------------------------------------------------
|
||||
|
||||
% written by: Johannes Pfeifer,
|
||||
% based on code by James P. LeSage, who in turn
|
||||
% drew on MATLAB programs written by Siddartha Chib
|
||||
% written by: Johannes Pfeifer,
|
||||
% based on code by James P. LeSage, who in turn
|
||||
% drew on MATLAB programs written by Siddartha Chib
|
||||
|
||||
|
||||
|
||||
ndraw = size(draws,1);
|
||||
n_groups=100;
|
||||
taper_steps=Dynareoptions.convergence.geweke.taper_steps;
|
||||
|
@ -66,7 +66,7 @@ window_means= zeros(n_groups,1);
|
|||
window_uncentered_variances= zeros(n_groups,1);
|
||||
for ig=1:n_groups
|
||||
window_means(ig,1)=sum(draws((ig-1)*ns+1:ig*ns,1))/ns;
|
||||
window_uncentered_variances(ig,1)=sum(draws((ig-1)*ns+1:ig*ns,1).^2)/ns;
|
||||
window_uncentered_variances(ig,1)=sum(draws((ig-1)*ns+1:ig*ns,1).^2)/ns;
|
||||
end %for ig
|
||||
total_mean=mean(window_means);
|
||||
total_variance=mean(window_uncentered_variances)-total_mean^2;
|
||||
|
@ -106,4 +106,3 @@ for taper_index=1:length(taper_steps)
|
|||
eval(['results_struct.nse_taper_',num2str(taper),'= NSE_taper;']);
|
||||
eval(['results_struct.rne_taper_',num2str(taper),'= total_variance/(n_draws_used*NSE_taper^2);']);
|
||||
end % end of for mm loop
|
||||
|
||||
|
|
|
@ -1,71 +1,71 @@
|
|||
function Ifac = mcmc_ifac(X, Nc)
|
||||
% function Ifac = mcmc_ifac(X, Nc)
|
||||
% Compute inefficiency factor of a MCMC sample X based on a Parzen Window
|
||||
%
|
||||
% INPUTS
|
||||
% X: time series
|
||||
% Nc: # of lags
|
||||
%
|
||||
% OUTPUTS
|
||||
% Ifac: inefficiency factor of MCMC sample
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% none
|
||||
% ALGORITHM:
|
||||
% Inefficiency factors are computed as
|
||||
% \[
|
||||
% Ifac = 1 + 2\sum\limits_{i=1}^{Nc} {\hat \rho(i)}
|
||||
% \]
|
||||
% where $\hat \rho(i)$ denotes the autocorrelation at lag i and the terms
|
||||
% of the sum are truncated using a Parzen window.
|
||||
%
|
||||
% For inefficiency factors, see Section 6.1 of Paolo Giordani, Michael Pitt, and Robert Kohn (2011):
|
||||
% "Bayesian Inference for Time Series State Space Models" in : John Geweke, Gary Koop,
|
||||
% Herman van Dijk (editors): "The Oxford Handbook of Bayesian
|
||||
% Econometrics", Oxford University Press
|
||||
%
|
||||
% The Parzen-Window is given by
|
||||
% \[
|
||||
% k(x) = \left\{ {\begin{array}{*{20}{c}}
|
||||
% {1 - 6{x^2} + 6|x|^3} \text{ for } 0 \leqslant |x| \leqslant \frac{1}{2}} \\
|
||||
% {2(1-|x|^3) \text{ for } \frac{1}{2} \leqslant |x| \leqslant 1} \\
|
||||
% {0 \text{ otherwise}}
|
||||
% \end{array}} \right.
|
||||
% \]
|
||||
% See Donald W.K Andrews (1991): "Heteroskedasticity and autocorrelation
|
||||
% consistent covariance matrix estimation", Econometrica, 59(3), p. 817-858
|
||||
|
||||
|
||||
% Copyright (C) 2015-16 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/>.
|
||||
|
||||
Nc = floor(min(Nc, length(X)/2));
|
||||
if mod(Nc,2)
|
||||
Nc=Nc-1;
|
||||
end
|
||||
AcorrXSIM = dyn_autocorr(X(:), Nc);
|
||||
%
|
||||
%Calculate the Parzen Weight
|
||||
Parzen=zeros(Nc+1,1);
|
||||
for i=1: Nc/2+1
|
||||
Parzen(i)=1 - 6*(i/Nc)^2+ 6*(i/Nc)^3;
|
||||
end
|
||||
for i=(Nc/2)+1: Nc+1
|
||||
Parzen(i)=2 * (1-(i/Nc))^3;
|
||||
end
|
||||
Parzen=Parzen';
|
||||
Ifac= 1+2*sum(Parzen(:).* AcorrXSIM);
|
||||
function Ifac = mcmc_ifac(X, Nc)
|
||||
% function Ifac = mcmc_ifac(X, Nc)
|
||||
% Compute inefficiency factor of a MCMC sample X based on a Parzen Window
|
||||
%
|
||||
% INPUTS
|
||||
% X: time series
|
||||
% Nc: # of lags
|
||||
%
|
||||
% OUTPUTS
|
||||
% Ifac: inefficiency factor of MCMC sample
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
% none
|
||||
% ALGORITHM:
|
||||
% Inefficiency factors are computed as
|
||||
% \[
|
||||
% Ifac = 1 + 2\sum\limits_{i=1}^{Nc} {\hat \rho(i)}
|
||||
% \]
|
||||
% where $\hat \rho(i)$ denotes the autocorrelation at lag i and the terms
|
||||
% of the sum are truncated using a Parzen window.
|
||||
%
|
||||
% For inefficiency factors, see Section 6.1 of Paolo Giordani, Michael Pitt, and Robert Kohn (2011):
|
||||
% "Bayesian Inference for Time Series State Space Models" in : John Geweke, Gary Koop,
|
||||
% Herman van Dijk (editors): "The Oxford Handbook of Bayesian
|
||||
% Econometrics", Oxford University Press
|
||||
%
|
||||
% The Parzen-Window is given by
|
||||
% \[
|
||||
% k(x) = \left\{ {\begin{array}{*{20}{c}}
|
||||
% {1 - 6{x^2} + 6|x|^3} \text{ for } 0 \leqslant |x| \leqslant \frac{1}{2}} \\
|
||||
% {2(1-|x|^3) \text{ for } \frac{1}{2} \leqslant |x| \leqslant 1} \\
|
||||
% {0 \text{ otherwise}}
|
||||
% \end{array}} \right.
|
||||
% \]
|
||||
% See Donald W.K Andrews (1991): "Heteroskedasticity and autocorrelation
|
||||
% consistent covariance matrix estimation", Econometrica, 59(3), p. 817-858
|
||||
|
||||
|
||||
% Copyright (C) 2015-16 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/>.
|
||||
|
||||
Nc = floor(min(Nc, length(X)/2));
|
||||
if mod(Nc,2)
|
||||
Nc=Nc-1;
|
||||
end
|
||||
AcorrXSIM = dyn_autocorr(X(:), Nc);
|
||||
%
|
||||
%Calculate the Parzen Weight
|
||||
Parzen=zeros(Nc+1,1);
|
||||
for i=1: Nc/2+1
|
||||
Parzen(i)=1 - 6*(i/Nc)^2+ 6*(i/Nc)^3;
|
||||
end
|
||||
for i=(Nc/2)+1: Nc+1
|
||||
Parzen(i)=2 * (1-(i/Nc))^3;
|
||||
end
|
||||
Parzen=Parzen';
|
||||
Ifac= 1+2*sum(Parzen(:).* AcorrXSIM);
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
function [raftery_lewis] = raftery_lewis(runs,q,r,s)
|
||||
% function raftery_lewis = raftery_lewis(runs,q,r,s)
|
||||
% Computes the convergence diagnostics of Raftery and Lewis (1992), i.e. the
|
||||
% number of draws needed in MCMC to estimate the posterior cdf of the q-quantile
|
||||
% Computes the convergence diagnostics of Raftery and Lewis (1992), i.e. the
|
||||
% number of draws needed in MCMC to estimate the posterior cdf of the q-quantile
|
||||
% within an accuracy r with probability s
|
||||
%
|
||||
%
|
||||
% Inputs:
|
||||
% - draws [n_draws by n_var] double matrix of draws from the sampler
|
||||
% - draws [n_draws by n_var] double matrix of draws from the sampler
|
||||
% - q [scalar] quantile of the quantity of interest
|
||||
% - r [scalar] level of desired precision
|
||||
% - r [scalar] level of desired precision
|
||||
% - s [scalar] probability associated with r
|
||||
%
|
||||
%
|
||||
% Output:
|
||||
% raftery_lewis [structure] containing the fields:
|
||||
% - M_burn [n_draws by 1] number of draws required for burn-in
|
||||
|
@ -21,7 +21,7 @@ function [raftery_lewis] = raftery_lewis(runs,q,r,s)
|
|||
% iterations due to dependence in chain
|
||||
% - N_min [scalar] # draws if the chain is white noise
|
||||
% - N_total [n_draws by 1] nburn + nprec
|
||||
%
|
||||
%
|
||||
|
||||
% ---------------------------------------------------------------------
|
||||
% NOTES: Example values of q, r, s:
|
||||
|
@ -30,18 +30,18 @@ function [raftery_lewis] = raftery_lewis(runs,q,r,s)
|
|||
%
|
||||
% - The result is quite sensitive to r, being proportional to the
|
||||
% inverse of r^2.
|
||||
% - For epsilon (closeness of probabilities to equilibrium values),
|
||||
% - For epsilon (closeness of probabilities to equilibrium values),
|
||||
% Raftery/Lewis use 0.001 and argue that the results
|
||||
% are quite robust to changes in this value
|
||||
%
|
||||
% ---------------------------------------------------------------------
|
||||
% REFERENCES:
|
||||
% REFERENCES:
|
||||
% Raftery, Adrien E./Lewis, Steven (1992a): "How many iterations in the Gibbs sampler?"
|
||||
% in: Bernardo/Berger/Dawid/Smith (eds.): Bayesian Statistics, Vol. 4, Clarendon Press: Oxford,
|
||||
% pp. 763-773.
|
||||
% Raftery, Adrien E./Lewis, Steven (1992b): "Comment: One long run with diagnostics:
|
||||
% Implementation strategies for Markov chain Monte Carlo." Statistical Science,
|
||||
% 7(4), pp. 493-497.
|
||||
% in: Bernardo/Berger/Dawid/Smith (eds.): Bayesian Statistics, Vol. 4, Clarendon Press: Oxford,
|
||||
% pp. 763-773.
|
||||
% Raftery, Adrien E./Lewis, Steven (1992b): "Comment: One long run with diagnostics:
|
||||
% Implementation strategies for Markov chain Monte Carlo." Statistical Science,
|
||||
% 7(4), pp. 493-497.
|
||||
%
|
||||
% ----------------------------------------------------
|
||||
|
||||
|
@ -80,26 +80,26 @@ thinned_chain = zeros(n_runs,1);
|
|||
Phi = norminv((s+1)/2); %note the missing ^{-1} at the Phi in equation top page 5, see RL (1995)
|
||||
raftery_lewis.N_min = fix(Phi^2*(1-q)*q/r^2+1);
|
||||
|
||||
for nv = 1:n_vars % big loop over variables
|
||||
for nv = 1:n_vars % big loop over variables
|
||||
if q > 0 && q < 1
|
||||
work = (runs(:,nv) <= quantile(runs(:,nv),q));
|
||||
else
|
||||
error('Quantile must be between 0 and 1');
|
||||
error('Quantile must be between 0 and 1');
|
||||
end
|
||||
|
||||
k_thin_current_var = 1;
|
||||
bic = 1;
|
||||
|
||||
k_thin_current_var = 1;
|
||||
bic = 1;
|
||||
epss = 0.001;
|
||||
% Find thinning factor for which first-order Markov Chain is preferred to second-order one
|
||||
while(bic > 0)
|
||||
thinned_chain=work(1:k_thin_current_var:n_runs,1);
|
||||
thinned_chain=work(1:k_thin_current_var:n_runs,1);
|
||||
[g2, bic] = first_vs_second_order_MC_test(thinned_chain);
|
||||
k_thin_current_var = k_thin_current_var+1;
|
||||
end
|
||||
|
||||
|
||||
k_thin_current_var = k_thin_current_var-1; %undo last step
|
||||
|
||||
%compute transition probabilities
|
||||
|
||||
%compute transition probabilities
|
||||
transition_matrix = zeros(2,2);
|
||||
for i1 = 2:size(thinned_chain,1)
|
||||
transition_matrix(thinned_chain(i1-1)+1,thinned_chain(i1)+1) = transition_matrix(thinned_chain(i1-1)+1,thinned_chain(i1)+1)+1;
|
||||
|
@ -109,13 +109,13 @@ for nv = 1:n_vars % big loop over variables
|
|||
|
||||
kmind=k_thin_current_var;
|
||||
[g2, bic]=independence_chain_test(thinned_chain);
|
||||
|
||||
|
||||
while(bic > 0)
|
||||
thinned_chain=work(1:kmind:n_runs,1);
|
||||
thinned_chain=work(1:kmind:n_runs,1);
|
||||
[g2, bic] = independence_chain_test(thinned_chain);
|
||||
kmind = kmind+1;
|
||||
end
|
||||
|
||||
|
||||
m_star = log((alpha + beta)*epss/max(alpha,beta))/log(abs(1 - alpha - beta)); %equation bottom page 4
|
||||
raftery_lewis.M_burn(nv) = fix((m_star+1)*k_thin_current_var);
|
||||
n_star = (2 - (alpha + beta))*alpha*beta*(Phi^2)/((alpha + beta)^3 * r^2); %equation top page 5
|
||||
|
@ -131,7 +131,7 @@ end
|
|||
function [g2, bic] = first_vs_second_order_MC_test(d)
|
||||
%conducts a test of first vs. second order Markov Chain via BIC criterion
|
||||
n_obs=size(d,1);
|
||||
g2 = 0;
|
||||
g2 = 0;
|
||||
tran=zeros(2,2,2);
|
||||
for t_iter=3:n_obs % count state transitions
|
||||
tran(d(t_iter-2,1)+1,d(t_iter-1,1)+1,d(t_iter,1)+1)=tran(d(t_iter-2,1)+1,d(t_iter-1,1)+1,d(t_iter,1)+1)+1;
|
||||
|
@ -142,17 +142,17 @@ for ind_1 = 1:2
|
|||
for ind_3 = 1:2
|
||||
if tran(ind_1,ind_2,ind_3) ~= 0
|
||||
fitted = (tran(ind_1,ind_2,1) + tran(ind_1,ind_2,2))*(tran(1,ind_2,ind_3) + tran(2,ind_2,ind_3))/...
|
||||
(tran(1,ind_2,1) + tran(1,ind_2,2) + tran(2,ind_2,1) + tran(2,ind_2,2));
|
||||
(tran(1,ind_2,1) + tran(1,ind_2,2) + tran(2,ind_2,1) + tran(2,ind_2,2));
|
||||
focus = tran(ind_1,ind_2,ind_3);
|
||||
g2 = g2 + log(focus/fitted)*focus;
|
||||
end
|
||||
end % end of for i3
|
||||
end % end of for i2
|
||||
end % end of for i1
|
||||
g2 = g2*2;
|
||||
bic = g2 - log(n_obs-2)*2;
|
||||
g2 = g2*2;
|
||||
bic = g2 - log(n_obs-2)*2;
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
function [g2, bic] = independence_chain_test(d)
|
||||
|
@ -162,18 +162,18 @@ trans = zeros(2,2);
|
|||
for ind_1 = 2:n_obs
|
||||
trans(d(ind_1-1)+1,d(ind_1)+1)=trans(d(ind_1-1)+1,d(ind_1)+1)+1;
|
||||
end
|
||||
dcm1 = n_obs - 1;
|
||||
dcm1 = n_obs - 1;
|
||||
g2 = 0;
|
||||
% Compute the log likelihood ratio statistic for second-order MC vs first-order MC. G2 statistic of Bishop, Fienberg and Holland (1975)
|
||||
for ind_1 = 1:2
|
||||
for ind_2 = 1:2
|
||||
if trans(ind_1,ind_2) ~= 0
|
||||
fitted = ((trans(ind_1,1) + trans(ind_1,2))*(trans(1,ind_2) + trans(2,ind_2)))/dcm1;
|
||||
fitted = ((trans(ind_1,1) + trans(ind_1,2))*(trans(1,ind_2) + trans(2,ind_2)))/dcm1;
|
||||
focus = trans(ind_1,ind_2);
|
||||
g2 = g2 + log(focus/fitted)*focus;
|
||||
end
|
||||
end
|
||||
end
|
||||
g2 = g2*2;
|
||||
g2 = g2*2;
|
||||
bic = g2 - log(dcm1);
|
||||
end
|
||||
|
|
|
@ -40,7 +40,7 @@ if isfield(oo_,'PointForecast')
|
|||
oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})=...
|
||||
[oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(:,end)*ones(M_.maximum_endo_lag,1) oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})];
|
||||
oo_.PointForecast.(moment_names{moment_iter}).(var_names{var_iter})=...
|
||||
[oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(:,end)*ones(M_.maximum_endo_lag,1) oo_.PointForecast.(moment_names{moment_iter}).(var_names{var_iter})];
|
||||
[oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(:,end)*ones(M_.maximum_endo_lag,1) oo_.PointForecast.(moment_names{moment_iter}).(var_names{var_iter})];
|
||||
else
|
||||
oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})=...
|
||||
[oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(end)*ones(M_.maximum_endo_lag,1); oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})];
|
||||
|
@ -106,7 +106,7 @@ if isfield(oo_,'UpdatedVariables')
|
|||
for ii=1:length(names)
|
||||
%make sure Bayesian fields are not affected
|
||||
if ~strcmp(names{ii},'Mean') && ~strcmp(names{ii},'Median') && ~strcmp(names{ii},'deciles') ...
|
||||
&& ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup')
|
||||
&& ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup')
|
||||
current_var_index=find(strmatch(names{ii},deblank(M_.endo_names),'exact'));
|
||||
if options_.loglinear == 1 %logged steady state must be used
|
||||
constant_current_variable=log(oo_.dr.ys(current_var_index));
|
||||
|
@ -127,7 +127,7 @@ if isfield(oo_,'FilteredVariables')
|
|||
for ii=1:length(names)
|
||||
%make sure Bayesian fields are not affected
|
||||
if ~strcmp(names{ii},'Mean') && ~strcmp(names{ii},'Median') && ~strcmp(names{ii},'deciles') ...
|
||||
&& ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup')
|
||||
&& ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup')
|
||||
current_var_index=find(strmatch(names{ii},deblank(M_.endo_names),'exact'));
|
||||
if options_.loglinear == 1 %logged steady state must be used
|
||||
constant_current_variable=log(oo_.dr.ys(current_var_index));
|
||||
|
@ -147,11 +147,11 @@ end
|
|||
if ~isempty(options_.nk) && options_.nk ~= 0 && ~isempty(bayestopt_)
|
||||
if ~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file)) %no Bayesian estimation
|
||||
positions_in_decision_order=oo_.dr.inv_order_var(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list));
|
||||
if options_.loglinear == 1 %logged steady state must be used
|
||||
constant_all_variables=log(oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list)));
|
||||
elseif options_.loglinear == 0 %unlogged steady state must be used
|
||||
constant_all_variables=oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list));
|
||||
end
|
||||
if options_.loglinear == 1 %logged steady state must be used
|
||||
constant_all_variables=log(oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list)));
|
||||
elseif options_.loglinear == 0 %unlogged steady state must be used
|
||||
constant_all_variables=oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list));
|
||||
end
|
||||
if ~(options_.selected_variables_only && ~(options_.forecast > 0)) %happens only when selected_variables_only is not used
|
||||
oo_.FilteredVariablesKStepAhead(:,positions_in_decision_order,:)=oo_.FilteredVariablesKStepAhead-constant_all_variables;
|
||||
if ~isempty(PK) %get K-step ahead variances
|
||||
|
@ -182,11 +182,11 @@ end
|
|||
|
||||
%Deal with OSR
|
||||
if ~isempty(M_.osr.variable_weights)
|
||||
evalin('base','optim_weights_=M_.osr.variable_weights')
|
||||
evalin('base','optim_weights_=M_.osr.variable_weights')
|
||||
end
|
||||
if ~isempty(M_.osr.variable_indices)
|
||||
evalin('base','obj_var_=M_.osr.variable_indices')
|
||||
evalin('base','obj_var_=M_.osr.variable_indices')
|
||||
end
|
||||
if ~isempty(M_.osr.param_names)
|
||||
evalin('base','osr_params_=char(M_.osr.param_names)')
|
||||
evalin('base','osr_params_=char(M_.osr.param_names)')
|
||||
end
|
||||
|
|
|
@ -81,5 +81,5 @@ else
|
|||
end
|
||||
|
||||
eval(['oo_ = convert_dyn_' strrep(new_from_ver, '.', '') '_to_' ...
|
||||
strrep(to_ver, '.', '') '(M_, options_, oo_);']);
|
||||
strrep(to_ver, '.', '') '(M_, options_, oo_);']);
|
||||
end
|
||||
|
|
|
@ -137,7 +137,7 @@ end
|
|||
|
||||
function oo_ = fill_output_structure(var1,var2,type,oo_,moment,lag,result)
|
||||
switch moment
|
||||
case {'Mean','Median','Variance','HPDinf','HPDsup'}
|
||||
case {'Mean','Median','Variance','HPDinf','HPDsup'}
|
||||
oo_.([type, 'TheoreticalMoments']).dsge.correlation.(moment).(var1).(var2)(lag,1) = result;
|
||||
case {'deciles','density'}
|
||||
oo_.([type, 'TheoreticalMoments']).dsge.correlation.(moment).(var1).(var2)(lag,1) = {result};
|
||||
|
|
|
@ -37,6 +37,3 @@ if rank(yhat)
|
|||
else
|
||||
co=0;
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
function oo_ = covariance_mc_analysis(NumberOfSimulations,type,dname,fname,vartan,nvar,var1,var2,mh_conf_sig,oo_,options_)
|
||||
% This function analyses the (posterior or prior) distribution of the
|
||||
% endogenous variables' covariance matrix.
|
||||
%
|
||||
%
|
||||
% INPUTS
|
||||
% NumberOfSimulations [integer] scalar, number of simulations.
|
||||
% type [string] 'prior' or 'posterior'
|
||||
|
@ -14,7 +14,7 @@ function oo_ = covariance_mc_analysis(NumberOfSimulations,type,dname,fname,varta
|
|||
% mh_conf_sig [double] 2 by 1 vector with upper
|
||||
% and lower bound of HPD intervals
|
||||
% oo_ [structure] Dynare structure where the results are saved.
|
||||
% options_ [structure] Dynare options structure
|
||||
% options_ [structure] Dynare options structure
|
||||
%
|
||||
% OUTPUTS
|
||||
% oo_ [structure] Dynare structure where the results are saved.
|
||||
|
@ -64,7 +64,7 @@ var1=deblank(var1);
|
|||
var2=deblank(var2);
|
||||
|
||||
if isfield(oo_,[ TYPE 'TheoreticalMoments'])
|
||||
temporary_structure = oo_.([TYPE, 'TheoreticalMoments']);
|
||||
temporary_structure = oo_.([TYPE, 'TheoreticalMoments']);
|
||||
if isfield(temporary_structure,'dsge')
|
||||
temporary_structure = oo_.([TYPE, 'TheoreticalMoments']).dsge;
|
||||
if isfield(temporary_structure,'covariance')
|
||||
|
@ -104,17 +104,17 @@ for file = 1:length(ListOfFiles)
|
|||
temp=Covariance_matrix(:,cov_pos)./(sqrt(Covariance_matrix(:,var_pos_1)).*sqrt(Covariance_matrix(:,var_pos_2)));
|
||||
temp(Covariance_matrix(:,cov_pos)==0)=0; %filter out 0 correlations that would result in 0/0
|
||||
tmp_corr_mat(i1:i2)=temp;
|
||||
end
|
||||
end
|
||||
i1 = i2+1;
|
||||
end
|
||||
|
||||
if options_.estimation.moments_posterior_density.indicator
|
||||
[p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ...
|
||||
posterior_moments(tmp,1,mh_conf_sig);
|
||||
posterior_moments(tmp,1,mh_conf_sig);
|
||||
oo_.([TYPE, 'TheoreticalMoments']).dsge.covariance.density.(var1).(var2) = density;
|
||||
else
|
||||
[p_mean, p_median, p_var, hpd_interval, p_deciles] = ...
|
||||
posterior_moments(tmp,0,mh_conf_sig);
|
||||
posterior_moments(tmp,0,mh_conf_sig);
|
||||
end
|
||||
oo_.([TYPE, 'TheoreticalMoments']).dsge.covariance.Mean.(var1).(var2) = p_mean;
|
||||
oo_.([TYPE, 'TheoreticalMoments']).dsge.covariance.Median.(var1).(var2) = p_median;
|
||||
|
|
|
@ -12,7 +12,7 @@ function [x,rc] = csolve(FUN,x,gradfun,crit,itmax,varargin)
|
|||
% the equation is solved.
|
||||
% itmax: the solver stops when this number of iterations is reached, with rc=4
|
||||
% varargin: in this position the user can place any number of additional arguments, all
|
||||
% of which are passed on to FUN and gradfun (when it is non-empty) as a list of
|
||||
% of which are passed on to FUN and gradfun (when it is non-empty) as a list of
|
||||
% arguments following x.
|
||||
% rc: 0 means normal solution, 1 and 3 mean no solution despite extremely fine adjustments
|
||||
% in step length (very likely a numerical problem, or a discontinuity). 4 means itmax
|
||||
|
@ -60,7 +60,7 @@ if isempty(varargin)
|
|||
f0=feval(FUN,x);
|
||||
else
|
||||
f0=feval(FUN,x,varargin{:});
|
||||
end
|
||||
end
|
||||
af0=sum(abs(f0));
|
||||
af00=af0;
|
||||
itct=0;
|
||||
|
|
|
@ -29,8 +29,8 @@ function [nodes, weights] = cubature_with_gaussian_weight(d,n,method)
|
|||
%! The routine returns nodes and associated weights to compute a multivariate integral of the form:
|
||||
%!
|
||||
%! \int_D f(x)*\exp(-<x,x>) dx
|
||||
%!
|
||||
%!
|
||||
%!
|
||||
%!
|
||||
%! @end deftypefn
|
||||
%@eod:
|
||||
|
||||
|
@ -52,7 +52,7 @@ function [nodes, weights] = cubature_with_gaussian_weight(d,n,method)
|
|||
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
% AUTHOR(S) stephane DOT adjemian AT univ DASH lemans DOT fr
|
||||
|
||||
|
||||
% Set default.
|
||||
if nargin<3 || isempty(method)
|
||||
method = 'Stroud';
|
||||
|
@ -90,7 +90,7 @@ if strcmp(method,'Stroud') && isequal(n,5)
|
|||
nodes = zeros(d,m);
|
||||
weights = zeros(m,1);
|
||||
% Set the weight for the first node (0)
|
||||
weights(1) = A;
|
||||
weights(1) = A;
|
||||
skip = 1;
|
||||
% Set the remaining nodes and associated weights.
|
||||
nodes(:,skip+(1:d)) = r*eye(d);
|
||||
|
@ -117,20 +117,20 @@ end
|
|||
|
||||
|
||||
function v = e(n,i)
|
||||
v = zeros(n,1);
|
||||
v(i) = 1;
|
||||
|
||||
v = zeros(n,1);
|
||||
v(i) = 1;
|
||||
|
||||
function m = ee(n,i,j)
|
||||
m = zeros(n,4);
|
||||
m(:,1) = e(n,i)+e(n,j);
|
||||
m(:,2) = e(n,i)-e(n,j);
|
||||
m(:,3) = -m(:,2);
|
||||
m(:,4) = -m(:,1);
|
||||
|
||||
m = zeros(n,4);
|
||||
m(:,1) = e(n,i)+e(n,j);
|
||||
m(:,2) = e(n,i)-e(n,j);
|
||||
m(:,3) = -m(:,2);
|
||||
m(:,4) = -m(:,1);
|
||||
|
||||
%@test:1
|
||||
%$ % Set problem
|
||||
%$ d = 4;
|
||||
%$
|
||||
%$
|
||||
%$ t = zeros(5,1);
|
||||
%$
|
||||
%$ % Call the tested routine
|
||||
|
@ -289,7 +289,7 @@ function m = ee(n,i,j)
|
|||
%@test:5
|
||||
%$ % Set problem
|
||||
%$ d = 5;
|
||||
%$
|
||||
%$
|
||||
%$ t = zeros(6,1);
|
||||
%$
|
||||
%$ % Call the tested routine
|
||||
|
@ -333,7 +333,7 @@ function m = ee(n,i,j)
|
|||
%@test:6
|
||||
%$ % Set problem
|
||||
%$ d = 3;
|
||||
%$
|
||||
%$
|
||||
%$ t = zeros(4,1);
|
||||
%$
|
||||
%$ % Call the tested routine
|
||||
|
|
|
@ -76,7 +76,7 @@ id0 = 1:n;
|
|||
id2 = id0+n;
|
||||
|
||||
cont = 1;
|
||||
while cont
|
||||
while cont
|
||||
tmp = ([A0; A2]/A1)*[A0 A2];
|
||||
A1 = A1 - tmp(id0,id2) - tmp(id2,id0);
|
||||
A0 = -tmp(id0,id0);
|
||||
|
@ -97,7 +97,7 @@ while cont
|
|||
info(2) = log(norm(A1,1));
|
||||
end
|
||||
return
|
||||
end
|
||||
end
|
||||
it = it + 1;
|
||||
end
|
||||
|
||||
|
|
|
@ -3,16 +3,16 @@ function datatomfile (s, var_list, names)
|
|||
% This command saves the simulation results in a text file. The name of each
|
||||
% variable preceeds the corresponding results. This command must follow SIMUL
|
||||
% or STOCH_SIMUL commands.
|
||||
%
|
||||
% INPUTS
|
||||
%
|
||||
% INPUTS
|
||||
% - s: data file name
|
||||
% - var_list: vector of selected endogenous variables
|
||||
% - names: vector of strings (alternative names for the endogenous variables in the data file)
|
||||
%
|
||||
% OUTPUTS
|
||||
% OUTPUTS
|
||||
% none
|
||||
%
|
||||
% REMARKS
|
||||
% REMARKS
|
||||
% Only the first argument is mandatory. If only one input argument is
|
||||
% provided, all the variables as defined in M_.endo_names will be saved in
|
||||
% the generated m file.
|
||||
|
@ -36,7 +36,7 @@ function datatomfile (s, var_list, names)
|
|||
|
||||
global M_ oo_
|
||||
|
||||
% Open the data file.
|
||||
% Open the data file.
|
||||
sm=[s,'.m'];
|
||||
fid=fopen(sm,'w') ;
|
||||
|
||||
|
@ -65,8 +65,8 @@ for i=1:n
|
|||
end
|
||||
end
|
||||
stack = dbstack;
|
||||
fprintf(fid,'%% Dataset generated by %s.\n',stack(2).file);
|
||||
fprintf(fid,['%% ' datestr(now,0) '\n']);
|
||||
fprintf(fid,'%% Dataset generated by %s.\n',stack(2).file);
|
||||
fprintf(fid,['%% ' datestr(now,0) '\n']);
|
||||
% Save the selected data.
|
||||
for i = 1:n
|
||||
fprintf(fid,[strtrim(names(i,:)), ' = ['],'\n') ;
|
||||
|
@ -78,4 +78,3 @@ end
|
|||
|
||||
% Close the data file.
|
||||
fclose(fid) ;
|
||||
|
||||
|
|
|
@ -52,5 +52,3 @@ z = mean(mean(abs(x(j,i)-y(j,i)))) ;
|
|||
disp (['The mean absolute difference between set ' s1(1,:) 'and set ' s1(2,:)]) ;
|
||||
disp (['is : ' num2str(z)]) ;
|
||||
return ;
|
||||
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
function info = delete_mh_history_files(MetropolisFolder, ModelName)
|
||||
|
||||
|
||||
% Copyright (C) 2013 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
|
|
@ -39,7 +39,7 @@ if isfield(M_,'orig_model')
|
|||
M_.maximum_lag = orig_model.maximum_lag;
|
||||
M_.maximum_endo_lag = orig_model.maximum_endo_lag;
|
||||
else
|
||||
M_.orig_model = M_;
|
||||
M_.orig_model = M_;
|
||||
end
|
||||
|
||||
beta = get_optimal_policy_discount_factor(M_.params,M_.param_names);
|
||||
|
@ -53,10 +53,10 @@ if isfield(M_,'orig_model')
|
|||
MaxLead = orig_model.maximum_lead;
|
||||
MaxLag = orig_model.maximum_lag;
|
||||
else
|
||||
endo_names = M_.endo_names;
|
||||
endo_nbr = M_.endo_nbr;
|
||||
MaxLag=M_.maximum_lag;
|
||||
MaxLead=M_.maximum_lead;
|
||||
endo_names = M_.endo_names;
|
||||
endo_nbr = M_.endo_nbr;
|
||||
MaxLag=M_.maximum_lag;
|
||||
MaxLead=M_.maximum_lead;
|
||||
lead_lag_incidence = M_.lead_lag_incidence;
|
||||
end
|
||||
|
||||
|
@ -64,7 +64,7 @@ end
|
|||
if options_.steadystate_flag
|
||||
% explicit steady state file
|
||||
[junk,M_.params,info] = evaluate_steady_state_file(oo_.steady_state,[oo_.exo_steady_state; oo_.exo_det_steady_state],M_, ...
|
||||
options_,0);
|
||||
options_,0);
|
||||
end
|
||||
[U,Uy,W] = feval([M_.fname,'_objective_static'],zeros(endo_nbr,1),[], M_.params);
|
||||
if any(any(Uy~=0))
|
||||
|
@ -96,32 +96,32 @@ eq_nbr= size(jacobia_,1);
|
|||
instr_nbr=endo_nbr-eq_nbr;
|
||||
|
||||
if instr_nbr==0
|
||||
error('discretionary_policy:: There are no available instruments, because the model has as many equations as variables.')
|
||||
error('discretionary_policy:: There are no available instruments, because the model has as many equations as variables.')
|
||||
end
|
||||
if size(Instruments,1)~= instr_nbr
|
||||
error('discretionary_policy:: There are more declared instruments than omitted equations.')
|
||||
end
|
||||
error('discretionary_policy:: There are more declared instruments than omitted equations.')
|
||||
end
|
||||
|
||||
instr_id=nan(instr_nbr,1);
|
||||
for j=1:instr_nbr
|
||||
vj=deblank(Instruments(j,:));
|
||||
vj_id=strmatch(vj,endo_names,'exact');
|
||||
if ~isempty(vj_id)
|
||||
instr_id(j)=vj_id;
|
||||
else
|
||||
error([mfilename,':: instrument ',vj,' not found'])
|
||||
end
|
||||
vj=deblank(Instruments(j,:));
|
||||
vj_id=strmatch(vj,endo_names,'exact');
|
||||
if ~isempty(vj_id)
|
||||
instr_id(j)=vj_id;
|
||||
else
|
||||
error([mfilename,':: instrument ',vj,' not found'])
|
||||
end
|
||||
end
|
||||
|
||||
Indices={'lag','0','lead'};
|
||||
iter=1;
|
||||
for j=1:numel(Indices)
|
||||
eval(['A',Indices{j},'=zeros(eq_nbr,endo_nbr);'])
|
||||
if strcmp(Indices{j},'0')||(strcmp(Indices{j},'lag') && MaxLag)||(strcmp(Indices{j},'lead') && MaxLead)
|
||||
[junk,row,col]=find(lead_lag_incidence(iter,:));
|
||||
eval(['A',Indices{j},'(:,row)=jacobia_(:,col);'])
|
||||
iter=iter+1;
|
||||
end
|
||||
if strcmp(Indices{j},'0')||(strcmp(Indices{j},'lag') && MaxLag)||(strcmp(Indices{j},'lead') && MaxLead)
|
||||
[junk,row,col]=find(lead_lag_incidence(iter,:));
|
||||
eval(['A',Indices{j},'(:,row)=jacobia_(:,col);'])
|
||||
iter=iter+1;
|
||||
end
|
||||
end
|
||||
B=jacobia_(:,nnz(iyv)+1:end);
|
||||
|
||||
|
@ -131,17 +131,17 @@ solve_maxit = options_.dp.maxit;
|
|||
discretion_tol = options_.discretionary_tol;
|
||||
|
||||
if ~isempty(Hold)
|
||||
[H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,Hold);
|
||||
[H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,Hold);
|
||||
else
|
||||
[H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium);
|
||||
[H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium);
|
||||
end
|
||||
|
||||
if info
|
||||
dr=[];
|
||||
return
|
||||
else
|
||||
Hold=H; %save previous solution
|
||||
% Hold=[]; use this line if persistent command is not used.
|
||||
Hold=H; %save previous solution
|
||||
% Hold=[]; use this line if persistent command is not used.
|
||||
end
|
||||
% set the state
|
||||
dr=oo_.dr;
|
||||
|
@ -159,7 +159,7 @@ dr.ys=ys; % <--- dr.ys =zeros(NewEndo_nbr,1);
|
|||
|
||||
function ys=NondistortionarySteadyState(M_)
|
||||
if exist([M_.fname,'_steadystate.m'],'file')
|
||||
eval(['ys=',M_.fname,'_steadystate.m;'])
|
||||
eval(['ys=',M_.fname,'_steadystate.m;'])
|
||||
else
|
||||
ys=zeros(M_.endo_nbr,1);
|
||||
ys=zeros(M_.endo_nbr,1);
|
||||
end
|
||||
|
|
|
@ -1,23 +1,23 @@
|
|||
function [H,G,retcode]=discretionary_policy_engine(AAlag,AA0,AAlead,BB,bigw,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,H00,verbose)
|
||||
|
||||
% Solves the discretionary problem for a model of the form:
|
||||
%
|
||||
%
|
||||
% Loss=E_0 sum_{t=0}^{\infty} beta^t [y_t'*W*y+x_t'*Q*x_t]
|
||||
% subject to
|
||||
% AAlag*yy_{t-1}+AA0*yy_t+AAlead*yy_{t+1}+BB*e=0
|
||||
%
|
||||
%
|
||||
% with W the weight on the variables in vector y_t.
|
||||
%
|
||||
%
|
||||
% The solution takes the form
|
||||
% y_t=H*y_{t-1}+G*e_t
|
||||
% where H=[H1;F1] and G=[H2;F2].
|
||||
%
|
||||
%
|
||||
% We use the Dennis (2007, Macroeconomic Dynamics) algorithm and so we need
|
||||
% to re-write the model in the form
|
||||
% A0*y_t=A1*y_{t-1}+A2*y_{t+1}+A3*x_t+A4*x_{t+1}+A5*e_t, with W the
|
||||
% weight on the y_t vector and Q the weight on the x_t vector of
|
||||
% instruments.
|
||||
%
|
||||
%
|
||||
% Inputs:
|
||||
% AAlag [double] matrix of coefficients on lagged
|
||||
% variables
|
||||
|
@ -28,7 +28,7 @@ function [H,G,retcode]=discretionary_policy_engine(AAlag,AA0,AAlead,BB,bigw,inst
|
|||
% BB [double] matrix of coefficients on
|
||||
% shocks
|
||||
% bigw [double] matrix of coefficients on variables in
|
||||
% loss/objective function; stacks [W and Q]
|
||||
% loss/objective function; stacks [W and Q]
|
||||
% instr_id [double] location vector of the instruments in the yy_t vector.
|
||||
% beta [scalar] planner discount factor
|
||||
% solve_maxit [scalar] maximum number of iterations
|
||||
|
@ -41,12 +41,12 @@ function [H,G,retcode]=discretionary_policy_engine(AAlag,AA0,AAlead,BB,bigw,inst
|
|||
% H [double] (endo_nbr*endo_nbr) solution matrix for endogenous
|
||||
% variables, stacks [H1 and H1]
|
||||
% G [double] (endo_nbr*exo_nbr) solution matrix for shocks, stacks [H2 and F2]
|
||||
%
|
||||
%
|
||||
% retcode [scalar] return code
|
||||
%
|
||||
% Algorithm:
|
||||
% Dennis, Richard (2007): Optimal policy in rational expectations models: new solution algorithms,
|
||||
% Macroeconomic Dynamics, 11, 31–55.
|
||||
% Macroeconomic Dynamics, 11, 3155.
|
||||
|
||||
% Copyright (C) 2007-2017 Dynare Team
|
||||
%
|
||||
|
@ -121,10 +121,10 @@ while 1
|
|||
end
|
||||
D=A0-A2*H1-A4*F1; %equation (20)
|
||||
Dinv=inv(D);
|
||||
A3DPD=A3'*Dinv'*P*Dinv;
|
||||
A3DPD=A3'*Dinv'*P*Dinv;
|
||||
F1=-(Q+A3DPD*A3)\(A3DPD*A1); %component of (26)
|
||||
H1=Dinv*(A1+A3*F1); %component of (27)
|
||||
|
||||
|
||||
[rcode,NQ]=CheckConvergence([H1;F1]-[H10;F10],iter,solve_maxit,discretion_tol);
|
||||
if rcode
|
||||
break
|
||||
|
@ -174,7 +174,7 @@ else
|
|||
H(instr_id,endo_augm_id)=F1;
|
||||
G(endo_augm_id,:)=H2;
|
||||
G(instr_id,:)=F2;
|
||||
|
||||
|
||||
% Account for auxilliary variables
|
||||
H(:,instr_id(aux))=H(:,end-(AuxiliaryVariables_nbr-1:-1:0));
|
||||
H=H(1:endo_nbr,1:endo_nbr);
|
||||
|
@ -253,7 +253,7 @@ end
|
|||
|
||||
function v = SylvesterHessenbergSchur(d,g,h)
|
||||
%
|
||||
% DSYLHS Solves a discrete time sylvester equation using the
|
||||
% DSYLHS Solves a discrete time sylvester equation using the
|
||||
% Hessenberg-Schur algorithm
|
||||
%
|
||||
% v = DSYLHS(g,d,h) computes the matrix v that satisfies the
|
||||
|
@ -301,7 +301,7 @@ if i< n
|
|||
i = i+1;
|
||||
else
|
||||
A = [w-g*h(i,i) (-g*h(i+1,i));...
|
||||
-g*h(i,i+1) w-g*h(i+1,i+1)];
|
||||
-g*h(i,i+1) w-g*h(i+1,i+1)];
|
||||
C = [d(:,i); d(:,i+1)];
|
||||
X = A\C;
|
||||
v(:,i) = X(1:m,:);
|
||||
|
@ -320,9 +320,9 @@ while i<n
|
|||
i = i+1;
|
||||
else
|
||||
A = [w - g*h(i,i) (-g*h(i+1,i)); ...
|
||||
-g*h(i,i+1) w - g*h(i+1,i+1)];
|
||||
-g*h(i,i+1) w - g*h(i+1,i+1)];
|
||||
C = [d(:,i) + temp*h(1:b,i); ...
|
||||
d(:,i+1) + temp*h(1:b,i+1)];
|
||||
d(:,i+1) + temp*h(1:b,i+1)];
|
||||
X = A\C;
|
||||
v(:,i) = X(1:m,:);
|
||||
v(:,i+1) = X(m+1:2*m, :);
|
||||
|
|
|
@ -7,7 +7,7 @@ function disp_dr(dr,order,var_list)
|
|||
% order [int]: order of approximation
|
||||
% var_list [char array]: list of endogenous variables for which the
|
||||
% decision rules should be printed
|
||||
%
|
||||
%
|
||||
% Copyright (C) 2001-2017 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -80,7 +80,7 @@ var_name_width=max([max(size(deblank(M_.endo_names(k1(ivar),:)),2)),max(size(deb
|
|||
|
||||
%deal with covariances
|
||||
if order > 1
|
||||
var_name_width=max(2*(var_name_width+aux_var_additional_characters)+2,20); %account for covariances, separated by comma
|
||||
var_name_width=max(2*(var_name_width+aux_var_additional_characters)+2,20); %account for covariances, separated by comma
|
||||
else
|
||||
var_name_width=max(var_name_width+aux_var_additional_characters,20);
|
||||
end
|
||||
|
@ -90,7 +90,7 @@ label_format = sprintf('%%-%ds',var_name_width);
|
|||
%% start displayimg
|
||||
disp('POLICY AND TRANSITION FUNCTIONS')
|
||||
% variable names
|
||||
str = char(32*ones(1,var_name_width));
|
||||
str = char(32*ones(1,var_name_width));
|
||||
for i=1:nvar
|
||||
str = [str sprintf(header_label_format,deblank(M_.endo_names(k1(ivar(i)),:)))];
|
||||
end
|
||||
|
@ -232,7 +232,7 @@ for i = 1:length(M_.aux_vars)
|
|||
if M_.aux_vars(i).endo_index == aux_index
|
||||
switch M_.aux_vars(i).type
|
||||
case 0
|
||||
str = sprintf('%s(%d)',deblank(M_.endo_names(aux_index,:)),aux_lead_lag);
|
||||
str = sprintf('%s(%d)',deblank(M_.endo_names(aux_index,:)),aux_lead_lag);
|
||||
return
|
||||
case 1
|
||||
orig_name = deblank(M_.endo_names(M_.aux_vars(i).orig_index, :));
|
||||
|
@ -256,10 +256,10 @@ error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :)))
|
|||
end
|
||||
|
||||
function [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_)
|
||||
if abs(x) >= options_.dr_display_tol
|
||||
flag = 1;
|
||||
str = [str sprintf(value_format_float,x)];
|
||||
else
|
||||
str = [str sprintf(value_format_zero,0)];
|
||||
end
|
||||
if abs(x) >= options_.dr_display_tol
|
||||
flag = 1;
|
||||
str = [str sprintf(value_format_float,x)];
|
||||
else
|
||||
str = [str sprintf(value_format_zero,0)];
|
||||
end
|
||||
end
|
|
@ -118,7 +118,7 @@ if any(idemodel.ino)
|
|||
disp([' [',name{jx(1)},',',name{jy(1)},'] are PAIRWISE collinear (with tol = 1.e-10) !' ])
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
end
|
||||
skipline()
|
||||
for j=1:npar
|
||||
|
@ -133,23 +133,23 @@ if any(idemodel.ino)
|
|||
end
|
||||
end
|
||||
end
|
||||
% if npar>(j+1),
|
||||
% [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))'>(1-1.e-10));
|
||||
% else
|
||||
% [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))>(1-1.e-10));
|
||||
% end
|
||||
% if ~isempty(jpair),
|
||||
% for jx=j+1:npar,
|
||||
% ixp = find(jx==(jpair+j));
|
||||
% if ~isempty(ixp)
|
||||
% if SampleSize > 1,
|
||||
% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ])
|
||||
% else
|
||||
% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10)!' ])
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
% if npar>(j+1),
|
||||
% [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))'>(1-1.e-10));
|
||||
% else
|
||||
% [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))>(1-1.e-10));
|
||||
% end
|
||||
% if ~isempty(jpair),
|
||||
% for jx=j+1:npar,
|
||||
% ixp = find(jx==(jpair+j));
|
||||
% if ~isempty(ixp)
|
||||
% if SampleSize > 1,
|
||||
% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ])
|
||||
% else
|
||||
% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10)!' ])
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
end
|
||||
|
||||
if ~any(idemodel.ino) && ~any(any(idemodel.ind0==0))
|
||||
|
@ -167,10 +167,10 @@ if any(idemoments.ino)
|
|||
end
|
||||
% disp('WARNING !!!')
|
||||
% disp(['The rank of J (moments) is deficient for ', num2str(length(find(idemoments.ino))/SampleSize*100),'% of MC runs!' ]),
|
||||
% indno=[];
|
||||
% for j=1:SampleSize, indno=[indno;idemoments.indno{j}]; end
|
||||
% freqno = mean(indno)*100;
|
||||
% ifreq=find(freqno);
|
||||
% indno=[];
|
||||
% for j=1:SampleSize, indno=[indno;idemoments.indno{j}]; end
|
||||
% freqno = mean(indno)*100;
|
||||
% ifreq=find(freqno);
|
||||
% disp('MOMENT RANK FAILURE DUE TO COLLINEARITY OF PARAMETERS:');
|
||||
skipline()
|
||||
for j=1:npar
|
||||
|
@ -199,7 +199,7 @@ if any(idemoments.ino)
|
|||
disp([' [',name{jx(1)},',',name{jy(1)},'] are PAIRWISE collinear (with tol = 1.e-10) !' ])
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
end
|
||||
skipline()
|
||||
for j=1:npar
|
||||
|
@ -214,25 +214,25 @@ if any(idemoments.ino)
|
|||
end
|
||||
end
|
||||
end
|
||||
% if npar>(j+1),
|
||||
% [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))'>(1-1.e-10));
|
||||
% else
|
||||
% [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))>(1-1.e-10));
|
||||
% end
|
||||
% if ~isempty(jpair),
|
||||
% for jx=j+1:npar,
|
||||
% ixp = find(jx==(jpair+j));
|
||||
% if ~isempty(ixp)
|
||||
% if SampleSize > 1
|
||||
% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ])
|
||||
% else
|
||||
% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) !' ])
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
% if npar>(j+1),
|
||||
% [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))'>(1-1.e-10));
|
||||
% else
|
||||
% [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))>(1-1.e-10));
|
||||
% end
|
||||
% if ~isempty(jpair),
|
||||
% for jx=j+1:npar,
|
||||
% ixp = find(jx==(jpair+j));
|
||||
% if ~isempty(ixp)
|
||||
% if SampleSize > 1
|
||||
% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ])
|
||||
% else
|
||||
% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) !' ])
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
% end
|
||||
end
|
||||
if ~any(idemoments.ino) && ~any(any(idemoments.ind0==0))
|
||||
skipline()
|
||||
|
@ -255,12 +255,12 @@ end
|
|||
% if advanced && (~options_.noprint),
|
||||
% for j=1:length(kokP),
|
||||
% dyntable([name{kokP(j)},' pairwise correlations in the model'],char(' ','min','mean','max'), ...
|
||||
% char(name{jpM{j}}),[pminM{j}' pmeanM{j}' pmaxM{j}'],10,10,3);
|
||||
% char(name{jpM{j}}),[pminM{j}' pmeanM{j}' pmaxM{j}'],10,10,3);
|
||||
% end
|
||||
%
|
||||
%
|
||||
% for j=1:length(kokPJ),
|
||||
% dyntable([name{kokPJ(j)},' pairwise correlations in J moments'],char(' ','min','mean','max'), ...
|
||||
% char(name{jpJ{j}}),[pminJ{j}' pmeanJ{j}' pmaxJ{j}'],10,10,3);
|
||||
% char(name{jpJ{j}}),[pminJ{j}' pmeanJ{j}' pmaxJ{j}'],10,10,3);
|
||||
% end
|
||||
% end
|
||||
% disp(' ')
|
||||
|
|
|
@ -4,7 +4,7 @@ function disp_model_summary(M,dr,options)
|
|||
% displays the model summary
|
||||
%
|
||||
% INPUTS
|
||||
% M [matlab structure] Definition of the model.
|
||||
% M [matlab structure] Definition of the model.
|
||||
% dr [matlab structure] Decision rules
|
||||
% options [matlab structure] Options
|
||||
%
|
||||
|
@ -40,4 +40,3 @@ labels = deblank(M.exo_names);
|
|||
headers = char('Variables',labels);
|
||||
lh = size(labels,2)+2;
|
||||
dyntable(options,my_title,headers,labels,M.Sigma_e,lh,10,6);
|
||||
|
||||
|
|
|
@ -7,7 +7,7 @@ function oo_=disp_moments(y,var_list,M_,options_,oo_)
|
|||
% M_ [structure] Dynare's model structure
|
||||
% oo_ [structure] Dynare's results structure
|
||||
% options_ [structure] Dynare's options structure
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% oo_ [structure] Dynare's results structure,
|
||||
|
||||
|
@ -57,18 +57,18 @@ s2 = mean(y.*y);
|
|||
s = sqrt(s2);
|
||||
oo_.mean = transpose(m);
|
||||
oo_.var = y'*y/size(y,1);
|
||||
oo_.skewness = (mean(y.^3)./s2.^1.5)';
|
||||
oo_.skewness = (mean(y.^3)./s2.^1.5)';
|
||||
oo_.kurtosis = (mean(y.^4)./(s2.*s2)-3)';
|
||||
|
||||
labels = deblank(M_.endo_names(ivar,:));
|
||||
labels_TeX = deblank(M_.endo_names_tex(ivar,:));
|
||||
|
||||
if options_.nomoments == 0
|
||||
z = [ m' s' s2' (mean(y.^3)./s2.^1.5)' (mean(y.^4)./(s2.*s2)-3)' ];
|
||||
z = [ m' s' s2' (mean(y.^3)./s2.^1.5)' (mean(y.^4)./(s2.*s2)-3)' ];
|
||||
title='MOMENTS OF SIMULATED VARIABLES';
|
||||
|
||||
|
||||
title=add_filter_subtitle(title,options_);
|
||||
|
||||
|
||||
headers=char('VARIABLE','MEAN','STD. DEV.','VARIANCE','SKEWNESS', ...
|
||||
'KURTOSIS');
|
||||
dyntable(options_,title,headers,labels,z,size(labels,2)+2,16,6);
|
||||
|
@ -79,7 +79,7 @@ end
|
|||
|
||||
if options_.nocorr == 0
|
||||
corr = (y'*y/size(y,1))./(s'*s);
|
||||
if options_.contemporaneous_correlation
|
||||
if options_.contemporaneous_correlation
|
||||
oo_.contemporaneous_correlation = corr;
|
||||
end
|
||||
if options_.noprint == 0
|
||||
|
@ -98,7 +98,7 @@ if options_.nocorr == 0
|
|||
end
|
||||
|
||||
if options_.noprint == 0 && length(options_.conditional_variance_decomposition)
|
||||
fprintf('\nSTOCH_SIMUL: conditional_variance_decomposition requires theoretical moments, i.e. periods=0.\n')
|
||||
fprintf('\nSTOCH_SIMUL: conditional_variance_decomposition requires theoretical moments, i.e. periods=0.\n')
|
||||
end
|
||||
|
||||
ar = options_.ar;
|
||||
|
@ -119,7 +119,7 @@ if ar > 0
|
|||
dyn_latex_table(M_,options_,title,'sim_autocorr_matrix',headers,labels_TeX,autocorr,size(labels_TeX,2)+2,8,4);
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
end
|
||||
|
||||
|
||||
|
@ -143,7 +143,7 @@ if ~options_.nodecomposition
|
|||
chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var)); %decompose rest
|
||||
shock_mat=zeros(options_.periods,M_.exo_nbr); %initialize
|
||||
shock_mat(:,i_exo_var)=oo_.exo_simul(:,i_exo_var)/chol_S; %invert construction of oo_.exo_simul from simult.m
|
||||
|
||||
|
||||
for shock_iter=1:length(i_exo_var)
|
||||
temp_shock_mat=zeros(size(shock_mat));
|
||||
temp_shock_mat(:,i_exo_var(shock_iter))=shock_mat(:,i_exo_var(shock_iter));
|
||||
|
@ -156,9 +156,9 @@ if ~options_.nodecomposition
|
|||
if ~options_.noprint %options_.nomoments == 0
|
||||
skipline()
|
||||
title='VARIANCE DECOMPOSITION SIMULATING ONE SHOCK AT A TIME (in percent)';
|
||||
|
||||
|
||||
title=add_filter_subtitle(title,options_);
|
||||
|
||||
|
||||
headers = M_.exo_names;
|
||||
headers(M_.exo_names_orig_ord,:) = headers;
|
||||
headers = char(' ',headers);
|
||||
|
@ -181,12 +181,12 @@ if ~options_.nodecomposition
|
|||
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
warning(warning_old_state);
|
||||
end
|
||||
|
||||
function y=get_filtered_time_series(y,m,options_)
|
||||
|
||||
|
||||
if options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpass.indicator
|
||||
[hptrend,y] = sample_hp_filter(y,options_.hp_filter);
|
||||
elseif ~options_.hp_filter && options_.one_sided_hp_filter && ~options_.bandpass.indicator
|
||||
|
@ -197,8 +197,8 @@ elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && options_.bandpass
|
|||
y=data_temp.data;
|
||||
elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpass.indicator
|
||||
y = bsxfun(@minus, y, m);
|
||||
else
|
||||
else
|
||||
error('disp_moments:: You cannot use more than one filter at the same time')
|
||||
end
|
||||
|
||||
|
||||
end
|
|
@ -1,11 +1,11 @@
|
|||
function disp_steady_state(M,oo)
|
||||
% function disp_steady_state(M,oo)
|
||||
% computes and prints the steady state calculations
|
||||
%
|
||||
%
|
||||
% INPUTS
|
||||
% M structure of parameters
|
||||
% oo structure of results
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% none
|
||||
%
|
||||
|
|
|
@ -76,7 +76,7 @@ if size(stationary_vars, 1) > 0
|
|||
if M_.exo_nbr > 1 && ~nodecomposition
|
||||
skipline()
|
||||
if options_.order == 2
|
||||
title='APPROXIMATED VARIANCE DECOMPOSITION (in percent)';
|
||||
title='APPROXIMATED VARIANCE DECOMPOSITION (in percent)';
|
||||
else
|
||||
title='VARIANCE DECOMPOSITION (in percent)';
|
||||
end
|
||||
|
@ -86,7 +86,7 @@ if size(stationary_vars, 1) > 0
|
|||
headers = char(' ',headers);
|
||||
lh = size(deblank(M_.endo_names(ivar(stationary_vars),:)),2)+2;
|
||||
dyntable(options_,title,headers,deblank(M_.endo_names(ivar(stationary_vars), ...
|
||||
:)),100* ...
|
||||
:)),100* ...
|
||||
oo_.gamma_y{options_.ar+2}(stationary_vars,:),lh,8,2);
|
||||
if options_.TeX
|
||||
headers=M_.exo_names_tex;
|
||||
|
@ -97,7 +97,7 @@ if size(stationary_vars, 1) > 0
|
|||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
conditional_variance_steps = options_.conditional_variance_decomposition;
|
||||
if length(conditional_variance_steps)
|
||||
StateSpaceModel.number_of_state_equations = M_.endo_nbr;
|
||||
|
@ -107,10 +107,10 @@ if size(stationary_vars, 1) > 0
|
|||
StateSpaceModel.state_innovations_covariance_matrix = M_.Sigma_e;
|
||||
StateSpaceModel.order_var = dr.order_var;
|
||||
oo_.conditional_variance_decomposition = conditional_variance_decomposition(StateSpaceModel,conditional_variance_steps,ivar);
|
||||
|
||||
|
||||
if options_.noprint == 0
|
||||
display_conditional_variance_decomposition(oo_.conditional_variance_decomposition,conditional_variance_steps,...
|
||||
ivar,M_,options_);
|
||||
ivar,M_,options_);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -124,13 +124,13 @@ end
|
|||
|
||||
if options_.nocorr == 0 && size(stationary_vars, 1) > 0
|
||||
corr = oo_.gamma_y{1}(i1,i1)./(sd(i1)*sd(i1)');
|
||||
if options_.contemporaneous_correlation
|
||||
if options_.contemporaneous_correlation
|
||||
oo_.contemporaneous_correlation = corr;
|
||||
end
|
||||
if ~options_.noprint
|
||||
skipline()
|
||||
if options_.order == 2
|
||||
title='APPROXIMATED MATRIX OF CORRELATIONS';
|
||||
title='APPROXIMATED MATRIX OF CORRELATIONS';
|
||||
else
|
||||
title='MATRIX OF CORRELATIONS';
|
||||
end
|
||||
|
@ -154,22 +154,22 @@ if options_.ar > 0 && size(stationary_vars, 1) > 0
|
|||
z(:,i) = diag(oo_.gamma_y{i+1}(i1,i1));
|
||||
end
|
||||
if ~options_.noprint
|
||||
skipline()
|
||||
skipline()
|
||||
if options_.order == 2
|
||||
title='APPROXIMATED COEFFICIENTS OF AUTOCORRELATION';
|
||||
title='APPROXIMATED COEFFICIENTS OF AUTOCORRELATION';
|
||||
else
|
||||
title='COEFFICIENTS OF AUTOCORRELATION';
|
||||
end
|
||||
title=add_filter_subtitle(title,options_);
|
||||
labels = deblank(M_.endo_names(ivar(i1),:));
|
||||
labels = deblank(M_.endo_names(ivar(i1),:));
|
||||
headers = char('Order ',int2str([1:options_.ar]'));
|
||||
lh = size(labels,2)+2;
|
||||
dyntable(options_,title,headers,labels,z,lh,8,4);
|
||||
if options_.TeX
|
||||
labels = deblank(M_.endo_names_tex(ivar(i1),:));
|
||||
labels = deblank(M_.endo_names_tex(ivar(i1),:));
|
||||
headers=char('Order ',int2str([1:options_.ar]'));
|
||||
lh = size(labels,2)+2;
|
||||
dyn_latex_table(M_,options_,title,'th_autocorr_matrix',headers,labels,z,lh,8,4);
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
function display_conditional_variance_decomposition(conditional_decomposition_array,Steps,SubsetOfVariables,M_,options_)
|
||||
% This function displays the conditional variance decomposition of a given state space model
|
||||
% for a subset of endogenous variables.
|
||||
%
|
||||
% INPUTS
|
||||
%
|
||||
% INPUTS
|
||||
% conditional_decomposition_array [matrix] Output matrix from compute_conditional_variance_decomposition
|
||||
% Steps [integer] 1*h vector of dates.
|
||||
% SubsetOfVariables [integer] 1*q vector of indices.
|
||||
|
@ -10,7 +10,7 @@ function display_conditional_variance_decomposition(conditional_decomposition_ar
|
|||
% Model description
|
||||
% options_ [structure] Dynare structure containing the
|
||||
% options
|
||||
% OUTPUTS
|
||||
% OUTPUTS
|
||||
% none
|
||||
%
|
||||
% Copyright (C) 2010-2016 Dynare Team
|
||||
|
@ -56,10 +56,10 @@ for i=1:length(Steps)
|
|||
dyntable(options_,'',headers,...
|
||||
deblank(M_.endo_names(SubsetOfVariables,:)),...
|
||||
vardec_i,lh,8,2);
|
||||
if options_.TeX
|
||||
labels_TeX = deblank(M_.endo_names_tex(SubsetOfVariables,:));
|
||||
headers_TeX=char('',deblank(M_.exo_names_tex));
|
||||
lh = size(labels_TeX,2)+2;
|
||||
dyn_latex_table(M_,options_,[title,'; Period ' int2str(Steps(i))],['th_var_decomp_cond_h',int2str(Steps(i))],headers_TeX,labels_TeX,vardec_i,lh,8,2);
|
||||
end
|
||||
if options_.TeX
|
||||
labels_TeX = deblank(M_.endo_names_tex(SubsetOfVariables,:));
|
||||
headers_TeX=char('',deblank(M_.exo_names_tex));
|
||||
lh = size(labels_TeX,2)+2;
|
||||
dyn_latex_table(M_,options_,[title,'; Period ' int2str(Steps(i))],['th_var_decomp_cond_h',int2str(Steps(i))],headers_TeX,labels_TeX,vardec_i,lh,8,2);
|
||||
end
|
||||
end
|
|
@ -1,20 +1,20 @@
|
|||
function oo_=display_estimation_results_table(xparam1,stdh,M_,options_,estim_params_,bayestopt_,oo_,pnames,table_title,field_name)
|
||||
%function oo_=display_results_table(xparam1,stdh,M_,estim_params_,bayestopt_,oo_,pnames,table_title,field_name)
|
||||
% Display estimation results on screen and write them to TeX-file
|
||||
%
|
||||
% INPUTS
|
||||
%
|
||||
% INPUTS
|
||||
% o xparam1 [double] (p*1) vector of estimate parameters.
|
||||
% o stdh [double] (p*1) vector of estimate parameters.
|
||||
% o M_ Matlab's structure describing the Model (initialized by dynare, see @ref{M_}).
|
||||
% o M_ Matlab's structure describing the Model (initialized by dynare, see @ref{M_}).
|
||||
% o estim_params_ Matlab's structure describing the estimated_parameters (initialized by dynare, see @ref{estim_params_}).
|
||||
% o options_ Matlab's structure describing the options (initialized by dynare, see @ref{options_}).
|
||||
% o bayestopt_ Matlab's structure describing the priors (initialized by dynare, see @ref{bayesopt_}).
|
||||
% o oo_ Matlab's structure gathering the results (initialized by dynare, see @ref{oo_}).
|
||||
% o pnames [string] Character Array storing the names for prior distributions
|
||||
% o table_title [string] Title of the Table
|
||||
% o pnames [string] Character Array storing the names for prior distributions
|
||||
% o table_title [string] Title of the Table
|
||||
% o field_name [string] String storing the name of the fields for oo_ where the parameters are stored
|
||||
%
|
||||
% OUTPUTS
|
||||
%
|
||||
% OUTPUTS
|
||||
% o oo_ Matlab's structure gathering the results
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
|
@ -64,13 +64,13 @@ if np
|
|||
name = bayestopt_.name{ip};
|
||||
if strcmp(field_name,'posterior')
|
||||
fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ...
|
||||
header_width,name, ...
|
||||
bayestopt_.p1(ip),xparam1(ip),stdh(ip), ...
|
||||
pnames(bayestopt_.pshape(ip)+1,:), ...
|
||||
bayestopt_.p2(ip));
|
||||
header_width,name, ...
|
||||
bayestopt_.p1(ip),xparam1(ip),stdh(ip), ...
|
||||
pnames(bayestopt_.pshape(ip)+1,:), ...
|
||||
bayestopt_.p2(ip));
|
||||
else
|
||||
fprintf('%-*s %8.4f %7.4f %7.4f \n', ...
|
||||
header_width,name,xparam1(ip),stdh(ip),tstath(ip));
|
||||
header_width,name,xparam1(ip),stdh(ip),tstath(ip));
|
||||
end
|
||||
eval(['oo_.' field_name '_mode.parameters.' name ' = xparam1(ip);']);
|
||||
eval(['oo_.' field_name '_std_at_mode.parameters.' name ' = stdh(ip);']);
|
||||
|
@ -87,9 +87,9 @@ if nvx
|
|||
name = deblank(M_.exo_names(k,:));
|
||||
if strcmp(field_name,'posterior')
|
||||
fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ...
|
||||
header_width,name,bayestopt_.p1(ip),xparam1(ip), ...
|
||||
stdh(ip),pnames(bayestopt_.pshape(ip)+1,:), ...
|
||||
bayestopt_.p2(ip));
|
||||
header_width,name,bayestopt_.p1(ip),xparam1(ip), ...
|
||||
stdh(ip),pnames(bayestopt_.pshape(ip)+1,:), ...
|
||||
bayestopt_.p2(ip));
|
||||
else
|
||||
fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip));
|
||||
end
|
||||
|
@ -99,28 +99,28 @@ if nvx
|
|||
ip = ip+1;
|
||||
end
|
||||
skipline()
|
||||
end
|
||||
if nvn
|
||||
end
|
||||
if nvn
|
||||
disp('standard deviation of measurement errors')
|
||||
disp(tit1)
|
||||
ip = nvx+1;
|
||||
for i=1:nvn
|
||||
name = options_.varobs{estim_params_.nvn_observable_correspondence(i,1)};
|
||||
if strcmp(field_name,'posterior')
|
||||
if strcmp(field_name,'posterior')
|
||||
fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ...
|
||||
header_width,name,bayestopt_.p1(ip), ...
|
||||
xparam1(ip),stdh(ip), ...
|
||||
pnames(bayestopt_.pshape(ip)+1,:), ...
|
||||
bayestopt_.p2(ip));
|
||||
header_width,name,bayestopt_.p1(ip), ...
|
||||
xparam1(ip),stdh(ip), ...
|
||||
pnames(bayestopt_.pshape(ip)+1,:), ...
|
||||
bayestopt_.p2(ip));
|
||||
else
|
||||
fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip))
|
||||
fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip))
|
||||
end
|
||||
eval(['oo_.' field_name '_mode.measurement_errors_std.' name ' = xparam1(ip);']);
|
||||
eval(['oo_.' field_name '_std_at_mode.measurement_errors_std.' name ' = stdh(ip);']);
|
||||
ip = ip+1;
|
||||
end
|
||||
skipline()
|
||||
end
|
||||
end
|
||||
|
||||
if ncx
|
||||
disp('correlation of shocks')
|
||||
|
@ -131,12 +131,12 @@ if ncx
|
|||
k2 = estim_params_.corrx(i,2);
|
||||
name = [deblank(M_.exo_names(k1,:)) ',' deblank(M_.exo_names(k2,:))];
|
||||
NAME = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))];
|
||||
if strcmp(field_name,'posterior')
|
||||
if strcmp(field_name,'posterior')
|
||||
fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ...
|
||||
header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip), ...
|
||||
pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip));
|
||||
header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip), ...
|
||||
pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip));
|
||||
else
|
||||
fprintf('%-*s %8.4f %7.4f %7.4f \n', header_width,name,xparam1(ip),stdh(ip),tstath(ip));
|
||||
fprintf('%-*s %8.4f %7.4f %7.4f \n', header_width,name,xparam1(ip),stdh(ip),tstath(ip));
|
||||
end
|
||||
M_.Sigma_e(k1,k2) = xparam1(ip)*sqrt(M_.Sigma_e(k1,k1)*M_.Sigma_e(k2,k2));
|
||||
M_.Sigma_e(k2,k1) = M_.Sigma_e(k1,k2);
|
||||
|
@ -156,12 +156,12 @@ if ncn
|
|||
k2 = estim_params_.corrn(i,2);
|
||||
name = [deblank(M_.endo_names(k1,:)) ',' deblank(M_.endo_names(k2,:))];
|
||||
NAME = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))];
|
||||
if strcmp(field_name,'posterior')
|
||||
if strcmp(field_name,'posterior')
|
||||
fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ...
|
||||
header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip), ...
|
||||
pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip));
|
||||
header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip), ...
|
||||
pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip));
|
||||
else
|
||||
fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip));
|
||||
fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip));
|
||||
end
|
||||
eval(['oo_.' field_name '_mode.measurement_errors_corr.' NAME ' = xparam1(ip);']);
|
||||
eval(['oo_.' field_name '_std_at_mode.measurement_errors_corr.' NAME ' = stdh(ip);']);
|
||||
|
@ -268,17 +268,17 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
|
|||
TeXEnd(fidTeX)
|
||||
end
|
||||
elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
|
||||
if np
|
||||
if np
|
||||
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_1.tex'];
|
||||
fidTeX = fopen(filename,'w');
|
||||
TeXBegin_ML(fidTeX,1,'parameters',table_title,LaTeXtitle)
|
||||
TeXBegin_ML(fidTeX,1,'parameters',table_title,LaTeXtitle)
|
||||
ip = nvx+nvn+ncx+ncn+1;
|
||||
for i=1:np
|
||||
fprintf(fidTeX,'$%s$ & %8.4f & %7.4f & %7.4f\\\\ \n',...
|
||||
M_.param_names_tex(estim_params_.param_vals(i,1),:),...
|
||||
xparam1(ip),...
|
||||
stdh(ip),...
|
||||
tstath(ip));
|
||||
tstath(ip));
|
||||
ip = ip + 1;
|
||||
end
|
||||
TeXEnd(fidTeX)
|
||||
|
@ -286,7 +286,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
|
|||
if nvx
|
||||
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_2.tex'];
|
||||
fidTeX = fopen(filename,'w');
|
||||
TeXBegin_ML(fidTeX,2,'standard deviation of structural shocks',table_title,LaTeXtitle)
|
||||
TeXBegin_ML(fidTeX,2,'standard deviation of structural shocks',table_title,LaTeXtitle)
|
||||
ip = 1;
|
||||
for i=1:nvx
|
||||
k = estim_params_.var_exo(i,1);
|
||||
|
@ -302,11 +302,11 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
|
|||
if nvn
|
||||
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_3.tex'];
|
||||
fidTeX = fopen(filename,'w');
|
||||
TeXBegin_ML(fidTeX,3,'standard deviation of measurement errors',table_title,LaTeXtitle)
|
||||
TeXBegin_ML(fidTeX,3,'standard deviation of measurement errors',table_title,LaTeXtitle)
|
||||
ip = nvx+1;
|
||||
for i=1:nvn
|
||||
idx = strmatch(options_.varobs{estim_params_.nvn_observable_correspondence(i,1)},M_.endo_names);
|
||||
fprintf(fidTeX,'$%s$ & %8.4f & %7.4f & %7.4f \\\\ \n',...
|
||||
idx = strmatch(options_.varobs{estim_params_.nvn_observable_correspondence(i,1)},M_.endo_names);
|
||||
fprintf(fidTeX,'$%s$ & %8.4f & %7.4f & %7.4f \\\\ \n',...
|
||||
deblank(M_.endo_names_tex(idx,:)), ...
|
||||
xparam1(ip),...
|
||||
stdh(ip),...
|
||||
|
@ -318,7 +318,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
|
|||
if ncx
|
||||
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_4.tex'];
|
||||
fidTeX = fopen(filename,'w');
|
||||
TeXBegin_ML(fidTeX,4,'correlation of structural shocks',table_title,LaTeXtitle)
|
||||
TeXBegin_ML(fidTeX,4,'correlation of structural shocks',table_title,LaTeXtitle)
|
||||
ip = nvx+nvn+1;
|
||||
for i=1:ncx
|
||||
k1 = estim_params_.corrx(i,1);
|
||||
|
@ -335,7 +335,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
|
|||
if ncn
|
||||
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_5.tex'];
|
||||
fidTeX = fopen(filename,'w');
|
||||
TeXBegin_ML(fidTeX,5,'correlation of measurement errors',table_title,LaTeXtitle)
|
||||
TeXBegin_ML(fidTeX,5,'correlation of measurement errors',table_title,LaTeXtitle)
|
||||
ip = nvx+nvn+ncx+1;
|
||||
for i=1:ncn
|
||||
k1 = estim_params_.corrn(i,1);
|
||||
|
@ -347,7 +347,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
|
|||
tstath(ip));
|
||||
ip = ip+1;
|
||||
end
|
||||
TeXEnd(fidTeX)
|
||||
TeXEnd(fidTeX)
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -356,51 +356,51 @@ end
|
|||
%% subfunctions:
|
||||
%
|
||||
function TeXBegin_Bayesian(fid,fnum,title)
|
||||
fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n');
|
||||
fprintf(fid,['%% RESULTS FROM POSTERIOR MAXIMIZATION (' title ')\n']);
|
||||
fprintf(fid,['%% ' datestr(now,0)]);
|
||||
fprintf(fid,' \n');
|
||||
fprintf(fid,' \n');
|
||||
fprintf(fid,'\\begin{center}\n');
|
||||
fprintf(fid,'\\begin{longtable}{llcccc} \n');
|
||||
fprintf(fid,['\\caption{Results from posterior maximization (' title ')}\\\\\n ']);
|
||||
fprintf(fid,['\\label{Table:Posterior:' int2str(fnum) '}\\\\\n']);
|
||||
fprintf(fid,'\\toprule \n');
|
||||
fprintf(fid,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{2}{c}{Posterior} \\\\\n');
|
||||
fprintf(fid,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n');
|
||||
fprintf(fid,' & Dist. & Mean & Stdev & Mode & Stdev \\\\ \n');
|
||||
fprintf(fid,'\\midrule \\endfirsthead \n');
|
||||
fprintf(fid,'\\caption{(continued)}\\\\\n ');
|
||||
fprintf(fid,'\\bottomrule \n');
|
||||
fprintf(fid,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{2}{c}{Posterior} \\\\\n');
|
||||
fprintf(fid,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n');
|
||||
fprintf(fid,' & Dist. & Mean & Stdev & Mode & Stdev \\\\ \n');
|
||||
fprintf(fid,'\\midrule \\endhead \n');
|
||||
fprintf(fid,'\\bottomrule \\multicolumn{6}{r}{(Continued on next page)}\\endfoot \n');
|
||||
fprintf(fid,'\\bottomrule\\endlastfoot \n');
|
||||
fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n');
|
||||
fprintf(fid,['%% RESULTS FROM POSTERIOR MAXIMIZATION (' title ')\n']);
|
||||
fprintf(fid,['%% ' datestr(now,0)]);
|
||||
fprintf(fid,' \n');
|
||||
fprintf(fid,' \n');
|
||||
fprintf(fid,'\\begin{center}\n');
|
||||
fprintf(fid,'\\begin{longtable}{llcccc} \n');
|
||||
fprintf(fid,['\\caption{Results from posterior maximization (' title ')}\\\\\n ']);
|
||||
fprintf(fid,['\\label{Table:Posterior:' int2str(fnum) '}\\\\\n']);
|
||||
fprintf(fid,'\\toprule \n');
|
||||
fprintf(fid,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{2}{c}{Posterior} \\\\\n');
|
||||
fprintf(fid,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n');
|
||||
fprintf(fid,' & Dist. & Mean & Stdev & Mode & Stdev \\\\ \n');
|
||||
fprintf(fid,'\\midrule \\endfirsthead \n');
|
||||
fprintf(fid,'\\caption{(continued)}\\\\\n ');
|
||||
fprintf(fid,'\\bottomrule \n');
|
||||
fprintf(fid,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{2}{c}{Posterior} \\\\\n');
|
||||
fprintf(fid,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n');
|
||||
fprintf(fid,' & Dist. & Mean & Stdev & Mode & Stdev \\\\ \n');
|
||||
fprintf(fid,'\\midrule \\endhead \n');
|
||||
fprintf(fid,'\\bottomrule \\multicolumn{6}{r}{(Continued on next page)}\\endfoot \n');
|
||||
fprintf(fid,'\\bottomrule\\endlastfoot \n');
|
||||
|
||||
function TeXBegin_ML(fid,fnum,title,table_title,LaTeXtitle)
|
||||
fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n');
|
||||
fprintf(fid,['%% RESULTS FROM ' table_title ' MAXIMIZATION (' title ')\n']);
|
||||
fprintf(fid,['%% ' datestr(now,0)]);
|
||||
fprintf(fid,' \n');
|
||||
fprintf(fid,' \n');
|
||||
fprintf(fid,'\\begin{center}\n');
|
||||
fprintf(fid,'\\begin{longtable}{llcc} \n');
|
||||
fprintf(fid,['\\caption{Results from ' table_title ' maximization (' title ')}\\\\\n ']);
|
||||
fprintf(fid,['\\label{Table:' LaTeXtitle ':' int2str(fnum) '}\\\\\n']);
|
||||
fprintf(fid,'\\toprule \n');
|
||||
fprintf(fid,' & Mode & s.d. & t-stat\\\\ \n');
|
||||
fprintf(fid,'\\midrule \\endfirsthead \n');
|
||||
fprintf(fid,'\\caption{(continued)}\\\\\n ');
|
||||
fprintf(fid,'\\toprule \n');
|
||||
fprintf(fid,' & Mode & s.d. & t-stat\\\\ \n');
|
||||
fprintf(fid,'\\midrule \\endhead \n');
|
||||
fprintf(fid,'\\bottomrule \\multicolumn{4}{r}{(Continued on next page)} \\endfoot \n');
|
||||
fprintf(fid,'\\bottomrule \\endlastfoot \n');
|
||||
|
||||
function TeXBegin_ML(fid,fnum,title,table_title,LaTeXtitle)
|
||||
fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n');
|
||||
fprintf(fid,['%% RESULTS FROM ' table_title ' MAXIMIZATION (' title ')\n']);
|
||||
fprintf(fid,['%% ' datestr(now,0)]);
|
||||
fprintf(fid,' \n');
|
||||
fprintf(fid,' \n');
|
||||
fprintf(fid,'\\begin{center}\n');
|
||||
fprintf(fid,'\\begin{longtable}{llcc} \n');
|
||||
fprintf(fid,['\\caption{Results from ' table_title ' maximization (' title ')}\\\\\n ']);
|
||||
fprintf(fid,['\\label{Table:' LaTeXtitle ':' int2str(fnum) '}\\\\\n']);
|
||||
fprintf(fid,'\\toprule \n');
|
||||
fprintf(fid,' & Mode & s.d. & t-stat\\\\ \n');
|
||||
fprintf(fid,'\\midrule \\endfirsthead \n');
|
||||
fprintf(fid,'\\caption{(continued)}\\\\\n ');
|
||||
fprintf(fid,'\\toprule \n');
|
||||
fprintf(fid,' & Mode & s.d. & t-stat\\\\ \n');
|
||||
fprintf(fid,'\\midrule \\endhead \n');
|
||||
fprintf(fid,'\\bottomrule \\multicolumn{4}{r}{(Continued on next page)} \\endfoot \n');
|
||||
fprintf(fid,'\\bottomrule \\endlastfoot \n');
|
||||
|
||||
function TeXEnd(fid)
|
||||
fprintf(fid,'\\end{longtable}\n ');
|
||||
fprintf(fid,'\\end{longtable}\n ');
|
||||
fprintf(fid,'\\end{center}\n');
|
||||
fprintf(fid,'%% End of TeX file.\n');
|
||||
fclose(fid);
|
|
@ -1,20 +1,20 @@
|
|||
function []=display_problematic_vars_Jacobian(problemrow,problemcol,M_,x,type,caller_string)
|
||||
% []=display_problematic_vars_Jacobian(problemrow,problemcol,M_,ys,caller_string)
|
||||
% print the equation numbers and variables associated with problematic entries
|
||||
% of the Jacobian
|
||||
% print the equation numbers and variables associated with problematic entries
|
||||
% of the Jacobian
|
||||
%
|
||||
% INPUTS
|
||||
% problemrow [vector] rows associated with problematic entries
|
||||
% problemcol [vector] columns associated with problematic entries
|
||||
% M_ [matlab structure] Definition of the model.
|
||||
% M_ [matlab structure] Definition of the model.
|
||||
% x [vector] point at which the Jacobian was evaluated
|
||||
% type [string] 'static' or 'dynamic' depending on the type of
|
||||
% Jacobian
|
||||
% caller_string [string] contains name of calling function for printing
|
||||
%
|
||||
% caller_string [string] contains name of calling function for printing
|
||||
%
|
||||
% OUTPUTS
|
||||
% none.
|
||||
%
|
||||
%
|
||||
|
||||
% Copyright (C) 2014-16 Dynare Team
|
||||
%
|
||||
|
@ -62,25 +62,25 @@ if strcmp(type,'dynamic')
|
|||
fprintf('Derivative of Equation %d with respect to %s Variable %s (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(var_index,:)),deblank(M_.endo_names(var_index,:)),x(var_index))
|
||||
end
|
||||
elseif problemcol(ii)<=max(max(M_.lead_lag_incidence)) && var_index>M_.orig_endo_nbr %auxiliary vars
|
||||
if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier
|
||||
if problemrow(ii)<=aux_eq_nbr
|
||||
eq_nbr=problemrow(ii);
|
||||
fprintf('Derivative of Auxiliary Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
|
||||
else
|
||||
eq_nbr=problemrow(ii)-aux_eq_nbr;
|
||||
fprintf('Derivative of Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
|
||||
end
|
||||
if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier
|
||||
if problemrow(ii)<=aux_eq_nbr
|
||||
eq_nbr=problemrow(ii);
|
||||
fprintf('Derivative of Auxiliary Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
|
||||
else
|
||||
if problemrow(ii)<=aux_eq_nbr
|
||||
eq_nbr=problemrow(ii);
|
||||
orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index;
|
||||
fprintf('Derivative of Auxiliary Equation %d with respect to %s Variable %s (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index))
|
||||
else
|
||||
eq_nbr=problemrow(ii)-aux_eq_nbr;
|
||||
orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index;
|
||||
fprintf('Derivative of Equation %d with respect to %s Variable %s (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index))
|
||||
end
|
||||
eq_nbr=problemrow(ii)-aux_eq_nbr;
|
||||
fprintf('Derivative of Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
|
||||
end
|
||||
else
|
||||
if problemrow(ii)<=aux_eq_nbr
|
||||
eq_nbr=problemrow(ii);
|
||||
orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index;
|
||||
fprintf('Derivative of Auxiliary Equation %d with respect to %s Variable %s (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index))
|
||||
else
|
||||
eq_nbr=problemrow(ii)-aux_eq_nbr;
|
||||
orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index;
|
||||
fprintf('Derivative of Equation %d with respect to %s Variable %s (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index))
|
||||
end
|
||||
end
|
||||
elseif problemcol(ii)>max(max(M_.lead_lag_incidence)) && var_index<=M_.exo_nbr
|
||||
if problemrow(ii)<=aux_eq_nbr
|
||||
eq_nbr=problemrow(ii);
|
||||
|
@ -88,7 +88,7 @@ if strcmp(type,'dynamic')
|
|||
else
|
||||
eq_nbr=problemrow(ii)-aux_eq_nbr;
|
||||
fprintf('Derivative of Equation %d with respect to %s shock %s \n',eq_nbr,type_string,deblank(M_.exo_names(var_index,:)));
|
||||
end
|
||||
end
|
||||
else
|
||||
error('display_problematic_vars_Jacobian:: The error should not happen. Please contact the developers')
|
||||
end
|
||||
|
@ -108,24 +108,24 @@ elseif strcmp(type,'static')
|
|||
fprintf('Derivative of Equation %d with respect to Variable %s (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(problemcol(ii),:)),deblank(M_.endo_names(problemcol(ii),:)),x(problemcol(ii)))
|
||||
end
|
||||
else %auxiliary vars
|
||||
if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier
|
||||
if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier
|
||||
if problemrow(ii)<=aux_eq_nbr
|
||||
eq_nbr=problemrow(ii);
|
||||
fprintf('Derivative of Auxiliary Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
|
||||
fprintf('Derivative of Auxiliary Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
|
||||
else
|
||||
eq_nbr=problemrow(ii)-aux_eq_nbr;
|
||||
fprintf('Derivative of Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
|
||||
fprintf('Derivative of Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
|
||||
end
|
||||
else
|
||||
if problemrow(ii)<=aux_eq_nbr
|
||||
eq_nbr=problemrow(ii);
|
||||
orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index;
|
||||
fprintf('Derivative of Auxiliary Equation %d with respect to Variable %s (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii)))
|
||||
else
|
||||
eq_nbr=problemrow(ii)-aux_eq_nbr;
|
||||
orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index;
|
||||
fprintf('Derivative of Equation %d with respect to Variable %s (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii)))
|
||||
end
|
||||
if problemrow(ii)<=aux_eq_nbr
|
||||
eq_nbr=problemrow(ii);
|
||||
orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index;
|
||||
fprintf('Derivative of Auxiliary Equation %d with respect to Variable %s (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii)))
|
||||
else
|
||||
eq_nbr=problemrow(ii)-aux_eq_nbr;
|
||||
orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index;
|
||||
fprintf('Derivative of Equation %d with respect to Variable %s (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii)))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -134,5 +134,5 @@ elseif strcmp(type,'static')
|
|||
fprintf('%s and evaluating it at the steady state then results in a division by 0.\n',caller_string)
|
||||
fprintf('%s If you are using model-local variables (# operator), check their values as well.\n',caller_string)
|
||||
else
|
||||
error('Unknown Type')
|
||||
error('Unknown Type')
|
||||
end
|
|
@ -2,13 +2,13 @@ function [a, b] = beta_specification(mu, sigma2, lb, ub, name) % --*-- Unitary
|
|||
|
||||
% Returns the hyperparameters of the beta distribution given the expectation and variance.
|
||||
%
|
||||
% INPUTS
|
||||
% INPUTS
|
||||
% - mu [double] Expectation of the Gamma random variable.
|
||||
% - sigma2 [double] Variance of the Gamma random variable.
|
||||
% - lb [double] Lower bound of the domain (default is zero).
|
||||
% - ub [double] Upper bound of the domain (default is one).
|
||||
%
|
||||
% OUTPUTS
|
||||
% OUTPUTS
|
||||
% - a [double] First hyperparameter of the Beta density.
|
||||
% - b [double] Second hyperparameter of the Beta density.
|
||||
|
||||
|
@ -63,7 +63,7 @@ if sigma2>(1-mu)*mu
|
|||
error('Beta prior%s. Given the declared prior expectation, prior lower and upper bounds, the prior std. has to be smaller than %f.',name2,sqrt((1-mu)*mu))
|
||||
end
|
||||
|
||||
a = (1-mu)*mu*mu/sigma2-mu;
|
||||
a = (1-mu)*mu*mu/sigma2-mu;
|
||||
b = a*(1/mu-1);
|
||||
|
||||
%@test:1
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
function m = compute_prior_mode(hyperparameters,shape) % --*-- Unitary tests --*--
|
||||
% This function computes the mode of the prior distribution given the (two, three or four) hyperparameters
|
||||
% of the prior distribution.
|
||||
%
|
||||
% INPUTS
|
||||
%
|
||||
% INPUTS
|
||||
% hyperparameters [double] 1*n vector of hyper parameters.
|
||||
% shape [integer] scalar specifying the prior shape:
|
||||
% shape=1 => Beta distribution,
|
||||
|
@ -12,14 +12,14 @@ function m = compute_prior_mode(hyperparameters,shape) % --*-- Unitary tests --*
|
|||
% shape=5 => Uniform distribution,
|
||||
% shape=6 => Inverse Gamma (type 2) distribution,
|
||||
% shape=8 => Weibull distribution.
|
||||
%
|
||||
% OUTPUTS
|
||||
%
|
||||
% OUTPUTS
|
||||
% m [double] scalar or 2*1 vector, the prior mode.
|
||||
%
|
||||
% REMARKS
|
||||
% [1] The size of the vector of hyperparameters is 3 when the Gamma or Inverse Gamma is shifted and 4 when
|
||||
% the support of the Beta distribution is not [0,1].
|
||||
% [2] The hyperparameters of the uniform distribution are the lower and upper bounds.
|
||||
% REMARKS
|
||||
% [1] The size of the vector of hyperparameters is 3 when the Gamma or Inverse Gamma is shifted and 4 when
|
||||
% the support of the Beta distribution is not [0,1].
|
||||
% [2] The hyperparameters of the uniform distribution are the lower and upper bounds.
|
||||
% [3] The uniform distribution has an infinity of modes. In this case the function returns the prior mean.
|
||||
% [4] For the beta distribution we can have 1, 2 or an infinity of modes.
|
||||
|
||||
|
|
|
@ -2,13 +2,13 @@ function [a, b] = gamma_specification(mu, sigma2, lb, name) % --*-- Unitary te
|
|||
|
||||
% Returns the hyperparameters of the gamma distribution given the expectation and variance.
|
||||
%
|
||||
% INPUTS
|
||||
% INPUTS
|
||||
% - mu [double] Expectation of the Gamma random variable.
|
||||
% - sigma2 [double] Variance of the Gamma random variable.
|
||||
% - lb [double] Lower bound of the domain (default is zero).
|
||||
% - name [string] Name of the parameter (or random variable).
|
||||
%
|
||||
% OUTPUTS
|
||||
% OUTPUTS
|
||||
% - a [double] First hyperparameter of the Gamma density (shape).
|
||||
% - b [double] Second hyperparameter of the Gamma density (scale).
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@ function [s,nu] = inverse_gamma_specification(mu, sigma2, lb, type, use_fzero_fl
|
|||
|
||||
% Computes the inverse Gamma hyperparameters from the prior mean and standard deviation.
|
||||
%
|
||||
% INPUTS
|
||||
% INPUTS
|
||||
% - mu [double] scalar, prior mean.
|
||||
% - sigma2 [double] positive scalar, prior variance.
|
||||
% - type [integer] scalar equal to 1 or 2, type of the inverse gamma distribution
|
||||
|
@ -10,11 +10,11 @@ function [s,nu] = inverse_gamma_specification(mu, sigma2, lb, type, use_fzero_fl
|
|||
% dynare's implementation of the secant method otherwise.
|
||||
% - name [string] name of the parameter or random variable.
|
||||
%
|
||||
% OUTPUS
|
||||
% OUTPUS
|
||||
% - s [double] scalar, first hyperparameter.
|
||||
% - nu [double] scalar, second hyperparameter.
|
||||
%
|
||||
% REMARK
|
||||
% REMARK
|
||||
% The call to the matlab's implementation of the secant method is here for testing purpose and should not be used. This routine fails
|
||||
% more often in finding an interval for nu containing a signe change because it expands the interval on both sides and eventually
|
||||
% violates the condition nu>2.
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
function [ldens,Dldens,D2ldens] = lpdfgweibull(x,a,b,c) % --*-- Unitary tests --*--
|
||||
|
||||
% Evaluates the logged Weibull PDF at x.
|
||||
% Evaluates the logged Weibull PDF at x.
|
||||
%
|
||||
% INPUTS
|
||||
% INPUTS
|
||||
% - x [double] m*n matrix of points where the (logged) density will be evaluated,
|
||||
% - a [double] m*n matrix of First Weibull distribution parameters (shape parameter, k),
|
||||
% - b [double] m*n matrix of Second Weibull distribution parameters (scale parameter, λ),
|
||||
% - c [double] m*n matrix of Third Weibull distribution parameters (location parameter, default is 0).
|
||||
%
|
||||
% OUTPUTS
|
||||
% OUTPUTS
|
||||
% - ldens [double] m*n matrix of logged (generalized) Weibull densities.
|
||||
% - Dldens [double] m*n matrix (first order derivatives w.r.t. x)
|
||||
% - D2ldens [double] m*n matrix (second order derivatives w.r.t. x)
|
||||
|
@ -54,11 +54,11 @@ end
|
|||
if ~isscalar(x)
|
||||
if isscalar(a)
|
||||
a = repmat(a, size(x));
|
||||
end
|
||||
end
|
||||
if isscalar(b)
|
||||
b = repmat(b, size(x));
|
||||
end
|
||||
if isscalar(c)
|
||||
if isscalar(c)
|
||||
c = repmat(c, size(x));
|
||||
end
|
||||
end
|
||||
|
@ -77,7 +77,7 @@ if isempty(idx), return, end
|
|||
|
||||
jdx = find( abs(a-1)<1e-12 & x>=c & (x-c)<1e-12) ;
|
||||
ldens(jdx) = 1.0;
|
||||
|
||||
|
||||
if ~isempty(idx)
|
||||
x0 = x(idx)-c(idx);
|
||||
x1 = x0./b(idx);
|
||||
|
@ -136,7 +136,7 @@ end
|
|||
%$ catch
|
||||
%$ t(1) = false;
|
||||
%$ end
|
||||
%$
|
||||
%$
|
||||
%$ if t(1)
|
||||
%$ t(2) = isinf(a);
|
||||
%$ end
|
||||
|
@ -179,7 +179,7 @@ end
|
|||
%$ scale = 1;
|
||||
%$ shape = 2;
|
||||
%$ mode = scale*((shape-1)/shape)^(1/shape);
|
||||
%$
|
||||
%$
|
||||
%$ try
|
||||
%$ [a, b, c] = lpdfgweibull(mode, shape, scale);
|
||||
%$ p = rand(1000,1)*4;
|
||||
|
@ -203,7 +203,7 @@ end
|
|||
%$ scale = 1;
|
||||
%$ shape = 2;
|
||||
%$ density = @(x) exp(lpdfgweibull(x,shape,scale));
|
||||
%$
|
||||
%$
|
||||
%$ try
|
||||
%$ if isoctave
|
||||
%$ s = quadv(density, .0000000001, 100000,1e-10);
|
||||
|
@ -226,7 +226,7 @@ end
|
|||
%$ scale = 1;
|
||||
%$ shape = 1;
|
||||
%$ density = @(x) exp(lpdfgweibull(x,shape,scale));
|
||||
%$
|
||||
%$
|
||||
%$ try
|
||||
%$ if isoctave
|
||||
%$ s = quadv(density, .0000000001, 100000,1e-10);
|
||||
|
@ -249,7 +249,7 @@ end
|
|||
%$ scale = 1;
|
||||
%$ shape = .5;
|
||||
%$ density = @(x) exp(lpdfgweibull(x,shape,scale));
|
||||
%$
|
||||
%$
|
||||
%$ try
|
||||
%$ if isoctave
|
||||
%$ s = quadv(density, .0000000001, 100000,1e-10)
|
||||
|
@ -276,7 +276,7 @@ end
|
|||
%$ scale = 1;
|
||||
%$ shape = 2;
|
||||
%$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale));
|
||||
%$
|
||||
%$
|
||||
%$ try
|
||||
%$ if isoctave
|
||||
%$ s = quadv(xdens, .0000000001, 20,1e-10)
|
||||
|
@ -299,7 +299,7 @@ end
|
|||
%$ scale = 1;
|
||||
%$ shape = 1;
|
||||
%$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale));
|
||||
%$
|
||||
%$
|
||||
%$ try
|
||||
%$ if isoctave
|
||||
%$ s = quadv(xdens, .0000000001, 100000,1e-10)
|
||||
|
@ -322,7 +322,7 @@ end
|
|||
%$ scale = 1;
|
||||
%$ shape = .5;
|
||||
%$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale));
|
||||
%$
|
||||
%$
|
||||
%$ try
|
||||
%$ if isoctave
|
||||
%$ s = quadv(xdens, .0000000001, 100000,1e-10)
|
||||
|
|
|
@ -1,21 +1,21 @@
|
|||
function [mu, parameters] = mode_and_variance_to_mean(m,s2,distribution,lower_bound,upper_bound)
|
||||
% This function computes the mean of a distribution given the mode and variance of this distribution.
|
||||
%
|
||||
% INPUTS
|
||||
% INPUTS
|
||||
% m [double] scalar, mode of the distribution.
|
||||
% s2 [double] scalar, variance of the distribution.
|
||||
% distribution [integer] scalar for the distribution shape
|
||||
% distribution [integer] scalar for the distribution shape
|
||||
% 1 gamma
|
||||
% 2 inv-gamma-2
|
||||
% 3 inv-gamma-1
|
||||
% 4 beta
|
||||
% 4 beta
|
||||
% lower_bound [double] scalar, lower bound of the random variable support (optional).
|
||||
% upper_bound [double] scalar, upper bound of the random variable support (optional).
|
||||
%
|
||||
% OUTPUT
|
||||
%
|
||||
% OUTPUT
|
||||
% mu [double] scalar, mean of the distribution.
|
||||
% parameters [double] 2*1 vector, parameters of the distribution.
|
||||
%
|
||||
%
|
||||
|
||||
% Copyright (C) 2009 Dynare Team
|
||||
%
|
||||
|
@ -34,7 +34,7 @@ function [mu, parameters] = mode_and_variance_to_mean(m,s2,distribution,lower_bo
|
|||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
% Check input aruments.
|
||||
% Check input aruments.
|
||||
if ~(nargin==3 || nargin==5 || nargin==4 )
|
||||
error('mode_and_variance_to mean:: 3 or 5 input arguments are needed!')
|
||||
end
|
||||
|
@ -80,7 +80,7 @@ if (distribution==1)% Gamma distribution
|
|||
end
|
||||
if (m-lower_bound)<1e-12
|
||||
error('The gamma distribution should be specified with the mean and variance.')
|
||||
end
|
||||
end
|
||||
m = m - lower_bound ;
|
||||
beta = -.5*m*(1-sqrt(1+4*s2/(m*m))) ;
|
||||
alpha = (m+beta)/beta ;
|
||||
|
|
|
@ -1,18 +1,18 @@
|
|||
function density = multivariate_normal_pdf(X,Mean,Sigma_upper_chol,n)
|
||||
% Evaluates the density of a multivariate gaussian, with expectation Mean
|
||||
% and variance Sigma_upper_chol'*Sigma_upper_chol, at X.
|
||||
%
|
||||
%
|
||||
% INPUTS
|
||||
%
|
||||
% X [double] 1*n vector
|
||||
% INPUTS
|
||||
%
|
||||
% X [double] 1*n vector
|
||||
% Mean [double] 1*n vector, expectation of the multivariate random variable.
|
||||
% Sigma_upper_chol [double] n*n matrix, upper triangular Cholesky decomposition of Sigma (the covariance matrix).
|
||||
% n [integer] dimension.
|
||||
%
|
||||
% OUTPUTS
|
||||
% density [double] density
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% density [double] density
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
|
||||
% Copyright (C) 2003-2017 Dynare Team
|
||||
|
@ -31,6 +31,6 @@ function density = multivariate_normal_pdf(X,Mean,Sigma_upper_chol,n)
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
|
||||
density = (2*pi)^(-.5*n) * ...
|
||||
density = (2*pi)^(-.5*n) * ...
|
||||
prod(diag(Sigma_upper_chol))^(-1) * ...
|
||||
exp(-.5*(X-Mean)*(Sigma_upper_chol\(transpose(Sigma_upper_chol)\transpose(X-Mean))));
|
|
@ -2,16 +2,16 @@ function density = multivariate_student_pdf(X,Mean,Sigma_upper_chol,df)
|
|||
% Evaluates the density of a multivariate student, with expectation Mean,
|
||||
% variance Sigma_upper_chol'*Sigma_upper_chol and degrees of freedom df, at X.
|
||||
%
|
||||
% INPUTS
|
||||
% INPUTS
|
||||
%
|
||||
% X [double] 1*n vector
|
||||
% X [double] 1*n vector
|
||||
% Mean [double] 1*n vector, expectation of the multivariate random variable.
|
||||
% Sigma_upper_chol [double] n*n matrix, upper triangular Cholesky decomposition of Sigma (the "covariance matrix").
|
||||
% df [integer] degrees of freedom.
|
||||
%
|
||||
% OUTPUTS
|
||||
% density [double] density.
|
||||
%
|
||||
%
|
||||
% OUTPUTS
|
||||
% density [double] density.
|
||||
%
|
||||
% SPECIAL REQUIREMENTS
|
||||
|
||||
% Copyright (C) 2003-2017 Dynare Team
|
||||
|
|
|
@ -17,12 +17,12 @@ function G = rand_inverse_wishart(m, v, H_inv_upper_chol)
|
|||
% OUTPUTS:
|
||||
% G: G ~ IW(m, v, H) where H = inv(H_inv_upper_chol'*H_inv_upper_chol)
|
||||
% or, equivalently, using the correspondence between Wishart and
|
||||
% inverse-Wishart: inv(G) ~ W(m, v, S) where
|
||||
% inverse-Wishart: inv(G) ~ W(m, v, S) where
|
||||
% S = H_inv_upper_chol'*H_inv_upper_chol = inv(H)
|
||||
%
|
||||
%
|
||||
% SPECIAL REQUIREMENT
|
||||
% none
|
||||
%
|
||||
%
|
||||
|
||||
% Copyright (C) 2003-2009 Dynare Team
|
||||
%
|
||||
|
@ -41,7 +41,7 @@ function G = rand_inverse_wishart(m, v, H_inv_upper_chol)
|
|||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
X = randn(v, m) * H_inv_upper_chol;
|
||||
X = randn(v, m) * H_inv_upper_chol;
|
||||
|
||||
|
||||
% At this point, X'*X is Wishart distributed
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue