Beautified MATLAB code (Unix newline convention + Emacs indentation), except: AIM, swz, particle

git-svn-id: https://www.dynare.org/svn/dynare/trunk@3250 ac1d8469-bf42-47a9-8791-bf33cf982152
time-shift
sebastien 2009-12-16 17:17:34 +00:00
parent e6f1a53e60
commit 502e3e1df8
306 changed files with 25732 additions and 25746 deletions

View File

@ -1,142 +1,142 @@
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
% 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, . . . ,?
% 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'= £
%
% INPUTS
% jacobia_ [matrix] 1st order derivative of the model
% dr [matlab structure] Decision rules for stochastic simulations.
% M_ [matlab structure] Definition of the model.
%
% OUTPUTS
% dr [matlab structure] Decision rules for stochastic simulations.
% aimcode [integer] 1: the model defines variables uniquely
% aimcode is resolved in AIMerr as
% (c==1) e='Aim: unique solution.';
% (c==2) e='Aim: roots not correctly computed by real_schur.';
% (c==3) e='Aim: too many big roots.';
% (c==35) e='Aim: too many big roots, and q(:,right) is singular.';
% (c==4) e='Aim: too few big roots.';
% (c==45) e='Aim: too few big roots, and q(:,right) is singular.';
% (c==5) e='Aim: q(:,right) is singular.';
% (c==61) e='Aim: too many exact shiftrights.';
% (c==62) e='Aim: too many numeric shiftrights.';
% else e='Aimerr: return code not properly specified';
%
% SPECIAL REQUIREMENTS
% 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
% (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
% Copyright (C) 2008 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/>.
aimcode=-1;
neq= size(jacobia_,1); % no of equations
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
% without exogenous shoc
theAIM_H(:,find(lli(:)))=jacobia_(:,nonzeros(lli(:)));
condn = 1.e-10;%SPAmalg uses this in zero tests
uprbnd = 1 + 1.e-6;%allow unit roots
% forward only models - AIM must have at least 1 lead and 1 lag.
if lags ==0
theAIM_H =[zeros(neq) theAIM_H];
lags=1;
klen=(leads+lags+1);
end
% backward looking only models
if leads ==0
theAIM_H =[theAIM_H zeros(neq)];
leads=1;
klen=(leads+lags+1);
end
%disp('gensysToAMA:running ama');
try % try to run AIM
[bb,rts,ia,nexact,nnumeric,lgroots,aimcode] =...
SPAmalg(theAIM_H,neq, lags,leads,condn,uprbnd);
catch
err = lasterror;
disp(['Dynare AIM Solver error:' sprintf('%s; ID:%s',err.message, err.identifier)]);
rethrow(lasterror);
end
if aimcode==1 %if OK
col_order=[];
for i =1:lags
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
% variables)
i_lagged_vars = flipud(cumsum(M_.lead_lag_incidence(1:M_.maximum_lag,dr.order_var),1))';
dr.ghx= bb_ord(:,find(i_lagged_vars(:))); % get columns reported in
% Dynare solution
if M_.exo_nbr % if there are exogenous shocks then derive gu for the shocks:
% get H0 and H+1=HM
% theH0= theAIM_H (:,M_.maximum_endo_lag*neq+1: (M_.maximum_endo_lag+1)*neq);
%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);%
%? = inv(H0 + H1B1)
%phi= (theH0+theHP*sparse(bb(:,(lags-1)*neq+1:end)))\eye( neq);
%AIM_ghu=phi*theAIM_Psi;
%dr.ghu =AIM_ghu(dr.order_var,:); % order gu
% Using AIM SPObstruct
scof = SPObstruct(theAIM_H,bb,neq,lags,leads);
scof1= scof(:,(lags)*neq+1:end);
scof1= scof1(:,dr.order_var);
dr.ghu =scof1\theAIM_Psi;
else
dr.ghu = [];
end
else
err=SPAimerr(aimcode);
%warning('Error in AIM: aimcode=%d, erro=%s', aimcode, err);;
disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]);
if aimcode < 1 || aimcode > 5 % too big exception, use mjdgges
error('Error in AIM: aimcode=%d ; %s', aimcode, err);
end
% if aimcode > 5
% disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]);
% aimcode=5;
% end
end
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
% 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, . . . ,?
% 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'= £
%
% INPUTS
% jacobia_ [matrix] 1st order derivative of the model
% dr [matlab structure] Decision rules for stochastic simulations.
% M_ [matlab structure] Definition of the model.
%
% OUTPUTS
% dr [matlab structure] Decision rules for stochastic simulations.
% aimcode [integer] 1: the model defines variables uniquely
% aimcode is resolved in AIMerr as
% (c==1) e='Aim: unique solution.';
% (c==2) e='Aim: roots not correctly computed by real_schur.';
% (c==3) e='Aim: too many big roots.';
% (c==35) e='Aim: too many big roots, and q(:,right) is singular.';
% (c==4) e='Aim: too few big roots.';
% (c==45) e='Aim: too few big roots, and q(:,right) is singular.';
% (c==5) e='Aim: q(:,right) is singular.';
% (c==61) e='Aim: too many exact shiftrights.';
% (c==62) e='Aim: too many numeric shiftrights.';
% else e='Aimerr: return code not properly specified';
%
% SPECIAL REQUIREMENTS
% 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
% (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
% Copyright (C) 2008 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/>.
aimcode=-1;
neq= size(jacobia_,1); % no of equations
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
% without exogenous shoc
theAIM_H(:,find(lli(:)))=jacobia_(:,nonzeros(lli(:)));
condn = 1.e-10;%SPAmalg uses this in zero tests
uprbnd = 1 + 1.e-6;%allow unit roots
% forward only models - AIM must have at least 1 lead and 1 lag.
if lags ==0
theAIM_H =[zeros(neq) theAIM_H];
lags=1;
klen=(leads+lags+1);
end
% backward looking only models
if leads ==0
theAIM_H =[theAIM_H zeros(neq)];
leads=1;
klen=(leads+lags+1);
end
%disp('gensysToAMA:running ama');
try % try to run AIM
[bb,rts,ia,nexact,nnumeric,lgroots,aimcode] =...
SPAmalg(theAIM_H,neq, lags,leads,condn,uprbnd);
catch
err = lasterror;
disp(['Dynare AIM Solver error:' sprintf('%s; ID:%s',err.message, err.identifier)]);
rethrow(lasterror);
end
if aimcode==1 %if OK
col_order=[];
for i =1:lags
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
% variables)
i_lagged_vars = flipud(cumsum(M_.lead_lag_incidence(1:M_.maximum_lag,dr.order_var),1))';
dr.ghx= bb_ord(:,find(i_lagged_vars(:))); % get columns reported in
% Dynare solution
if M_.exo_nbr % if there are exogenous shocks then derive gu for the shocks:
% get H0 and H+1=HM
% theH0= theAIM_H (:,M_.maximum_endo_lag*neq+1: (M_.maximum_endo_lag+1)*neq);
%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);%
%? = inv(H0 + H1B1)
%phi= (theH0+theHP*sparse(bb(:,(lags-1)*neq+1:end)))\eye( neq);
%AIM_ghu=phi*theAIM_Psi;
%dr.ghu =AIM_ghu(dr.order_var,:); % order gu
% Using AIM SPObstruct
scof = SPObstruct(theAIM_H,bb,neq,lags,leads);
scof1= scof(:,(lags)*neq+1:end);
scof1= scof1(:,dr.order_var);
dr.ghu =scof1\theAIM_Psi;
else
dr.ghu = [];
end
else
err=SPAimerr(aimcode);
%warning('Error in AIM: aimcode=%d, erro=%s', aimcode, err);;
disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]);
if aimcode < 1 || aimcode > 5 % too big exception, use mjdgges
error('Error in AIM: aimcode=%d ; %s', aimcode, err);
end
% if aimcode > 5
% disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]);
% aimcode=5;
% end
end

View File

@ -1,215 +1,215 @@
function [ErrorCode] = AnalyseComputationalEnviroment(DataInput)
% Input/Output description:
%
% DataInput is the strcture option_.parallel, with the follow fields:
%
% Local Define the computation place: 1 is on local machine, 0 remote
% PcName Intuitive: contain the computer name.
% NumCPU Intuitive: contain the CPU number.
% user Intuitive: contain the use name for the PcName.
% passwd Intuitive: contain the password for the user name in PcName.
% RemoteDrive Drive used for Local/Remote computation (data exchange, etc) must be contain 'RemoteFolder'.
% RemoteFolder Folder in RemoteDrive used for Local/Remote computation.
%
% This information is typed by the user using the *.mod file,
% the goal of this function is to check if it correct.
%
%
% The variable ErrorCode is initialized at 0. If there are non problems with
% Local, PcName connections,... in general with parallel software execution,
% the ErrorCode is unchanged, in the others cases 1, 2 , ... The values
% table is below.
%
%
% Table for ErrorCode Values.
%
% ErrorCode -> 0 Initial Value -> No Error Detected!!!
% ErrorCode -> > 1 When an error happens. The value 1, 2, 3... are
% used to specify the kind of error.
%
% Value 1: The variable 'Local' has a bad value!
%
% Value 2: The variable 'NumCPU' has a bad value. Parallel Dynare
% require an input data like [s:d] with s<=d, in this case we
% have s>d!
% 2.1 The user asks to use more CPU of those available.
% 2.2 There are CPU not used!
%
% Value 3: The remote computer is unreachable!!!
%
% Value 4: The user name and/or password is/are incorrect on the
% remote computer!
%
% Value 5: It is impossible write/read file on remote computer.
%
% Then at the point call of this function it is possible react in a best way, in accord
% with the ErrorCode.
% Copyright (C) 2009 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/>.
ErrorCode=0;
% The function is composed by two main blocks, determined by the 'Local'
% variable.
if ((DataInput.Local == 0) |(DataInput.Local == 1))
% Continue it is Ok!
else
ErrorCode=1;
return
end
%%%%%%%%%% Local Machine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% In this case we need to check only the variable 'NumCPU'.
% We run the parallel code on local computer, so the others fields are automatically
% fixed by Dynare. Then the user can also fill them with wrong values.
if (DataInput.Local == 1)
yn=isempty(DataInput.NumCPU);
if yn==1
ErrorCode=2;
return
end
% We look for the information on local computer hardware.
si=[];
de=[];
[si de]=system(['psinfo \\']);
RealNumCPU=-1;
RealNumCPU=GiveCPUnumber(de);
% Trasforming the input data provided in a form [n1:n2] in a single numerical
% value.
DataInput.NumCPU=length(DataInput.NumCPU);
if DataInput.NumCPU == RealNumCPU
% It is Ok!
end
if DataInput.NumCPU > RealNumCPU
ErrorCode=2.1;
end
if DataInput.NumCPU < RealNumCPU
ErrorCode=2.2;
end
end
%%%%%%%%%% Remote Machine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% In this case we need more sophisticated check.
if (DataInput.Local == 0)
si=[];
de=[];
[si de]=system(['ping ', DataInput.PcName]);
if si==1
% It is impossiblie to be connected to the
% remote computer.
ErrorCode=3;
return;
end
% -> IL CODICE SEGUENTE E' DA CONTROLLARE E VERIFICARE!
% The Local Machine can be connetted with Remote Computer.
% Now we verify if user name and password are correct and if remote
% drive and remote folder exist on the remote computer and it is
% possible to exchange data with them.
si=[];
de=[];
[si de]=system(['psinfo \\', DataInput.PcName, ' -u ',DataInput.user, ' -p ',DataInput.passwd ]);
if si<0
% It is possible to be connected to the remote computer but it is not usable because the user
% name and/or password is/are incorrect.
ErrorCodeComputer=4;
return;
else
% Username and Password are correct!
end
% Now we verify if it possible to exchange data with the remote
% computer:
fid = fopen('Tracing.txt','w+');
fclose (fid);
% ATTENZIONE: verificare perche sembra funzionare anche se il RemoteFolder non
% esiste.
Status=movefile('Tracing.txt', ['\\',DataInput.PcName,'\',DataInput.RemoteDrive,'$\',DataInput.RemoteFolder]);
if Status==1
% Remote Drive/Folder exist on Remote computer and
% it is possible to exchange data with him.
else
% Move file error!
ErrorCodeComputer=5;
return;
end
% At this point we can to analyze the remote computer hardware.
RealNumCPU=-1;
RealNumCPU=GiveCPUnumber(de);
% Trasforming the input data provided in a form [n1:n2] in a single numerical
% value.
DataInput.NumCPU=length(DataInput.NumCPU);
if DataInput.NumCPU == RealNumCPU
% It is Ok!
end
if DataInput.NumCPU > RealNumCPU
ErrorCode=2.1;
end
if DataInput.NumCPU < RealNumCPU
ErrorCode=2.2;
end
end
function [ErrorCode] = AnalyseComputationalEnviroment(DataInput)
% Input/Output description:
%
% DataInput is the strcture option_.parallel, with the follow fields:
%
% Local Define the computation place: 1 is on local machine, 0 remote
% PcName Intuitive: contain the computer name.
% NumCPU Intuitive: contain the CPU number.
% user Intuitive: contain the use name for the PcName.
% passwd Intuitive: contain the password for the user name in PcName.
% RemoteDrive Drive used for Local/Remote computation (data exchange, etc) must be contain 'RemoteFolder'.
% RemoteFolder Folder in RemoteDrive used for Local/Remote computation.
%
% This information is typed by the user using the *.mod file,
% the goal of this function is to check if it correct.
%
%
% The variable ErrorCode is initialized at 0. If there are non problems with
% Local, PcName connections,... in general with parallel software execution,
% the ErrorCode is unchanged, in the others cases 1, 2 , ... The values
% table is below.
%
%
% Table for ErrorCode Values.
%
% ErrorCode -> 0 Initial Value -> No Error Detected!!!
% ErrorCode -> > 1 When an error happens. The value 1, 2, 3... are
% used to specify the kind of error.
%
% Value 1: The variable 'Local' has a bad value!
%
% Value 2: The variable 'NumCPU' has a bad value. Parallel Dynare
% require an input data like [s:d] with s<=d, in this case we
% have s>d!
% 2.1 The user asks to use more CPU of those available.
% 2.2 There are CPU not used!
%
% Value 3: The remote computer is unreachable!!!
%
% Value 4: The user name and/or password is/are incorrect on the
% remote computer!
%
% Value 5: It is impossible write/read file on remote computer.
%
% Then at the point call of this function it is possible react in a best way, in accord
% with the ErrorCode.
% Copyright (C) 2009 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/>.
ErrorCode=0;
% The function is composed by two main blocks, determined by the 'Local'
% variable.
if ((DataInput.Local == 0) |(DataInput.Local == 1))
% Continue it is Ok!
else
ErrorCode=1;
return
end
%%%%%%%%%% Local Machine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% In this case we need to check only the variable 'NumCPU'.
% We run the parallel code on local computer, so the others fields are automatically
% fixed by Dynare. Then the user can also fill them with wrong values.
if (DataInput.Local == 1)
yn=isempty(DataInput.NumCPU);
if yn==1
ErrorCode=2;
return
end
% We look for the information on local computer hardware.
si=[];
de=[];
[si de]=system(['psinfo \\']);
RealNumCPU=-1;
RealNumCPU=GiveCPUnumber(de);
% Trasforming the input data provided in a form [n1:n2] in a single numerical
% value.
DataInput.NumCPU=length(DataInput.NumCPU);
if DataInput.NumCPU == RealNumCPU
% It is Ok!
end
if DataInput.NumCPU > RealNumCPU
ErrorCode=2.1;
end
if DataInput.NumCPU < RealNumCPU
ErrorCode=2.2;
end
end
%%%%%%%%%% Remote Machine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% In this case we need more sophisticated check.
if (DataInput.Local == 0)
si=[];
de=[];
[si de]=system(['ping ', DataInput.PcName]);
if si==1
% It is impossiblie to be connected to the
% remote computer.
ErrorCode=3;
return;
end
% -> IL CODICE SEGUENTE E' DA CONTROLLARE E VERIFICARE!
% The Local Machine can be connetted with Remote Computer.
% Now we verify if user name and password are correct and if remote
% drive and remote folder exist on the remote computer and it is
% possible to exchange data with them.
si=[];
de=[];
[si de]=system(['psinfo \\', DataInput.PcName, ' -u ',DataInput.user, ' -p ',DataInput.passwd ]);
if si<0
% It is possible to be connected to the remote computer but it is not usable because the user
% name and/or password is/are incorrect.
ErrorCodeComputer=4;
return;
else
% Username and Password are correct!
end
% Now we verify if it possible to exchange data with the remote
% computer:
fid = fopen('Tracing.txt','w+');
fclose (fid);
% ATTENZIONE: verificare perche sembra funzionare anche se il RemoteFolder non
% esiste.
Status=movefile('Tracing.txt', ['\\',DataInput.PcName,'\',DataInput.RemoteDrive,'$\',DataInput.RemoteFolder]);
if Status==1
% Remote Drive/Folder exist on Remote computer and
% it is possible to exchange data with him.
else
% Move file error!
ErrorCodeComputer=5;
return;
end
% At this point we can to analyze the remote computer hardware.
RealNumCPU=-1;
RealNumCPU=GiveCPUnumber(de);
% Trasforming the input data provided in a form [n1:n2] in a single numerical
% value.
DataInput.NumCPU=length(DataInput.NumCPU);
if DataInput.NumCPU == RealNumCPU
% It is Ok!
end
if DataInput.NumCPU > RealNumCPU
ErrorCode=2.1;
end
if DataInput.NumCPU < RealNumCPU
ErrorCode=2.2;
end
end

View File

@ -1,44 +1,44 @@
function DirectoryName = CheckPath(type)
% Creates the subfolder "./M_.dname/type" if it does not exist yet.
%
% INPUTS
% type [string] Name of the subfolder.
%
% OUTPUTS
% none.
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2005-2009 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/>.
global M_
DirectoryName = [ M_.dname '/' type ];
if ~isdir(M_.dname)
% Make sure there isn't a file with the same name, see trac ticket #47
delete(M_.dname)
mkdir('.', M_.dname);
end
if ~isdir(DirectoryName)
% Make sure there isn't a file with the same name, see trac ticket #47
delete(DirectoryName)
mkdir('.',DirectoryName);
end
function DirectoryName = CheckPath(type)
% Creates the subfolder "./M_.dname/type" if it does not exist yet.
%
% INPUTS
% type [string] Name of the subfolder.
%
% OUTPUTS
% none.
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2005-2009 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/>.
global M_
DirectoryName = [ M_.dname '/' type ];
if ~isdir(M_.dname)
% Make sure there isn't a file with the same name, see trac ticket #47
delete(M_.dname)
mkdir('.', M_.dname);
end
if ~isdir(DirectoryName)
% Make sure there isn't a file with the same name, see trac ticket #47
delete(DirectoryName)
mkdir('.',DirectoryName);
end

View File

@ -1,177 +1,177 @@
function [alphahat,etahat,atilde, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf)
% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf)
% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar1: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% trend
% pp: number of observed variables
% mm: number of state variables
% smpl: sample size
% mf: observed variables index in the state vector
%
% OUTPUTS
% alphahat: smoothed state variables (a_{t|T})
% etahat: smoothed shocks
% atilde: matrix of updated variables (a_{t|t})
% aK: 3D array of k step ahead filtered state variables (a_{t+k|t})
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% modified by M. Ratto:
% new output argument aK (1-step to k-step predictions)
% new options_.nk: the max step ahed prediction in aK (default is 4)
% new crit1 value for rank of Pinf
% it is assured that P is symmetric
global options_
nk = options_.nk;
spinf = size(Pinf1);
spstar = size(Pstar1);
v = zeros(pp,smpl);
a = zeros(mm,smpl+1);
atilde = zeros(mm,smpl);
aK = zeros(nk,mm,smpl+1);
iF = zeros(pp,pp,smpl);
Fstar = zeros(pp,pp,smpl);
iFinf = zeros(pp,pp,smpl);
K = zeros(mm,pp,smpl);
L = zeros(mm,mm,smpl);
Linf = zeros(mm,mm,smpl);
Kstar = zeros(mm,pp,smpl);
P = zeros(mm,mm,smpl+1);
Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
crit = options_.kalman_tol;
crit1 = 1.e-8;
steady = smpl;
rr = size(Q,1);
QQ = R*Q*transpose(R);
QRt = Q*transpose(R);
alphahat = zeros(mm,smpl);
etahat = zeros(rr,smpl);
r = zeros(mm,smpl+1);
Z = zeros(pp,mm);
for i=1:pp;
Z(i,mf(i)) = 1;
end
t = 0;
while rank(Pinf(:,:,t+1),crit1) & t<smpl
t = t+1;
v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
if rcond(Pinf(mf,mf,t)) < crit
return
end
iFinf(:,:,t) = inv(Pinf(mf,mf,t));
PZI = Pinf(:,mf,t)*iFinf(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
Kinf(:,:,t) = T*PZI;
a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1);
for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end
Linf(:,:,t) = T - Kinf(:,:,t)*Z;
Fstar(:,:,t) = Pstar(mf,mf,t);
Kstar(:,:,t) = (T*Pstar(:,mf,t)-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t);
Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)-T*Pstar(:,mf,t)*transpose(Kinf(:,:,t))-Kinf(:,:,t)*Pinf(mf,mf,t)*transpose(Kstar(:,:,t)) + QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T)-T*Pinf(:,mf,t)*transpose(Kinf(:,:,t));
end
d = t;
P(:,:,d+1) = Pstar(:,:,d+1);
iFinf = iFinf(:,:,1:d);
Linf = Linf(:,:,1:d);
Fstar = Fstar(:,:,1:d);
Kstar = Kstar(:,:,1:d);
Pstar = Pstar(:,:,1:d);
Pinf = Pinf(:,:,1:d);
notsteady = 1;
while notsteady & t<smpl
t = t+1;
v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
if rcond(P(mf,mf,t)) < crit
return
end
iF(:,:,t) = inv(P(mf,mf,t));
PZI = P(:,mf,t)*iF(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
K(:,:,t) = T*PZI;
L(:,:,t) = T-K(:,:,t)*Z;
a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1);
for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end
P(:,:,t+1) = T*P(:,:,t)*transpose(T)-T*P(:,mf,t)*transpose(K(:,:,t)) + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end
if t<smpl
PZI_s = PZI;
K_s = K(:,:,t);
iF_s = iF(:,:,t);
P_s = P(:,:,t+1);
t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
iF = cat(3,iF(:,:,1:t),repmat(inv(P_s(mf,mf)),[1 1 smpl-t_steady+1]));
L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t_steady+1]));
K = cat(3,K(:,:,1:t),repmat(T*P_s(:,mf)*iF_s,[1 1 smpl-t_steady+1]));
end
while t<smpl
t=t+1;
v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
a(:,t+1) = T*a(:,t) + K_s*v(:,t);
aK(1,:,t+1) = a(:,t+1);
for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end
end
t = smpl+1;
while t>d+1
t = t-1;
r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1);
alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
end
if d
r0 = zeros(mm,d+1);
r0(:,d+1) = r(:,d+1);
r1 = zeros(mm,d+1);
for t = d:-1:1
r0(:,t) = Linf(:,:,t)'*r0(:,t+1);
r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1);
alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t);
etahat(:,t) = QRt*r0(:,t);
end
end
function [alphahat,etahat,atilde, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf)
% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf)
% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar1: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% trend
% pp: number of observed variables
% mm: number of state variables
% smpl: sample size
% mf: observed variables index in the state vector
%
% OUTPUTS
% alphahat: smoothed state variables (a_{t|T})
% etahat: smoothed shocks
% atilde: matrix of updated variables (a_{t|t})
% aK: 3D array of k step ahead filtered state variables (a_{t+k|t})
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% modified by M. Ratto:
% new output argument aK (1-step to k-step predictions)
% new options_.nk: the max step ahed prediction in aK (default is 4)
% new crit1 value for rank of Pinf
% it is assured that P is symmetric
global options_
nk = options_.nk;
spinf = size(Pinf1);
spstar = size(Pstar1);
v = zeros(pp,smpl);
a = zeros(mm,smpl+1);
atilde = zeros(mm,smpl);
aK = zeros(nk,mm,smpl+1);
iF = zeros(pp,pp,smpl);
Fstar = zeros(pp,pp,smpl);
iFinf = zeros(pp,pp,smpl);
K = zeros(mm,pp,smpl);
L = zeros(mm,mm,smpl);
Linf = zeros(mm,mm,smpl);
Kstar = zeros(mm,pp,smpl);
P = zeros(mm,mm,smpl+1);
Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
crit = options_.kalman_tol;
crit1 = 1.e-8;
steady = smpl;
rr = size(Q,1);
QQ = R*Q*transpose(R);
QRt = Q*transpose(R);
alphahat = zeros(mm,smpl);
etahat = zeros(rr,smpl);
r = zeros(mm,smpl+1);
Z = zeros(pp,mm);
for i=1:pp;
Z(i,mf(i)) = 1;
end
t = 0;
while rank(Pinf(:,:,t+1),crit1) & t<smpl
t = t+1;
v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
if rcond(Pinf(mf,mf,t)) < crit
return
end
iFinf(:,:,t) = inv(Pinf(mf,mf,t));
PZI = Pinf(:,mf,t)*iFinf(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
Kinf(:,:,t) = T*PZI;
a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1);
for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end
Linf(:,:,t) = T - Kinf(:,:,t)*Z;
Fstar(:,:,t) = Pstar(mf,mf,t);
Kstar(:,:,t) = (T*Pstar(:,mf,t)-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t);
Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)-T*Pstar(:,mf,t)*transpose(Kinf(:,:,t))-Kinf(:,:,t)*Pinf(mf,mf,t)*transpose(Kstar(:,:,t)) + QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T)-T*Pinf(:,mf,t)*transpose(Kinf(:,:,t));
end
d = t;
P(:,:,d+1) = Pstar(:,:,d+1);
iFinf = iFinf(:,:,1:d);
Linf = Linf(:,:,1:d);
Fstar = Fstar(:,:,1:d);
Kstar = Kstar(:,:,1:d);
Pstar = Pstar(:,:,1:d);
Pinf = Pinf(:,:,1:d);
notsteady = 1;
while notsteady & t<smpl
t = t+1;
v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
if rcond(P(mf,mf,t)) < crit
return
end
iF(:,:,t) = inv(P(mf,mf,t));
PZI = P(:,mf,t)*iF(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
K(:,:,t) = T*PZI;
L(:,:,t) = T-K(:,:,t)*Z;
a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1);
for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end
P(:,:,t+1) = T*P(:,:,t)*transpose(T)-T*P(:,mf,t)*transpose(K(:,:,t)) + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end
if t<smpl
PZI_s = PZI;
K_s = K(:,:,t);
iF_s = iF(:,:,t);
P_s = P(:,:,t+1);
t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
iF = cat(3,iF(:,:,1:t),repmat(inv(P_s(mf,mf)),[1 1 smpl-t_steady+1]));
L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t_steady+1]));
K = cat(3,K(:,:,1:t),repmat(T*P_s(:,mf)*iF_s,[1 1 smpl-t_steady+1]));
end
while t<smpl
t=t+1;
v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
a(:,t+1) = T*a(:,t) + K_s*v(:,t);
aK(1,:,t+1) = a(:,t+1);
for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end
end
t = smpl+1;
while t>d+1
t = t-1;
r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1);
alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
end
if d
r0 = zeros(mm,d+1);
r0(:,d+1) = r(:,d+1);
r1 = zeros(mm,d+1);
for t = d:-1:1
r0(:,t) = Linf(:,:,t)'*r0(:,t+1);
r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1);
alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t);
etahat(:,t) = QRt*r0(:,t);
end
end

View File

@ -1,208 +1,208 @@
function [alphahat,etahat,atilde,P,aK,PK,d,decomp] = DiffuseKalmanSmoother1_Z(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl)
% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl)
% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% Z: pp*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar1: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% pp: number of observed variables
% mm: number of state variables
% smpl: sample size
%
% OUTPUTS
% alphahat: smoothed variables (a_{t|T})
% etahat: smoothed shocks
% atilde: matrix of updated variables (a_{t|t})
% aK: 3D array of k step ahead filtered state variables (a_{t+k|t)
% (meaningless for periods 1:d)
% P: 3D array of one-step ahead forecast error variance
% matrices
% PK: 4D array of k-step ahead forecast error variance
% matrices (meaningless for periods 1:d)
% d: number of periods where filter remains in diffuse part
% (should be equal to the order of integration of the model)
% decomp: decomposition of the effect of shocks on filtered values
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% modified by M. Ratto:
% new output argument aK (1-step to k-step predictions)
% new options_.nk: the max step ahed prediction in aK (default is 4)
% new crit1 value for rank of Pinf
% it is assured that P is symmetric
global options_
d = 0;
decomp = [];
nk = options_.nk;
spinf = size(Pinf1);
spstar = size(Pstar1);
v = zeros(pp,smpl);
a = zeros(mm,smpl+1);
atilde = zeros(mm,smpl);
aK = zeros(nk,mm,smpl+nk);
PK = zeros(nk,mm,mm,smpl+nk);
iF = zeros(pp,pp,smpl);
Fstar = zeros(pp,pp,smpl);
iFinf = zeros(pp,pp,smpl);
K = zeros(mm,pp,smpl);
L = zeros(mm,mm,smpl);
Linf = zeros(mm,mm,smpl);
Kstar = zeros(mm,pp,smpl);
P = zeros(mm,mm,smpl+1);
Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
crit = options_.kalman_tol;
crit1 = 1.e-8;
steady = smpl;
rr = size(Q,1);
QQ = R*Q*transpose(R);
QRt = Q*transpose(R);
alphahat = zeros(mm,smpl);
etahat = zeros(rr,smpl);
r = zeros(mm,smpl+1);
t = 0;
while rank(Pinf(:,:,t+1),crit1) & t<smpl
t = t+1;
v(:,t)= Y(:,t) - Z*a(:,t);
F = Z*Pinf(:,:,t)*Z';
if rcond(F) < crit
return
end
iFinf(:,:,t) = inv(F);
PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
Kinf(:,:,t) = T*PZI;
a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1);
% isn't a meaningless as long as we are in the diffuse part? MJ
for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end
Linf(:,:,t) = T - Kinf(:,:,t)*Z;
Fstar(:,:,t) = Z*Pstar(:,:,t)*Z';
Kstar(:,:,t) = (T*Pstar(:,:,t)*Z'-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t);
Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'-T*Pstar(:,:,t)*Z'*Kinf(:,:,t)'-Kinf(:,:,t)*F*Kstar(:,:,t)' + QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*Z'*Kinf(:,:,t)';
end
d = t;
P(:,:,d+1) = Pstar(:,:,d+1);
iFinf = iFinf(:,:,1:d);
Linf = Linf(:,:,1:d);
Fstar = Fstar(:,:,1:d);
Kstar = Kstar(:,:,1:d);
Pstar = Pstar(:,:,1:d);
Pinf = Pinf(:,:,1:d);
notsteady = 1;
while notsteady & t<smpl
t = t+1;
v(:,t) = Y(:,t) - Z*a(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
F = Z*P(:,:,t)*Z';
if rcond(F) < crit
return
end
iF(:,:,t) = inv(F);
PZI = P(:,:,t)*Z'*iF(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
K(:,:,t) = T*PZI;
L(:,:,t) = T-K(:,:,t)*Z;
a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end
if t<smpl
PZI_s = PZI;
K_s = K(:,:,t);
iF_s = iF(:,:,t);
P_s = P(:,:,t+1);
P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t]));
iF = cat(3,iF(:,:,1:t),repmat(iF_s,[1 1 smpl-t]));
L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t]));
K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t]));
end
while t<smpl
t=t+1;
v(:,t) = Y(:,t) - Z*a(:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
end
t = smpl+1;
while t>d+1
t = t-1;
r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1);
alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
end
if d
r0 = zeros(mm,d+1);
r0(:,d+1) = r(:,d+1);
r1 = zeros(mm,d+1);
for t = d:-1:1
r0(:,t) = Linf(:,:,t)'*r0(:,t+1);
r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1);
alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t);
etahat(:,t) = QRt*r0(:,t);
end
end
if nargout > 7
decomp = zeros(nk,mm,rr,smpl+nk);
ZRQinv = inv(Z*QQ*Z');
for t = max(d,1):smpl
ri_d = Z'*iF(:,:,t)*v(:,t);
% calculate eta_tm1t
eta_tm1t = QRt*ri_d;
% calculate decomposition
Ttok = eye(mm,mm);
for h = 1:nk
for j=1:rr
eta=zeros(rr,1);
eta(j) = eta_tm1t(j);
decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta;
end
end
end
end
function [alphahat,etahat,atilde,P,aK,PK,d,decomp] = DiffuseKalmanSmoother1_Z(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl)
% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl)
% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% Z: pp*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar1: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% pp: number of observed variables
% mm: number of state variables
% smpl: sample size
%
% OUTPUTS
% alphahat: smoothed variables (a_{t|T})
% etahat: smoothed shocks
% atilde: matrix of updated variables (a_{t|t})
% aK: 3D array of k step ahead filtered state variables (a_{t+k|t)
% (meaningless for periods 1:d)
% P: 3D array of one-step ahead forecast error variance
% matrices
% PK: 4D array of k-step ahead forecast error variance
% matrices (meaningless for periods 1:d)
% d: number of periods where filter remains in diffuse part
% (should be equal to the order of integration of the model)
% decomp: decomposition of the effect of shocks on filtered values
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% modified by M. Ratto:
% new output argument aK (1-step to k-step predictions)
% new options_.nk: the max step ahed prediction in aK (default is 4)
% new crit1 value for rank of Pinf
% it is assured that P is symmetric
global options_
d = 0;
decomp = [];
nk = options_.nk;
spinf = size(Pinf1);
spstar = size(Pstar1);
v = zeros(pp,smpl);
a = zeros(mm,smpl+1);
atilde = zeros(mm,smpl);
aK = zeros(nk,mm,smpl+nk);
PK = zeros(nk,mm,mm,smpl+nk);
iF = zeros(pp,pp,smpl);
Fstar = zeros(pp,pp,smpl);
iFinf = zeros(pp,pp,smpl);
K = zeros(mm,pp,smpl);
L = zeros(mm,mm,smpl);
Linf = zeros(mm,mm,smpl);
Kstar = zeros(mm,pp,smpl);
P = zeros(mm,mm,smpl+1);
Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
crit = options_.kalman_tol;
crit1 = 1.e-8;
steady = smpl;
rr = size(Q,1);
QQ = R*Q*transpose(R);
QRt = Q*transpose(R);
alphahat = zeros(mm,smpl);
etahat = zeros(rr,smpl);
r = zeros(mm,smpl+1);
t = 0;
while rank(Pinf(:,:,t+1),crit1) & t<smpl
t = t+1;
v(:,t)= Y(:,t) - Z*a(:,t);
F = Z*Pinf(:,:,t)*Z';
if rcond(F) < crit
return
end
iFinf(:,:,t) = inv(F);
PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
Kinf(:,:,t) = T*PZI;
a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1);
% isn't a meaningless as long as we are in the diffuse part? MJ
for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end
Linf(:,:,t) = T - Kinf(:,:,t)*Z;
Fstar(:,:,t) = Z*Pstar(:,:,t)*Z';
Kstar(:,:,t) = (T*Pstar(:,:,t)*Z'-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t);
Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'-T*Pstar(:,:,t)*Z'*Kinf(:,:,t)'-Kinf(:,:,t)*F*Kstar(:,:,t)' + QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*Z'*Kinf(:,:,t)';
end
d = t;
P(:,:,d+1) = Pstar(:,:,d+1);
iFinf = iFinf(:,:,1:d);
Linf = Linf(:,:,1:d);
Fstar = Fstar(:,:,1:d);
Kstar = Kstar(:,:,1:d);
Pstar = Pstar(:,:,1:d);
Pinf = Pinf(:,:,1:d);
notsteady = 1;
while notsteady & t<smpl
t = t+1;
v(:,t) = Y(:,t) - Z*a(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
F = Z*P(:,:,t)*Z';
if rcond(F) < crit
return
end
iF(:,:,t) = inv(F);
PZI = P(:,:,t)*Z'*iF(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
K(:,:,t) = T*PZI;
L(:,:,t) = T-K(:,:,t)*Z;
a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end
if t<smpl
PZI_s = PZI;
K_s = K(:,:,t);
iF_s = iF(:,:,t);
P_s = P(:,:,t+1);
P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t]));
iF = cat(3,iF(:,:,1:t),repmat(iF_s,[1 1 smpl-t]));
L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t]));
K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t]));
end
while t<smpl
t=t+1;
v(:,t) = Y(:,t) - Z*a(:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
end
t = smpl+1;
while t>d+1
t = t-1;
r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1);
alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
end
if d
r0 = zeros(mm,d+1);
r0(:,d+1) = r(:,d+1);
r1 = zeros(mm,d+1);
for t = d:-1:1
r0(:,t) = Linf(:,:,t)'*r0(:,t+1);
r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1);
alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t);
etahat(:,t) = QRt*r0(:,t);
end
end
if nargout > 7
decomp = zeros(nk,mm,rr,smpl+nk);
ZRQinv = inv(Z*QQ*Z');
for t = max(d,1):smpl
ri_d = Z'*iF(:,:,t)*v(:,t);
% calculate eta_tm1t
eta_tm1t = QRt*ri_d;
% calculate decomposition
Ttok = eye(mm,mm);
for h = 1:nk
for j=1:rr
eta=zeros(rr,1);
eta(j) = eta_tm1t(j);
decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta;
end
end
end
end

View File

@ -70,9 +70,9 @@ aK = zeros(nk,mm,smpl+nk);
PK = zeros(nk,mm,mm,smpl+nk);
if isempty(options_.diffuse_d),
smpl_diff = 1;
smpl_diff = 1;
else
smpl_diff=rank(Pinf1);
smpl_diff=rank(Pinf1);
end
Fstar = zeros(pp,smpl_diff);
@ -101,81 +101,81 @@ r = zeros(mm,smpl+1);
Z = zeros(pp,mm);
for i=1:pp;
Z(i,mf(i)) = 1;
Z(i,mf(i)) = 1;
end
t = 0;
icc=0;
newRank = rank(Pinf(:,:,1),crit1);
while newRank & t < smpl
t = t+1;
a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp
v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t);
Fstar(i,t) = Pstar(mf(i),mf(i),t);
Finf(i,t) = Pinf(mf(i),mf(i),t);
Kstar(:,i,t) = Pstar(:,mf(i),t);
if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit
icc=icc+1;
Kinf(:,i,t) = Pinf(:,mf(i),t);
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t);
a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*transpose(Kinf(:,i,t)) +...
Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
% new terminiation criteria by M. Ratto
P0=Pinf(:,:,t);
% newRank = any(diag(P0(mf,mf))>crit);
% if newRank==0, id = i; end,
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
%if newRank & any(diag(P0(mf,mf))>crit)==0;
if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc;
newRank=0;
t = t+1;
a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp
v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t);
Fstar(i,t) = Pstar(mf(i),mf(i),t);
Finf(i,t) = Pinf(mf(i),mf(i),t);
Kstar(:,i,t) = Pstar(:,mf(i),t);
if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit
icc=icc+1;
Kinf(:,i,t) = Pinf(:,mf(i),t);
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t);
a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*transpose(Kinf(:,i,t)) +...
Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
% new terminiation criteria by M. Ratto
P0=Pinf(:,:,t);
% newRank = any(diag(P0(mf,mf))>crit);
% if newRank==0, id = i; end,
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
%if newRank & any(diag(P0(mf,mf))>crit)==0;
if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc;
newRank=0;
end
else
%newRank = any(diag(P0(mf,mf))>crit);
newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1));
if newRank==0,
options_.diffuse_d = icc;
end
end,
% if newRank==0,
% options_.diffuse_d=i; %this is buggy
% end
% end new terminiation criteria by M. Ratto
elseif Fstar(i,t) > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
end
else
%newRank = any(diag(P0(mf,mf))>crit);
newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1));
if newRank==0,
options_.diffuse_d = icc;
end
end,
% if newRank==0,
% options_.diffuse_d=i; %this is buggy
% end
% end new terminiation criteria by M. Ratto
elseif Fstar(i,t) > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
end
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T);
P0=Pinf(:,:,t+1);
if newRank,
%newRank = any(diag(P0(mf,mf))>crit);
newRank = rank(P0,crit1);
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T);
P0=Pinf(:,:,t+1);
if newRank,
%newRank = any(diag(P0(mf,mf))>crit);
newRank = rank(P0,crit1);
end
end
@ -192,96 +192,96 @@ Pstar1 = Pstar1(:,:,1:d);
Pinf1 = Pinf1(:,:,1:d);
notsteady = 1;
while notsteady & t<smpl
t = t+1;
a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
P1(:,:,t) = P(:,:,t);
for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t);
Fi(i,t) = P(mf(i),mf(i),t);
Ki(:,i,t) = P(:,mf(i),t);
if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t);
a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);
P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
t = t+1;
a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
P1(:,:,t) = P(:,:,t);
for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t);
Fi(i,t) = P(mf(i),mf(i),t);
Ki(:,i,t) = P(:,mf(i),t);
if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t);
a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);
P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
end
end
end
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end
P_s=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
Fi_s = Fi(:,t);
Ki_s = Ki(:,:,t);
L_s =Li(:,:,:,t);
if t<smpl
t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1]));
Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1]));
Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1]));
t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1]));
Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1]));
Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1]));
end
while t<smpl
t=t+1;
a(:,t) = a1(:,t);
for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t);
if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i);
t=t+1;
a(:,t) = a1(:,t);
for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t);
if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i);
end
end
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
end
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
end
ri=zeros(mm,1);
t = smpl+1;
while t>d+1
t = t-1;
for i=pp:-1:1
if Fi(i,t) > crit
ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
t = t-1;
for i=pp:-1:1
if Fi(i,t) > crit
ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
end
end
end
r(:,t) = ri;
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
ri = T'*ri;
r(:,t) = ri;
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
ri = T'*ri;
end
if d
r0 = zeros(mm,d);
r0(:,d) = ri;
r1 = zeros(mm,d);
for t = d:-1:1
for i=pp:-1:1
if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination
%r1(:,t) = transpose(Z)*v(:,t)/Finf(i,t) + ... BUG HERE in transpose(Z)
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0
r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end
r0 = zeros(mm,d);
r0(:,d) = ri;
r1 = zeros(mm,d);
for t = d:-1:1
for i=pp:-1:1
if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination
%r1(:,t) = transpose(Z)*v(:,t)/Finf(i,t) + ... BUG HERE in transpose(Z)
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0
r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end
end
alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
r(:,t) = r0(:,t);
etahat(:,t) = QRt*r(:,t);
if t > 1
r0(:,t-1) = T'*r0(:,t);
r1(:,t-1) = T'*r1(:,t);
end
end
alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
r(:,t) = r0(:,t);
etahat(:,t) = QRt*r(:,t);
if t > 1
r0(:,t-1) = T'*r0(:,t);
r1(:,t-1) = T'*r1(:,t);
end
end
end
if nargout > 7

View File

@ -76,9 +76,9 @@ a1 = zeros(mm,smpl+1);
aK = zeros(nk,mm,smpl+nk);
if isempty(options_.diffuse_d),
smpl_diff = 1;
smpl_diff = 1;
else
smpl_diff=rank(Pinf1);
smpl_diff=rank(Pinf1);
end
Fstar = zeros(pp,smpl_diff);
@ -111,67 +111,67 @@ t = 0;
icc=0;
newRank = rank(Pinf(:,:,1),crit1);
while newRank & t < smpl
t = t+1;
a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t)-Zi*a(:,t);
Fstar(i,t) = Zi*Pstar(:,:,t)*Zi';
Finf(i,t) = Zi*Pinf(:,:,t)*Zi';
Kstar(:,i,t) = Pstar(:,:,t)*Zi';
if Finf(i,t) > crit & newRank
icc=icc+1;
Kinf(:,i,t) = Pinf(:,:,t)*Zi';
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Zi/Finf(i,t);
a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*Kinf(:,i,t)' +...
Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
% new terminiation criteria by M. Ratto
P0=Pinf(:,:,t);
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc;
newRank=0;
t = t+1;
a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t)-Zi*a(:,t);
Fstar(i,t) = Zi*Pstar(:,:,t)*Zi';
Finf(i,t) = Zi*Pinf(:,:,t)*Zi';
Kstar(:,i,t) = Pstar(:,:,t)*Zi';
if Finf(i,t) > crit & newRank
icc=icc+1;
Kinf(:,i,t) = Pinf(:,:,t)*Zi';
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Zi/Finf(i,t);
a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*Kinf(:,i,t)' +...
Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
% new terminiation criteria by M. Ratto
P0=Pinf(:,:,t);
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc;
newRank=0;
end
else
newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1));
if newRank==0,
options_.diffuse_d = icc;
end
end,
% end new terminiation criteria by M. Ratto
elseif Fstar(i,t) > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
end
else
newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1));
if newRank==0,
options_.diffuse_d = icc;
end
end,
% end new terminiation criteria by M. Ratto
elseif Fstar(i,t) > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
end
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*T';
P0=Pinf(:,:,t+1);
if newRank,
newRank = rank(P0,crit1);
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*T';
P0=Pinf(:,:,t+1);
if newRank,
newRank = rank(P0,crit1);
end
end
@ -188,31 +188,31 @@ Pstar1 = Pstar1(:,:,1:d);
Pinf1 = Pinf1(:,:,1:d);
notsteady = 1;
while notsteady & t<smpl
t = t+1;
a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
P1(:,:,t) = P(:,:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t);
Fi(i,t) = Zi*P(:,:,t)*Zi';
Ki(:,i,t) = P(:,:,t)*Zi';
if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t);
a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);
P(:,:,t) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
t = t+1;
a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
P1(:,:,t) = P(:,:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t);
Fi(i,t) = Zi*P(:,:,t)*Zi';
Ki(:,i,t) = P(:,:,t)*Zi';
if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t);
a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);
P(:,:,t) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
end
end
end
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
P(:,:,t+1) = T*P(:,:,t)*T' + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
P(:,:,t+1) = T*P(:,:,t)*T' + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end
P_s=tril(P(:,:,t))+tril(P(:,:,t),-1)';
P1_s=tril(P1(:,:,t))+tril(P1(:,:,t),-1)';
@ -220,67 +220,67 @@ Fi_s = Fi(:,t);
Ki_s = Ki(:,:,t);
L_s =Li(:,:,:,t);
if t<smpl
P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t]));
P1 = cat(3,P1(:,:,1:t),repmat(P1_s,[1 1 smpl-t]));
Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t]));
Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t]));
Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t]));
P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t]));
P1 = cat(3,P1(:,:,1:t),repmat(P1_s,[1 1 smpl-t]));
Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t]));
Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t]));
Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t]));
end
while t<smpl
t=t+1;
a(:,t) = a1(:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t);
if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i);
t=t+1;
a(:,t) = a1(:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t);
if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i);
end
end
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
end
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
end
ri=zeros(mm,1);
t = smpl+1;
while t > d+1
t = t-1;
for i=pp:-1:1
if Fi(i,t) > crit
ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
t = t-1;
for i=pp:-1:1
if Fi(i,t) > crit
ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
end
end
end
r(:,t) = ri;
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
ri = T'*ri;
r(:,t) = ri;
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
ri = T'*ri;
end
if d
r0 = zeros(mm,d);
r0(:,d) = ri;
r1 = zeros(mm,d);
for t = d:-1:1
for i=pp:-1:1
% if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination
if Finf(i,t) > crit
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0
r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end
r0 = zeros(mm,d);
r0(:,d) = ri;
r1 = zeros(mm,d);
for t = d:-1:1
for i=pp:-1:1
% if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination
if Finf(i,t) > crit
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0
r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end
end
alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
r(:,t) = r0(:,t);
etahat(:,t) = QRt*r(:,t);
if t > 1
r0(:,t-1) = T'*r0(:,t);
r1(:,t-1) = T'*r1(:,t);
end
end
alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
r(:,t) = r0(:,t);
etahat(:,t) = QRt*r(:,t);
if t > 1
r0(:,t-1) = T'*r0(:,t);
r1(:,t-1) = T'*r1(:,t);
end
end
end
if nargout > 7

View File

@ -1,212 +1,212 @@
function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,d,decomp] = DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl)
% function [alphahat,etahat,atilde, aK] = DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl)
% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% Z: pp*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% H: pp*pp matrix variance of measurement errors
% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar1: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% pp: number of observed variables
% mm: number of state variables
% smpl: sample size
%
% OUTPUTS
% alphahat: smoothed variables (a_{t|T})
% epsilonhat:smoothed measurement errors
% etahat: smoothed shocks
% atilde: matrix of updated variables (a_{t|t})
% aK: 3D array of k step ahead filtered state variables (a_{t+k|t)
% (meaningless for periods 1:d)
% P: 3D array of one-step ahead forecast error variance
% matrices
% PK: 4D array of k-step ahead forecast error variance
% matrices (meaningless for periods 1:d)
% d: number of periods where filter remains in diffuse part
% (should be equal to the order of integration of the model)
% decomp: decomposition of the effect of shocks on filtered values
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% modified by M. Ratto:
% new output argument aK (1-step to k-step predictions)
% new options_.nk: the max step ahed prediction in aK (default is 4)
% new crit1 value for rank of Pinf
% it is assured that P is symmetric
global options_
d = 0;
decomp = [];
nk = options_.nk;
spinf = size(Pinf1);
spstar = size(Pstar1);
v = zeros(pp,smpl);
a = zeros(mm,smpl+1);
atilde = zeros(mm,smpl);
aK = zeros(nk,mm,smpl+nk);
PK = zeros(nk,mm,mm,smpl+nk);
iF = zeros(pp,pp,smpl);
Fstar = zeros(pp,pp,smpl);
iFinf = zeros(pp,pp,smpl);
K = zeros(mm,pp,smpl);
L = zeros(mm,mm,smpl);
Linf = zeros(mm,mm,smpl);
Kstar = zeros(mm,pp,smpl);
P = zeros(mm,mm,smpl+1);
Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
crit = options_.kalman_tol;
crit1 = 1.e-8;
steady = smpl;
rr = size(Q,1);
QQ = R*Q*transpose(R);
QRt = Q*transpose(R);
alphahat = zeros(mm,smpl);
etahat = zeros(rr,smpl);
epsilonhat = zeros(size(Y));
r = zeros(mm,smpl+1);
t = 0;
while rank(Pinf(:,:,t+1),crit1) & t<smpl
t = t+1;
v(:,t)= Y(:,t) - Z*a(:,t);
F = Z*Pinf(:,:,t)*Z';
if rcond(F) < crit
return
end
iFinf(:,:,t) = inv(F);
PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
Kinf(:,:,t) = T*PZI;
a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1);
% isn't a meaningless as long as we are in the diffuse part? MJ
for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end
Linf(:,:,t) = T - Kinf(:,:,t)*Z;
Fstar(:,:,t) = Z*Pstar(:,:,t)*Z' + H;
Kstar(:,:,t) = (T*Pstar(:,:,t)*Z'-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t);
Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'-T*Pstar(:,:,t)*Z'*Kinf(:,:,t)'-Kinf(:,:,t)*F*Kstar(:,:,t)' + QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*Z'*Kinf(:,:,t)';
end
d = t;
P(:,:,d+1) = Pstar(:,:,d+1);
iFinf = iFinf(:,:,1:d);
Linf = Linf(:,:,1:d);
Fstar = Fstar(:,:,1:d);
Kstar = Kstar(:,:,1:d);
Pstar = Pstar(:,:,1:d);
Pinf = Pinf(:,:,1:d);
notsteady = 1;
while notsteady & t<smpl
t = t+1;
v(:,t) = Y(:,t) - Z*a(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
F = Z*P(:,:,t)*Z' + H;
if rcond(F) < crit
return
end
iF(:,:,t) = inv(F);
PZI = P(:,:,t)*Z'*iF(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
K(:,:,t) = T*PZI;
L(:,:,t) = T-K(:,:,t)*Z;
a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end
if t<smpl
PZI_s = PZI;
K_s = K(:,:,t);
iF_s = iF(:,:,t);
P_s = P(:,:,t+1);
P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t]));
iF = cat(3,iF(:,:,1:t),repmat(iF_s,[1 1 smpl-t]));
L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t]));
K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t]));
end
while t<smpl
t=t+1;
v(:,t) = Y(:,t) - Z*a(:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
end
t = smpl+1;
while t>d+1
t = t-1;
r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1);
alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
end
if d
r0 = zeros(mm,d+1);
r0(:,d+1) = r(:,d+1);
r1 = zeros(mm,d+1);
for t = d:-1:1
r0(:,t) = Linf(:,:,t)'*r0(:,t+1);
r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1);
alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t);
etahat(:,t) = QRt*r0(:,t);
end
end
if nargout > 7
decomp = zeros(nk,mm,rr,smpl+nk);
ZRQinv = inv(Z*QQ*Z');
for t = max(d,1):smpl
ri_d = Z'*iF(:,:,t)*v(:,t);
% calculate eta_tm1t
eta_tm1t = QRt*ri_d;
% calculate decomposition
Ttok = eye(mm,mm);
for h = 1:nk
for j=1:rr
eta=zeros(rr,1);
eta(j) = eta_tm1t(j);
decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta;
end
end
end
end
epsilonhat = Y-Z*alphahat;
function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,d,decomp] = DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl)
% function [alphahat,etahat,atilde, aK] = DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl)
% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% Z: pp*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% H: pp*pp matrix variance of measurement errors
% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar1: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% pp: number of observed variables
% mm: number of state variables
% smpl: sample size
%
% OUTPUTS
% alphahat: smoothed variables (a_{t|T})
% epsilonhat:smoothed measurement errors
% etahat: smoothed shocks
% atilde: matrix of updated variables (a_{t|t})
% aK: 3D array of k step ahead filtered state variables (a_{t+k|t)
% (meaningless for periods 1:d)
% P: 3D array of one-step ahead forecast error variance
% matrices
% PK: 4D array of k-step ahead forecast error variance
% matrices (meaningless for periods 1:d)
% d: number of periods where filter remains in diffuse part
% (should be equal to the order of integration of the model)
% decomp: decomposition of the effect of shocks on filtered values
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% modified by M. Ratto:
% new output argument aK (1-step to k-step predictions)
% new options_.nk: the max step ahed prediction in aK (default is 4)
% new crit1 value for rank of Pinf
% it is assured that P is symmetric
global options_
d = 0;
decomp = [];
nk = options_.nk;
spinf = size(Pinf1);
spstar = size(Pstar1);
v = zeros(pp,smpl);
a = zeros(mm,smpl+1);
atilde = zeros(mm,smpl);
aK = zeros(nk,mm,smpl+nk);
PK = zeros(nk,mm,mm,smpl+nk);
iF = zeros(pp,pp,smpl);
Fstar = zeros(pp,pp,smpl);
iFinf = zeros(pp,pp,smpl);
K = zeros(mm,pp,smpl);
L = zeros(mm,mm,smpl);
Linf = zeros(mm,mm,smpl);
Kstar = zeros(mm,pp,smpl);
P = zeros(mm,mm,smpl+1);
Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
crit = options_.kalman_tol;
crit1 = 1.e-8;
steady = smpl;
rr = size(Q,1);
QQ = R*Q*transpose(R);
QRt = Q*transpose(R);
alphahat = zeros(mm,smpl);
etahat = zeros(rr,smpl);
epsilonhat = zeros(size(Y));
r = zeros(mm,smpl+1);
t = 0;
while rank(Pinf(:,:,t+1),crit1) & t<smpl
t = t+1;
v(:,t)= Y(:,t) - Z*a(:,t);
F = Z*Pinf(:,:,t)*Z';
if rcond(F) < crit
return
end
iFinf(:,:,t) = inv(F);
PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
Kinf(:,:,t) = T*PZI;
a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1);
% isn't a meaningless as long as we are in the diffuse part? MJ
for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end
Linf(:,:,t) = T - Kinf(:,:,t)*Z;
Fstar(:,:,t) = Z*Pstar(:,:,t)*Z' + H;
Kstar(:,:,t) = (T*Pstar(:,:,t)*Z'-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t);
Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'-T*Pstar(:,:,t)*Z'*Kinf(:,:,t)'-Kinf(:,:,t)*F*Kstar(:,:,t)' + QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*Z'*Kinf(:,:,t)';
end
d = t;
P(:,:,d+1) = Pstar(:,:,d+1);
iFinf = iFinf(:,:,1:d);
Linf = Linf(:,:,1:d);
Fstar = Fstar(:,:,1:d);
Kstar = Kstar(:,:,1:d);
Pstar = Pstar(:,:,1:d);
Pinf = Pinf(:,:,1:d);
notsteady = 1;
while notsteady & t<smpl
t = t+1;
v(:,t) = Y(:,t) - Z*a(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
F = Z*P(:,:,t)*Z' + H;
if rcond(F) < crit
return
end
iF(:,:,t) = inv(F);
PZI = P(:,:,t)*Z'*iF(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
K(:,:,t) = T*PZI;
L(:,:,t) = T-K(:,:,t)*Z;
a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end
if t<smpl
PZI_s = PZI;
K_s = K(:,:,t);
iF_s = iF(:,:,t);
P_s = P(:,:,t+1);
P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t]));
iF = cat(3,iF(:,:,1:t),repmat(iF_s,[1 1 smpl-t]));
L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t]));
K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t]));
end
while t<smpl
t=t+1;
v(:,t) = Y(:,t) - Z*a(:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t);
a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
end
t = smpl+1;
while t>d+1
t = t-1;
r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1);
alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
end
if d
r0 = zeros(mm,d+1);
r0(:,d+1) = r(:,d+1);
r1 = zeros(mm,d+1);
for t = d:-1:1
r0(:,t) = Linf(:,:,t)'*r0(:,t+1);
r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1);
alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t);
etahat(:,t) = QRt*r0(:,t);
end
end
if nargout > 7
decomp = zeros(nk,mm,rr,smpl+nk);
ZRQinv = inv(Z*QQ*Z');
for t = max(d,1):smpl
ri_d = Z'*iF(:,:,t)*v(:,t);
% calculate eta_tm1t
eta_tm1t = QRt*ri_d;
% calculate decomposition
Ttok = eye(mm,mm);
for h = 1:nk
for j=1:rr
eta=zeros(rr,1);
eta(j) = eta_tm1t(j);
decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta;
end
end
end
end
epsilonhat = Y-Z*alphahat;

View File

@ -68,9 +68,9 @@ a1 = zeros(mm,smpl+1);
aK = zeros(nk,mm,smpl+nk);
if isempty(options_.diffuse_d),
smpl_diff = 1;
smpl_diff = 1;
else
smpl_diff=rank(Pinf1);
smpl_diff=rank(Pinf1);
end
Fstar = zeros(pp,smpl_diff);
@ -99,81 +99,81 @@ r = zeros(mm,smpl+1);
Z = zeros(pp,mm);
for i=1:pp;
Z(i,mf(i)) = 1;
Z(i,mf(i)) = 1;
end
t = 0;
icc=0;
newRank = rank(Pinf(:,:,1),crit1);
while newRank & t < smpl
t = t+1;
a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp
v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t);
Fstar(i,t) = Pstar(mf(i),mf(i),t) + H(i,i);
Finf(i,t) = Pinf(mf(i),mf(i),t);
Kstar(:,i,t) = Pstar(:,mf(i),t);
if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit
icc=icc+1;
Kinf(:,i,t) = Pinf(:,mf(i),t);
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t);
a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*transpose(Kinf(:,i,t)) +...
Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
% new terminiation criteria by M. Ratto
P0=Pinf(:,:,t);
% newRank = any(diag(P0(mf,mf))>crit);
% if newRank==0, options_.diffuse_d = i; end,
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
%if newRank & any(diag(P0(mf,mf))>crit)==0;
if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc;
newRank=0;
end
else
%newRank = any(diag(P0(mf,mf))>crit);
newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1));
if newRank==0,
options_.diffuse_d = icc;
end
end,
% if newRank==0,
% options_.diffuse_d=i; % this line is buggy!
% end
% end new terminiation criteria by M. Ratto
elseif Fstar(i,t) > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
t = t+1;
a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp
v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t);
Fstar(i,t) = Pstar(mf(i),mf(i),t) + H(i,i);
Finf(i,t) = Pinf(mf(i),mf(i),t);
Kstar(:,i,t) = Pstar(:,mf(i),t);
if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit
icc=icc+1;
Kinf(:,i,t) = Pinf(:,mf(i),t);
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t);
a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*transpose(Kinf(:,i,t)) +...
Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
% new terminiation criteria by M. Ratto
P0=Pinf(:,:,t);
% newRank = any(diag(P0(mf,mf))>crit);
% if newRank==0, options_.diffuse_d = i; end,
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
%if newRank & any(diag(P0(mf,mf))>crit)==0;
if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc;
newRank=0;
end
else
%newRank = any(diag(P0(mf,mf))>crit);
newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1));
if newRank==0,
options_.diffuse_d = icc;
end
end,
% if newRank==0,
% options_.diffuse_d=i; % this line is buggy!
% end
% end new terminiation criteria by M. Ratto
elseif Fstar(i,t) > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
end
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T);
P0=Pinf(:,:,t+1);
if newRank,
%newRank = any(diag(P0(mf,mf))>crit);
newRank = rank(P0,crit1);
end
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T);
P0=Pinf(:,:,t+1);
if newRank,
%newRank = any(diag(P0(mf,mf))>crit);
newRank = rank(P0,crit1);
end
end
@ -190,89 +190,89 @@ Pstar1 = Pstar1(:,:,1:d);
Pinf1 = Pinf1(:,:,1:d);
notsteady = 1;
while notsteady & t<smpl
t = t+1;
a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
P1(:,:,t) = P(:,:,t);
for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t);
Fi(i,t) = P(mf(i),mf(i),t)+H(i,i);
Ki(:,i,t) = P(:,mf(i),t);
if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t);
a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);
P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
t = t+1;
a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
P1(:,:,t) = P(:,:,t);
for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t);
Fi(i,t) = P(mf(i),mf(i),t)+H(i,i);
Ki(:,i,t) = P(:,mf(i),t);
if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t);
a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);
P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
end
end
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end
P_s=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
Fi_s = Fi(:,t);
Ki_s = Ki(:,:,t);
L_s =Li(:,:,:,t);
if t<smpl
t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1]));
Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1]));
Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1]));
t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1]));
Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1]));
Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1]));
end
while t<smpl
t=t+1;
a(:,t) = a1(:,t);
for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t);
if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i);
t=t+1;
a(:,t) = a1(:,t);
for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t);
if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i);
end
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
end
ri=zeros(mm,1);
t = smpl+1;
while t>d+1
t = t-1;
for i=pp:-1:1
if Fi(i,t) > crit
ri=Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
t = t-1;
for i=pp:-1:1
if Fi(i,t) > crit
ri=Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
end
end
end
r(:,t) = ri;
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
ri = T'*ri;
r(:,t) = ri;
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
ri = T'*ri;
end
if d
r0 = zeros(mm,d);
r0(:,d) = ri;
r1 = zeros(mm,d);
for t = d:-1:1
for i=pp:-1:1
if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0
r0(:,t)=Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end
r0 = zeros(mm,d);
r0(:,d) = ri;
r1 = zeros(mm,d);
for t = d:-1:1
for i=pp:-1:1
if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0
r0(:,t)=Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end
end
alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
r(:,t) = r0(:,t);
etahat(:,t) = QRt*r(:,t);
if t > 1
r0(:,t-1) = transpose(T)*r0(:,t);
r1(:,t-1) = transpose(T)*r1(:,t);
end
end
alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
r(:,t) = r0(:,t);
etahat(:,t) = QRt*r(:,t);
if t > 1
r0(:,t-1) = transpose(T)*r0(:,t);
r1(:,t-1) = transpose(T)*r1(:,t);
end
end
end
epsilonhat = Y-alphahat(mf,:)-trend;

View File

@ -77,9 +77,9 @@ a1 = zeros(mm,smpl+1);
aK = zeros(nk,mm,smpl+nk);
if isempty(options_.diffuse_d),
smpl_diff = 1;
smpl_diff = 1;
else
smpl_diff=rank(Pinf1);
smpl_diff=rank(Pinf1);
end
Fstar = zeros(pp,smpl_diff);
@ -112,67 +112,67 @@ t = 0;
icc=0;
newRank = rank(Pinf(:,:,1),crit1);
while newRank & t < smpl
t = t+1;
a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t)-Zi*a(:,t);
Fstar(i,t) = Zi*Pstar(:,:,t)*Zi' +H(i,i);
Finf(i,t) = Zi*Pinf(:,:,t)*Zi';
Kstar(:,i,t) = Pstar(:,:,t)*Zi';
if Finf(i,t) > crit & newRank
icc=icc+1;
Kinf(:,i,t) = Pinf(:,:,t)*Zi';
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Zi/Finf(i,t);
a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*Kinf(:,i,t)' +...
Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
% new terminiation criteria by M. Ratto
P0=Pinf(:,:,t);
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc;
newRank=0;
t = t+1;
a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t)-Zi*a(:,t);
Fstar(i,t) = Zi*Pstar(:,:,t)*Zi' +H(i,i);
Finf(i,t) = Zi*Pinf(:,:,t)*Zi';
Kstar(:,i,t) = Pstar(:,:,t)*Zi';
if Finf(i,t) > crit & newRank
icc=icc+1;
Kinf(:,i,t) = Pinf(:,:,t)*Zi';
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Zi/Finf(i,t);
a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*Kinf(:,i,t)' +...
Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
% new terminiation criteria by M. Ratto
P0=Pinf(:,:,t);
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc;
newRank=0;
end
else
newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1));
if newRank==0,
options_.diffuse_d = icc;
end
end,
% end new terminiation criteria by M. Ratto
elseif Fstar(i,t) > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
end
else
newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1));
if newRank==0,
options_.diffuse_d = icc;
end
end,
% end new terminiation criteria by M. Ratto
elseif Fstar(i,t) > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
end
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*T';
P0=Pinf(:,:,t+1);
if newRank,
newRank = rank(P0,crit1);
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*T';
P0=Pinf(:,:,t+1);
if newRank,
newRank = rank(P0,crit1);
end
end
@ -189,31 +189,31 @@ Pstar1 = Pstar1(:,:,1:d);
Pinf1 = Pinf1(:,:,1:d);
notsteady = 1;
while notsteady & t<smpl
t = t+1;
a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
P1(:,:,t) = P(:,:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t);
Fi(i,t) = Zi*P(:,:,t)*Zi' + H(i,i);
Ki(:,i,t) = P(:,:,t)*Zi';
if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t);
a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);
P(:,:,t) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
t = t+1;
a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
P1(:,:,t) = P(:,:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t);
Fi(i,t) = Zi*P(:,:,t)*Zi' + H(i,i);
Ki(:,i,t) = P(:,:,t)*Zi';
if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t);
a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);
P(:,:,t) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
end
end
end
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
P(:,:,t+1) = T*P(:,:,t)*T' + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
P(:,:,t+1) = T*P(:,:,t)*T' + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end
P_s=tril(P(:,:,t))+tril(P(:,:,t),-1)';
P1_s=tril(P1(:,:,t))+tril(P1(:,:,t),-1)';
@ -221,67 +221,67 @@ Fi_s = Fi(:,t);
Ki_s = Ki(:,:,t);
L_s =Li(:,:,:,t);
if t<smpl
P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t]));
P1 = cat(3,P1(:,:,1:t),repmat(P1_s,[1 1 smpl-t]));
Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t]));
Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t]));
Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t]));
P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t]));
P1 = cat(3,P1(:,:,1:t),repmat(P1_s,[1 1 smpl-t]));
Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t]));
Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t]));
Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t]));
end
while t<smpl
t=t+1;
a(:,t) = a1(:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t);
if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i);
t=t+1;
a(:,t) = a1(:,t);
for i=1:pp
Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t);
if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i);
end
end
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
end
a1(:,t+1) = T*a(:,t);
Pf = P(:,:,t);
for jnk=1:nk,
Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
PK(jnk,:,:,t+jnk) = Pf;
end
end
ri=zeros(mm,1);
t = smpl+1;
while t>d+1
t = t-1;
for i=pp:-1:1
if Fi(i,t) > crit
ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
t = t-1;
for i=pp:-1:1
if Fi(i,t) > crit
ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
end
end
end
r(:,t) = ri;
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
ri = T'*ri;
r(:,t) = ri;
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
ri = T'*ri;
end
if d
r0 = zeros(mm,d);
r0(:,d) = ri;
r1 = zeros(mm,d);
for t = d:-1:2
for i=pp:-1:1
% if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination
if Finf(i,t) > crit
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0
r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end
r0 = zeros(mm,d);
r0(:,d) = ri;
r1 = zeros(mm,d);
for t = d:-1:2
for i=pp:-1:1
% if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination
if Finf(i,t) > crit
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0
r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end
end
alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
r(:,t) = r0(:,t);
etahat(:,t) = QRt*r(:,t);
if t > 1
r0(:,t-1) = T'*r0(:,t);
r1(:,t-1) = T'*r1(:,t);
end
end
alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
r(:,t) = r0(:,t);
etahat(:,t) = QRt*r(:,t);
if t > 1
r0(:,t-1) = T'*r0(:,t);
r1(:,t-1) = T'*r1(:,t);
end
end
end
if nargout > 7

View File

@ -54,7 +54,7 @@ T = cat(1,cat(2,T,zeros(mm,pp)),zeros(pp,mm+pp));
R = cat(1,cat(2,R,zeros(mm,pp)),cat(2,zeros(pp,rr),eye(pp)));
Q = cat(1,cat(2,Q,zeros(rr,pp)),cat(2,zeros(pp,rr),H));
if size(Pinf1,1) % Otherwise Pinf = 0 (no unit root)
Pinf1 = cat(1,cat(2,Pinf1,zeros(mm,pp)),zeros(pp,mm+pp));
Pinf1 = cat(1,cat(2,Pinf1,zeros(mm,pp)),zeros(pp,mm+pp));
end
Pstar1 = cat(1,cat(2,Pstar1,zeros(mm,pp)),cat(2,zeros(pp,mm),H));
spinf = size(Pinf1);
@ -88,8 +88,8 @@ epsilonhat = zeros(pp,smpl);
r = zeros(mm+pp,smpl+1);
Z = zeros(pp,mm+pp);
for i=1:pp;
Z(i,mf(i)) = 1;
Z(i,mm+i) = 1;
Z(i,mf(i)) = 1;
Z(i,mm+i) = 1;
end
%% [1] Kalman filter...
t = 0;
@ -99,28 +99,28 @@ while newRank & t < smpl
a(:,t) = a1(:,t);
Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp
v(i,t) = Y(i,t)-a(mf(i),t)-a(mm+i,t)-trend(i,t);
Fstar(i,t) = Pstar(mf(i),mf(i),t)+Pstar(mm+i,mm+i,t);
Finf(i,t) = Pinf(mf(i),mf(i),t);
Kstar(:,i,t) = Pstar(:,mf(i),t)+Pstar(:,mm+i,t);
if Finf(i,t) > crit
Kinf(:,i,t) = Pinf(:,mf(i),t);
for i=1:pp
v(i,t) = Y(i,t)-a(mf(i),t)-a(mm+i,t)-trend(i,t);
Fstar(i,t) = Pstar(mf(i),mf(i),t)+Pstar(mm+i,mm+i,t);
Finf(i,t) = Pinf(mf(i),mf(i),t);
Kstar(:,i,t) = Pstar(:,mf(i),t)+Pstar(:,mm+i,t);
if Finf(i,t) > crit
Kinf(:,i,t) = Pinf(:,mf(i),t);
Linf(:,:,i,t) = eye(mm+pp) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t);
a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ...
a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*transpose(Kinf(:,i,t)) +...
Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t);
else %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t);
(Kstar(:,i,t)*transpose(Kinf(:,i,t)) +...
Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t);
else %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t);
end
end
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
@ -147,11 +147,11 @@ while notsteady & t<smpl
a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
P1(:,:,t) = P(:,:,t);
for i=1:pp
for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - a(mm+i,t) - trend(i,t);
Fi(i,t) = P(mf(i),mf(i),t)+P(mm+i,mm+i,t);
Fi(i,t) = P(mf(i),mf(i),t)+P(mm+i,mm+i,t);
Ki(:,i,t) = P(:,mf(i),t)+P(:,mm+i,t);
if Fi(i,t) > crit
if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm+pp)-Ki(:,i,t)*Z(i,:)/Fi(i,t);
a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);
P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t);
@ -170,11 +170,11 @@ Fi_s = Fi(:,t);
Ki_s = Ki(:,:,t);
L_s =Li(:,:,:,t);
if t<smpl
t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1]));
Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1]));
Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1]));
t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1]));
Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1]));
Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1]));
end
while t<smpl
t=t+1;
@ -219,16 +219,16 @@ if d
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = transpose(Linf(:,:,i,t))*r0(:,t);
end
end
alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
r(:,t-1) = r0(:,t);
tmp = QRt*r(:,t);
etahat(:,t) = tmp(1:rr);
epsilonhat(:,t) = tmp(rr+(1:pp));
if t > 1
r0(:,t-1) = T'*r0(:,t);
r1(:,t-1) = T'*r1(:,t);
end
end
alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
r(:,t-1) = r0(:,t);
tmp = QRt*r(:,t);
etahat(:,t) = tmp(1:rr);
epsilonhat(:,t) = tmp(rr+(1:pp));
if t > 1
r0(:,t-1) = T'*r0(:,t);
r1(:,t-1) = T'*r1(:,t);
end
end
end
alphahat = alphahat(1:mm,:);

View File

@ -1,130 +1,130 @@
function [LIK, lik] = DiffuseLikelihood1(T,R,Q,Pinf,Pstar,Y,trend,start)
% function [LIK, lik] = DiffuseLikelihood1(T,R,Q,Pinf,Pstar,Y,trend,start)
% Computes the diffuse likelihood without measurement error, in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% trend
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output
global bayestopt_ options_
mf = bayestopt_.mf;
smpl = size(Y,2);
mm = size(T,2);
pp = size(Y,1);
a = zeros(mm,1);
dF = 1;
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
LIK = Inf;
notsteady = 1;
crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl
t = t+1;
v = Y(:,t)-a(mf)-trend(:,t);
Finf = Pinf(mf,mf);
if rcond(Finf) < crit
if ~all(abs(Finf(:)) < crit)
return
else
iFstar = inv(Pstar(mf,mf));
dFstar = det(Pstar(mf,mf));
Kstar = Pstar(:,mf)*iFstar;
lik(t) = log(dFstar) + transpose(v)*iFstar*v;
Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ;
a = T*(a+Kstar*v);
end
else
lik(t) = log(det(Finf));
iFinf = inv(Finf);
Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane)
Fstar = Pstar(mf,mf);
Kstar = (Pstar(:,mf)-Kinf*Fstar)*iFinf; %% premultiplication by the transition matrix T is removed (stephane)
Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ;
Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T);
a = T*(a+Kinf*v);
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
F_singular = 1;
while notsteady & t < smpl
t = t+1;
v = Y(:,t)-a(mf)-trend(:,t);
F = Pstar(mf,mf);
oldPstar = Pstar;
dF = det(F);
if rcond(F) < crit
if ~all(abs(F(:))<crit)
return
else
a = T*a;
Pstar = T*Pstar*transpose(T)+QQ;
end
else
F_singular = 0;
iF = inv(F);
lik(t) = log(dF)+transpose(v)*iF*v;
K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane)
a = T*(a+K*v); %% --> factorization of the transition matrix...
Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane)
end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end
if F_singular == 1
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)-trend(:,t);
a = T*(a+K*v);
lik(t) = transpose(v)*iF*v;
end
lik(t0:smpl) = lik(t0:smpl) + log(dF);
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.
function [LIK, lik] = DiffuseLikelihood1(T,R,Q,Pinf,Pstar,Y,trend,start)
% function [LIK, lik] = DiffuseLikelihood1(T,R,Q,Pinf,Pstar,Y,trend,start)
% Computes the diffuse likelihood without measurement error, in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% trend
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output
global bayestopt_ options_
mf = bayestopt_.mf;
smpl = size(Y,2);
mm = size(T,2);
pp = size(Y,1);
a = zeros(mm,1);
dF = 1;
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
LIK = Inf;
notsteady = 1;
crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl
t = t+1;
v = Y(:,t)-a(mf)-trend(:,t);
Finf = Pinf(mf,mf);
if rcond(Finf) < crit
if ~all(abs(Finf(:)) < crit)
return
else
iFstar = inv(Pstar(mf,mf));
dFstar = det(Pstar(mf,mf));
Kstar = Pstar(:,mf)*iFstar;
lik(t) = log(dFstar) + transpose(v)*iFstar*v;
Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ;
a = T*(a+Kstar*v);
end
else
lik(t) = log(det(Finf));
iFinf = inv(Finf);
Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane)
Fstar = Pstar(mf,mf);
Kstar = (Pstar(:,mf)-Kinf*Fstar)*iFinf; %% premultiplication by the transition matrix T is removed (stephane)
Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ;
Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T);
a = T*(a+Kinf*v);
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
F_singular = 1;
while notsteady & t < smpl
t = t+1;
v = Y(:,t)-a(mf)-trend(:,t);
F = Pstar(mf,mf);
oldPstar = Pstar;
dF = det(F);
if rcond(F) < crit
if ~all(abs(F(:))<crit)
return
else
a = T*a;
Pstar = T*Pstar*transpose(T)+QQ;
end
else
F_singular = 0;
iF = inv(F);
lik(t) = log(dF)+transpose(v)*iF*v;
K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane)
a = T*(a+K*v); %% --> factorization of the transition matrix...
Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane)
end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end
if F_singular == 1
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)-trend(:,t);
a = T*(a+K*v);
lik(t) = transpose(v)*iF*v;
end
lik(t0:smpl) = lik(t0:smpl) + log(dF);
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.

View File

@ -1,130 +1,130 @@
function [LIK, lik] = DiffuseLikelihood1_Z(T,Z,R,Q,Pinf,Pstar,Y,start)
% function [LIK, lik] = DiffuseLikelihood1_Z(T,Z,R,Q,Pinf,Pstar,Y,start)
% Computes the diffuse likelihood without measurement error, in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% Z: pp,mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output
global bayestopt_ options_
smpl = size(Y,2);
mm = size(T,2);
pp = size(Y,1);
a = zeros(mm,1);
dF = 1;
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
LIK = Inf;
notsteady = 1;
crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl
t = t+1;
v = Y(:,t)-Z*a;
Finf = Z*Pinf*Z';
if rcond(Finf) < crit
if ~all(abs(Finf(:)) < crit)
return
else
Fstar = Z*Pstar*Z';
iFstar = inv(Fstar);
dFstar = det(Fstar);
Kstar = Pstar*Z'*iFstar;
lik(t) = log(dFstar) + v'*iFstar*v;
Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ;
a = T*(a+Kstar*v);
end
else
lik(t) = log(det(Finf));
iFinf = inv(Finf);
Kinf = Pinf*Z'*iFinf;
Fstar = Z*Pstar*Z';
Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf;
Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ;
Pinf = T*(Pinf-Pinf*Z'*Kinf')*T';
a = T*(a+Kinf*v);
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
F_singular = 1;
while notsteady & t < smpl
t = t+1;
v = Y(:,t)-Z*a;
F = Z*Pstar*Z';
oldPstar = Pstar;
dF = det(F);
if rcond(F) < crit
if ~all(abs(F(:))<crit)
return
else
a = T*a;
Pstar = T*Pstar*T'+QQ;
end
else
F_singular = 0;
iF = inv(F);
lik(t) = log(dF)+v'*iF*v;
K = Pstar*Z'*iF;
a = T*(a+K*v);
Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ;
end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end
if F_singular == 1
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)-Z*a;
a = T*(a+K*v);
lik(t) = v'*iF*v;
end
lik(t0:smpl) = lik(t0:smpl) + log(dF);
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.
function [LIK, lik] = DiffuseLikelihood1_Z(T,Z,R,Q,Pinf,Pstar,Y,start)
% function [LIK, lik] = DiffuseLikelihood1_Z(T,Z,R,Q,Pinf,Pstar,Y,start)
% Computes the diffuse likelihood without measurement error, in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% Z: pp,mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output
global bayestopt_ options_
smpl = size(Y,2);
mm = size(T,2);
pp = size(Y,1);
a = zeros(mm,1);
dF = 1;
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
LIK = Inf;
notsteady = 1;
crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl
t = t+1;
v = Y(:,t)-Z*a;
Finf = Z*Pinf*Z';
if rcond(Finf) < crit
if ~all(abs(Finf(:)) < crit)
return
else
Fstar = Z*Pstar*Z';
iFstar = inv(Fstar);
dFstar = det(Fstar);
Kstar = Pstar*Z'*iFstar;
lik(t) = log(dFstar) + v'*iFstar*v;
Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ;
a = T*(a+Kstar*v);
end
else
lik(t) = log(det(Finf));
iFinf = inv(Finf);
Kinf = Pinf*Z'*iFinf;
Fstar = Z*Pstar*Z';
Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf;
Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ;
Pinf = T*(Pinf-Pinf*Z'*Kinf')*T';
a = T*(a+Kinf*v);
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
F_singular = 1;
while notsteady & t < smpl
t = t+1;
v = Y(:,t)-Z*a;
F = Z*Pstar*Z';
oldPstar = Pstar;
dF = det(F);
if rcond(F) < crit
if ~all(abs(F(:))<crit)
return
else
a = T*a;
Pstar = T*Pstar*T'+QQ;
end
else
F_singular = 0;
iF = inv(F);
lik(t) = log(dF)+v'*iF*v;
K = Pstar*Z'*iF;
a = T*(a+K*v);
Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ;
end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end
if F_singular == 1
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)-Z*a;
a = T*(a+K*v);
lik(t) = v'*iF*v;
end
lik(t0:smpl) = lik(t0:smpl) + log(dF);
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.

View File

@ -1,195 +1,195 @@
function [LIK, lik] = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,Y,trend,start)%//Z,T,R,Q,Pinf,Pstar,Y)
% function [LIK, lik] = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,Y,trend,start)
% Computes the diffuse likelihood without measurement error, in the case of
% a singular var-cov matrix.
% Univariate treatment of multivariate time series.
%
% INPUTS
% T: mm*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% trend
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output [October 2005]
% changes by M. Ratto [April 2005]
% introduced new options options_.diffuse_d for termination of DKF
% new icc counter for Finf steps in DKF
% new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero.
% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf
% introduced a specific crit1 for the DKF termination
global bayestopt_ options_
mf = bayestopt_.mf;
pp = size(Y,1);
mm = size(T,1);
smpl = size(Y,2);
a = zeros(mm,1);
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
notsteady = 1;
crit = options_.kalman_tol;
crit1 = 1.e-6;
newRank = rank(Pinf,crit1);
icc=0;
while newRank & t < smpl
t = t+1;
for i=1:pp
v(i) = Y(i,t)-a(mf(i))-trend(i,t);
Fstar = Pstar(mf(i),mf(i));
Finf = Pinf(mf(i),mf(i));
Kstar = Pstar(:,mf(i));
if Finf > crit & newRank, %added newRank criterion
icc=icc+1;
Kinf = Pinf(:,mf(i));
a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ...
(Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf;
Pinf = Pinf - Kinf*transpose(Kinf)/Finf;
lik(t) = lik(t) + log(Finf);
% start new termination criterion for DKF
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
%if newRank & any(diag(Pinf(mf,mf))>crit)==0; % M. Ratto this line is BUGGY
if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc;
newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation')
end
else
%newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY
newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1));
if newRank==0,
P0= T*Pinf*transpose(T);
%newRank = any(diag(P0(mf,mf))>crit); % M. Ratto this line is BUGGY
newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005
if newRank==0,
options_.diffuse_d = icc;
end
end
end,
% end new termination and checks for DKF
elseif Fstar > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf,crit) == 0
% the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables
% presample options can be used to ignore initial time points
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
%end
a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*transpose(Kstar)/Fstar;
else
%disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)])
end
end
% if all(abs(Pinf(:))<crit),
% oldRank = 0;
% else
% oldRank = rank(Pinf,crit);
% end
if newRank,
oldRank = rank(Pinf,crit1);
else
oldRank = 0;
end
a = T*a;
Pstar = T*Pstar*transpose(T)+QQ;
Pinf = T*Pinf*transpose(T);
% if all(abs(Pinf(:))<crit),
% newRank = 0;
% else
% newRank = rank(Pinf,crit);
% end
if newRank,
newRank = rank(Pinf,crit1); % new crit1 is used
end
if oldRank ~= newRank
disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!')
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
while notsteady & t < smpl
t = t+1;
oldP = Pstar;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i));
if Fi > crit
Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
Pstar = T*Pstar*transpose(T) + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end
while t < smpl
t = t+1;
Pstar = oldP;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i));
if Fi > crit
Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.
function [LIK, lik] = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,Y,trend,start)%//Z,T,R,Q,Pinf,Pstar,Y)
% function [LIK, lik] = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,Y,trend,start)
% Computes the diffuse likelihood without measurement error, in the case of
% a singular var-cov matrix.
% Univariate treatment of multivariate time series.
%
% INPUTS
% T: mm*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% trend
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output [October 2005]
% changes by M. Ratto [April 2005]
% introduced new options options_.diffuse_d for termination of DKF
% new icc counter for Finf steps in DKF
% new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero.
% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf
% introduced a specific crit1 for the DKF termination
global bayestopt_ options_
mf = bayestopt_.mf;
pp = size(Y,1);
mm = size(T,1);
smpl = size(Y,2);
a = zeros(mm,1);
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
notsteady = 1;
crit = options_.kalman_tol;
crit1 = 1.e-6;
newRank = rank(Pinf,crit1);
icc=0;
while newRank & t < smpl
t = t+1;
for i=1:pp
v(i) = Y(i,t)-a(mf(i))-trend(i,t);
Fstar = Pstar(mf(i),mf(i));
Finf = Pinf(mf(i),mf(i));
Kstar = Pstar(:,mf(i));
if Finf > crit & newRank, %added newRank criterion
icc=icc+1;
Kinf = Pinf(:,mf(i));
a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ...
(Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf;
Pinf = Pinf - Kinf*transpose(Kinf)/Finf;
lik(t) = lik(t) + log(Finf);
% start new termination criterion for DKF
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
%if newRank & any(diag(Pinf(mf,mf))>crit)==0; % M. Ratto this line is BUGGY
if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc;
newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation')
end
else
%newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY
newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1));
if newRank==0,
P0= T*Pinf*transpose(T);
%newRank = any(diag(P0(mf,mf))>crit); % M. Ratto this line is BUGGY
newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005
if newRank==0,
options_.diffuse_d = icc;
end
end
end,
% end new termination and checks for DKF
elseif Fstar > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf,crit) == 0
% the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables
% presample options can be used to ignore initial time points
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
%end
a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*transpose(Kstar)/Fstar;
else
%disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)])
end
end
% if all(abs(Pinf(:))<crit),
% oldRank = 0;
% else
% oldRank = rank(Pinf,crit);
% end
if newRank,
oldRank = rank(Pinf,crit1);
else
oldRank = 0;
end
a = T*a;
Pstar = T*Pstar*transpose(T)+QQ;
Pinf = T*Pinf*transpose(T);
% if all(abs(Pinf(:))<crit),
% newRank = 0;
% else
% newRank = rank(Pinf,crit);
% end
if newRank,
newRank = rank(Pinf,crit1); % new crit1 is used
end
if oldRank ~= newRank
disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!')
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
while notsteady & t < smpl
t = t+1;
oldP = Pstar;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i));
if Fi > crit
Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
Pstar = T*Pstar*transpose(T) + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end
while t < smpl
t = t+1;
Pstar = oldP;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i));
if Fi > crit
Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.

View File

@ -1,180 +1,180 @@
function [LIK, lik] = DiffuseLikelihood3_Z(T,Z,R,Q,Pinf,Pstar,Y,start)
% function [LIK, lik] = DiffuseLikelihood3_Z(T,Z,R,Q,Pinf,Pstar,Y,start)
% Computes the diffuse likelihood without measurement error, in the case of
% a singular var-cov matrix.
% Univariate treatment of multivariate time series.
%
% INPUTS
% T: mm*mm matrix
% Z: pp*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output [October 2005]
% changes by M. Ratto [April 2005]
% introduced new options options_.diffuse_d for termination of DKF
% new icc counter for Finf steps in DKF
% new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero.
% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf
% introduced a specific crit1 for the DKF termination
global bayestopt_ options_
pp = size(Y,1);
mm = size(T,1);
smpl = size(Y,2);
a = zeros(mm,1);
QQ = R*Q*R';
t = 0;
lik = zeros(smpl,1);
notsteady = 1;
crit = options_.kalman_tol;
crit1 = 1.e-6;
newRank = rank(Pinf,crit1);
icc=0;
while newRank & t < smpl
t = t+1;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t)-Zi*a;
Fstar = Zi*Pstar*Zi';
Finf = Zi*Pinf*Zi';
Kstar = Pstar*Zi';
if Finf > crit & newRank
icc=icc+1;
Kinf = Pinf*Zi';
a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ...
(Kstar*Kinf'+Kinf*Kstar')/Finf;
Pinf = Pinf - Kinf*Kinf'/Finf;
lik(t) = lik(t) + log(Finf);
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc;
newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation')
end
else
newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1));
if newRank==0,
P0= T*Pinf*T';
newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005
if newRank==0,
options_.diffuse_d = icc;
end
end
end,
elseif Fstar > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf,crit) == 0
% the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables
% presample options can be used to ignore initial time points
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*(Kstar'/Fstar);
else
%disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)])
end
end
if newRank,
oldRank = rank(Pinf,crit1);
else
oldRank = 0;
end
a = T*a;
Pstar = T*Pstar*T'+QQ;
Pinf = T*Pinf*T';
if newRank,
newRank = rank(Pinf,crit1);
end
if oldRank ~= newRank
disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!')
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
while notsteady & t < smpl
t = t+1;
oldP = Pstar;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi';
if Fi > crit
Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*(Ki'/Fi);
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
Pstar = T*Pstar*T' + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end
while t < smpl
t = t+1;
Pstar = oldP;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi';
if Fi > crit
Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*Ki'/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.
function [LIK, lik] = DiffuseLikelihood3_Z(T,Z,R,Q,Pinf,Pstar,Y,start)
% function [LIK, lik] = DiffuseLikelihood3_Z(T,Z,R,Q,Pinf,Pstar,Y,start)
% Computes the diffuse likelihood without measurement error, in the case of
% a singular var-cov matrix.
% Univariate treatment of multivariate time series.
%
% INPUTS
% T: mm*mm matrix
% Z: pp*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output [October 2005]
% changes by M. Ratto [April 2005]
% introduced new options options_.diffuse_d for termination of DKF
% new icc counter for Finf steps in DKF
% new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero.
% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf
% introduced a specific crit1 for the DKF termination
global bayestopt_ options_
pp = size(Y,1);
mm = size(T,1);
smpl = size(Y,2);
a = zeros(mm,1);
QQ = R*Q*R';
t = 0;
lik = zeros(smpl,1);
notsteady = 1;
crit = options_.kalman_tol;
crit1 = 1.e-6;
newRank = rank(Pinf,crit1);
icc=0;
while newRank & t < smpl
t = t+1;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t)-Zi*a;
Fstar = Zi*Pstar*Zi';
Finf = Zi*Pinf*Zi';
Kstar = Pstar*Zi';
if Finf > crit & newRank
icc=icc+1;
Kinf = Pinf*Zi';
a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ...
(Kstar*Kinf'+Kinf*Kstar')/Finf;
Pinf = Pinf - Kinf*Kinf'/Finf;
lik(t) = lik(t) + log(Finf);
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc;
newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation')
end
else
newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1));
if newRank==0,
P0= T*Pinf*T';
newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005
if newRank==0,
options_.diffuse_d = icc;
end
end
end,
elseif Fstar > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf,crit) == 0
% the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables
% presample options can be used to ignore initial time points
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*(Kstar'/Fstar);
else
%disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)])
end
end
if newRank,
oldRank = rank(Pinf,crit1);
else
oldRank = 0;
end
a = T*a;
Pstar = T*Pstar*T'+QQ;
Pinf = T*Pinf*T';
if newRank,
newRank = rank(Pinf,crit1);
end
if oldRank ~= newRank
disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!')
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
while notsteady & t < smpl
t = t+1;
oldP = Pstar;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi';
if Fi > crit
Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*(Ki'/Fi);
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
Pstar = T*Pstar*T' + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end
while t < smpl
t = t+1;
Pstar = oldP;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi';
if Fi > crit
Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*Ki'/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.

View File

@ -1,131 +1,131 @@
function [LIK, lik] = DiffuseLikelihoodH1(T,R,Q,H,Pinf,Pstar,Y,trend,start)
% function [LIK, lik] = DiffuseLikelihoodH1(T,R,Q,H,Pinf,Pstar,Y,trend,start)
% Computes the diffuse likelihood (H=measurement error) in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% trend
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2005-2008 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/>.
% M. Ratto added lik in output
global bayestopt_ options_
mf = bayestopt_.mf;
smpl = size(Y,2);
mm = size(T,2);
pp = size(Y,1);
a = zeros(mm,1);
dF = 1;
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
LIK = Inf;
notsteady = 1;
crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl
t = t+1;
v = Y(:,t)-a(mf)-trend(:,t);
Finf = Pinf(mf,mf);
if rcond(Finf) < crit
if ~all(abs(Finf(:))<crit)
return
else
iFstar = inv(Pstar(mf,mf)+H);
dFstar = det(Pstar(mf,mf)+H);
Kstar = Pstar(:,mf)*iFstar;
lik(t) = log(dFstar) + transpose(v)*iFstar*v;
Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ;
a = T*(a+Kstar*v);
end
else
lik(t) = log(det(Finf));
iFinf = inv(Finf);
Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane)
Fstar = Pstar(mf,mf)+H;
Kstar = (Pstar(:,mf)-Kinf*Fstar)*iFinf; %% premultiplication by the transition matrix T is removed (stephane)
Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ;
Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T);
a = T*(a+Kinf*v);
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
F_singular = 1;
while notsteady & t < smpl
t = t+1;
v = Y(:,t)-a(mf)-trend(:,t);
F = Pstar(mf,mf)+H;
oldPstar = Pstar;
dF = det(F);
if rcond(F) < crit
if ~all(abs(F(:))<crit)
return
else
a = T*a;
Pstar = T*Pstar*transpose(T)+QQ;
end
else
F_singular = 0;
iF = inv(F);
lik(t) = log(dF)+transpose(v)*iF*v;
K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane)
a = T*(a+K*v); %% --> factorization of the transition matrix...
Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane)
end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end
if F_singular == 1
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)-trend(:,t);
a = T*(a+K*v);
lik(t) = transpose(v)*iF*v;
end
lik(t0:smpl) = lik(t0:smpl) + log(dF);
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.
function [LIK, lik] = DiffuseLikelihoodH1(T,R,Q,H,Pinf,Pstar,Y,trend,start)
% function [LIK, lik] = DiffuseLikelihoodH1(T,R,Q,H,Pinf,Pstar,Y,trend,start)
% Computes the diffuse likelihood (H=measurement error) in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% trend
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2005-2008 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/>.
% M. Ratto added lik in output
global bayestopt_ options_
mf = bayestopt_.mf;
smpl = size(Y,2);
mm = size(T,2);
pp = size(Y,1);
a = zeros(mm,1);
dF = 1;
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
LIK = Inf;
notsteady = 1;
crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl
t = t+1;
v = Y(:,t)-a(mf)-trend(:,t);
Finf = Pinf(mf,mf);
if rcond(Finf) < crit
if ~all(abs(Finf(:))<crit)
return
else
iFstar = inv(Pstar(mf,mf)+H);
dFstar = det(Pstar(mf,mf)+H);
Kstar = Pstar(:,mf)*iFstar;
lik(t) = log(dFstar) + transpose(v)*iFstar*v;
Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ;
a = T*(a+Kstar*v);
end
else
lik(t) = log(det(Finf));
iFinf = inv(Finf);
Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane)
Fstar = Pstar(mf,mf)+H;
Kstar = (Pstar(:,mf)-Kinf*Fstar)*iFinf; %% premultiplication by the transition matrix T is removed (stephane)
Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ;
Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T);
a = T*(a+Kinf*v);
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
F_singular = 1;
while notsteady & t < smpl
t = t+1;
v = Y(:,t)-a(mf)-trend(:,t);
F = Pstar(mf,mf)+H;
oldPstar = Pstar;
dF = det(F);
if rcond(F) < crit
if ~all(abs(F(:))<crit)
return
else
a = T*a;
Pstar = T*Pstar*transpose(T)+QQ;
end
else
F_singular = 0;
iF = inv(F);
lik(t) = log(dF)+transpose(v)*iF*v;
K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane)
a = T*(a+K*v); %% --> factorization of the transition matrix...
Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane)
end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end
if F_singular == 1
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)-trend(:,t);
a = T*(a+K*v);
lik(t) = transpose(v)*iF*v;
end
lik(t0:smpl) = lik(t0:smpl) + log(dF);
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.

View File

@ -1,132 +1,132 @@
function [LIK, lik] = DiffuseLikelihoodH1_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start)
% function [LIK, lik] = DiffuseLikelihoodH1_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start)
% Computes the diffuse likelihood (H=measurement error) in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% Z: pp,mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output
global bayestopt_ options_
smpl = size(Y,2);
mm = size(T,2);
pp = size(Y,1);
a = zeros(mm,1);
dF = 1;
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
LIK = Inf;
notsteady = 1;
crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl
t = t+1;
v = Y(:,t)-Z*a;
Finf = Z*Pinf*Z';
if rcond(Finf) < crit
if ~all(abs(Finf(:)) < crit)
return
else
Fstar = Z*Pstar*Z'+H;
iFstar = inv(Fstar);
dFstar = det(Fstar);
Kstar = Pstar*Z'*iFstar;
lik(t) = log(dFstar) + v'*iFstar*v;
Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ;
a = T*(a+Kstar*v);
end
else
lik(t) = log(det(Finf));
iFinf = inv(Finf);
Kinf = Pinf*Z'*iFinf;
Fstar = Z*Pstar*Z'+H;
Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf;
Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ;
Pinf = T*(Pinf-Pinf*Z'*Kinf')*T';
a = T*(a+Kinf*v);
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
F_singular = 1;
while notsteady & t < smpl
t = t+1;
v = Y(:,t)-Z*a;
F = Z*Pstar*Z'+H;
oldPstar = Pstar;
dF = det(F);
if rcond(F) < crit
if ~all(abs(F(:))<crit)
return
else
a = T*a;
Pstar = T*Pstar*T'+QQ;
end
else
F_singular = 0;
iF = inv(F);
lik(t) = log(dF)+v'*iF*v;
K = Pstar*Z'*iF;
a = T*(a+K*v);
Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ;
end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end
if F_singular == 1
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)-Z*a;
a = T*(a+K*v);
lik(t) = v'*iF*v;
end
lik(t0:smpl) = lik(t0:smpl) + log(dF);
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.
function [LIK, lik] = DiffuseLikelihoodH1_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start)
% function [LIK, lik] = DiffuseLikelihoodH1_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start)
% Computes the diffuse likelihood (H=measurement error) in the case of a non-singular var-cov matrix
%
% INPUTS
% T: mm*mm matrix
% Z: pp,mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output
global bayestopt_ options_
smpl = size(Y,2);
mm = size(T,2);
pp = size(Y,1);
a = zeros(mm,1);
dF = 1;
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
LIK = Inf;
notsteady = 1;
crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl
t = t+1;
v = Y(:,t)-Z*a;
Finf = Z*Pinf*Z';
if rcond(Finf) < crit
if ~all(abs(Finf(:)) < crit)
return
else
Fstar = Z*Pstar*Z'+H;
iFstar = inv(Fstar);
dFstar = det(Fstar);
Kstar = Pstar*Z'*iFstar;
lik(t) = log(dFstar) + v'*iFstar*v;
Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ;
a = T*(a+Kstar*v);
end
else
lik(t) = log(det(Finf));
iFinf = inv(Finf);
Kinf = Pinf*Z'*iFinf;
Fstar = Z*Pstar*Z'+H;
Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf;
Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ;
Pinf = T*(Pinf-Pinf*Z'*Kinf')*T';
a = T*(a+Kinf*v);
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
F_singular = 1;
while notsteady & t < smpl
t = t+1;
v = Y(:,t)-Z*a;
F = Z*Pstar*Z'+H;
oldPstar = Pstar;
dF = det(F);
if rcond(F) < crit
if ~all(abs(F(:))<crit)
return
else
a = T*a;
Pstar = T*Pstar*T'+QQ;
end
else
F_singular = 0;
iF = inv(F);
lik(t) = log(dF)+v'*iF*v;
K = Pstar*Z'*iF;
a = T*(a+K*v);
Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ;
end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end
if F_singular == 1
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)-Z*a;
a = T*(a+K*v);
lik(t) = v'*iF*v;
end
lik(t0:smpl) = lik(t0:smpl) + log(dF);
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.

View File

@ -1,178 +1,178 @@
function [LIK, lik] = DiffuseLikelihoodH3(T,R,Q,H,Pinf,Pstar,Y,trend,start)
% function [LIK, lik] = DiffuseLikelihoodH3(T,R,Q,H,Pinf,Pstar,Y,trend,start)
% Computes the diffuse likelihood with measurement error, in the case of
% a singular var-cov matrix.
% Univariate treatment of multivariate time series.
%
% INPUTS
% T: mm*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% trend
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2005-2008 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/>.
% M. Ratto added lik in output [October 2005]
% changes by M. Ratto
% introduced new global variable id_ for termination of DKF
% introduced a persistent fmax, in order to keep track the max order of
% magnitude of the 'zero' values in Pinf at DKF termination
% new icc counter for Finf steps in DKF
% new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero. this bug is fixed.
global bayestopt_ options_
mf = bayestopt_.mf;
pp = size(Y,1);
mm = size(T,1);
smpl = size(Y,2);
a = zeros(mm,1);
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
notsteady = 1;
crit = options_.kalman_tol;
crit1 = 1.e-6;
newRank = rank(Pinf,crit1);
icc = 0;
while newRank & t < smpl %% Matrix Finf is assumed to be zero
t = t+1;
for i=1:pp
v(i) = Y(i,t)-a(mf(i))-trend(i,t);
Fstar = Pstar(mf(i),mf(i))+H(i,i);
Finf = Pinf(mf(i),mf(i));
Kstar = Pstar(:,mf(i));
if Finf > crit & newRank
icc = icc + 1;
Kinf = Pinf(:,mf(i));
a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ...
(Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf;
Pinf = Pinf - Kinf*transpose(Kinf)/Finf;
lik(t) = lik(t) + log(Finf);
% start new termination criterion for DKF
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
%if newRank & any(diag(Pinf(mf,mf))>crit)==0; % M. Ratto this line is BUGGY
if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc;
newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation')
end
else
%newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY
newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1));
if newRank==0,
P0= T*Pinf*transpose(T);
%newRank = any(diag(P0(mf,mf))>crit); % M. Ratto this line is BUGGY
newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 10 Oct 2005
if newRank==0,
options_.diffuse_d = icc;
end
end
end,
% end new termination and checks for DKF and fmax
elseif Finf > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf) == 0
% the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
%end
a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*transpose(Kstar)/Fstar;
else
% disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fi)])
end
end
if newRank
oldRank = rank(Pinf,crit1);
else
oldRank = 0;
end
a = T*a;
Pstar = T*Pstar*transpose(T)+QQ;
Pinf = T*Pinf*transpose(T);
if newRank
newRank = rank(Pinf,crit1);
end
if oldRank ~= newRank
disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!')
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
while notsteady & t < smpl
t = t+1;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i))+H(i,i);
if Fi > crit
Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
end
end
oldP = Pstar;
a = T*a;
Pstar = T*Pstar*transpose(T) + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end
while t < smpl
t = t+1;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i))+H(i,i);
if Fi > crit
Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
end
end
a = T*a;
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.
function [LIK, lik] = DiffuseLikelihoodH3(T,R,Q,H,Pinf,Pstar,Y,trend,start)
% function [LIK, lik] = DiffuseLikelihoodH3(T,R,Q,H,Pinf,Pstar,Y,trend,start)
% Computes the diffuse likelihood with measurement error, in the case of
% a singular var-cov matrix.
% Univariate treatment of multivariate time series.
%
% INPUTS
% T: mm*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% trend
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2005-2008 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/>.
% M. Ratto added lik in output [October 2005]
% changes by M. Ratto
% introduced new global variable id_ for termination of DKF
% introduced a persistent fmax, in order to keep track the max order of
% magnitude of the 'zero' values in Pinf at DKF termination
% new icc counter for Finf steps in DKF
% new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero. this bug is fixed.
global bayestopt_ options_
mf = bayestopt_.mf;
pp = size(Y,1);
mm = size(T,1);
smpl = size(Y,2);
a = zeros(mm,1);
QQ = R*Q*transpose(R);
t = 0;
lik = zeros(smpl,1);
notsteady = 1;
crit = options_.kalman_tol;
crit1 = 1.e-6;
newRank = rank(Pinf,crit1);
icc = 0;
while newRank & t < smpl %% Matrix Finf is assumed to be zero
t = t+1;
for i=1:pp
v(i) = Y(i,t)-a(mf(i))-trend(i,t);
Fstar = Pstar(mf(i),mf(i))+H(i,i);
Finf = Pinf(mf(i),mf(i));
Kstar = Pstar(:,mf(i));
if Finf > crit & newRank
icc = icc + 1;
Kinf = Pinf(:,mf(i));
a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ...
(Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf;
Pinf = Pinf - Kinf*transpose(Kinf)/Finf;
lik(t) = lik(t) + log(Finf);
% start new termination criterion for DKF
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
%if newRank & any(diag(Pinf(mf,mf))>crit)==0; % M. Ratto this line is BUGGY
if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc;
newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation')
end
else
%newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY
newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1));
if newRank==0,
P0= T*Pinf*transpose(T);
%newRank = any(diag(P0(mf,mf))>crit); % M. Ratto this line is BUGGY
newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 10 Oct 2005
if newRank==0,
options_.diffuse_d = icc;
end
end
end,
% end new termination and checks for DKF and fmax
elseif Finf > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf) == 0
% the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
%end
a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*transpose(Kstar)/Fstar;
else
% disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fi)])
end
end
if newRank
oldRank = rank(Pinf,crit1);
else
oldRank = 0;
end
a = T*a;
Pstar = T*Pstar*transpose(T)+QQ;
Pinf = T*Pinf*transpose(T);
if newRank
newRank = rank(Pinf,crit1);
end
if oldRank ~= newRank
disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!')
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
while notsteady & t < smpl
t = t+1;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i))+H(i,i);
if Fi > crit
Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
end
end
oldP = Pstar;
a = T*a;
Pstar = T*Pstar*transpose(T) + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end
while t < smpl
t = t+1;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i))+H(i,i);
if Fi > crit
Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
end
end
a = T*a;
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.

View File

@ -1,182 +1,182 @@
function [LIK, lik] = DiffuseLikelihoodH3_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start)
% function [LIK, lik] = DiffuseLikelihoodH3_A(T,R,Q,H,Pinf,Pstar,Y,start)
% Computes the diffuse likelihood without measurement error, in the case of
% a singular var-cov matrix.
% Univariate treatment of multivariate time series.
%
% INPUTS
% T: mm*mm matrix
% Z: pp*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output [October 2005]
% changes by M. Ratto [April 2005]
% introduced new options options_.diffuse_d for termination of DKF
% new icc counter for Finf steps in DKF
% new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero.
% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf
% introduced a specific crit1 for the DKF termination
global bayestopt_ options_
pp = size(Y,1);
mm = size(T,1);
smpl = size(Y,2);
a = zeros(mm,1);
QQ = R*Q*R';
t = 0;
lik = zeros(smpl,1);
notsteady = 1;
crit = options_.kalman_tol;
crit1 = 1.e-6;
newRank = rank(Pinf,crit1);
icc=0;
while newRank & t < smpl
t = t+1;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t)-Zi*a;
Fstar = Zi*Pstar*Zi'+H(i,i);
Finf = Zi*Pinf*Zi';
Kstar = Pstar*Zi';
if Finf > crit & newRank
icc=icc+1;
Kinf = Pinf*Zi';
a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ...
(Kstar*Kinf'+Kinf*Kstar')/Finf;
Pinf = Pinf - Kinf*Kinf'/Finf;
lik(t) = lik(t) + log(Finf);
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc;
newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation')
end
else
newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1));
if newRank==0,
P0= T*Pinf*T';
newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005
if newRank==0,
options_.diffuse_d = icc;
end
end
end,
elseif Fstar > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf,crit) == 0
% the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables
% presample options can be used to ignore initial time points
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*Kstar'/Fstar;
else
%disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)])
end
end
if newRank,
oldRank = rank(Pinf,crit1);
else
oldRank = 0;
end
a = T*a;
Pstar = T*Pstar*T'+QQ;
Pinf = T*Pinf*T';
if newRank,
newRank = rank(Pinf,crit1);
end
if oldRank ~= newRank
disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!')
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
while notsteady & t < smpl
t = t+1;
oldP = Pstar;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi'+H(i,i);
if Fi > crit
Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*Ki'/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
Pstar = T*Pstar*T' + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end
while t < smpl
t = t+1;
Pstar = oldP;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi'+H(i,i);
if Fi > crit
Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*Ki'/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.
function [LIK, lik] = DiffuseLikelihoodH3_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start)
% function [LIK, lik] = DiffuseLikelihoodH3_A(T,R,Q,H,Pinf,Pstar,Y,start)
% Computes the diffuse likelihood without measurement error, in the case of
% a singular var-cov matrix.
% Univariate treatment of multivariate time series.
%
% INPUTS
% T: mm*mm matrix
% Z: pp*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
% H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
% start: likelihood evaluation at 'start'
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 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/>.
% M. Ratto added lik in output [October 2005]
% changes by M. Ratto [April 2005]
% introduced new options options_.diffuse_d for termination of DKF
% new icc counter for Finf steps in DKF
% new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero.
% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf
% introduced a specific crit1 for the DKF termination
global bayestopt_ options_
pp = size(Y,1);
mm = size(T,1);
smpl = size(Y,2);
a = zeros(mm,1);
QQ = R*Q*R';
t = 0;
lik = zeros(smpl,1);
notsteady = 1;
crit = options_.kalman_tol;
crit1 = 1.e-6;
newRank = rank(Pinf,crit1);
icc=0;
while newRank & t < smpl
t = t+1;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t)-Zi*a;
Fstar = Zi*Pstar*Zi'+H(i,i);
Finf = Zi*Pinf*Zi';
Kstar = Pstar*Zi';
if Finf > crit & newRank
icc=icc+1;
Kinf = Pinf*Zi';
a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ...
(Kstar*Kinf'+Kinf*Kstar')/Finf;
Pinf = Pinf - Kinf*Kinf'/Finf;
lik(t) = lik(t) + log(Finf);
if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc;
newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation')
end
else
newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1));
if newRank==0,
P0= T*Pinf*T';
newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005
if newRank==0,
options_.diffuse_d = icc;
end
end
end,
elseif Fstar > crit
%% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf,crit) == 0
% the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables
% presample options can be used to ignore initial time points
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*Kstar'/Fstar;
else
%disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)])
end
end
if newRank,
oldRank = rank(Pinf,crit1);
else
oldRank = 0;
end
a = T*a;
Pstar = T*Pstar*T'+QQ;
Pinf = T*Pinf*T';
if newRank,
newRank = rank(Pinf,crit1);
end
if oldRank ~= newRank
disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!')
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
while notsteady & t < smpl
t = t+1;
oldP = Pstar;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi'+H(i,i);
if Fi > crit
Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*Ki'/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
Pstar = T*Pstar*T' + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end
while t < smpl
t = t+1;
Pstar = oldP;
for i=1:pp
Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi'+H(i,i);
if Fi > crit
Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*Ki'/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end
end
a = T*a;
end
% adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood.

View File

@ -20,7 +20,7 @@ function [LIK lik] = DiffuseLikelihoodH3corr(T,R,Q,H,Pinf,Pstar,Y,trend,start)
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ options_
mf = bayestopt_.mf;
pp = size(Y,1);
mm = size(T,1);
@ -30,7 +30,7 @@ T = cat(1,cat(2,T,zeros(mm,pp)),zeros(pp,mm+pp));
R = cat(1,cat(2,R,zeros(mm,pp)),cat(2,zeros(pp,rr),eye(pp)));
Q = cat(1,cat(2,Q,zeros(rr,pp)),cat(2,zeros(pp,rr),H));
if size(Pinf,1) % Otherwise Pinf = 0 (no unit root)
Pinf = cat(1,cat(2,Pinf,zeros(mm,pp)),zeros(pp,mm+pp));
Pinf = cat(1,cat(2,Pinf,zeros(mm,pp)),zeros(pp,mm+pp));
end
Pstar = cat(1,cat(2,Pstar,zeros(mm,pp)),cat(2,zeros(pp,mm),H));
a = zeros(mm+pp,1);
@ -42,71 +42,71 @@ crit = options_.kalman_tol;
newRank = rank(Pinf,crit);
while rank(Pinf,crit) & t < smpl %% Matrix Finf is assumed to be zero
t = t+1;
for i=1:pp
v(i) = Y(i,t)-a(mf(i))-a(mm+i)-trend(i,t);
Fstar = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i);
Finf = Pinf(mf(i),mf(i));
Kstar = Pstar(:,mf(i))+Pstar(:,mm+i);
if Finf > crit
Kinf = Pinf(:,mf(i));
a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ...
(Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf;
Pinf = Pinf - Kinf*transpose(Kinf)/Finf;
lik(t) = lik(t) + log(Finf);
else %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
if rank(Pinf) == 0
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
end
a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*transpose(Kstar)/Fstar;
end
oldRank = rank(Pinf,crit);
a = T*a;
Pstar = T*Pstar*transpose(T)+QQ;
Pinf = T*Pinf*transpose(T);
newRank = rank(Pinf,crit);
if oldRank ~= newRank
disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!')
end
end
t = t+1;
for i=1:pp
v(i) = Y(i,t)-a(mf(i))-a(mm+i)-trend(i,t);
Fstar = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i);
Finf = Pinf(mf(i),mf(i));
Kstar = Pstar(:,mf(i))+Pstar(:,mm+i);
if Finf > crit
Kinf = Pinf(:,mf(i));
a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ...
(Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf;
Pinf = Pinf - Kinf*transpose(Kinf)/Finf;
lik(t) = lik(t) + log(Finf);
else %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
%% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
%% rank(Pinf)=0. [stéphane,11-03-2004].
if rank(Pinf) == 0
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
end
a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*transpose(Kstar)/Fstar;
end
oldRank = rank(Pinf,crit);
a = T*a;
Pstar = T*Pstar*transpose(T)+QQ;
Pinf = T*Pinf*transpose(T);
newRank = rank(Pinf,crit);
if oldRank ~= newRank
disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!')
end
end
end
if t == smpl
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']);
end
while notsteady & t < smpl
t = t+1;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t) -a(mm+i);
Fi = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i);
if Fi > crit
Ki = Pstar(:,mf(i))+Pstar(:,mm+i);
t = t+1;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t) -a(mm+i);
Fi = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i);
if Fi > crit
Ki = Pstar(:,mf(i))+Pstar(:,mm+i);
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
end
end
end
end
oldP = Pstar;
a = T*a;
Pstar = T*Pstar*transpose(T) + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end
while t < smpl
t = t+1;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t) - a(mm+i);
Fi = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i);
if Fi > crit
Ki = Pstar(:,mf(i))+Pstar(:,mm+i);
t = t+1;
for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t) - a(mm+i);
Fi = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i);
if Fi > crit
Ki = Pstar(:,mf(i))+Pstar(:,mm+i);
a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
end
end
end
end
a = T*a;
end
% adding log-likelihhod constants

View File

@ -38,290 +38,290 @@ function [fval,cost_flag,ys,trend_coeff,info] = DsgeLikelihood(xparam1,gend,data
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_
fval = [];
ys = [];
trend_coeff = [];
cost_flag = 1;
nobs = size(options_.varobs,1);
%------------------------------------------------------------------------------
% 1. Get the structural parameters & define penalties
%------------------------------------------------------------------------------
if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
k = find(xparam1 < bayestopt_.lb);
fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
cost_flag = 0;
info = 41;
return;
end
if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
k = find(xparam1 > bayestopt_.ub);
fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
cost_flag = 0;
info = 42;
return;
end
Q = M_.Sigma_e;
H = M_.H;
for i=1:estim_params_.nvx
global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_
fval = [];
ys = [];
trend_coeff = [];
cost_flag = 1;
nobs = size(options_.varobs,1);
%------------------------------------------------------------------------------
% 1. Get the structural parameters & define penalties
%------------------------------------------------------------------------------
if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
k = find(xparam1 < bayestopt_.lb);
fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
cost_flag = 0;
info = 41;
return;
end
if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
k = find(xparam1 > bayestopt_.ub);
fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
cost_flag = 0;
info = 42;
return;
end
Q = M_.Sigma_e;
H = M_.H;
for i=1:estim_params_.nvx
k =estim_params_.var_exo(i,1);
Q(k,k) = xparam1(i)*xparam1(i);
end
offset = estim_params_.nvx;
if estim_params_.nvn
end
offset = estim_params_.nvx;
if estim_params_.nvn
for i=1:estim_params_.nvn
k = estim_params_.var_endo(i,1);
H(k,k) = xparam1(i+offset)*xparam1(i+offset);
k = estim_params_.var_endo(i,1);
H(k,k) = xparam1(i+offset)*xparam1(i+offset);
end
offset = offset+estim_params_.nvn;
end
if estim_params_.ncx
end
if estim_params_.ncx
for i=1:estim_params_.ncx
k1 =estim_params_.corrx(i,1);
k2 =estim_params_.corrx(i,2);
Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
Q(k2,k1) = Q(k1,k2);
k1 =estim_params_.corrx(i,1);
k2 =estim_params_.corrx(i,2);
Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
Q(k2,k1) = Q(k1,k2);
end
[CholQ,testQ] = chol(Q);
if testQ %% The variance-covariance matrix of the structural innovations is not definite positive.
%% We have to compute the eigenvalues of this matrix in order to build the penalty.
a = diag(eig(Q));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 43;
return
end
%% We have to compute the eigenvalues of this matrix in order to build the penalty.
a = diag(eig(Q));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 43;
return
end
end
offset = offset+estim_params_.ncx;
end
if estim_params_.ncn
end
if estim_params_.ncn
for i=1:estim_params_.ncn
k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
H(k2,k1) = H(k1,k2);
k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
H(k2,k1) = H(k1,k2);
end
[CholH,testH] = chol(H);
if testH
a = diag(eig(H));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 44;
return
end
a = diag(eig(H));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 44;
return
end
end
offset = offset+estim_params_.ncn;
end
if estim_params_.np > 0
M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
end
M_.Sigma_e = Q;
M_.H = H;
%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------
[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
bayestopt_.restrict_columns,...
bayestopt_.restrict_aux);
if info(1) == 1 || info(1) == 2 || info(1) == 5
fval = bayestopt_.penalty+1;
cost_flag = 0;
return
elseif info(1) == 3 || info(1) == 4 || info(1)==6 ||info(1) == 19 || info(1) == 20 || info(1) == 21
fval = bayestopt_.penalty+info(2);
cost_flag = 0;
return
end
bayestopt_.mf = bayestopt_.mf1;
if options_.noconstant
constant = zeros(nobs,1);
else
if options_.loglinear
constant = log(SteadyState(bayestopt_.mfys));
else
constant = SteadyState(bayestopt_.mfys);
end
end
if bayestopt_.with_trend
end
if estim_params_.np > 0
M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
end
M_.Sigma_e = Q;
M_.H = H;
%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------
[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
bayestopt_.restrict_columns,...
bayestopt_.restrict_aux);
if info(1) == 1 || info(1) == 2 || info(1) == 5
fval = bayestopt_.penalty+1;
cost_flag = 0;
return
elseif info(1) == 3 || info(1) == 4 || info(1)==6 ||info(1) == 19 || info(1) == 20 || info(1) == 21
fval = bayestopt_.penalty+info(2);
cost_flag = 0;
return
end
bayestopt_.mf = bayestopt_.mf1;
if options_.noconstant
constant = zeros(nobs,1);
else
if options_.loglinear
constant = log(SteadyState(bayestopt_.mfys));
else
constant = SteadyState(bayestopt_.mfys);
end
end
if bayestopt_.with_trend
trend_coeff = zeros(nobs,1);
t = options_.trend_coeffs;
for i=1:length(t)
if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i});
end
if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i});
end
end
trend = repmat(constant,1,gend)+trend_coeff*[1:gend];
else
else
trend = repmat(constant,1,gend);
end
start = options_.presample+1;
np = size(T,1);
mf = bayestopt_.mf;
no_missing_data_flag = (number_of_observations==gend*nobs);
%------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter
%------------------------------------------------------------------------------
kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = options_.Harvey_scale_factor*eye(np);
Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4
kalman_algo = 3;
end
[QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k);
nk1 = nk+1;
Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2
if ST(i,i-1) == 0
if i == np
c = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else
if i == np
c = zeros(np-nk,1);
c1 = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+...
ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1);
c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+...
ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+...
ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);...
-ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)];
z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1];
Pstar(nk1:i,i) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1;
end
end
if i == nk+2
c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1);
Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end
Z = QT(mf,:);
R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
if length(k) > 0
k1 = EE(:,k);
dd =ones(nk,1);
dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd);
end
end
if kalman_algo == 2
end
kalman_tol = options_.kalman_tol;
riccati_tol = options_.riccati_tol;
mf = bayestopt_.mf1;
Y = data-trend;
%------------------------------------------------------------------------------
% 4. Likelihood evaluation
%------------------------------------------------------------------------------
if (kalman_algo==1)% Multivariate Kalman Filter
if no_missing_data_flag
LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol);
else
LIK = ...
missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ...
data_index,number_of_observations,no_more_missing_observations);
end
if isinf(LIK)
kalman_algo = 2;
end
end
if (kalman_algo==2)% Univariate Kalman Filter
no_correlation_flag = 1;
if length(H)==1 & H == 0
H = zeros(nobs,1);
else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H);
else
no_correlation_flag = 0;
end
end
if no_correlation_flag
LIK = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
else
LIK = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
end
end
if (kalman_algo==3)% Multivariate Diffuse Kalman Filter
if no_missing_data_flag
LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol, ...
riccati_tol);
else
LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf, ...
Pstar,Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,...
no_more_missing_observations);
end
if isinf(LIK)
kalman_algo = 4;
end
end
if (kalman_algo==4)% Univariate Diffuse Kalman Filter
no_correlation_flag = 1;
if length(H)==1 & H == 0
H = zeros(nobs,1);
else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H);
else
no_correlation_flag = 0;
end
end
if no_correlation_flag
LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y, ...
start,Z,kalman_tol,riccati_tol,data_index,...
number_of_observations,no_more_missing_observations);
else
LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar, ...
Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,...
no_more_missing_observations);
end
end
if imag(LIK) ~= 0
likelihood = bayestopt_.penalty;
else
likelihood = LIK;
end
% ------------------------------------------------------------------------------
% Adds prior if necessary
% ------------------------------------------------------------------------------
lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
fval = (likelihood-lnprior);
options_.kalman_algo = kalman_algo;
end
start = options_.presample+1;
np = size(T,1);
mf = bayestopt_.mf;
no_missing_data_flag = (number_of_observations==gend*nobs);
%------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter
%------------------------------------------------------------------------------
kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = options_.Harvey_scale_factor*eye(np);
Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4
kalman_algo = 3;
end
[QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k);
nk1 = nk+1;
Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2
if ST(i,i-1) == 0
if i == np
c = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else
if i == np
c = zeros(np-nk,1);
c1 = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+...
ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1);
c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+...
ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+...
ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);...
-ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)];
z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1];
Pstar(nk1:i,i) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1;
end
end
if i == nk+2
c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1);
Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end
Z = QT(mf,:);
R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
if length(k) > 0
k1 = EE(:,k);
dd =ones(nk,1);
dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd);
end
end
if kalman_algo == 2
end
kalman_tol = options_.kalman_tol;
riccati_tol = options_.riccati_tol;
mf = bayestopt_.mf1;
Y = data-trend;
%------------------------------------------------------------------------------
% 4. Likelihood evaluation
%------------------------------------------------------------------------------
if (kalman_algo==1)% Multivariate Kalman Filter
if no_missing_data_flag
LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol);
else
LIK = ...
missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ...
data_index,number_of_observations,no_more_missing_observations);
end
if isinf(LIK)
kalman_algo = 2;
end
end
if (kalman_algo==2)% Univariate Kalman Filter
no_correlation_flag = 1;
if length(H)==1 & H == 0
H = zeros(nobs,1);
else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H);
else
no_correlation_flag = 0;
end
end
if no_correlation_flag
LIK = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
else
LIK = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
end
end
if (kalman_algo==3)% Multivariate Diffuse Kalman Filter
if no_missing_data_flag
LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol, ...
riccati_tol);
else
LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf, ...
Pstar,Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,...
no_more_missing_observations);
end
if isinf(LIK)
kalman_algo = 4;
end
end
if (kalman_algo==4)% Univariate Diffuse Kalman Filter
no_correlation_flag = 1;
if length(H)==1 & H == 0
H = zeros(nobs,1);
else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H);
else
no_correlation_flag = 0;
end
end
if no_correlation_flag
LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y, ...
start,Z,kalman_tol,riccati_tol,data_index,...
number_of_observations,no_more_missing_observations);
else
LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar, ...
Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,...
no_more_missing_observations);
end
end
if imag(LIK) ~= 0
likelihood = bayestopt_.penalty;
else
likelihood = LIK;
end
% ------------------------------------------------------------------------------
% Adds prior if necessary
% ------------------------------------------------------------------------------
lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
fval = (likelihood-lnprior);
options_.kalman_algo = kalman_algo;

View File

@ -38,284 +38,283 @@ function [fval,llik,cost_flag,ys,trend_coeff,info] = DsgeLikelihood_hh(xparam1,g
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_
fval = [];
ys = [];
trend_coeff = [];
llik = NaN;
cost_flag = 1;
nobs = size(options_.varobs,1);
%------------------------------------------------------------------------------
% 1. Get the structural parameters & define penalties
%------------------------------------------------------------------------------
if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
k = find(xparam1 < bayestopt_.lb);
fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
cost_flag = 0;
info = 41;
return;
end
if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
k = find(xparam1 > bayestopt_.ub);
fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
cost_flag = 0;
info = 42;
return;
end
Q = M_.Sigma_e;
H = M_.H;
for i=1:estim_params_.nvx
global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_
fval = [];
ys = [];
trend_coeff = [];
llik = NaN;
cost_flag = 1;
nobs = size(options_.varobs,1);
%------------------------------------------------------------------------------
% 1. Get the structural parameters & define penalties
%------------------------------------------------------------------------------
if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
k = find(xparam1 < bayestopt_.lb);
fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
cost_flag = 0;
info = 41;
return;
end
if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
k = find(xparam1 > bayestopt_.ub);
fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
cost_flag = 0;
info = 42;
return;
end
Q = M_.Sigma_e;
H = M_.H;
for i=1:estim_params_.nvx
k =estim_params_.var_exo(i,1);
Q(k,k) = xparam1(i)*xparam1(i);
end
offset = estim_params_.nvx;
if estim_params_.nvn
end
offset = estim_params_.nvx;
if estim_params_.nvn
for i=1:estim_params_.nvn
k = estim_params_.var_endo(i,1);
H(k,k) = xparam1(i+offset)*xparam1(i+offset);
k = estim_params_.var_endo(i,1);
H(k,k) = xparam1(i+offset)*xparam1(i+offset);
end
offset = offset+estim_params_.nvn;
end
if estim_params_.ncx
end
if estim_params_.ncx
for i=1:estim_params_.ncx
k1 =estim_params_.corrx(i,1);
k2 =estim_params_.corrx(i,2);
Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
Q(k2,k1) = Q(k1,k2);
k1 =estim_params_.corrx(i,1);
k2 =estim_params_.corrx(i,2);
Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
Q(k2,k1) = Q(k1,k2);
end
[CholQ,testQ] = chol(Q);
if testQ %% The variance-covariance matrix of the structural innovations is not definite positive.
%% We have to compute the eigenvalues of this matrix in order to build the penalty.
a = diag(eig(Q));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 43;
return
end
%% We have to compute the eigenvalues of this matrix in order to build the penalty.
a = diag(eig(Q));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 43;
return
end
end
offset = offset+estim_params_.ncx;
end
if estim_params_.ncn
end
if estim_params_.ncn
for i=1:estim_params_.ncn
k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
H(k2,k1) = H(k1,k2);
k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
H(k2,k1) = H(k1,k2);
end
[CholH,testH] = chol(H);
if testH
a = diag(eig(H));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 44;
return
end
a = diag(eig(H));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 44;
return
end
end
offset = offset+estim_params_.ncn;
end
if estim_params_.np > 0
M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
end
M_.Sigma_e = Q;
M_.H = H;
%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------
[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
bayestopt_.restrict_columns,...
bayestopt_.restrict_aux);
if info(1) == 1 | info(1) == 2 | info(1) == 5
end
if estim_params_.np > 0
M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
end
M_.Sigma_e = Q;
M_.H = H;
%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------
[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
bayestopt_.restrict_columns,...
bayestopt_.restrict_aux);
if info(1) == 1 | info(1) == 2 | info(1) == 5
fval = bayestopt_.penalty+1;
cost_flag = 0;
return
elseif info(1) == 3 | info(1) == 4 | info(1) == 20
elseif info(1) == 3 | info(1) == 4 | info(1) == 20
fval = bayestopt_.penalty+info(2);%^2; % penalty power raised in DR1.m and resol already. GP July'08
cost_flag = 0;
return
end
bayestopt_.mf = bayestopt_.mf1;
if ~options_.noconstant
end
bayestopt_.mf = bayestopt_.mf1;
if ~options_.noconstant
if options_.loglinear == 1
constant = log(SteadyState(bayestopt_.mfys));
constant = log(SteadyState(bayestopt_.mfys));
else
constant = SteadyState(bayestopt_.mfys);
constant = SteadyState(bayestopt_.mfys);
end
else
else
constant = zeros(nobs,1);
end
if bayestopt_.with_trend == 1
end
if bayestopt_.with_trend == 1
trend_coeff = zeros(nobs,1);
t = options_.trend_coeffs;
for i=1:length(t)
if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i});
end
if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i});
end
end
trend = repmat(constant,1,gend)+trend_coeff*[1:gend];
else
else
trend = repmat(constant,1,gend);
end
start = options_.presample+1;
np = size(T,1);
mf = bayestopt_.mf;
no_missing_data_flag = (number_of_observations==gend*nobs);
%------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter
%------------------------------------------------------------------------------
kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = options_.Harvey_scale_factor*eye(np);
Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4
kalman_algo = 3;
end
[QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k);
nk1 = nk+1;
Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2
if ST(i,i-1) == 0
if i == np
c = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else
if i == np
c = zeros(np-nk,1);
c1 = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+...
ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1);
c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+...
ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+...
ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);...
-ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)];
z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1];
Pstar(nk1:i,i) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1;
end
end
if i == nk+2
c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1);
Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end
Z = QT(mf,:);
R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
if length(k) > 0
k1 = EE(:,k);
dd =ones(nk,1);
dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd);
end
end
if kalman_algo == 2
no_correlation_flag = 1;
if length(H)==1
H = zeros(nobs,1);
else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H);
else
no_correlation_flag = 1;
end
end
end
kalman_tol = options_.kalman_tol;
riccati_tol = options_.riccati_tol;
mf = bayestopt_.mf1;
Y = data-trend;
%------------------------------------------------------------------------------
% 4. Likelihood evaluation
%------------------------------------------------------------------------------
if (kalman_algo==1)% Multivariate Kalman Filter
if no_missing_data_flag
[LIK, lik] = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol);
else
[LIK, lik] = ...
missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ...
data_index,number_of_observations,no_more_missing_observations);
end
if isinf(LIK)
kalman_algo = 2;
end
end
if (kalman_algo==2)% Univariate Kalman Filter
if no_correlation_flag
[LIK, lik] = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
else
[LIK, lik] = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
end
end
if (kalman_algo==3)% Multivariate Diffuse Kalman Filter
if no_missing_data_flag
data1 = data - trend;
if any(any(H ~= 0))
[LIK, lik] = DiffuseLikelihoodH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,start);
else
[LIK, lik] = DiffuseLikelihood1_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start);
end
if isinf(LIK)
kalman_algo = 4;
end
else
error(['The diffuse filter is not yet implemented for models with missing observations'])
end
end
if (kalman_algo==4)% Univariate Diffuse Kalman Filter
data1 = data - trend;
if any(any(H ~= 0))
if ~estim_params_.ncn
[LIK, lik] = DiffuseLikelihoodH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start);
else
[LIK, lik] = DiffuseLikelihoodH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start);
end
else
[LIK, lik] = DiffuseLikelihood3_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start);
end
end
if imag(LIK) ~= 0
likelihood = bayestopt_.penalty;
else
likelihood = LIK;
end
% ------------------------------------------------------------------------------
% Adds prior if necessary
% ------------------------------------------------------------------------------
lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
fval = (likelihood-lnprior);
options_.kalman_algo = kalman_algo;
llik=[-lnprior; lik(start:end)];
end
start = options_.presample+1;
np = size(T,1);
mf = bayestopt_.mf;
no_missing_data_flag = (number_of_observations==gend*nobs);
%------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter
%------------------------------------------------------------------------------
kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = options_.Harvey_scale_factor*eye(np);
Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4
kalman_algo = 3;
end
[QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k);
nk1 = nk+1;
Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2
if ST(i,i-1) == 0
if i == np
c = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else
if i == np
c = zeros(np-nk,1);
c1 = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+...
ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1);
c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+...
ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+...
ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);...
-ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)];
z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1];
Pstar(nk1:i,i) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1;
end
end
if i == nk+2
c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1);
Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end
Z = QT(mf,:);
R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
if length(k) > 0
k1 = EE(:,k);
dd =ones(nk,1);
dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd);
end
end
if kalman_algo == 2
no_correlation_flag = 1;
if length(H)==1
H = zeros(nobs,1);
else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H);
else
no_correlation_flag = 1;
end
end
end
kalman_tol = options_.kalman_tol;
riccati_tol = options_.riccati_tol;
mf = bayestopt_.mf1;
Y = data-trend;
%------------------------------------------------------------------------------
% 4. Likelihood evaluation
%------------------------------------------------------------------------------
if (kalman_algo==1)% Multivariate Kalman Filter
if no_missing_data_flag
[LIK, lik] = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol);
else
[LIK, lik] = ...
missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ...
data_index,number_of_observations,no_more_missing_observations);
end
if isinf(LIK)
kalman_algo = 2;
end
end
if (kalman_algo==2)% Univariate Kalman Filter
if no_correlation_flag
[LIK, lik] = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
else
[LIK, lik] = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
end
end
if (kalman_algo==3)% Multivariate Diffuse Kalman Filter
if no_missing_data_flag
data1 = data - trend;
if any(any(H ~= 0))
[LIK, lik] = DiffuseLikelihoodH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,start);
else
[LIK, lik] = DiffuseLikelihood1_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start);
end
if isinf(LIK)
kalman_algo = 4;
end
else
error(['The diffuse filter is not yet implemented for models with missing observations'])
end
end
if (kalman_algo==4)% Univariate Diffuse Kalman Filter
data1 = data - trend;
if any(any(H ~= 0))
if ~estim_params_.ncn
[LIK, lik] = DiffuseLikelihoodH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start);
else
[LIK, lik] = DiffuseLikelihoodH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start);
end
else
[LIK, lik] = DiffuseLikelihood3_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start);
end
end
if imag(LIK) ~= 0
likelihood = bayestopt_.penalty;
else
likelihood = LIK;
end
% ------------------------------------------------------------------------------
% Adds prior if necessary
% ------------------------------------------------------------------------------
lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
fval = (likelihood-lnprior);
options_.kalman_algo = kalman_algo;
llik=[-lnprior; lik(start:end)];

View File

@ -47,281 +47,281 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,d,
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ M_ oo_ estim_params_ options_
global bayestopt_ M_ oo_ estim_params_ options_
alphahat = [];
etahat = [];
epsilonhat = [];
ahat = [];
SteadyState = [];
trend_coeff = [];
aK = [];
T = [];
R = [];
P = [];
PK = [];
d = [];
decomp = [];
nobs = size(options_.varobs,1);
smpl = size(Y,2);
alphahat = [];
etahat = [];
epsilonhat = [];
ahat = [];
SteadyState = [];
trend_coeff = [];
aK = [];
T = [];
R = [];
P = [];
PK = [];
d = [];
decomp = [];
nobs = size(options_.varobs,1);
smpl = size(Y,2);
set_all_parameters(xparam1);
set_all_parameters(xparam1);
%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------
[T,R,SteadyState] = dynare_resolve;
bayestopt_.mf = bayestopt_.mf2;
if options_.noconstant
constant = zeros(nobs,1);
else
if options_.loglinear == 1
constant = log(SteadyState(bayestopt_.mfys));
else
constant = SteadyState(bayestopt_.mfys);
end
end
trend_coeff = zeros(nobs,1);
if bayestopt_.with_trend == 1
%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------
[T,R,SteadyState] = dynare_resolve;
bayestopt_.mf = bayestopt_.mf2;
if options_.noconstant
constant = zeros(nobs,1);
else
if options_.loglinear == 1
constant = log(SteadyState(bayestopt_.mfys));
else
constant = SteadyState(bayestopt_.mfys);
end
end
trend_coeff = zeros(nobs,1);
if bayestopt_.with_trend == 1
trend_coeff = zeros(nobs,1);
t = options_.trend_coeffs;
for i=1:length(t)
if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i});
end
if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i});
end
end
trend = constant*ones(1,gend)+trend_coeff*(1:gend);
else
else
trend = constant*ones(1,gend);
end
start = options_.presample+1;
np = size(T,1);
mf = bayestopt_.mf;
% ------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter
% ------------------------------------------------------------------------------
%
% C'est ici qu'il faut déterminer Pinf et Pstar. Si le modèle est stationnaire,
% alors il suffit de poser Pstar comme la solution de l'éuation de Lyapounov et
% Pinf=[].
%
Q = M_.Sigma_e;
H = M_.H;
kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = lyapunov_symm(T,R*Q*transpose(R),options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = options_.Harvey_scale_factor*eye(np);
Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4
kalman_algo = 3;
end
[QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k);
nk1 = nk+1;
Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2
if ST(i,i-1) == 0
if i == np
c = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else
if i == np
c = zeros(np-nk,1);
c1 = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+...
ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1);
c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+...
ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+...
ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);...
-ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)];
z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1];
Pstar(nk1:i,i) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1;
end
end
if i == nk+2
c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1);
Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end
Z = QT(mf,:);
R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
if length(k) > 0
k1 = EE(:,k);
dd =ones(nk,1);
dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd);
end
end
% -----------------------------------------------------------------------------
% 4. Kalman smoother
% -----------------------------------------------------------------------------
if any(any(H ~= 0)) % should be replaced by a flag
if kalman_algo == 1
[alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH1(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
if all(alphahat(:)==0)
kalman_algo = 2;
if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
else
[alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ...
nobs,np,smpl,mf);
end
end
elseif options_.kalman_algo == 2
if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
else
[alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ...
nobs,np,smpl,mf);
end
elseif kalman_algo == 3 | kalman_algo == 4
data1 = Y - trend;
if kalman_algo == 3
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl);
if all(alphahat(:)==0)
kalman_algo = 4;
if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl);
else
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ...
nobs,np,smpl);
end
end
else
if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ...
nobs,np,smpl);
else
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ...
nobs,np,smpl);
end
end
alphahat = QT*alphahat;
ahat = QT*ahat;
nk = options_.nk;
for jnk=1:nk
aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:));
for i=1:size(PK,4)
PK(jnk,:,:,i) = QT*squeeze(PK(jnk,:,:,i))*QT';
end
for i=1:size(decomp,4)
decomp(jnk,:,:,i) = QT*squeeze(decomp(jnk,:,:,i));
end
end
for i=1:size(P,4)
P(:,:,i) = QT*squeeze(P(:,:,i))*QT';
end
end
else
if kalman_algo == 1
if missing_value
[alphahat,etahat,ahat,aK] = missing_DiffuseKalmanSmoother1(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index);
else
[alphahat,etahat,ahat,aK] = DiffuseKalmanSmoother1(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
end
if all(alphahat(:)==0)
kalman_algo = 2;
end
end
if kalman_algo == 2
if missing_value
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index);
else
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
end
end
if kalman_algo == 3
data1 = Y - trend;
if missing_value
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother1_Z(ST, ...
Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index);
else
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother1_Z(ST, ...
Z,R1,Q,Pinf,Pstar, ...
data1,nobs,np,smpl);
end
if all(alphahat(:)==0)
options_.kalman_algo = 4;
end
end
if kalman_algo == 4
data1 = Y - trend;
if missing_value
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3_Z(ST, ...
Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index);
else
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3_Z(ST, ...
Z,R1,Q,Pinf,Pstar, ...
data1,nobs,np,smpl);
end
end
if kalman_algo == 3 | kalman_algo == 4
alphahat = QT*alphahat;
ahat = QT*ahat;
nk = options_.nk;
end
start = options_.presample+1;
np = size(T,1);
mf = bayestopt_.mf;
% ------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter
% ------------------------------------------------------------------------------
%
% C'est ici qu'il faut déterminer Pinf et Pstar. Si le modèle est stationnaire,
% alors il suffit de poser Pstar comme la solution de l'éuation de Lyapounov et
% Pinf=[].
%
Q = M_.Sigma_e;
H = M_.H;
kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = lyapunov_symm(T,R*Q*transpose(R),options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = options_.Harvey_scale_factor*eye(np);
Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4
kalman_algo = 3;
end
[QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k);
nk1 = nk+1;
Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2
if ST(i,i-1) == 0
if i == np
c = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else
if i == np
c = zeros(np-nk,1);
c1 = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+...
ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1);
c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+...
ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+...
ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);...
-ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)];
z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1];
Pstar(nk1:i,i) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1;
end
end
if i == nk+2
c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1);
Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end
Z = QT(mf,:);
R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
if length(k) > 0
k1 = EE(:,k);
dd =ones(nk,1);
dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd);
end
end
% -----------------------------------------------------------------------------
% 4. Kalman smoother
% -----------------------------------------------------------------------------
if any(any(H ~= 0)) % should be replaced by a flag
if kalman_algo == 1
[alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH1(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
if all(alphahat(:)==0)
kalman_algo = 2;
if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
else
[alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ...
nobs,np,smpl,mf);
end
end
elseif options_.kalman_algo == 2
if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
else
[alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ...
nobs,np,smpl,mf);
end
elseif kalman_algo == 3 | kalman_algo == 4
data1 = Y - trend;
if kalman_algo == 3
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl);
if all(alphahat(:)==0)
kalman_algo = 4;
if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl);
else
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ...
nobs,np,smpl);
end
end
else
if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ...
nobs,np,smpl);
else
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ...
nobs,np,smpl);
end
end
alphahat = QT*alphahat;
ahat = QT*ahat;
nk = options_.nk;
for jnk=1:nk
aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:));
for i=1:size(PK,4)
PK(jnk,:,:,i) = QT*squeeze(PK(jnk,:,:,i))*QT';
end
for i=1:size(decomp,4)
decomp(jnk,:,:,i) = QT*squeeze(decomp(jnk,:,:,i));
end
end
for i=1:size(P,4)
P(:,:,i) = QT*squeeze(P(:,:,i))*QT';
end
end
else
if kalman_algo == 1
if missing_value
[alphahat,etahat,ahat,aK] = missing_DiffuseKalmanSmoother1(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index);
else
[alphahat,etahat,ahat,aK] = DiffuseKalmanSmoother1(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
end
if all(alphahat(:)==0)
kalman_algo = 2;
end
end
if kalman_algo == 2
if missing_value
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index);
else
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
end
end
if kalman_algo == 3
data1 = Y - trend;
if missing_value
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother1_Z(ST, ...
Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index);
else
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother1_Z(ST, ...
Z,R1,Q,Pinf,Pstar, ...
data1,nobs,np,smpl);
end
if all(alphahat(:)==0)
options_.kalman_algo = 4;
end
end
if kalman_algo == 4
data1 = Y - trend;
if missing_value
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3_Z(ST, ...
Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index);
else
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3_Z(ST, ...
Z,R1,Q,Pinf,Pstar, ...
data1,nobs,np,smpl);
end
end
if kalman_algo == 3 | kalman_algo == 4
alphahat = QT*alphahat;
ahat = QT*ahat;
nk = options_.nk;
% $$$ if M_.exo_nbr<2 % Fix the crash of Dynare when the estimated model has only one structural shock (problem with
% $$$ % the squeeze function, that does not affect 2D arrays).
% $$$ size_decomp = 0;
% $$$ else
% $$$ size_decomp = size(decomp,4);
% $$$ end
for jnk=1:nk
aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:));
for i=1:size(PK,4)
PK(jnk,:,:,i) = QT*dynare_squeeze(PK(jnk,:,:,i))*QT';
end
for i=1:size(decomp,4)
decomp(jnk,:,:,i) = QT*dynare_squeeze(decomp(jnk,:,:,i));
end
end
for i=1:size(P,4)
P(:,:,i) = QT*dynare_squeeze(P(:,:,i))*QT';
end
end
end
for jnk=1:nk
aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:));
for i=1:size(PK,4)
PK(jnk,:,:,i) = QT*dynare_squeeze(PK(jnk,:,:,i))*QT';
end
for i=1:size(decomp,4)
decomp(jnk,:,:,i) = QT*dynare_squeeze(decomp(jnk,:,:,i));
end
end
for i=1:size(P,4)
P(:,:,i) = QT*dynare_squeeze(P(:,:,i))*QT';
end
end
end

View File

@ -146,15 +146,15 @@ TheoreticalAutoCovarianceOfTheObservedVariables = ...
zeros(NumberOfObservedVariables,NumberOfObservedVariables,NumberOfLags+1);
TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) = tmp0(mf,mf)+constant'*constant;
for lag = 1:NumberOfLags
tmp0 = T*tmp0;
TheoreticalAutoCovarianceOfTheObservedVariables(:,:,lag+1) = tmp0(mf,mf) ...
+ constant'*constant;
tmp0 = T*tmp0;
TheoreticalAutoCovarianceOfTheObservedVariables(:,:,lag+1) = tmp0(mf,mf) ...
+ constant'*constant;
end
% Build the theoretical "covariance" between Y and X
GYX = zeros(NumberOfObservedVariables,NumberOfParameters);
for i=1:NumberOfLags
GYX(:,(i-1)*NumberOfObservedVariables+1:i*NumberOfObservedVariables) = ...
TheoreticalAutoCovarianceOfTheObservedVariables(:,:,i+1);
GYX(:,(i-1)*NumberOfObservedVariables+1:i*NumberOfObservedVariables) = ...
TheoreticalAutoCovarianceOfTheObservedVariables(:,:,i+1);
end
if ~options_.noconstant
GYX(:,end) = constant';
@ -181,41 +181,41 @@ assignin('base','GXX',GXX);
assignin('base','GYX',GYX);
if ~isinf(dsge_prior_weight)
tmp0 = dsge_prior_weight*gend*TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) + mYY ;
tmp1 = dsge_prior_weight*gend*GYX + mYX;
tmp2 = inv(dsge_prior_weight*gend*GXX+mXX);
SIGMAu = tmp0 - tmp1*tmp2*tmp1'; clear('tmp0');
if ~ispd(SIGMAu)
v = diag(SIGMAu);
k = find(v<0);
fval = bayestopt_.penalty + sum(v(k).^2);
info = 52;
cost_flag = 0;
return;
end
SIGMAu = SIGMAu / (gend*(1+dsge_prior_weight));
PHI = tmp2*tmp1'; clear('tmp1');
prodlng1 = sum(gammaln(.5*((1+dsge_prior_weight)*gend- ...
NumberOfObservedVariables*NumberOfLags ...
+1-(1:NumberOfObservedVariables)')));
prodlng2 = sum(gammaln(.5*(dsge_prior_weight*gend- ...
NumberOfObservedVariables*NumberOfLags ...
+1-(1:NumberOfObservedVariables)')));
lik = .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX+mXX)) ...
+ .5*((dsge_prior_weight+1)*gend-NumberOfParameters)*log(det((dsge_prior_weight+1)*gend*SIGMAu)) ...
- .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX)) ...
- .5*(dsge_prior_weight*gend-NumberOfParameters)*log(det(dsge_prior_weight*gend*(GYY-GYX*inv(GXX)*GYX'))) ...
+ .5*NumberOfObservedVariables*gend*log(2*pi) ...
- .5*log(2)*NumberOfObservedVariables*((dsge_prior_weight+1)*gend-NumberOfParameters) ...
+ .5*log(2)*NumberOfObservedVariables*(dsge_prior_weight*gend-NumberOfParameters) ...
- prodlng1 + prodlng2;
tmp0 = dsge_prior_weight*gend*TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) + mYY ;
tmp1 = dsge_prior_weight*gend*GYX + mYX;
tmp2 = inv(dsge_prior_weight*gend*GXX+mXX);
SIGMAu = tmp0 - tmp1*tmp2*tmp1'; clear('tmp0');
if ~ispd(SIGMAu)
v = diag(SIGMAu);
k = find(v<0);
fval = bayestopt_.penalty + sum(v(k).^2);
info = 52;
cost_flag = 0;
return;
end
SIGMAu = SIGMAu / (gend*(1+dsge_prior_weight));
PHI = tmp2*tmp1'; clear('tmp1');
prodlng1 = sum(gammaln(.5*((1+dsge_prior_weight)*gend- ...
NumberOfObservedVariables*NumberOfLags ...
+1-(1:NumberOfObservedVariables)')));
prodlng2 = sum(gammaln(.5*(dsge_prior_weight*gend- ...
NumberOfObservedVariables*NumberOfLags ...
+1-(1:NumberOfObservedVariables)')));
lik = .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX+mXX)) ...
+ .5*((dsge_prior_weight+1)*gend-NumberOfParameters)*log(det((dsge_prior_weight+1)*gend*SIGMAu)) ...
- .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX)) ...
- .5*(dsge_prior_weight*gend-NumberOfParameters)*log(det(dsge_prior_weight*gend*(GYY-GYX*inv(GXX)*GYX'))) ...
+ .5*NumberOfObservedVariables*gend*log(2*pi) ...
- .5*log(2)*NumberOfObservedVariables*((dsge_prior_weight+1)*gend-NumberOfParameters) ...
+ .5*log(2)*NumberOfObservedVariables*(dsge_prior_weight*gend-NumberOfParameters) ...
- prodlng1 + prodlng2;
else
iGXX = inv(GXX);
SIGMAu = GYY - GYX*iGXX*transpose(GYX);
PHI = iGXX*transpose(GYX);
lik = gend * ( log(det(SIGMAu)) + NumberOfObservedVariables*log(2*pi) + ...
trace(inv(SIGMAu)*(mYY - transpose(mYX*PHI) - mYX*PHI + transpose(PHI)*mXX*PHI)/gend));
lik = .5*lik;% Minus likelihood
iGXX = inv(GXX);
SIGMAu = GYY - GYX*iGXX*transpose(GYX);
PHI = iGXX*transpose(GYX);
lik = gend * ( log(det(SIGMAu)) + NumberOfObservedVariables*log(2*pi) + ...
trace(inv(SIGMAu)*(mYY - transpose(mYX*PHI) - mYX*PHI + transpose(PHI)*mXX*PHI)/gend));
lik = .5*lik;% Minus likelihood
end
lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);

View File

@ -1,91 +1,91 @@
function Draws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumberOfMhFile, NumberOfDraws, blck)
% function Draws = GetAllPosteriorDraws(column,FirstMhFile,FirstLine,TotalNumberOfMhFile,NumberOfDraws)
% Gets all posterior draws
%
% INPUTS
% column: column
% FirstMhFile: first mh file
% FirstLine: first line
% TotalNumberOfMhFile: total number of mh file
% NumberOfDraws: number of draws
% OUTPUTS
% Draws: draws from posterior distribution
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2005-2008 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/>.
global M_ options_
nblck = options_.mh_nblck;
iline = FirstLine;
linee = 1;
DirectoryName = CheckPath('metropolis');
if nblck>1 && nargin<6
Draws = zeros(NumberOfDraws*nblck,1);
iline0=iline;
if column>0
for blck = 1:nblck
iline=iline0;
for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2')
NumberOfLines = size(x2(iline:end,:),1);
Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column);
linee = linee+NumberOfLines;
iline = 1;
end
end
else
for blck = 1:nblck
iline=iline0;
for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2')
NumberOfLines = size(logpo2(iline:end),1);
Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end);
linee = linee+NumberOfLines;
iline = 1;
end
end
end
else
if nblck==1
blck=1;
end
if column>0
for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2')
NumberOfLines = size(x2(iline:end,:),1);
Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column);
linee = linee+NumberOfLines;
iline = 1;
end
else
for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2')
NumberOfLines = size(logpo2(iline:end,:),1);
Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end);
linee = linee+NumberOfLines;
iline = 1;
end
end
function Draws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumberOfMhFile, NumberOfDraws, blck)
% function Draws = GetAllPosteriorDraws(column,FirstMhFile,FirstLine,TotalNumberOfMhFile,NumberOfDraws)
% Gets all posterior draws
%
% INPUTS
% column: column
% FirstMhFile: first mh file
% FirstLine: first line
% TotalNumberOfMhFile: total number of mh file
% NumberOfDraws: number of draws
% OUTPUTS
% Draws: draws from posterior distribution
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2005-2008 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/>.
global M_ options_
nblck = options_.mh_nblck;
iline = FirstLine;
linee = 1;
DirectoryName = CheckPath('metropolis');
if nblck>1 && nargin<6
Draws = zeros(NumberOfDraws*nblck,1);
iline0=iline;
if column>0
for blck = 1:nblck
iline=iline0;
for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2')
NumberOfLines = size(x2(iline:end,:),1);
Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column);
linee = linee+NumberOfLines;
iline = 1;
end
end
else
for blck = 1:nblck
iline=iline0;
for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2')
NumberOfLines = size(logpo2(iline:end),1);
Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end);
linee = linee+NumberOfLines;
iline = 1;
end
end
end
else
if nblck==1
blck=1;
end
if column>0
for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2')
NumberOfLines = size(x2(iline:end,:),1);
Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column);
linee = linee+NumberOfLines;
iline = 1;
end
else
for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2')
NumberOfLines = size(logpo2(iline:end,:),1);
Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end);
linee = linee+NumberOfLines;
iline = 1;
end
end
end

View File

@ -1,39 +1,39 @@
function [xparams, logpost] = GetOneDraw(type)
% function [xparams, logpost] = GetOneDraw(type)
% draws one row from metropolis
%
% INPUTS
% type: posterior
% prior
%
% OUTPUTS
% xparams: vector of estimated parameters (drawn from posterior distribution)
% logpost: log of the posterior density relative to this row
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2005-2008 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/>.
switch type
case 'posterior'
[xparams, logpost] = metropolis_draw(0);
case 'prior'
xparams = prior_draw(0);
end
function [xparams, logpost] = GetOneDraw(type)
% function [xparams, logpost] = GetOneDraw(type)
% draws one row from metropolis
%
% INPUTS
% type: posterior
% prior
%
% OUTPUTS
% xparams: vector of estimated parameters (drawn from posterior distribution)
% logpost: log of the posterior density relative to this row
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2005-2008 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/>.
switch type
case 'posterior'
[xparams, logpost] = metropolis_draw(0);
case 'prior'
xparams = prior_draw(0);
end

View File

@ -307,57 +307,57 @@ end
%% subfunctions:
%
function fid = TeXBegin(directory,fname,fnum,title)
TeXfile = [directory '/' fname '_Posterior_Mean_' int2str(fnum) '.TeX'];
fidTeX = fopen(TeXfile,'w');
fprintf(fidTeX,'%% TeX-table generated by Dynare.\n');
fprintf(fidTeX,['%% RESULTS FROM METROPOLIS HASTINGS (' title ')\n']);
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{table}\n');
fprintf(fidTeX,'\\centering\n');
fprintf(fidTeX,'\\begin{tabular}{l|lcccccc} \n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,[' & Prior distribution & Prior mean & Prior ' ...
's.d. & Posterior mean & Posterior s.d. & HPD inf & HPD sup\\\\ \n']);
fprintf(fidTeX,'\\hline \\\\ \n');
fid = fidTeX;
TeXfile = [directory '/' fname '_Posterior_Mean_' int2str(fnum) '.TeX'];
fidTeX = fopen(TeXfile,'w');
fprintf(fidTeX,'%% TeX-table generated by Dynare.\n');
fprintf(fidTeX,['%% RESULTS FROM METROPOLIS HASTINGS (' title ')\n']);
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{table}\n');
fprintf(fidTeX,'\\centering\n');
fprintf(fidTeX,'\\begin{tabular}{l|lcccccc} \n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,[' & Prior distribution & Prior mean & Prior ' ...
's.d. & Posterior mean & Posterior s.d. & HPD inf & HPD sup\\\\ \n']);
fprintf(fidTeX,'\\hline \\\\ \n');
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'],...
name,...
shape,...
priormean,...
priorstd,...
postmean,...
poststd,...
hpd(1),...
hpd(2));
fprintf(fid,['$%s$ & %s & %7.3f & %6.4f & %7.3f& %6.4f & %7.4f & %7.4f \\\\ \n'],...
name,...
shape,...
priormean,...
priorstd,...
postmean,...
poststd,...
hpd(1),...
hpd(2));
function TeXEnd(fid,fnum,title)
fprintf(fid,'\\hline\\hline \n');
fprintf(fid,'\\end{tabular}\n ');
fprintf(fid,['\\caption{Results from Metropolis-Hastings (' title ')}\n ']);
fprintf(fid,['\\label{Table:MHPosterior:' int2str(fnum) '}\n']);
fprintf(fid,'\\end{table}\n');
fprintf(fid,'%% End of TeX file.\n');
fclose(fid);
fprintf(fid,'\\hline\\hline \n');
fprintf(fid,'\\end{tabular}\n ');
fprintf(fid,['\\caption{Results from Metropolis-Hastings (' title ')}\n ']);
fprintf(fid,['\\label{Table:MHPosterior:' int2str(fnum) '}\n']);
fprintf(fid,'\\end{table}\n');
fprintf(fid,'%% End of TeX file.\n');
fclose(fid);
function oo = Filloo(oo,name,type,postmean,hpdinterval,postmedian,postvar,postdecile,density)
eval(['oo.posterior_mean.' type '.' name ' = postmean;']);
eval(['oo.posterior_hpdinf.' type '.' name ' = hpdinterval(1);']);
eval(['oo.posterior_hpdsup.' type '.' name ' = hpdinterval(2);']);
eval(['oo.posterior_median.' type '.' name ' = postmedian;']);
eval(['oo.posterior_variance.' type '.' name ' = postvar;']);
eval(['oo.posterior_deciles.' type '.' name ' = postdecile;']);
eval(['oo.posterior_density.' type '.' name ' = density;']);
eval(['oo.posterior_mean.' type '.' name ' = postmean;']);
eval(['oo.posterior_hpdinf.' type '.' name ' = hpdinterval(1);']);
eval(['oo.posterior_hpdsup.' type '.' name ' = hpdinterval(2);']);
eval(['oo.posterior_median.' type '.' name ' = postmedian;']);
eval(['oo.posterior_variance.' type '.' name ' = postvar;']);
eval(['oo.posterior_deciles.' type '.' name ' = postdecile;']);
eval(['oo.posterior_density.' type '.' name ' = density;']);
function [post_mean,hpd_interval,post_var] = Extractoo(oo,name,type)
hpd_interval = zeros(2,1);
eval(['post_mean = oo.posterior_mean.' type '.' name ';']);
eval(['hpd_interval(1) = oo.posterior_hpdinf.' type '.' name ';']);
eval(['hpd_interval(2) = oo.posterior_hpdsup.' type '.' name ';']);
eval(['post_var = oo.posterior_variance.' type '.' name ';']);
hpd_interval = zeros(2,1);
eval(['post_mean = oo.posterior_mean.' type '.' name ';']);
eval(['hpd_interval(1) = oo.posterior_hpdinf.' type '.' name ';']);
eval(['hpd_interval(2) = oo.posterior_hpdsup.' type '.' name ';']);
eval(['post_var = oo.posterior_variance.' type '.' name ';']);

View File

@ -1,169 +1,169 @@
function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info)
% Copyright (C) 2005 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/>.
global M_ options_
FigHandle = figure('Name',FigureProperties.Name);
NAMES = cell(NumberOfPlots,1);
if options_.TeX
TeXNAMES = cell(NumberOfPlots,1);
end
if NumberOfPlots == 9
nr = 3;
nc = 3;
elseif NumberOfPlots == 8
nr = 3;
nc = 3;
elseif NumberOfPlots == 7
nr = 3;
nc = 3;
elseif NumberOfPlots == 6
nr = 2;
nc = 3;
elseif NumberOfPlots == 5
nr = 3;
nc = 2;
elseif NumberOfPlots == 4
nr = 2;
nc = 2;
elseif NumberOfPlots == 3
nr = 2;
nc = 2;
elseif NumberOfPlots == 2
nr = 1;
nc = 2;
elseif NumberOfPlots == 1
nr = 1;
nc = 1;
end
for plt = 1:NumberOfPlots
eval(['NumberOfCurves = Info.Box' int2str(plt) '.Number;'])
NumberOfObservations = zeros(2,1);
x = cell(NumberOfCurves,1);
y = cell(NumberOfCurves,1);
PltType = cell(NumberofCurves,1);
top = NaN(NumberOfCurves,1);
bottom = NaN(NumberOfCurves,1);
binf = NaN(NumberOfCurves,1);
bsup = NaN(NumberOfCurves,1);
for curve = 1:NumberOfCurves
eval(['x{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.xdata;'])
eval(['y{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.ydata;'])
eval(['name = Info.Box' int2str(plt) '.Curve' int2str(curve) '.variablename;'])
eval(['PltType{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.type']);
if length(x{curve})-length(y{curve})
disp('MakeFigure :: The number of observations in x doesn''t match with ')
disp(['the number of observation in y for ' name ])
return
end
if Info.PlotProperties.CutTop
top(curve) = max(y{curve});
else Info.PlotProperties.CutBottom
bottom(curve) = min(y{curve});
end
binf(curve) = min(x{curve});
bsup(curve) = max(x{curve});
end
ymax = max(top);
ymin = min(bottom);
xmin = min(binf);
xmax = max(bsup);
if isnan(ymin(plt))
ymin = 0;
end
eval(['NAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.name;'])
if options_.TeX
eval(['TeXNAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.texname;'])
end
subplot(nr,nc,plt)
hold on
for curve = 1:NumberOfCurves
hh = plot(x{curve},y{curve});
if strcmpi(PltType{curve},'PriorDensity')
set(hh,'Color',[0.7 0.7 0.7],'LineStyle','-','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'DensityEstimate')
set(hh,'Color','k','LineStyle','-','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'ModeEstimate')
set(hh,'Color','g','LineStyle','--','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'SmoothVariable')
set(hh,'Color','k','LineStyle','-','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'Deciles')
set(hh,'Color','g','LineStyle','-','LineWidth',1)
%
%
elseif strcmpi(PltType{curve},'Forecasts')
set(hh,'Color','','LineStyle','-','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'ForecastsHPD')
set(hh,'Color','k','LineStyle','-','LineWidth',1)
%
%
elseif strcmpi(PltType{curve},'ForecastsDeciles')
set(hh,'Color','g','LineStyle','-','LineWidth',1)
%
%
elseif strcmpi(PltType{curve},'DiagnosticWithin')
set(hh,'Color','b','LineStyle','-','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'DiagnosticPooled')
set(hh,'Color','r','LineStyle','-','LineWidth',2)
%
%
end
end
axis([xmin xmax ymin ymax])
title(NAMES{plt})
drawnow
hold off
end
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']);
end
end
if Info.SaveFormat.Pdf && ~exist('OCTAVE_VERSION')
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]);
end
end
if Info.SaveFormat.Fig && ~exist('OCTAVE_VERSION')
if isempty(Info.SaveFormat.Name)
saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.fig']);
else
saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.fig']);
end
function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info)
% Copyright (C) 2005 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/>.
global M_ options_
FigHandle = figure('Name',FigureProperties.Name);
NAMES = cell(NumberOfPlots,1);
if options_.TeX
TeXNAMES = cell(NumberOfPlots,1);
end
if NumberOfPlots == 9
nr = 3;
nc = 3;
elseif NumberOfPlots == 8
nr = 3;
nc = 3;
elseif NumberOfPlots == 7
nr = 3;
nc = 3;
elseif NumberOfPlots == 6
nr = 2;
nc = 3;
elseif NumberOfPlots == 5
nr = 3;
nc = 2;
elseif NumberOfPlots == 4
nr = 2;
nc = 2;
elseif NumberOfPlots == 3
nr = 2;
nc = 2;
elseif NumberOfPlots == 2
nr = 1;
nc = 2;
elseif NumberOfPlots == 1
nr = 1;
nc = 1;
end
for plt = 1:NumberOfPlots
eval(['NumberOfCurves = Info.Box' int2str(plt) '.Number;'])
NumberOfObservations = zeros(2,1);
x = cell(NumberOfCurves,1);
y = cell(NumberOfCurves,1);
PltType = cell(NumberofCurves,1);
top = NaN(NumberOfCurves,1);
bottom = NaN(NumberOfCurves,1);
binf = NaN(NumberOfCurves,1);
bsup = NaN(NumberOfCurves,1);
for curve = 1:NumberOfCurves
eval(['x{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.xdata;'])
eval(['y{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.ydata;'])
eval(['name = Info.Box' int2str(plt) '.Curve' int2str(curve) '.variablename;'])
eval(['PltType{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.type']);
if length(x{curve})-length(y{curve})
disp('MakeFigure :: The number of observations in x doesn''t match with ')
disp(['the number of observation in y for ' name ])
return
end
if Info.PlotProperties.CutTop
top(curve) = max(y{curve});
else Info.PlotProperties.CutBottom
bottom(curve) = min(y{curve});
end
binf(curve) = min(x{curve});
bsup(curve) = max(x{curve});
end
ymax = max(top);
ymin = min(bottom);
xmin = min(binf);
xmax = max(bsup);
if isnan(ymin(plt))
ymin = 0;
end
eval(['NAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.name;'])
if options_.TeX
eval(['TeXNAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.texname;'])
end
subplot(nr,nc,plt)
hold on
for curve = 1:NumberOfCurves
hh = plot(x{curve},y{curve});
if strcmpi(PltType{curve},'PriorDensity')
set(hh,'Color',[0.7 0.7 0.7],'LineStyle','-','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'DensityEstimate')
set(hh,'Color','k','LineStyle','-','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'ModeEstimate')
set(hh,'Color','g','LineStyle','--','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'SmoothVariable')
set(hh,'Color','k','LineStyle','-','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'Deciles')
set(hh,'Color','g','LineStyle','-','LineWidth',1)
%
%
elseif strcmpi(PltType{curve},'Forecasts')
set(hh,'Color','','LineStyle','-','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'ForecastsHPD')
set(hh,'Color','k','LineStyle','-','LineWidth',1)
%
%
elseif strcmpi(PltType{curve},'ForecastsDeciles')
set(hh,'Color','g','LineStyle','-','LineWidth',1)
%
%
elseif strcmpi(PltType{curve},'DiagnosticWithin')
set(hh,'Color','b','LineStyle','-','LineWidth',2)
%
%
elseif strcmpi(PltType{curve},'DiagnosticPooled')
set(hh,'Color','r','LineStyle','-','LineWidth',2)
%
%
end
end
axis([xmin xmax ymin ymax])
title(NAMES{plt})
drawnow
hold off
end
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']);
end
end
if Info.SaveFormat.Pdf && ~exist('OCTAVE_VERSION')
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]);
end
end
if Info.SaveFormat.Fig && ~exist('OCTAVE_VERSION')
if isempty(Info.SaveFormat.Name)
saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.fig']);
else
saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.fig']);
end
end

View File

@ -1,94 +1,94 @@
function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab)
% Core functionality for MCMC Diagnostics, which can be parallelized
% Copyright (C) 2005-2009 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/>.
if nargin<4,
whoiam=0;
end
struct2local(myinputs);
if ~exist('MhDirectoryName'),
MhDirectoryName = CheckPath('metropolis');
end
ALPHA = 0.2; % increase too much with the number of simulations.
tmp = zeros(NumberOfDraws*nblck,3);
UDIAG = zeros(NumberOfLines,6,npar-fpar+1);
if whoiam
waitbarString = ['Please wait... McMCDiagnostics (' int2str(fpar) 'of' int2str(npar) ')...'];
if Parallel(ThisMatlab).Local,
waitbarTitle=['Local '];
else
waitbarTitle=[Parallel(ThisMatlab).PcName];
end
fMessageStatus(0,whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo);
end
for j=fpar:npar,
fprintf(' Parameter %d... ',j);
for b = 1:nblck
startline = 0;
for n = 1:NumberOfMcFilesPerBlock
%load([MhDirectoryName '/' mcfiles(n,1,b).name],'x2');
load([MhDirectoryName '/' M_.fname '_mh',int2str(n),'_blck' int2str(b) ...
'.mat'],'x2');
nx2 = size(x2,1);
tmp((b-1)*NumberOfDraws+startline+(1:nx2),1) = x2(:,j);
% clear x2;
startline = startline + nx2;
end
% $$$ %load([MhDirectoryName '/' mcfiles(NumberOfMcFilesPerBlock,1,b).name],'x2');
% $$$ load([MhDirectoryName '/' M_.fname '_mh',int2str(NumberOfMcFilesPerBlock),'_blck' int2str(b) '.mat'],'x2');
% $$$ tmp((b-1)*NumberOfDraws+startline+1:(b-1)*NumberOfDraws+MAX_nruns*(LastFileNumber-1)+LastLineNumber,1) = x2(:,j);
% $$$ clear x2;
% $$$ startline = startline + LastLineNumber;
end
tmp(:,2) = kron(transpose(1:nblck),ones(NumberOfDraws,1));
tmp(:,3) = kron(ones(nblck,1),time');
tmp = sortrows(tmp,1);
ligne = 0;
for iter = Origin:StepSize:NumberOfDraws
ligne = ligne+1;
linea = ceil(0.5*iter);
n = iter-linea+1;
cinf = round(n*ALPHA/2);
csup = round(n*(1-ALPHA/2));
CINF = round(nblck*n*ALPHA/2);
CSUP = round(nblck*n*(1-ALPHA/2));
temp = tmp(find((tmp(:,3)>=linea) & (tmp(:,3)<=iter)),1:2);
UDIAG(ligne,1,j-fpar+1) = temp(CSUP,1)-temp(CINF,1);
moyenne = mean(temp(:,1));%% Pooled mean.
UDIAG(ligne,3,j-fpar+1) = sum((temp(:,1)-moyenne).^2)/(nblck*n-1);
UDIAG(ligne,5,j-fpar+1) = sum(abs(temp(:,1)-moyenne).^3)/(nblck*n-1);
for i=1:nblck
pmet = temp(find(temp(:,2)==i));
UDIAG(ligne,2,j-fpar+1) = UDIAG(ligne,2,j-fpar+1) + pmet(csup,1)-pmet(cinf,1);
moyenne = mean(pmet,1); %% Within mean.
UDIAG(ligne,4,j-fpar+1) = UDIAG(ligne,4,j-fpar+1) + sum((pmet(:,1)-moyenne).^2)/(n-1);
UDIAG(ligne,6,j-fpar+1) = UDIAG(ligne,6,j-fpar+1) + sum(abs(pmet(:,1)-moyenne).^3)/(n-1);
end
end
fprintf('Done! \n');
if whoiam,
waitbarString = [ 'Parameter ' int2str(j) '/' int2str(npar) ' done.'];
fMessageStatus((j-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo)
end
end
function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab)
% Core functionality for MCMC Diagnostics, which can be parallelized
% Copyright (C) 2005-2009 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/>.
if nargin<4,
whoiam=0;
end
struct2local(myinputs);
if ~exist('MhDirectoryName'),
MhDirectoryName = CheckPath('metropolis');
end
ALPHA = 0.2; % increase too much with the number of simulations.
tmp = zeros(NumberOfDraws*nblck,3);
UDIAG = zeros(NumberOfLines,6,npar-fpar+1);
if whoiam
waitbarString = ['Please wait... McMCDiagnostics (' int2str(fpar) 'of' int2str(npar) ')...'];
if Parallel(ThisMatlab).Local,
waitbarTitle=['Local '];
else
waitbarTitle=[Parallel(ThisMatlab).PcName];
end
fMessageStatus(0,whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo);
end
for j=fpar:npar,
fprintf(' Parameter %d... ',j);
for b = 1:nblck
startline = 0;
for n = 1:NumberOfMcFilesPerBlock
%load([MhDirectoryName '/' mcfiles(n,1,b).name],'x2');
load([MhDirectoryName '/' M_.fname '_mh',int2str(n),'_blck' int2str(b) ...
'.mat'],'x2');
nx2 = size(x2,1);
tmp((b-1)*NumberOfDraws+startline+(1:nx2),1) = x2(:,j);
% clear x2;
startline = startline + nx2;
end
% $$$ %load([MhDirectoryName '/' mcfiles(NumberOfMcFilesPerBlock,1,b).name],'x2');
% $$$ load([MhDirectoryName '/' M_.fname '_mh',int2str(NumberOfMcFilesPerBlock),'_blck' int2str(b) '.mat'],'x2');
% $$$ tmp((b-1)*NumberOfDraws+startline+1:(b-1)*NumberOfDraws+MAX_nruns*(LastFileNumber-1)+LastLineNumber,1) = x2(:,j);
% $$$ clear x2;
% $$$ startline = startline + LastLineNumber;
end
tmp(:,2) = kron(transpose(1:nblck),ones(NumberOfDraws,1));
tmp(:,3) = kron(ones(nblck,1),time');
tmp = sortrows(tmp,1);
ligne = 0;
for iter = Origin:StepSize:NumberOfDraws
ligne = ligne+1;
linea = ceil(0.5*iter);
n = iter-linea+1;
cinf = round(n*ALPHA/2);
csup = round(n*(1-ALPHA/2));
CINF = round(nblck*n*ALPHA/2);
CSUP = round(nblck*n*(1-ALPHA/2));
temp = tmp(find((tmp(:,3)>=linea) & (tmp(:,3)<=iter)),1:2);
UDIAG(ligne,1,j-fpar+1) = temp(CSUP,1)-temp(CINF,1);
moyenne = mean(temp(:,1));%% Pooled mean.
UDIAG(ligne,3,j-fpar+1) = sum((temp(:,1)-moyenne).^2)/(nblck*n-1);
UDIAG(ligne,5,j-fpar+1) = sum(abs(temp(:,1)-moyenne).^3)/(nblck*n-1);
for i=1:nblck
pmet = temp(find(temp(:,2)==i));
UDIAG(ligne,2,j-fpar+1) = UDIAG(ligne,2,j-fpar+1) + pmet(csup,1)-pmet(cinf,1);
moyenne = mean(pmet,1); %% Within mean.
UDIAG(ligne,4,j-fpar+1) = UDIAG(ligne,4,j-fpar+1) + sum((pmet(:,1)-moyenne).^2)/(n-1);
UDIAG(ligne,6,j-fpar+1) = UDIAG(ligne,6,j-fpar+1) + sum(abs(pmet(:,1)-moyenne).^3)/(n-1);
end
end
fprintf('Done! \n');
if whoiam,
waitbarString = [ 'Parameter ' int2str(j) '/' int2str(npar) ' done.'];
fMessageStatus((j-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo)
end
end
myoutput.UDIAG = UDIAG;

View File

@ -1,189 +1,189 @@
function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt_, oo_)
% function PlotPosteriorDistributions()
% plots posterior distributions
%
% INPUTS
% estim_params_ [structure]
% M_ [structure]
% options_ [structure]
% bayestopt_ [structure]
% oo_ [structure]
%
% OUTPUTS
% oo_ [structure]
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2005-2008 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/>.
OutputDirectoryName = CheckPath('Output');
TeX = options_.TeX;
nblck = options_.mh_nblck;
nvx = estim_params_.nvx;
nvn = estim_params_.nvn;
ncx = estim_params_.ncx;
ncn = estim_params_.ncn;
np = estim_params_.np ;
npar = nvx+nvn+ncx+ncn+np;
MaxNumberOfPlotPerFigure = 9;% The square root must be an integer!
nn = sqrt(MaxNumberOfPlotPerFigure);
figurename = 'Priors and posteriors';
if TeX
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']);
fprintf(fidTeX,' \n');
end
figunumber = 0;
subplotnum = 0;
for i=1:npar
subplotnum = subplotnum+1;
if subplotnum == 1
figunumber = figunumber+1;
if options_.nograph
hfig = figure('Name',figurename,'Visible','off');
else
hfig = figure('Name',figurename);
end
end
if subplotnum == 1
if TeX
TeXNAMES = [];
end
NAMES = [];
end
[nam,texnam] = get_the_name(i,TeX);
NAMES = strvcat(NAMES,nam);
if TeX
TeXNAMES = strvcat(TeXNAMES,texnam);
end
[x2,f2,abscissa,dens,binf2,bsup2] = draw_prior_density(i,bayestopt_);
top2 = max(f2);
if i <= nvx
name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:));
eval(['x1 = oo_.posterior_density.shocks_std.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.shocks_std.' name '(:,2);'])
eval(['oo_.prior_density.shocks_std.' name '(:,1) = x2;'])
eval(['oo_.prior_density.shocks_std.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.shocks_std.' name ';'])
end
elseif i <= nvx+nvn
name = deblank(options_.varobs(estim_params_.var_endo(i-nvx,1),:));
eval(['x1 = oo_.posterior_density.measurement_errors_std.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.measurement_errors_std.' name '(:,2);'])
eval(['oo_.prior_density.mearsurement_errors_std.' name '(:,1) = x2;'])
eval(['oo_.prior_density.measurement_errors_std.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.measurement_errors_std.' name ';'])
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,:))];
eval(['x1 = oo_.posterior_density.shocks_corr.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.shocks_corr.' name '(:,2);'])
eval(['oo_.prior_density.shocks_corr.' name '(:,1) = x2;'])
eval(['oo_.prior_density.shocks_corr.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.shocks_corr.' name ';'])
end
elseif i <= nvx+nvn+ncx+ncn
j = i - (nvx+nvn+ncx);
k1 = estim_params_.corrn(j,1);
k2 = estim_params_.corrn(j,2);
name = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))];
eval(['x1 = oo_.posterior_density.measurement_errors_corr.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.measurement_errors_corr.' name '(:,2);'])
eval(['oo_.prior_density.mearsurement_errors_corr.' name '(:,1) = x2;'])
eval(['oo_.prior_density.measurement_errors_corr.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.measurement_errors_corr.' name ';'])
end
else
j = i - (nvx+nvn+ncx+ncn);
name = deblank(M_.param_names(estim_params_.param_vals(j,1),:));
eval(['x1 = oo_.posterior_density.parameters.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.parameters.' name '(:,2);'])
eval(['oo_.prior_density.parameters.' name '(:,1) = x2;'])
eval(['oo_.prior_density.parameters.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.parameters.' name ';'])
end
end
top1 = max(f1);
top0 = max([top1;top2]);
binf1 = x1(1);
bsup1 = x1(end);
borneinf = min(binf1,binf2);
bornesup = max(bsup1,bsup2);
subplot(nn,nn,subplotnum)
hh = plot(x2,f2,'-k','linewidth',2);
set(hh,'color',[0.7 0.7 0.7]);
hold on;
plot(x1,f1,'-k','linewidth',2);
if options_.posterior_mode_estimation
plot( [pmod pmod], [0.0 1.1*top0], '--g', 'linewidth', 2);
end
box on;
axis([borneinf bornesup 0 1.1*top0]);
title(nam,'Interpreter','none');
hold off;
drawnow
if subplotnum == MaxNumberOfPlotPerFigure | i == npar;
eval(['print -depsc2 ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.eps']);
if ~exist('OCTAVE_VERSION')
eval(['print -dpdf ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber)]);
end
if options_.nograph,
set(hfig,'Visible','on');
end
if ~exist('OCTAVE_VERSION')
saveas(hfig,[OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.fig']);
end
if TeX
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
fprintf(fidTeX,'\\centering\n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_PriorsAndPosteriors%s}\n',M_.fname,int2str(figunumber));
fprintf(fidTeX,'\\caption{Priors and posteriors.}');
fprintf(fidTeX,'\\label{Fig:PriorsAndPosteriors:%s}\n',int2str(figunumber));
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
if i == npar
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end
end
if options_.nograph,
close(hfig),
end
subplotnum = 0;
end
function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt_, oo_)
% function PlotPosteriorDistributions()
% plots posterior distributions
%
% INPUTS
% estim_params_ [structure]
% M_ [structure]
% options_ [structure]
% bayestopt_ [structure]
% oo_ [structure]
%
% OUTPUTS
% oo_ [structure]
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2005-2008 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/>.
OutputDirectoryName = CheckPath('Output');
TeX = options_.TeX;
nblck = options_.mh_nblck;
nvx = estim_params_.nvx;
nvn = estim_params_.nvn;
ncx = estim_params_.ncx;
ncn = estim_params_.ncn;
np = estim_params_.np ;
npar = nvx+nvn+ncx+ncn+np;
MaxNumberOfPlotPerFigure = 9;% The square root must be an integer!
nn = sqrt(MaxNumberOfPlotPerFigure);
figurename = 'Priors and posteriors';
if TeX
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']);
fprintf(fidTeX,' \n');
end
figunumber = 0;
subplotnum = 0;
for i=1:npar
subplotnum = subplotnum+1;
if subplotnum == 1
figunumber = figunumber+1;
if options_.nograph
hfig = figure('Name',figurename,'Visible','off');
else
hfig = figure('Name',figurename);
end
end
if subplotnum == 1
if TeX
TeXNAMES = [];
end
NAMES = [];
end
[nam,texnam] = get_the_name(i,TeX);
NAMES = strvcat(NAMES,nam);
if TeX
TeXNAMES = strvcat(TeXNAMES,texnam);
end
[x2,f2,abscissa,dens,binf2,bsup2] = draw_prior_density(i,bayestopt_);
top2 = max(f2);
if i <= nvx
name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:));
eval(['x1 = oo_.posterior_density.shocks_std.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.shocks_std.' name '(:,2);'])
eval(['oo_.prior_density.shocks_std.' name '(:,1) = x2;'])
eval(['oo_.prior_density.shocks_std.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.shocks_std.' name ';'])
end
elseif i <= nvx+nvn
name = deblank(options_.varobs(estim_params_.var_endo(i-nvx,1),:));
eval(['x1 = oo_.posterior_density.measurement_errors_std.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.measurement_errors_std.' name '(:,2);'])
eval(['oo_.prior_density.mearsurement_errors_std.' name '(:,1) = x2;'])
eval(['oo_.prior_density.measurement_errors_std.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.measurement_errors_std.' name ';'])
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,:))];
eval(['x1 = oo_.posterior_density.shocks_corr.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.shocks_corr.' name '(:,2);'])
eval(['oo_.prior_density.shocks_corr.' name '(:,1) = x2;'])
eval(['oo_.prior_density.shocks_corr.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.shocks_corr.' name ';'])
end
elseif i <= nvx+nvn+ncx+ncn
j = i - (nvx+nvn+ncx);
k1 = estim_params_.corrn(j,1);
k2 = estim_params_.corrn(j,2);
name = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))];
eval(['x1 = oo_.posterior_density.measurement_errors_corr.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.measurement_errors_corr.' name '(:,2);'])
eval(['oo_.prior_density.mearsurement_errors_corr.' name '(:,1) = x2;'])
eval(['oo_.prior_density.measurement_errors_corr.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.measurement_errors_corr.' name ';'])
end
else
j = i - (nvx+nvn+ncx+ncn);
name = deblank(M_.param_names(estim_params_.param_vals(j,1),:));
eval(['x1 = oo_.posterior_density.parameters.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.parameters.' name '(:,2);'])
eval(['oo_.prior_density.parameters.' name '(:,1) = x2;'])
eval(['oo_.prior_density.parameters.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.parameters.' name ';'])
end
end
top1 = max(f1);
top0 = max([top1;top2]);
binf1 = x1(1);
bsup1 = x1(end);
borneinf = min(binf1,binf2);
bornesup = max(bsup1,bsup2);
subplot(nn,nn,subplotnum)
hh = plot(x2,f2,'-k','linewidth',2);
set(hh,'color',[0.7 0.7 0.7]);
hold on;
plot(x1,f1,'-k','linewidth',2);
if options_.posterior_mode_estimation
plot( [pmod pmod], [0.0 1.1*top0], '--g', 'linewidth', 2);
end
box on;
axis([borneinf bornesup 0 1.1*top0]);
title(nam,'Interpreter','none');
hold off;
drawnow
if subplotnum == MaxNumberOfPlotPerFigure | i == npar;
eval(['print -depsc2 ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.eps']);
if ~exist('OCTAVE_VERSION')
eval(['print -dpdf ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber)]);
end
if options_.nograph,
set(hfig,'Visible','on');
end
if ~exist('OCTAVE_VERSION')
saveas(hfig,[OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.fig']);
end
if TeX
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
fprintf(fidTeX,'\\centering\n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_PriorsAndPosteriors%s}\n',M_.fname,int2str(figunumber));
fprintf(fidTeX,'\\caption{Priors and posteriors.}');
fprintf(fidTeX,'\\label{Fig:PriorsAndPosteriors:%s}\n',int2str(figunumber));
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
if i == npar
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end
end
if options_.nograph,
close(hfig),
end
subplotnum = 0;
end
end

View File

@ -1,273 +1,273 @@
function PosteriorFilterSmootherAndForecast(Y,gend, type,data_index)
% function PosteriorFilterSmootherAndForecast(Y,gend, type)
% Computes posterior filter smoother and forecasts
%
% INPUTS
% Y: data
% gend: number of observations
% type: posterior
% prior
% gsa
%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2005-2008 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/>.
global options_ estim_params_ oo_ M_ bayestopt_
nvx = estim_params_.nvx;
nvn = estim_params_.nvn;
ncx = estim_params_.ncx;
ncn = estim_params_.ncn;
np = estim_params_.np ;
npar = nvx+nvn+ncx+ncn+np;
offset = npar-np;
naK = length(options_.filter_step_ahead);
%%
MaxNumberOfPlotPerFigure = 4;% The square root must be an integer!
MaxNumberOfBytes=options_.MaxNumberOfBytes;
endo_nbr=M_.endo_nbr;
exo_nbr=M_.exo_nbr;
nvobs = size(options_.varobs,1);
nn = sqrt(MaxNumberOfPlotPerFigure);
iendo = 1:endo_nbr;
i_last_obs = gend+(1-M_.maximum_endo_lag:0);
horizon = options_.forecast;
maxlag = M_.maximum_endo_lag;
%%
CheckPath('Plots/');
DirectoryName = CheckPath('metropolis');
load([ DirectoryName '/' M_.fname '_mh_history.mat'])
FirstMhFile = record.KeepedDraws.FirstMhFile;
FirstLine = record.KeepedDraws.FirstLine;
TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); LastMhFile = TotalNumberOfMhFiles;
TotalNumberOfMhDraws = sum(record.MhDraws(:,1));
NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws);
clear record;
B = min(1200, round(0.25*NumberOfDraws));
B = 200;
%%
MAX_nruns = min(B,ceil(options_.MaxNumberOfBytes/(npar+2)/8));
MAX_nsmoo = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*gend)/8));
MAX_ninno = min(B,ceil(MaxNumberOfBytes/(exo_nbr*gend)/8));
MAX_nerro = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)*gend)/8));
if naK
MAX_naK = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)* ...
length(options_.filter_step_ahead)*gend)/8));
end
if horizon
MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8));
MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ...
8));
IdObs = bayestopt_.mfys;
end
%%
varlist = options_.varlist;
if isempty(varlist)
varlist = M_.endo_names;
SelecVariables = transpose(1:M_.endo_nbr);
nvar = M_.endo_nbr;
else
nvar = size(varlist,1);
SelecVariables = [];
for i=1:nvar
if ~isempty(strmatch(varlist(i,:),M_.endo_names,'exact'))
SelecVariables = [SelecVariables;strmatch(varlist(i,:),M_.endo_names,'exact')];
end
end
end
irun1 = 1;
irun2 = 1;
irun3 = 1;
irun4 = 1;
irun5 = 1;
irun6 = 1;
irun7 = 1;
ifil1 = 0;
ifil2 = 0;
ifil3 = 0;
ifil4 = 0;
ifil5 = 0;
ifil6 = 0;
ifil7 = 0;
h = waitbar(0,'Bayesian smoother...');
stock_param = zeros(MAX_nruns, npar);
stock_logpo = zeros(MAX_nruns,1);
stock_ys = zeros(MAX_nruns,endo_nbr);
if options_.smoother
stock_smooth = zeros(endo_nbr,gend,MAX_nsmoo);
stock_innov = zeros(exo_nbr,gend,B);
stock_error = zeros(nvobs,gend,MAX_nerro);
end
if options_.filter_step_ahead
stock_filter = zeros(naK,endo_nbr,gend+options_.filter_step_ahead(end),MAX_naK);
end
if options_.forecast
stock_forcst_mean = zeros(endo_nbr,horizon+maxlag,MAX_nforc1);
stock_forcst_total = zeros(endo_nbr,horizon+maxlag,MAX_nforc2);
end
for b=1:B
%deep = GetOneDraw(NumberOfDraws,FirstMhFile,LastMhFile,FirstLine,MAX_nruns,DirectoryName);
[deep, logpo] = GetOneDraw(type);
set_all_parameters(deep);
dr = resol(oo_.steady_state,0);
[alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK] = ...
DsgeSmoother(deep,gend,Y,data_index);
if options_.loglinear
stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ...
repmat(log(dr.ys(dr.order_var)),1,gend);
else
stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ...
repmat(dr.ys(dr.order_var),1,gend);
end
if nvx
stock_innov(:,:,irun2) = etahat;
end
if nvn
stock_error(:,:,irun3) = epsilonhat;
end
if naK
stock_filter(:,dr.order_var,:,irun4) = aK(options_.filter_step_ahead,1:endo_nbr,:);
end
stock_param(irun5,:) = deep;
stock_logpo(irun5,1) = logpo;
stock_ys(irun5,:) = SteadyState';
if horizon
yyyy = alphahat(iendo,i_last_obs);
yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr));
if options_.prefilter == 1
yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ...
horizon+maxlag,1);
end
yf(:,IdObs) = yf(:,IdObs)+(gend+[1-maxlag:horizon]')*trend_coeff';
if options_.loglinear == 1
yf = yf+repmat(log(SteadyState'),horizon+maxlag,1);
% yf = exp(yf);
else
yf = yf+repmat(SteadyState',horizon+maxlag,1);
end
yf1 = forcst2(yyyy,horizon,dr,1);
if options_.prefilter == 1
yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ...
repmat(bayestopt_.mean_varobs',[horizon+maxlag,1,1]);
end
yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-maxlag:horizon]')* ...
trend_coeff',[1,1,1]);
if options_.loglinear == 1
yf1 = yf1 + repmat(log(SteadyState'),[horizon+maxlag,1,1]);
% yf1 = exp(yf1);
else
yf1 = yf1 + repmat(SteadyState',[horizon+maxlag,1,1]);
end
stock_forcst_mean(:,:,irun6) = yf';
stock_forcst_total(:,:,irun7) = yf1';
end
irun1 = irun1 + 1;
irun2 = irun2 + 1;
irun3 = irun3 + 1;
irun4 = irun4 + 1;
irun5 = irun5 + 1;
irun6 = irun6 + 1;
irun7 = irun7 + 1;
if irun1 > MAX_nsmoo | b == B
stock = stock_smooth(:,:,1:irun1-1);
ifil1 = ifil1 + 1;
save([DirectoryName '/' M_.fname '_smooth' int2str(ifil1) '.mat'],'stock');
irun1 = 1;
end
if nvx & (irun2 > MAX_ninno | b == B)
stock = stock_innov(:,:,1:irun2-1);
ifil2 = ifil2 + 1;
save([DirectoryName '/' M_.fname '_inno' int2str(ifil2) '.mat'],'stock');
irun2 = 1;
end
if nvn & (irun3 > MAX_error | b == B)
stock = stock_error(:,:,1:irun3-1);
ifil3 = ifil3 + 1;
save([DirectoryName '/' M_.fname '_error' int2str(ifil3) '.mat'],'stock');
irun3 = 1;
end
if naK & (irun4 > MAX_naK | b == B)
stock = stock_filter(:,:,:,1:irun4-1);
ifil4 = ifil4 + 1;
save([DirectoryName '/' M_.fname '_filter' int2str(ifil4) '.mat'],'stock');
irun4 = 1;
end
if irun5 > MAX_nruns | b == B
stock = stock_param(1:irun5-1,:);
ifil5 = ifil5 + 1;
save([DirectoryName '/' M_.fname '_param' int2str(ifil5) '.mat'],'stock','stock_logpo','stock_ys');
irun5 = 1;
end
if horizon & (irun6 > MAX_nforc1 | b == B)
stock = stock_forcst_mean(:,:,1:irun6-1);
ifil6 = ifil6 + 1;
save([DirectoryName '/' M_.fname '_forc_mean' int2str(ifil6) '.mat'],'stock');
irun6 = 1;
end
if horizon & (irun7 > MAX_nforc2 | b == B)
stock = stock_forcst_total(:,:,1:irun7-1);
ifil7 = ifil7 + 1;
save([DirectoryName '/' M_.fname '_forc_total' int2str(ifil7) '.mat'],'stock');
irun7 = 1;
end
waitbar(b/B,h);
end
close(h)
stock_gend=gend;
stock_data=Y;
save([DirectoryName '/' M_.fname '_data.mat'],'stock_gend','stock_data');
if options_.smoother
pm3(endo_nbr,gend,ifil1,B,'Smoothed variables',...
M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
'names2','smooth',[M_.fname '/metropolis'],'_smooth')
end
if options_.forecast
pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (mean)',...
M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
'names2','smooth',[M_.fname '/metropolis'],'_forc_mean')
pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (total)',...
M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
'names2','smooth',[M_.fname '/metropolis'],'_forc_total')
end
function PosteriorFilterSmootherAndForecast(Y,gend, type,data_index)
% function PosteriorFilterSmootherAndForecast(Y,gend, type)
% Computes posterior filter smoother and forecasts
%
% INPUTS
% Y: data
% gend: number of observations
% type: posterior
% prior
% gsa
%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2005-2008 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/>.
global options_ estim_params_ oo_ M_ bayestopt_
nvx = estim_params_.nvx;
nvn = estim_params_.nvn;
ncx = estim_params_.ncx;
ncn = estim_params_.ncn;
np = estim_params_.np ;
npar = nvx+nvn+ncx+ncn+np;
offset = npar-np;
naK = length(options_.filter_step_ahead);
%%
MaxNumberOfPlotPerFigure = 4;% The square root must be an integer!
MaxNumberOfBytes=options_.MaxNumberOfBytes;
endo_nbr=M_.endo_nbr;
exo_nbr=M_.exo_nbr;
nvobs = size(options_.varobs,1);
nn = sqrt(MaxNumberOfPlotPerFigure);
iendo = 1:endo_nbr;
i_last_obs = gend+(1-M_.maximum_endo_lag:0);
horizon = options_.forecast;
maxlag = M_.maximum_endo_lag;
%%
CheckPath('Plots/');
DirectoryName = CheckPath('metropolis');
load([ DirectoryName '/' M_.fname '_mh_history.mat'])
FirstMhFile = record.KeepedDraws.FirstMhFile;
FirstLine = record.KeepedDraws.FirstLine;
TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); LastMhFile = TotalNumberOfMhFiles;
TotalNumberOfMhDraws = sum(record.MhDraws(:,1));
NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws);
clear record;
B = min(1200, round(0.25*NumberOfDraws));
B = 200;
%%
MAX_nruns = min(B,ceil(options_.MaxNumberOfBytes/(npar+2)/8));
MAX_nsmoo = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*gend)/8));
MAX_ninno = min(B,ceil(MaxNumberOfBytes/(exo_nbr*gend)/8));
MAX_nerro = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)*gend)/8));
if naK
MAX_naK = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)* ...
length(options_.filter_step_ahead)*gend)/8));
end
if horizon
MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8));
MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ...
8));
IdObs = bayestopt_.mfys;
end
%%
varlist = options_.varlist;
if isempty(varlist)
varlist = M_.endo_names;
SelecVariables = transpose(1:M_.endo_nbr);
nvar = M_.endo_nbr;
else
nvar = size(varlist,1);
SelecVariables = [];
for i=1:nvar
if ~isempty(strmatch(varlist(i,:),M_.endo_names,'exact'))
SelecVariables = [SelecVariables;strmatch(varlist(i,:),M_.endo_names,'exact')];
end
end
end
irun1 = 1;
irun2 = 1;
irun3 = 1;
irun4 = 1;
irun5 = 1;
irun6 = 1;
irun7 = 1;
ifil1 = 0;
ifil2 = 0;
ifil3 = 0;
ifil4 = 0;
ifil5 = 0;
ifil6 = 0;
ifil7 = 0;
h = waitbar(0,'Bayesian smoother...');
stock_param = zeros(MAX_nruns, npar);
stock_logpo = zeros(MAX_nruns,1);
stock_ys = zeros(MAX_nruns,endo_nbr);
if options_.smoother
stock_smooth = zeros(endo_nbr,gend,MAX_nsmoo);
stock_innov = zeros(exo_nbr,gend,B);
stock_error = zeros(nvobs,gend,MAX_nerro);
end
if options_.filter_step_ahead
stock_filter = zeros(naK,endo_nbr,gend+options_.filter_step_ahead(end),MAX_naK);
end
if options_.forecast
stock_forcst_mean = zeros(endo_nbr,horizon+maxlag,MAX_nforc1);
stock_forcst_total = zeros(endo_nbr,horizon+maxlag,MAX_nforc2);
end
for b=1:B
%deep = GetOneDraw(NumberOfDraws,FirstMhFile,LastMhFile,FirstLine,MAX_nruns,DirectoryName);
[deep, logpo] = GetOneDraw(type);
set_all_parameters(deep);
dr = resol(oo_.steady_state,0);
[alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK] = ...
DsgeSmoother(deep,gend,Y,data_index);
if options_.loglinear
stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ...
repmat(log(dr.ys(dr.order_var)),1,gend);
else
stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ...
repmat(dr.ys(dr.order_var),1,gend);
end
if nvx
stock_innov(:,:,irun2) = etahat;
end
if nvn
stock_error(:,:,irun3) = epsilonhat;
end
if naK
stock_filter(:,dr.order_var,:,irun4) = aK(options_.filter_step_ahead,1:endo_nbr,:);
end
stock_param(irun5,:) = deep;
stock_logpo(irun5,1) = logpo;
stock_ys(irun5,:) = SteadyState';
if horizon
yyyy = alphahat(iendo,i_last_obs);
yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr));
if options_.prefilter == 1
yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ...
horizon+maxlag,1);
end
yf(:,IdObs) = yf(:,IdObs)+(gend+[1-maxlag:horizon]')*trend_coeff';
if options_.loglinear == 1
yf = yf+repmat(log(SteadyState'),horizon+maxlag,1);
% yf = exp(yf);
else
yf = yf+repmat(SteadyState',horizon+maxlag,1);
end
yf1 = forcst2(yyyy,horizon,dr,1);
if options_.prefilter == 1
yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ...
repmat(bayestopt_.mean_varobs',[horizon+maxlag,1,1]);
end
yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-maxlag:horizon]')* ...
trend_coeff',[1,1,1]);
if options_.loglinear == 1
yf1 = yf1 + repmat(log(SteadyState'),[horizon+maxlag,1,1]);
% yf1 = exp(yf1);
else
yf1 = yf1 + repmat(SteadyState',[horizon+maxlag,1,1]);
end
stock_forcst_mean(:,:,irun6) = yf';
stock_forcst_total(:,:,irun7) = yf1';
end
irun1 = irun1 + 1;
irun2 = irun2 + 1;
irun3 = irun3 + 1;
irun4 = irun4 + 1;
irun5 = irun5 + 1;
irun6 = irun6 + 1;
irun7 = irun7 + 1;
if irun1 > MAX_nsmoo | b == B
stock = stock_smooth(:,:,1:irun1-1);
ifil1 = ifil1 + 1;
save([DirectoryName '/' M_.fname '_smooth' int2str(ifil1) '.mat'],'stock');
irun1 = 1;
end
if nvx & (irun2 > MAX_ninno | b == B)
stock = stock_innov(:,:,1:irun2-1);
ifil2 = ifil2 + 1;
save([DirectoryName '/' M_.fname '_inno' int2str(ifil2) '.mat'],'stock');
irun2 = 1;
end
if nvn & (irun3 > MAX_error | b == B)
stock = stock_error(:,:,1:irun3-1);
ifil3 = ifil3 + 1;
save([DirectoryName '/' M_.fname '_error' int2str(ifil3) '.mat'],'stock');
irun3 = 1;
end
if naK & (irun4 > MAX_naK | b == B)
stock = stock_filter(:,:,:,1:irun4-1);
ifil4 = ifil4 + 1;
save([DirectoryName '/' M_.fname '_filter' int2str(ifil4) '.mat'],'stock');
irun4 = 1;
end
if irun5 > MAX_nruns | b == B
stock = stock_param(1:irun5-1,:);
ifil5 = ifil5 + 1;
save([DirectoryName '/' M_.fname '_param' int2str(ifil5) '.mat'],'stock','stock_logpo','stock_ys');
irun5 = 1;
end
if horizon & (irun6 > MAX_nforc1 | b == B)
stock = stock_forcst_mean(:,:,1:irun6-1);
ifil6 = ifil6 + 1;
save([DirectoryName '/' M_.fname '_forc_mean' int2str(ifil6) '.mat'],'stock');
irun6 = 1;
end
if horizon & (irun7 > MAX_nforc2 | b == B)
stock = stock_forcst_total(:,:,1:irun7-1);
ifil7 = ifil7 + 1;
save([DirectoryName '/' M_.fname '_forc_total' int2str(ifil7) '.mat'],'stock');
irun7 = 1;
end
waitbar(b/B,h);
end
close(h)
stock_gend=gend;
stock_data=Y;
save([DirectoryName '/' M_.fname '_data.mat'],'stock_gend','stock_data');
if options_.smoother
pm3(endo_nbr,gend,ifil1,B,'Smoothed variables',...
M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
'names2','smooth',[M_.fname '/metropolis'],'_smooth')
end
if options_.forecast
pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (mean)',...
M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
'names2','smooth',[M_.fname '/metropolis'],'_forc_mean')
pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (total)',...
M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
'names2','smooth',[M_.fname '/metropolis'],'_forc_total')
end

View File

@ -71,27 +71,27 @@ else
end
DirectoryName = CheckPath('Output');
if strcmpi(type,'posterior')
MhDirectoryName = CheckPath('metropolis');
MhDirectoryName = CheckPath('metropolis');
elseif strcmpi(type,'gsa')
MhDirectoryName = CheckPath('GSA');
MhDirectoryName = CheckPath('GSA');
else
MhDirectoryName = CheckPath('prior');
MhDirectoryName = CheckPath('prior');
end
if strcmpi(type,'posterior')
load([ MhDirectoryName '/' M_.fname '_mh_history.mat'])
TotalNumberOfMhDraws = sum(record.MhDraws(:,1));
NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws);
load([ MhDirectoryName '/' M_.fname '_mh_history.mat'])
TotalNumberOfMhDraws = sum(record.MhDraws(:,1));
NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws);
elseif strcmpi(type,'gsa')
load([ MhDirectoryName '/' M_.fname '_prior.mat'],'lpmat0','lpmat','istable')
x=[lpmat0(istable,:) lpmat(istable,:)];
clear lpmat istable
NumberOfDraws=size(x,1);
B=NumberOfDraws; options_.B = B;
load([ MhDirectoryName '/' M_.fname '_prior.mat'],'lpmat0','lpmat','istable')
x=[lpmat0(istable,:) lpmat(istable,:)];
clear lpmat istable
NumberOfDraws=size(x,1);
B=NumberOfDraws; options_.B = B;
else% type = 'prior'
NumberOfDraws = 500;
NumberOfDraws = 500;
end
if ~strcmpi(type,'gsa')
B = min([round(.5*NumberOfDraws),500]); options_.B = B;
B = min([round(.5*NumberOfDraws),500]); options_.B = B;
end
try delete([MhDirectoryName '/' M_.fname '_irf_dsge*.mat'])
catch disp('No _IRFs (dsge) files to be deleted!')
@ -106,22 +106,22 @@ NumberOfIRFfiles_dsge = 1;
NumberOfIRFfiles_dsgevar = 1;
ifil2 = 1;
if strcmpi(type,'posterior')
h = waitbar(0,'Bayesian (posterior) IRFs...');
h = waitbar(0,'Bayesian (posterior) IRFs...');
elseif strcmpi(type,'gsa')
h = waitbar(0,'GSA (prior) IRFs...');
h = waitbar(0,'GSA (prior) IRFs...');
else
h = waitbar(0,'Bayesian (prior) IRFs...');
h = waitbar(0,'Bayesian (prior) IRFs...');
end
% Create arrays
if B <= MAX_nruns
stock_param = zeros(B, npar);
stock_param = zeros(B, npar);
else
stock_param = zeros(MAX_nruns, npar);
stock_param = zeros(MAX_nruns, npar);
end
if B >= MAX_nirfs_dsge
stock_irf_dsge = zeros(options_.irf,nvar,M_.exo_nbr,MAX_nirfs_dsge);
stock_irf_dsge = zeros(options_.irf,nvar,M_.exo_nbr,MAX_nirfs_dsge);
else
stock_irf_dsge = zeros(options_.irf,nvar,M_.exo_nbr,B);
stock_irf_dsge = zeros(options_.irf,nvar,M_.exo_nbr,B);
end
if MAX_nirfs_dsgevar
if B >= MAX_nirfs_dsgevar
@ -204,14 +204,14 @@ while b<=B
SIGMA_inv_upper_chol);
% draw from the conditional posterior of PHI
PHI_draw = rand_matrix_normal(NumberOfParametersPerEquation,nvobs, PHI, ...
chol(SIGMAu_draw)', chol(iXX)');
chol(SIGMAu_draw)', chol(iXX)');
Companion_matrix(1:nvobs,:) = transpose(PHI_draw(1:NumberOfLagsTimesNvobs,:));
% Check for stationarity
explosive_var = any(abs(eig(Companion_matrix))>1.000000001);
end
% Get the mean
% $$$ if options_.noconstant
mu = zeros(1,nvobs);
mu = zeros(1,nvobs);
% $$$ else
% $$$ AA = eye(nvobs);
% $$$ for lag=1:NumberOfLags
@ -219,7 +219,7 @@ while b<=B
% $$$ end
% $$$ mu = transpose(AA\transpose(PHI_draw(end,:)));
% $$$ end
% Get rotation
% Get rotation
if dsge_prior_weight > 0
Atheta(oo_.dr.order_var,M_.exo_names_orig_ord) = oo_.dr.ghu*sqrt(M_.Sigma_e);
A0 = Atheta(bayestopt_.mfys,:);
@ -282,7 +282,7 @@ while b<=B
waitbar(b/B,h);
end
if nosaddle
disp(['PosteriorIRF :: Percentage of discarded posterior draws = ' num2str(nosaddle/(B+nosaddle))])
disp(['PosteriorIRF :: Percentage of discarded posterior draws = ' num2str(nosaddle/(B+nosaddle))])
end
close(h);
@ -292,7 +292,7 @@ if MAX_nirfs_dsgevar
end
if strcmpi(type,'gsa')
return
return
end
IRF_DSGEs = dir([MhDirectoryName '/' M_.fname '_IRF_DSGEs*.mat']);
@ -310,10 +310,10 @@ DistribIRF = zeros(options_.irf,9,nvar,M_.exo_nbr);
HPDIRF = zeros(options_.irf,2,nvar,M_.exo_nbr);
if options_.TeX
varlist_TeX = [];
for i=1:nvar
varlist_TeX = strvcat(varlist_TeX,M_.endo_names_tex(IndxVariables(i),:));
end
varlist_TeX = [];
for i=1:nvar
varlist_TeX = strvcat(varlist_TeX,M_.endo_names_tex(IndxVariables(i),:));
end
end
fprintf('MH: Posterior (dsge) IRFs...\n');
@ -321,31 +321,31 @@ tit(M_.exo_names_orig_ord,:) = M_.exo_names;
kdx = 0;
for file = 1:NumberOfIRFfiles_dsge
load([MhDirectoryName '/' M_.fname '_IRF_DSGEs' int2str(file) '.mat']);
for i = 1:M_.exo_nbr
for j = 1:nvar
for k = 1:size(STOCK_IRF_DSGE,1)
kk = k+kdx;
[MeanIRF(kk,j,i),MedianIRF(kk,j,i),VarIRF(kk,j,i),HPDIRF(kk,:,j,i),...
DistribIRF(kk,:,j,i)] = posterior_moments(squeeze(STOCK_IRF_DSGE(k,j,i,:)),0,options_.mh_conf_sig);
load([MhDirectoryName '/' M_.fname '_IRF_DSGEs' int2str(file) '.mat']);
for i = 1:M_.exo_nbr
for j = 1:nvar
for k = 1:size(STOCK_IRF_DSGE,1)
kk = k+kdx;
[MeanIRF(kk,j,i),MedianIRF(kk,j,i),VarIRF(kk,j,i),HPDIRF(kk,:,j,i),...
DistribIRF(kk,:,j,i)] = posterior_moments(squeeze(STOCK_IRF_DSGE(k,j,i,:)),0,options_.mh_conf_sig);
end
end
end
end
kdx = kdx + size(STOCK_IRF_DSGE,1);
kdx = kdx + size(STOCK_IRF_DSGE,1);
end
clear STOCK_IRF_DSGE;
for i = 1:M_.exo_nbr
for j = 1:nvar
name = [deblank(M_.endo_names(IndxVariables(j),:)) '_' deblank(tit(i,:))];
eval(['oo_.PosteriorIRF.dsge.Mean.' name ' = MeanIRF(:,j,i);']);
eval(['oo_.PosteriorIRF.dsge.Median.' name ' = MedianIRF(:,j,i);']);
eval(['oo_.PosteriorIRF.dsge.Var.' name ' = VarIRF(:,j,i);']);
eval(['oo_.PosteriorIRF.dsge.Distribution.' name ' = DistribIRF(:,:,j,i);']);
eval(['oo_.PosteriorIRF.dsge.HPDinf.' name ' = HPDIRF(:,1,j,i);']);
eval(['oo_.PosteriorIRF.dsge.HPDsup.' name ' = HPDIRF(:,2,j,i);']);
end
for j = 1:nvar
name = [deblank(M_.endo_names(IndxVariables(j),:)) '_' deblank(tit(i,:))];
eval(['oo_.PosteriorIRF.dsge.Mean.' name ' = MeanIRF(:,j,i);']);
eval(['oo_.PosteriorIRF.dsge.Median.' name ' = MedianIRF(:,j,i);']);
eval(['oo_.PosteriorIRF.dsge.Var.' name ' = VarIRF(:,j,i);']);
eval(['oo_.PosteriorIRF.dsge.Distribution.' name ' = DistribIRF(:,:,j,i);']);
eval(['oo_.PosteriorIRF.dsge.HPDinf.' name ' = HPDIRF(:,1,j,i);']);
eval(['oo_.PosteriorIRF.dsge.HPDsup.' name ' = HPDIRF(:,2,j,i);']);
end
end
@ -389,111 +389,111 @@ end
%% Finally I build the plots.
%%
if options_.TeX
fidTeX = fopen([DirectoryName '/' 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;
fidTeX = fopen([DirectoryName '/' 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;
end
%%
subplotnum = 0;
for i=1:M_.exo_nbr
NAMES = [];
if options_.TeX
TEXNAMES = [];
end
figunumber = 0;
for j=1:nvar
if max(abs(MeanIRF(:,j,i))) > 10^(-6)
subplotnum = subplotnum+1;
if options_.nograph
if subplotnum == 1 & options_.relative_irf
hh = figure('Name',['Relative response to orthogonalized shock to ' tit(i,:)],'Visible','off');
elseif subplotnum == 1 & ~options_.relative_irf
hh = figure('Name',['Orthogonalized shock to ' tit(i,:)],'Visible','off');
end
else
if subplotnum == 1 & options_.relative_irf
hh = figure('Name',['Relative response to orthogonalized shock to ' tit(i,:)]);
elseif subplotnum == 1 & ~options_.relative_irf
hh = figure('Name',['Orthogonalized shock to ' tit(i,:)]);
end
end
set(0,'CurrentFigure',hh)
subplot(nn,nn,subplotnum);
if ~MAX_nirfs_dsgevar
h1 = area(1:options_.irf,HPDIRF(:,2,j,i));
set(h1,'FaceColor',[.9 .9 .9]);
set(h1,'BaseValue',min(HPDIRF(:,1,j,i)));
hold on
h2 = area(1:options_.irf,HPDIRF(:,1,j,i),'FaceColor',[1 1 1],'BaseValue',min(HPDIRF(:,1,j,i)));
set(h2,'FaceColor',[1 1 1]);
set(h2,'BaseValue',min(HPDIRF(:,1,j,i)));
plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3)
% plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
box on
axis tight
xlim([1 options_.irf]);
hold off
else
h1 = area(1:options_.irf,HPDIRF(:,2,j,i));
set(h1,'FaceColor',[.9 .9 .9]);
set(h1,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))]));
hold on;
h2 = area(1:options_.irf,HPDIRF(:,1,j,i));
set(h2,'FaceColor',[1 1 1]);
set(h2,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))]));
plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3)
% plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
plot(1:options_.irf,MeanIRFdsgevar(:,j,i),'--k','linewidth',2)
plot(1:options_.irf,HPDIRFdsgevar(:,1,j,i),'--k','linewidth',1)
plot(1:options_.irf,HPDIRFdsgevar(:,2,j,i),'--k','linewidth',1)
box on
axis tight
xlim([1 options_.irf]);
hold off
end
name = deblank(varlist(j,:));
NAMES = strvcat(NAMES,name);
if options_.TeX
texname = deblank(varlist_TeX(j,:));
TEXNAMES = strvcat(TEXNAMES,['$' texname '$']);
end
title(name,'Interpreter','none')
NAMES = [];
if options_.TeX
TEXNAMES = [];
end
if subplotnum == MaxNumberOfPlotPerFigure | (j == nvar & subplotnum> 0)
figunumber = figunumber+1;
set(hh,'visible','on')
eval(['print -depsc2 ' DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber) '.eps']);
if ~exist('OCTAVE_VERSION')
eval(['print -dpdf ' DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber)]);
saveas(hh,[DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber) '.fig']);
end
set(hh,'visible','off')
if options_.nograph, close(hh), end
if options_.TeX
fprintf(fidTeX,'\\begin{figure}[H]\n');
for jj = 1:size(TEXNAMES,1)
fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
end
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Bayesian_IRF_%s}\n',M_.fname,deblank(tit(i,:)));
if options_.relative_irf
fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']);
else
fprintf(fidTeX,'\\caption{Bayesian IRF.}');
figunumber = 0;
for j=1:nvar
if max(abs(MeanIRF(:,j,i))) > 10^(-6)
subplotnum = subplotnum+1;
if options_.nograph
if subplotnum == 1 & options_.relative_irf
hh = figure('Name',['Relative response to orthogonalized shock to ' tit(i,:)],'Visible','off');
elseif subplotnum == 1 & ~options_.relative_irf
hh = figure('Name',['Orthogonalized shock to ' tit(i,:)],'Visible','off');
end
else
if subplotnum == 1 & options_.relative_irf
hh = figure('Name',['Relative response to orthogonalized shock to ' tit(i,:)]);
elseif subplotnum == 1 & ~options_.relative_irf
hh = figure('Name',['Orthogonalized shock to ' tit(i,:)]);
end
end
set(0,'CurrentFigure',hh)
subplot(nn,nn,subplotnum);
if ~MAX_nirfs_dsgevar
h1 = area(1:options_.irf,HPDIRF(:,2,j,i));
set(h1,'FaceColor',[.9 .9 .9]);
set(h1,'BaseValue',min(HPDIRF(:,1,j,i)));
hold on
h2 = area(1:options_.irf,HPDIRF(:,1,j,i),'FaceColor',[1 1 1],'BaseValue',min(HPDIRF(:,1,j,i)));
set(h2,'FaceColor',[1 1 1]);
set(h2,'BaseValue',min(HPDIRF(:,1,j,i)));
plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3)
% plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
box on
axis tight
xlim([1 options_.irf]);
hold off
else
h1 = area(1:options_.irf,HPDIRF(:,2,j,i));
set(h1,'FaceColor',[.9 .9 .9]);
set(h1,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))]));
hold on;
h2 = area(1:options_.irf,HPDIRF(:,1,j,i));
set(h2,'FaceColor',[1 1 1]);
set(h2,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))]));
plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3)
% plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
plot(1:options_.irf,MeanIRFdsgevar(:,j,i),'--k','linewidth',2)
plot(1:options_.irf,HPDIRFdsgevar(:,1,j,i),'--k','linewidth',1)
plot(1:options_.irf,HPDIRFdsgevar(:,2,j,i),'--k','linewidth',1)
box on
axis tight
xlim([1 options_.irf]);
hold off
end
name = deblank(varlist(j,:));
NAMES = strvcat(NAMES,name);
if options_.TeX
texname = deblank(varlist_TeX(j,:));
TEXNAMES = strvcat(TEXNAMES,['$' texname '$']);
end
title(name,'Interpreter','none')
end
fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s}\n',deblank(tit(i,:)));
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
end
subplotnum = 0;
end
end% loop over selected endo_var
if subplotnum == MaxNumberOfPlotPerFigure | (j == nvar & subplotnum> 0)
figunumber = figunumber+1;
set(hh,'visible','on')
eval(['print -depsc2 ' DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber) '.eps']);
if ~exist('OCTAVE_VERSION')
eval(['print -dpdf ' DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber)]);
saveas(hh,[DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber) '.fig']);
end
set(hh,'visible','off')
if options_.nograph, close(hh), end
if options_.TeX
fprintf(fidTeX,'\\begin{figure}[H]\n');
for jj = 1:size(TEXNAMES,1)
fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
end
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Bayesian_IRF_%s}\n',M_.fname,deblank(tit(i,:)));
if options_.relative_irf
fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']);
else
fprintf(fidTeX,'\\caption{Bayesian IRF.}');
end
fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s}\n',deblank(tit(i,:)));
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
end
subplotnum = 0;
end
end% loop over selected endo_var
end% loop over exo_var
%%
if options_.TeX
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end
fprintf('MH: Posterior IRFs, done!\n');

View File

@ -1,183 +1,183 @@
function ReshapeMatFiles(type, type2)
% function ReshapeMatFiles(type, type2)
% Reshapes and sorts (along the mcmc simulations) the mat files generated by DYNARE.
% 4D-arrays are splitted along the first dimension.
% 3D-arrays are splitted along the second dimension.
%
% INPUTS:
% type: statistics type in the repertory:
% dgse
% irf_bvardsge
% smooth
% filter
% error
% innov
% forcst
% forcst1
% type2: analysis type:
% posterior
% gsa
% prior
%
% OUTPUTS:
% none
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2007 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/>.
global M_ options_
if nargin==1,
MhDirectoryName = [ CheckPath('metropolis') '/' ];
else
if strcmpi(type2,'posterior')
MhDirectoryName = [CheckPath('metropolis') '/' ];
elseif strcmpi(type2,'gsa')
if options_.opt_gsa.morris==1,
MhDirectoryName = [CheckPath('GSA\SCREEN') '/' ];
elseif options_.opt_gsa.morris==2,
MhDirectoryName = [CheckPath('GSA\IDENTIF') '/' ];
else
MhDirectoryName = [CheckPath('GSA') '/' ];
end
else
MhDirectoryName = [CheckPath('prior') '/' ];
end
end
switch type
case 'irf_dsge'
CAPtype = 'IRF_DSGE';
TYPEsize = [ options_.irf , size(options_.varlist,1) , M_.exo_nbr ];
TYPEarray = 4;
case 'irf_bvardsge'
CAPtype = 'IRF_BVARDSGE';
TYPEsize = [ options_.irf , size(options_.varobs,1) , M_.exo_nbr ];
TYPEarray = 4;
case 'smooth'
CAPtype = 'SMOOTH';
TYPEsize = [ M_.endo_nbr , options_.nobs ];
TYPEarray = 3;
case 'filter'
CAPtype = 'FILTER';
TYPEsize = [ M_.endo_nbr , options_.nobs + 1 ];% TO BE CHECKED!
TYPEarray = 3;
case 'error'
CAPtype = 'ERROR';
TYPEsize = [ size(options_.varobs,1) , options_.nobs ];
TYPEarray = 3;
case 'innov'
CAPtype = 'INNOV';
TYPEsize = [ M_.exo_nbr , options_.nobs ];
TYPEarray = 3;
case 'forcst'
CAPtype = 'FORCST';
TYPEsize = [ M_.endo_nbr , options_.forecast ];
TYPEarray = 3;
case 'forcst1'
CAPtype = 'FORCST1';
TYPEsize = [ M_.endo_nbr , options_.forecast ];
TYPEarray = 3;
otherwise
disp('ReshapeMatFiles :: Unknown argument!')
return
end
TYPEfiles = dir([MhDirectoryName M_.fname '_' type '*.mat']);
NumberOfTYPEfiles = length(TYPEfiles);
B = options_.B;
switch TYPEarray
case 4
if NumberOfTYPEfiles > 1
NumberOfPeriodsPerTYPEfiles = ceil(TYPEsize(1)/NumberOfTYPEfiles);
foffset = NumberOfTYPEfiles-floor(TYPEsize(1)/NumberOfPeriodsPerTYPEfiles);
reste = TYPEsize(1)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-foffset);
idx = 0;
jdx = 0;
for f1=1:NumberOfTYPEfiles-foffset
eval(['STOCK_' CAPtype ' = zeros(NumberOfPeriodsPerTYPEfiles,TYPEsize(2),TYPEsize(3),B);'])
for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']);
eval(['STOCK_' CAPtype '(:,:,:,idx+1:idx+size(stock_' type ',4))=stock_' ...
type '(jdx+1:jdx+NumberOfPeriodsPerTYPEfiles,:,:,:);'])
eval(['idx = idx + size(stock_' type ',4);'])
end
%eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]);
jdx = jdx + NumberOfPeriodsPerTYPEfiles;
idx = 0;
end
if reste
eval(['STOCK_' CAPtype ' = zeros(reste,TYPEsize(2),TYPEsize(3),B);'])
for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']);
eval(['STOCK_' CAPtype '(:,:,:,idx+1:idx+size(stock_' type ',4))=stock_' type '(jdx+1:jdx+reste,:,:,:);'])
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]);
end
else
load([MhDirectoryName M_.fname '_' type '1.mat']);
%eval(['STOCK_' CAPtype ' = sort(stock_' type ',4);'])
eval(['STOCK_' CAPtype ' = stock_' type ';'])
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
% delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat'])
% end
case 3
if NumberOfTYPEfiles>1
NumberOfPeriodsPerTYPEfiles = ceil( TYPEsize(2)/NumberOfTYPEfiles );
reste = TYPEsize(2)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-1);
idx = 0;
jdx = 0;
for f1=1:NumberOfTYPEfiles-1
eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),NumberOfPeriodsPerTYPEfiles,B);'])
for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']);
eval(['STOCK_' CAPtype '(:,:,idx+1:idx+size(stock_ ' type ',3))=stock_' type '(:,jdx+1:jdx+NumberOfPeriodsPerTYPEfiles,:);'])
eval(['idx = idx + size(stock_' type ',3);'])
end
%eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]);
jdx = jdx + NumberOfPeriodsPerTYPEfiles;
idx = 0;
end
eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),reste,B);'])
for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']);
eval(['STOCK_' CAPtype '(:,:,idx+1:idx+size(stock_' type ',3))=stock_' type '(:,jdx+1:jdx+reste,:);'])
eval(['idx = idx + size(stock_' type ',3);'])
end
%eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles) '.mat'],['STOCK_' CAPtype]);
else
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 ]);
end
% Original file format may be useful in some cases...
% for file = 1:NumberOfTYPEfiles
% delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat'])
% end
end
function ReshapeMatFiles(type, type2)
% function ReshapeMatFiles(type, type2)
% Reshapes and sorts (along the mcmc simulations) the mat files generated by DYNARE.
% 4D-arrays are splitted along the first dimension.
% 3D-arrays are splitted along the second dimension.
%
% INPUTS:
% type: statistics type in the repertory:
% dgse
% irf_bvardsge
% smooth
% filter
% error
% innov
% forcst
% forcst1
% type2: analysis type:
% posterior
% gsa
% prior
%
% OUTPUTS:
% none
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2007 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/>.
global M_ options_
if nargin==1,
MhDirectoryName = [ CheckPath('metropolis') '/' ];
else
if strcmpi(type2,'posterior')
MhDirectoryName = [CheckPath('metropolis') '/' ];
elseif strcmpi(type2,'gsa')
if options_.opt_gsa.morris==1,
MhDirectoryName = [CheckPath('GSA\SCREEN') '/' ];
elseif options_.opt_gsa.morris==2,
MhDirectoryName = [CheckPath('GSA\IDENTIF') '/' ];
else
MhDirectoryName = [CheckPath('GSA') '/' ];
end
else
MhDirectoryName = [CheckPath('prior') '/' ];
end
end
switch type
case 'irf_dsge'
CAPtype = 'IRF_DSGE';
TYPEsize = [ options_.irf , size(options_.varlist,1) , M_.exo_nbr ];
TYPEarray = 4;
case 'irf_bvardsge'
CAPtype = 'IRF_BVARDSGE';
TYPEsize = [ options_.irf , size(options_.varobs,1) , M_.exo_nbr ];
TYPEarray = 4;
case 'smooth'
CAPtype = 'SMOOTH';
TYPEsize = [ M_.endo_nbr , options_.nobs ];
TYPEarray = 3;
case 'filter'
CAPtype = 'FILTER';
TYPEsize = [ M_.endo_nbr , options_.nobs + 1 ];% TO BE CHECKED!
TYPEarray = 3;
case 'error'
CAPtype = 'ERROR';
TYPEsize = [ size(options_.varobs,1) , options_.nobs ];
TYPEarray = 3;
case 'innov'
CAPtype = 'INNOV';
TYPEsize = [ M_.exo_nbr , options_.nobs ];
TYPEarray = 3;
case 'forcst'
CAPtype = 'FORCST';
TYPEsize = [ M_.endo_nbr , options_.forecast ];
TYPEarray = 3;
case 'forcst1'
CAPtype = 'FORCST1';
TYPEsize = [ M_.endo_nbr , options_.forecast ];
TYPEarray = 3;
otherwise
disp('ReshapeMatFiles :: Unknown argument!')
return
end
TYPEfiles = dir([MhDirectoryName M_.fname '_' type '*.mat']);
NumberOfTYPEfiles = length(TYPEfiles);
B = options_.B;
switch TYPEarray
case 4
if NumberOfTYPEfiles > 1
NumberOfPeriodsPerTYPEfiles = ceil(TYPEsize(1)/NumberOfTYPEfiles);
foffset = NumberOfTYPEfiles-floor(TYPEsize(1)/NumberOfPeriodsPerTYPEfiles);
reste = TYPEsize(1)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-foffset);
idx = 0;
jdx = 0;
for f1=1:NumberOfTYPEfiles-foffset
eval(['STOCK_' CAPtype ' = zeros(NumberOfPeriodsPerTYPEfiles,TYPEsize(2),TYPEsize(3),B);'])
for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']);
eval(['STOCK_' CAPtype '(:,:,:,idx+1:idx+size(stock_' type ',4))=stock_' ...
type '(jdx+1:jdx+NumberOfPeriodsPerTYPEfiles,:,:,:);'])
eval(['idx = idx + size(stock_' type ',4);'])
end
%eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]);
jdx = jdx + NumberOfPeriodsPerTYPEfiles;
idx = 0;
end
if reste
eval(['STOCK_' CAPtype ' = zeros(reste,TYPEsize(2),TYPEsize(3),B);'])
for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']);
eval(['STOCK_' CAPtype '(:,:,:,idx+1:idx+size(stock_' type ',4))=stock_' type '(jdx+1:jdx+reste,:,:,:);'])
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]);
end
else
load([MhDirectoryName M_.fname '_' type '1.mat']);
%eval(['STOCK_' CAPtype ' = sort(stock_' type ',4);'])
eval(['STOCK_' CAPtype ' = stock_' type ';'])
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
% delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat'])
% end
case 3
if NumberOfTYPEfiles>1
NumberOfPeriodsPerTYPEfiles = ceil( TYPEsize(2)/NumberOfTYPEfiles );
reste = TYPEsize(2)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-1);
idx = 0;
jdx = 0;
for f1=1:NumberOfTYPEfiles-1
eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),NumberOfPeriodsPerTYPEfiles,B);'])
for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']);
eval(['STOCK_' CAPtype '(:,:,idx+1:idx+size(stock_ ' type ',3))=stock_' type '(:,jdx+1:jdx+NumberOfPeriodsPerTYPEfiles,:);'])
eval(['idx = idx + size(stock_' type ',3);'])
end
%eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]);
jdx = jdx + NumberOfPeriodsPerTYPEfiles;
idx = 0;
end
eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),reste,B);'])
for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']);
eval(['STOCK_' CAPtype '(:,:,idx+1:idx+size(stock_' type ',3))=stock_' type '(:,jdx+1:jdx+reste,:);'])
eval(['idx = idx + size(stock_' type ',3);'])
end
%eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles) '.mat'],['STOCK_' CAPtype]);
else
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 ]);
end
% Original file format may be useful in some cases...
% for file = 1:NumberOfTYPEfiles
% delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat'])
% end
end

View File

@ -1,179 +1,179 @@
function [omega,f] = UnivariateSpectralDensity(dr,var_list)
% This function computes the theoretical spectral density of each
% endogenous variable declared in var_list. Results are stored in
% oo_ and may be plotted.
%
% Adapted from th_autocovariances.m.
% Copyright (C) 2006-2009 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/>.
global options_ oo_ M_
omega = []; f = [];
if options_.order > 1
disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density')
disp('with a second order approximation of the DSGE model!')
disp('Set order = 1.')
return
end
pltinfo = 1;%options_.SpectralDensity.Th.plot;
cutoff = 150;%options_.SpectralDensity.Th.cutoff;
sdl = 0.01;%options_.SepctralDensity.Th.sdl;
omega = (0:sdl:pi)';
GridSize = length(omega);
exo_names_orig_ord = M_.exo_names_orig_ord;
if exist('OCTAVE_VERSION')
warning('off', 'Octave:divide-by-zero')
else
warning off MATLAB:dividebyzero
end
if nargin<2
var_list = [];
end
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
nvar = size(var_list,1);
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact');
if isempty(i_tmp)
error (['One of the variable specified does not exist']) ;
else
ivar(i) = i_tmp;
end
end
f = zeros(nvar,GridSize);
ghx = dr.ghx;
ghu = dr.ghu;
npred = dr.npred;
nstatic = dr.nstatic;
kstate = dr.kstate;
order = dr.order_var;
iv(order) = [1:length(order)];
nx = size(ghx,2);
ikx = [nstatic+1:nstatic+npred];
A = zeros(nx,nx);
k0 = kstate(find(kstate(:,2) <= M_.maximum_lag+1),:);
i0 = find(k0(:,2) == M_.maximum_lag+1);
i00 = i0;
n0 = length(i0);
A(i0,:) = ghx(ikx,:);
AS = ghx(:,i0);
ghu1 = zeros(nx,M_.exo_nbr);
ghu1(i0,:) = ghu(ikx,:);
for i=M_.maximum_lag:-1:2
i1 = find(k0(:,2) == i);
n1 = size(i1,1);
j1 = zeros(n1,1);
j2 = j1;
for k1 = 1:n1
j1(k1) = find(k0(i00,1)==k0(i1(k1),1));
j2(k1) = find(k0(i0,1)==k0(i1(k1),1));
end
AS(:,j1) = AS(:,j1)+ghx(:,i1);
i0 = i1;
end
Gamma = zeros(nvar,cutoff+1);
[A,B] = kalman_transition_matrix(dr,ikx',1:nx,dr.transition_auxiliary_variables,M_.exo_nbr);
[vx, u] = lyapunov_symm(A,B*M_.Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold);
iky = iv(ivar);
if ~isempty(u)
iky = iky(find(any(abs(ghx(iky,:)*u) < options_.Schur_vec_tol,2)));
ivar = dr.order_var(iky);
end
aa = ghx(iky,:);
bb = ghu(iky,:);
if options_.hp_filter == 0
tmp = aa*vx*aa'+ bb*M_.Sigma_e*bb';
k = find(abs(tmp) < 1e-12);
tmp(k) = 0;
Gamma(:,1) = diag(tmp);
vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb');
tmp = aa*vxy;
k = find(abs(tmp) < 1e-12);
tmp(k) = 0;
Gamma(:,2) = diag(tmp);
for i=2:cutoff
vxy = A*vxy;
tmp = aa*vxy;
k = find(abs(tmp) < 1e-12);
tmp(k) = 0;
Gamma(:,i+1) = diag(tmp);
end
else
iky = iv(ivar);
aa = ghx(iky,:);
bb = ghu(iky,:);
lambda = options_.hp_filter;
ngrid = options_.hp_ngrid;
freqs = 0 : ((2*pi)/ngrid) : (2*pi*(1 - .5/ngrid));
tpos = exp( sqrt(-1)*freqs);
tneg = exp(-sqrt(-1)*freqs);
hp1 = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2);
mathp_col = [];
IA = eye(size(A,1));
IE = eye(M_.exo_nbr);
for ig = 1:ngrid
f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*ghu1;IE]...
*M_.Sigma_e*[ghu1'*inv(IA-A'*tpos(ig)) IE]); % state variables
g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % selected variables
f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series
mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row
% for ifft
end;
imathp_col = real(ifft(mathp_col))*(2*pi);
tmp = reshape(imathp_col(1,:),nvar,nvar);
k = find(abs(tmp)<1e-12);
tmp(k) = 0;
Gamma(:,1) = diag(tmp);
sy = sqrt(Gamma(:,1));
sy = sy *sy';
for i=1:cutoff-1
tmp = reshape(imathp_col(i+1,:),nvar,nvar)./sy;
k = find(abs(tmp) < 1e-12);
tmp(k) = 0;
Gamma(:,i+1) = diag(tmp);
end
end
H = 1:cutoff;
for i=1:nvar
f(i,:) = Gamma(i,1)/(2*pi) + Gamma(i,H+1)*cos(H'*omega')/pi;
end
if exist('OCTAVE_VERSION')
warning('on', 'Octave:divide-by-zero')
else
warning on MATLAB:dividebyzero
end
if pltinfo
for i= 1:nvar
figure('Name',['Spectral Density of ' deblank(M_.endo_names(ivar(i),:)) '.'])
plot(omega,f(i,:),'-k','linewidth',2)
xlabel('0 \leq \omega \leq \pi')
ylabel('f(\omega)')
box on
axis tight
end
function [omega,f] = UnivariateSpectralDensity(dr,var_list)
% This function computes the theoretical spectral density of each
% endogenous variable declared in var_list. Results are stored in
% oo_ and may be plotted.
%
% Adapted from th_autocovariances.m.
% Copyright (C) 2006-2009 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/>.
global options_ oo_ M_
omega = []; f = [];
if options_.order > 1
disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density')
disp('with a second order approximation of the DSGE model!')
disp('Set order = 1.')
return
end
pltinfo = 1;%options_.SpectralDensity.Th.plot;
cutoff = 150;%options_.SpectralDensity.Th.cutoff;
sdl = 0.01;%options_.SepctralDensity.Th.sdl;
omega = (0:sdl:pi)';
GridSize = length(omega);
exo_names_orig_ord = M_.exo_names_orig_ord;
if exist('OCTAVE_VERSION')
warning('off', 'Octave:divide-by-zero')
else
warning off MATLAB:dividebyzero
end
if nargin<2
var_list = [];
end
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
nvar = size(var_list,1);
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact');
if isempty(i_tmp)
error (['One of the variable specified does not exist']) ;
else
ivar(i) = i_tmp;
end
end
f = zeros(nvar,GridSize);
ghx = dr.ghx;
ghu = dr.ghu;
npred = dr.npred;
nstatic = dr.nstatic;
kstate = dr.kstate;
order = dr.order_var;
iv(order) = [1:length(order)];
nx = size(ghx,2);
ikx = [nstatic+1:nstatic+npred];
A = zeros(nx,nx);
k0 = kstate(find(kstate(:,2) <= M_.maximum_lag+1),:);
i0 = find(k0(:,2) == M_.maximum_lag+1);
i00 = i0;
n0 = length(i0);
A(i0,:) = ghx(ikx,:);
AS = ghx(:,i0);
ghu1 = zeros(nx,M_.exo_nbr);
ghu1(i0,:) = ghu(ikx,:);
for i=M_.maximum_lag:-1:2
i1 = find(k0(:,2) == i);
n1 = size(i1,1);
j1 = zeros(n1,1);
j2 = j1;
for k1 = 1:n1
j1(k1) = find(k0(i00,1)==k0(i1(k1),1));
j2(k1) = find(k0(i0,1)==k0(i1(k1),1));
end
AS(:,j1) = AS(:,j1)+ghx(:,i1);
i0 = i1;
end
Gamma = zeros(nvar,cutoff+1);
[A,B] = kalman_transition_matrix(dr,ikx',1:nx,dr.transition_auxiliary_variables,M_.exo_nbr);
[vx, u] = lyapunov_symm(A,B*M_.Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold);
iky = iv(ivar);
if ~isempty(u)
iky = iky(find(any(abs(ghx(iky,:)*u) < options_.Schur_vec_tol,2)));
ivar = dr.order_var(iky);
end
aa = ghx(iky,:);
bb = ghu(iky,:);
if options_.hp_filter == 0
tmp = aa*vx*aa'+ bb*M_.Sigma_e*bb';
k = find(abs(tmp) < 1e-12);
tmp(k) = 0;
Gamma(:,1) = diag(tmp);
vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb');
tmp = aa*vxy;
k = find(abs(tmp) < 1e-12);
tmp(k) = 0;
Gamma(:,2) = diag(tmp);
for i=2:cutoff
vxy = A*vxy;
tmp = aa*vxy;
k = find(abs(tmp) < 1e-12);
tmp(k) = 0;
Gamma(:,i+1) = diag(tmp);
end
else
iky = iv(ivar);
aa = ghx(iky,:);
bb = ghu(iky,:);
lambda = options_.hp_filter;
ngrid = options_.hp_ngrid;
freqs = 0 : ((2*pi)/ngrid) : (2*pi*(1 - .5/ngrid));
tpos = exp( sqrt(-1)*freqs);
tneg = exp(-sqrt(-1)*freqs);
hp1 = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2);
mathp_col = [];
IA = eye(size(A,1));
IE = eye(M_.exo_nbr);
for ig = 1:ngrid
f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*ghu1;IE]...
*M_.Sigma_e*[ghu1'*inv(IA-A'*tpos(ig)) IE]); % state variables
g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % selected variables
f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series
mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row
% for ifft
end;
imathp_col = real(ifft(mathp_col))*(2*pi);
tmp = reshape(imathp_col(1,:),nvar,nvar);
k = find(abs(tmp)<1e-12);
tmp(k) = 0;
Gamma(:,1) = diag(tmp);
sy = sqrt(Gamma(:,1));
sy = sy *sy';
for i=1:cutoff-1
tmp = reshape(imathp_col(i+1,:),nvar,nvar)./sy;
k = find(abs(tmp) < 1e-12);
tmp(k) = 0;
Gamma(:,i+1) = diag(tmp);
end
end
H = 1:cutoff;
for i=1:nvar
f(i,:) = Gamma(i,1)/(2*pi) + Gamma(i,H+1)*cos(H'*omega')/pi;
end
if exist('OCTAVE_VERSION')
warning('on', 'Octave:divide-by-zero')
else
warning on MATLAB:dividebyzero
end
if pltinfo
for i= 1:nvar
figure('Name',['Spectral Density of ' deblank(M_.endo_names(ivar(i),:)) '.'])
plot(omega,f(i,:),'-k','linewidth',2)
xlabel('0 \leq \omega \leq \pi')
ylabel('f(\omega)')
box on
axis tight
end
end

View File

@ -1,7 +1,7 @@
function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ...
exo_steady_state, exo_det_steady_state,params)
exo_steady_state, exo_det_steady_state,params)
% Add auxiliary variables to the steady state vector
% Copyright (C) 2009 Dynare Team
%
% This file is part of Dynare.
@ -18,29 +18,28 @@ function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ...
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
n = length(aux_vars);
ys1 = [ys;zeros(n,1)];
k = size(ys,1)+1;
aux_lead_nbr = 0;
for i=1:n
if aux_vars(i).type == 1
ys1(k) = ys(aux_vars(i).orig_index);
elseif aux_vars(i).type == 0
aux_lead_nbr = aux_lead_nbr + 1;
end
k = k+1;
n = length(aux_vars);
ys1 = [ys;zeros(n,1)];
k = size(ys,1)+1;
aux_lead_nbr = 0;
for i=1:n
if aux_vars(i).type == 1
ys1(k) = ys(aux_vars(i).orig_index);
elseif aux_vars(i).type == 0
aux_lead_nbr = aux_lead_nbr + 1;
end
for i=1:aux_lead_nbr+1;
res = feval([fname '_static'],ys1,...
[exo_steady_state; ...
exo_det_steady_state],params);
for j=1:n
if aux_vars(j).type == 0
el = aux_vars(j).endo_index;
ys1(el) = ys1(el)-res(el);
end
k = k+1;
end
for i=1:aux_lead_nbr+1;
res = feval([fname '_static'],ys1,...
[exo_steady_state; ...
exo_det_steady_state],params);
for j=1:n
if aux_vars(j).type == 0
el = aux_vars(j).endo_index;
ys1(el) = ys1(el)-res(el);
end
end
end

View File

@ -59,28 +59,28 @@ function [InnovationVariance,AutoregressiveParameters] = autoregressive_process_
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
AutoregressiveParameters = NaN(p,1);
InnovationVariance = NaN;
switch p
case 1
AutoregressiveParameters = Rho(1);
case 2
tmp = (Rho(2)-1)/(Rho(1)*Rho(1)-1);
AutoregressiveParameters(1) = Rho(1)*tmp;
AutoregressiveParameters(2) = 1-tmp;
case 3
t1 = 1/(Rho(2)-2*Rho(1)*Rho(1)+1);
t2 = (1.5*Rho(1)-2*Rho(1)*Rho(1)*Rho(1)+.5*Rho(3))*t1;
t3 = .5*(Rho(1)- Rho(3))/(Rho(2)-1);
AutoregressiveParameters(1) = t2-t3-Rho(1);
AutoregressiveParameters(2) = (Rho(2)*Rho(2)-Rho(3)*Rho(1)-Rho(1)*Rho(1)+Rho(2))*t1 ;
AutoregressiveParameters(3) = t3-Rho(1)+t2;
otherwise
AutocorrelationMatrix = eye(p);
for i=1:p-1
AutocorrelationMatrix = AutocorrelationMatrix + diag(Rho(i)*ones(p-i,1),i);
AutocorrelationMatrix = AutocorrelationMatrix + diag(Rho(i)*ones(p-i,1),-i);
end
AutoregressiveParameters = AutocorrelationMatrix\Rho;
AutoregressiveParameters = NaN(p,1);
InnovationVariance = NaN;
switch p
case 1
AutoregressiveParameters = Rho(1);
case 2
tmp = (Rho(2)-1)/(Rho(1)*Rho(1)-1);
AutoregressiveParameters(1) = Rho(1)*tmp;
AutoregressiveParameters(2) = 1-tmp;
case 3
t1 = 1/(Rho(2)-2*Rho(1)*Rho(1)+1);
t2 = (1.5*Rho(1)-2*Rho(1)*Rho(1)*Rho(1)+.5*Rho(3))*t1;
t3 = .5*(Rho(1)- Rho(3))/(Rho(2)-1);
AutoregressiveParameters(1) = t2-t3-Rho(1);
AutoregressiveParameters(2) = (Rho(2)*Rho(2)-Rho(3)*Rho(1)-Rho(1)*Rho(1)+Rho(2))*t1 ;
AutoregressiveParameters(3) = t3-Rho(1)+t2;
otherwise
AutocorrelationMatrix = eye(p);
for i=1:p-1
AutocorrelationMatrix = AutocorrelationMatrix + diag(Rho(i)*ones(p-i,1),i);
AutocorrelationMatrix = AutocorrelationMatrix + diag(Rho(i)*ones(p-i,1),-i);
end
InnovationVariance = Variance * (1-AutoregressiveParameters'*Rho);
AutoregressiveParameters = AutocorrelationMatrix\Rho;
end
InnovationVariance = Variance * (1-AutoregressiveParameters'*Rho);

View File

@ -25,20 +25,20 @@ function H = bfgsi(H0,dg,dx)
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if size(dg,2)>1
dg=dg';
dg=dg';
end
if size(dx,2)>1
dx=dx';
dx=dx';
end
Hdg = H0*dg;
dgdx = dg'*dx;
if (abs(dgdx) >1e-12)
H = H0 + (1+(dg'*Hdg)/dgdx)*(dx*dx')/dgdx - (dx*Hdg'+Hdg*dx')/dgdx;
H = H0 + (1+(dg'*Hdg)/dgdx)*(dx*dx')/dgdx - (dx*Hdg'+Hdg*dx')/dgdx;
else
disp('bfgs update failed.')
disp(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))]);
disp(['dg''*dx = ' num2str(dgdx)])
disp(['|H*dg| = ' num2str(Hdg'*Hdg)])
H=H0;
disp('bfgs update failed.')
disp(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))]);
disp(['dg''*dx = ' num2str(dgdx)])
disp(['|H*dg| = ' num2str(Hdg'*Hdg)])
H=H0;
end
save H.dat H

View File

@ -17,20 +17,20 @@ function [x,status]=bicgstab_(func,b,x,tole,kmax,varargin)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
status = 0;
r=b-feval(func,x,varargin{:});
rh_0 = r;
rh = r;
rho_0 = 1;
alpha = 1;
w = 1;
v = 0;
p = 0;
k = 0;
rho_1 = rh_0'*r;
tolr = tole*norm(b);
while norm(r) > tolr & k < kmax
status = 0;
r=b-feval(func,x,varargin{:});
rh_0 = r;
rh = r;
rho_0 = 1;
alpha = 1;
w = 1;
v = 0;
p = 0;
k = 0;
rho_1 = rh_0'*r;
tolr = tole*norm(b);
while norm(r) > tolr & k < kmax
k = k+1;
beta = (rho_1/rho_0)*(alpha/w);
p = r+beta*(p-w*v);
@ -43,8 +43,8 @@ function [x,status]=bicgstab_(func,b,x,tole,kmax,varargin)
rho_1 = -w*(rh_0'*t);
x = x+alpha*p+w*r;
r = r-w*t;
end
end
if k == kmax
status = 1;
warning(sprintf('BICSTABN didn''t converge after %d iterations: norm(r) = %g',kmax,norm(r)));
status = 1;
warning(sprintf('BICSTABN didn''t converge after %d iterations: norm(r) = %g',kmax,norm(r)));
end

View File

@ -36,9 +36,9 @@ irf = iyf+(options_.periods-1)*ny ;
icf = [1:size(iyf,2)] ;
for i = 2:options_.periods
c(ir,jcf) = c(ir,jcf)-c(ir,icf)*c(irf,jcf) ;
ir = ir-ny ;
irf = irf-ny ;
c(ir,jcf) = c(ir,jcf)-c(ir,icf)*c(irf,jcf) ;
ir = ir-ny ;
irf = irf-ny ;
end
d = c(:,jcf) ;

View File

@ -49,28 +49,28 @@ ir = ir-ny ;
i = 2 ;
while i <= M_.maximum_lead | i <= options_.periods
irf1 = selif(irf,irf<=options_.periods*ny) ;
irf1 = selif(irf,irf<=options_.periods*ny) ;
ofs = (((options_.periods-i)*ny+1)-1)*jcf*8 ;
junk = fseek(fid,ofs,-1) ;
c = fread(fid,[jcf,ny],'float64')' ;
ofs = (((options_.periods-i)*ny+1)-1)*jcf*8 ;
junk = fseek(fid,ofs,-1) ;
c = fread(fid,[jcf,ny],'float64')' ;
d1(ir) = c(:,jcf) - c(:,1:size(irf1,1))*d1(irf1) ;
ir = ir - ny ;
irf = irf - ny ;
i = i + 1 ;
d1(ir) = c(:,jcf) - c(:,1:size(irf1,1))*d1(irf1) ;
ir = ir - ny ;
irf = irf - ny ;
i = i + 1 ;
end
while i <= options_.periods
ofs = (((options_.periods-i)*ny+1)-1)*jcf*8 ;
junk = fseek(fid,ofs,-1) ;
c = fread(fid,[jcf,ny],'float64')' ;
ofs = (((options_.periods-i)*ny+1)-1)*jcf*8 ;
junk = fseek(fid,ofs,-1) ;
c = fread(fid,[jcf,ny],'float64')' ;
d1(ir) = c(:,jcf)-c(:,icf)*d1(irf) ;
ir = ir-ny ;
irf = irf-ny ;
i = i+1;
d1(ir) = c(:,jcf)-c(:,icf)*d1(irf) ;
ir = ir-ny ;
irf = irf-ny ;
i = i+1;
end
return ;

View File

@ -19,12 +19,12 @@ function [r, g1] = block_mfs_steadystate(y, b)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_
ss = oo_.steady_state;
indx = M_.blocksMFS{b};
ss(indx) = y;
x = [oo_.exo_steady_state; oo_.exo_det_steady_state];
global M_ oo_
eval(['[r,g1] = ' M_.fname '_static(b, ss, x, M_.params);']);
ss = oo_.steady_state;
indx = M_.blocksMFS{b};
ss(indx) = y;
x = [oo_.exo_steady_state; oo_.exo_det_steady_state];
eval(['[r,g1] = ' M_.fname '_static(b, ss, x, M_.params);']);

View File

@ -23,26 +23,26 @@ s1=upper(deblank(s1));
s2=upper(deblank(s2));
for im = 1:m
key = s1(im,:) ;
h = size(s2,1) ;
l = 1 ;
while l <= h
mid = round((h+l)/2) ;
temp = s2(mid,:) ;
if ~ strcmp(key,temp)
for i = 1:min(length(key),length(temp))
if temp(i) > key(i)
h = mid - 1 ;
break
else
l = mid + 1 ;
break
end
end
else
x(im) = mid ;
break
end
end
key = s1(im,:) ;
h = size(s2,1) ;
l = 1 ;
while l <= h
mid = round((h+l)/2) ;
temp = s2(mid,:) ;
if ~ strcmp(key,temp)
for i = 1:min(length(key),length(temp))
if temp(i) > key(i)
h = mid - 1 ;
break
else
l = mid + 1 ;
break
end
end
else
x(im) = mid ;
break
end
end
end

View File

@ -29,21 +29,21 @@ function bvar_density(maxnlags)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
for nlags = 1:maxnlags
[ny, nx, posterior, prior] = bvar_toolbox(nlags);
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);
disp(' ')
fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ...
nlags, log_dnsty);
disp(' ')
end
for nlags = 1:maxnlags
[ny, nx, posterior, prior] = bvar_toolbox(nlags);
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);
disp(' ')
fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ...
nlags, log_dnsty);
disp(' ')
end
function w = matrictint(S, df, XXi)
@ -64,31 +64,31 @@ function w = matrictint(S, df, XXi)
% Original file downloaded from:
% http://sims.princeton.edu/yftp/VARtools/matlab/matrictint.m
k=size(XXi,1);
ny=size(S,1);
[cx,p]=chol(XXi);
[cs,q]=chol(S);
if any(diag(cx)<100*eps)
error('singular XXi')
end
if any(diag(cs<100*eps))
error('singular S')
end
k=size(XXi,1);
ny=size(S,1);
[cx,p]=chol(XXi);
[cs,q]=chol(S);
% Matrix-normal component
w1 = 0.5*k*ny*log(2*pi)+ny*sum(log(diag(cx)));
% Inverse-Wishart component
w2 = -df*sum(log(diag(cs))) + 0.5*df*ny*log(2) + ny*(ny-1)*0.25*log(pi) + ggammaln(ny, df);
w = w1 + w2;
if any(diag(cx)<100*eps)
error('singular XXi')
end
if any(diag(cs<100*eps))
error('singular S')
end
% Matrix-normal component
w1 = 0.5*k*ny*log(2*pi)+ny*sum(log(diag(cx)));
% Inverse-Wishart component
w2 = -df*sum(log(diag(cs))) + 0.5*df*ny*log(2) + ny*(ny-1)*0.25*log(pi) + ggammaln(ny, df);
w = w1 + w2;
function lgg = ggammaln(m, df)
if df <= (m-1)
error('too few df in ggammaln')
else
garg = 0.5*(df+(0:-1:1-m));
lgg = sum(gammaln(garg));
end
if df <= (m-1)
error('too few df in ggammaln')
else
garg = 0.5*(df+(0:-1:1-m));
lgg = sum(gammaln(garg));
end

View File

@ -28,158 +28,158 @@ function bvar_forecast(nlags)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_ oo_ M_
options_ = set_default_option(options_, 'bvar_replic', 2000);
if options_.forecast == 0
error('bvar_forecast: you must specify "forecast" option')
end
[ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags);
global options_ oo_ M_
sims_no_shock = NaN(options_.forecast, ny, options_.bvar_replic);
sims_with_shocks = NaN(options_.forecast, ny, options_.bvar_replic);
options_ = set_default_option(options_, 'bvar_replic', 2000);
if options_.forecast == 0
error('bvar_forecast: you must specify "forecast" option')
end
[ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags);
sims_no_shock = NaN(options_.forecast, ny, options_.bvar_replic);
sims_with_shocks = NaN(options_.forecast, ny, options_.bvar_replic);
S_inv_upper_chol = chol(inv(posterior.S));
% Option 'lower' of chol() not available in old versions of
% Matlab, so using transpose
XXi_lower_chol = chol(posterior.XXi)';
k = ny*nlags+nx;
% Declaration of the companion matrix
Companion_matrix = diag(ones(ny*(nlags-1),1),-ny);
% Number of explosive VAR models sampled
p = 0;
% Loop counter initialization
d = 0;
while d <= options_.bvar_replic
S_inv_upper_chol = chol(inv(posterior.S));
Sigma = rand_inverse_wishart(ny, posterior.df, S_inv_upper_chol);
% Option 'lower' of chol() not available in old versions of
% Matlab, so using transpose
XXi_lower_chol = chol(posterior.XXi)';
k = ny*nlags+nx;
% Declaration of the companion matrix
Companion_matrix = diag(ones(ny*(nlags-1),1),-ny);
% Number of explosive VAR models sampled
p = 0;
% Loop counter initialization
d = 0;
while d <= options_.bvar_replic
Sigma = rand_inverse_wishart(ny, posterior.df, S_inv_upper_chol);
Sigma_lower_chol = chol(Sigma)';
% Option 'lower' of chol() not available in old versions of
% Matlab, so using transpose
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,:)';
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
X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.xdata(t, :) ];
y = X * Phi;
lags_data(1:end-1,:) = lags_data(2:end, :);
lags_data(end,:) = y;
sims_no_shock(t, :, d) = y;
end
Phi = rand_matrix_normal(k, ny, posterior.PhiHat, Sigma_lower_chol, XXi_lower_chol);
% With shocks
lags_data = forecast_data.initval;
for t = 1:options_.forecast
X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.xdata(t, :) ];
shock = (Sigma_lower_chol * randn(ny, 1))';
y = X * Phi + shock;
lags_data(1:end-1,:) = lags_data(2:end, :);
lags_data(end,:) = y;
sims_with_shocks(t, :, d) = y;
end
% All the eigenvalues of the companion matrix have to be on or inside the unit circle
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
X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.xdata(t, :) ];
y = X * Phi;
lags_data(1:end-1,:) = lags_data(2:end, :);
lags_data(end,:) = y;
sims_no_shock(t, :, d) = y;
end
if p > 0
disp(' ')
disp(['Some of the VAR models sampled from the posterior distribution'])
disp(['were found to be explosive (' num2str(p/options_.bvar_replic) ' percent).'])
disp(' ')
% With shocks
lags_data = forecast_data.initval;
for t = 1:options_.forecast
X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.xdata(t, :) ];
shock = (Sigma_lower_chol * randn(ny, 1))';
y = X * Phi + shock;
lags_data(1:end-1,:) = lags_data(2:end, :);
lags_data(end,:) = y;
sims_with_shocks(t, :, d) = y;
end
end
if p > 0
disp(' ')
disp(['Some of the VAR models sampled from the posterior distribution'])
disp(['were found to be explosive (' num2str(p/options_.bvar_replic) ' percent).'])
disp(' ')
end
% Plot graphs
sims_no_shock_mean = mean(sims_no_shock, 3);
sort_idx = round((0.5 + [-options_.conf_sig, options_.conf_sig, 0]/2) * options_.bvar_replic);
sims_no_shock_sort = sort(sims_no_shock, 3);
sims_no_shock_down_conf = sims_no_shock_sort(:, :, sort_idx(1));
sims_no_shock_up_conf = sims_no_shock_sort(:, :, sort_idx(2));
sims_no_shock_median = sims_no_shock_sort(:, :, sort_idx(3));
sims_with_shocks_sort = sort(sims_with_shocks, 3);
sims_with_shocks_down_conf = sims_with_shocks_sort(:, :, sort_idx(1));
sims_with_shocks_up_conf = sims_with_shocks_sort(:, :, sort_idx(2));
dynare_graph_init(sprintf('BVAR forecasts (nlags = %d)', nlags), ny, {'b-' 'g-' 'g-' 'r-' 'r-'});
for i = 1:ny
dynare_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, :));
end
dynare_graph_close;
% 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, :) ];
y = X * posterior.PhiHat;
lags_data(1:end-1,:) = lags_data(2:end, :);
lags_data(end,:) = y;
sq_err_cumul = sq_err_cumul + (y - forecast_data.realized_val(t, :)) .^ 2;
end
% Plot graphs
sims_no_shock_mean = mean(sims_no_shock, 3);
rmse = sqrt(sq_err_cumul / size(sq_err_cumul, 1));
sort_idx = round((0.5 + [-options_.conf_sig, options_.conf_sig, 0]/2) * options_.bvar_replic);
fprintf('RMSE of BVAR(%d):\n', nlags);
sims_no_shock_sort = sort(sims_no_shock, 3);
sims_no_shock_down_conf = sims_no_shock_sort(:, :, sort_idx(1));
sims_no_shock_up_conf = sims_no_shock_sort(:, :, sort_idx(2));
sims_no_shock_median = sims_no_shock_sort(:, :, sort_idx(3));
sims_with_shocks_sort = sort(sims_with_shocks, 3);
sims_with_shocks_down_conf = sims_with_shocks_sort(:, :, sort_idx(1));
sims_with_shocks_up_conf = sims_with_shocks_sort(:, :, sort_idx(2));
dynare_graph_init(sprintf('BVAR forecasts (nlags = %d)', nlags), ny, {'b-' 'g-' 'g-' 'r-' 'r-'});
for i = 1:ny
dynare_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, :));
end
dynare_graph_close;
% 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, :) ];
y = X * posterior.PhiHat;
lags_data(1:end-1,:) = lags_data(2:end, :);
lags_data(end,:) = y;
sq_err_cumul = sq_err_cumul + (y - forecast_data.realized_val(t, :)) .^ 2;
end
rmse = sqrt(sq_err_cumul / size(sq_err_cumul, 1));
fprintf('RMSE of BVAR(%d):\n', nlags);
for i = 1:size(options_.varobs, 1)
fprintf('%s: %10.4f\n', options_.varobs(i, :), rmse(i));
end
end
% Store results
DirectoryName = [ M_.fname '/bvar_forecast' ];
if ~isdir(DirectoryName)
if ~isdir(M_.fname)
mkdir(M_.fname);
end
mkdir(DirectoryName);
end
save([ DirectoryName '/simulations.mat'], 'sims_no_shock', 'sims_with_shocks');
for i = 1:size(options_.varobs, 1)
name = options_.varobs(i, :);
fprintf('%s: %10.4f\n', options_.varobs(i, :), rmse(i));
end
end
sims = squeeze(sims_with_shocks(:,i,:));
eval(['oo_.bvar.forecast.with_shocks.Mean.' name ' = mean(sims, 2);']);
eval(['oo_.bvar.forecast.with_shocks.Median.' name ' = median(sims, 2);']);
eval(['oo_.bvar.forecast.with_shocks.Var.' name ' = var(sims, 0, 2);']);
eval(['oo_.bvar.forecast.with_shocks.HPDsup.' name ' = sims_with_shocks_up_conf(:,i);']);
eval(['oo_.bvar.forecast.with_shocks.HPDinf.' name ' = sims_with_shocks_down_conf(:,i);']);
% Store results
sims = squeeze(sims_no_shock(:,i,:));
eval(['oo_.bvar.forecast.no_shock.Mean.' name ' = sims_no_shock_mean(:,i);']);
eval(['oo_.bvar.forecast.no_shock.Median.' name ' = sims_no_shock_median(:,i);']);
eval(['oo_.bvar.forecast.no_shock.Var.' name ' = var(sims, 0, 2);']);
eval(['oo_.bvar.forecast.no_shock.HPDsup.' name ' = sims_no_shock_up_conf(:,i);']);
eval(['oo_.bvar.forecast.no_shock.HPDinf.' name ' = sims_no_shock_down_conf(:,i);']);
if exist('rmse')
eval(['oo_.bvar.forecast.rmse.' name ' = rmse(i);']);
end
DirectoryName = [ M_.fname '/bvar_forecast' ];
if ~isdir(DirectoryName)
if ~isdir(M_.fname)
mkdir(M_.fname);
end
mkdir(DirectoryName);
end
save([ DirectoryName '/simulations.mat'], 'sims_no_shock', 'sims_with_shocks');
for i = 1:size(options_.varobs, 1)
name = options_.varobs(i, :);
sims = squeeze(sims_with_shocks(:,i,:));
eval(['oo_.bvar.forecast.with_shocks.Mean.' name ' = mean(sims, 2);']);
eval(['oo_.bvar.forecast.with_shocks.Median.' name ' = median(sims, 2);']);
eval(['oo_.bvar.forecast.with_shocks.Var.' name ' = var(sims, 0, 2);']);
eval(['oo_.bvar.forecast.with_shocks.HPDsup.' name ' = sims_with_shocks_up_conf(:,i);']);
eval(['oo_.bvar.forecast.with_shocks.HPDinf.' name ' = sims_with_shocks_down_conf(:,i);']);
sims = squeeze(sims_no_shock(:,i,:));
eval(['oo_.bvar.forecast.no_shock.Mean.' name ' = sims_no_shock_mean(:,i);']);
eval(['oo_.bvar.forecast.no_shock.Median.' name ' = sims_no_shock_median(:,i);']);
eval(['oo_.bvar.forecast.no_shock.Var.' name ' = var(sims, 0, 2);']);
eval(['oo_.bvar.forecast.no_shock.HPDsup.' name ' = sims_no_shock_up_conf(:,i);']);
eval(['oo_.bvar.forecast.no_shock.HPDinf.' name ' = sims_no_shock_down_conf(:,i);']);
if exist('rmse')
eval(['oo_.bvar.forecast.rmse.' name ' = rmse(i);']);
end
end

View File

@ -28,125 +28,125 @@ function bvar_irf(nlags,identification)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_ oo_ M_
if nargin==1
identification = 'Cholesky';
end
options_ = set_default_option(options_, 'bvar_replic', 2000);
global options_ oo_ M_
[ny, nx, posterior, prior] = bvar_toolbox(nlags);
S_inv_upper_chol = chol(inv(posterior.S));
if nargin==1
identification = 'Cholesky';
end
% Option 'lower' of chol() not available in old versions of
% Matlab, so using transpose
XXi_lower_chol = chol(posterior.XXi)';
k = ny*nlags+nx;
% Declaration of the companion matrix
Companion_matrix = diag(ones(ny*(nlags-1),1),-ny);
% Number of explosive VAR models sampled
p = 0;
options_ = set_default_option(options_, 'bvar_replic', 2000);
% Initialize a four dimensional array.
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);
Sigma_lower_chol = transpose(Sigma_upper_chol);
[ny, nx, posterior, prior] = bvar_toolbox(nlags);
% 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,:));
% 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)));
if any(test>1.0000000000001)
p = p+1;
end
S_inv_upper_chol = chol(inv(posterior.S));
if strcmpi(identification,'Cholesky')
StructuralMat = Sigma_lower_chol;
elseif strcmpi(identification,'SquareRoot')
StructuralMat = sqrtm(Sigma);
end
% Build the IRFs...
lags_data = zeros(ny,ny*nlags) ;
sampled_irfs(:,:,1,draw) = Sigma_lower_chol ;
lags_data(:,1:ny) = Sigma_lower_chol ;
for t=2:options_.irf
sampled_irfs(:,:,t,draw) = lags_data(:,:)*Phi(1:ny*nlags,:) ;
lags_data(:,ny+1:end) = lags_data(:,1:end-ny) ;
lags_data(:,1:ny) = sampled_irfs(:,:,t,draw) ;
end
end
% Option 'lower' of chol() not available in old versions of
% Matlab, so using transpose
XXi_lower_chol = chol(posterior.XXi)';
k = ny*nlags+nx;
% Declaration of the companion matrix
Companion_matrix = diag(ones(ny*(nlags-1),1),-ny);
% Number of explosive VAR models sampled
p = 0;
% Initialize a four dimensional array.
sampled_irfs = NaN(ny, ny, options_.irf, options_.bvar_replic);
for draw=1:options_.bvar_replic
if p > 0
disp(' ')
disp(['Some of the VAR models sampled from the posterior distribution'])
disp(['were found to be explosive (' int2str(p) ' samples).'])
disp(' ')
% 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);
Sigma_lower_chol = transpose(Sigma_upper_chol);
% 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,:));
% 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)));
if any(test>1.0000000000001)
p = p+1;
end
posterior_mean_irfs = mean(sampled_irfs,4);
posterior_variance_irfs = var(sampled_irfs, 1, 4);
sorted_irfs = sort(sampled_irfs,4);
sort_idx = round((0.5 + [-options_.conf_sig, options_.conf_sig, .0]/2) * options_.bvar_replic);
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));
number_of_columns = fix(sqrt(ny));
number_of_rows = ceil(ny / number_of_columns) ;
% Plots of the IRFs
for shock=1:ny
figure('Name',['Posterior BVAR Impulse Responses (shock in equation ' int2str(shock) ').']);
for variable=1:ny
subplot(number_of_rows,number_of_columns,variable);
h1 = area(1:options_.irf,squeeze(posterior_up_conf_irfs(shock,variable,:)));
set(h1,'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))]))
set(h1,'FaceColor',[.9 .9 .9])
hold on
h2 = area(1:options_.irf,squeeze(posterior_down_conf_irfs(shock,variable,:)));
set(h2,'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))]))
set(h2,'FaceColor',[1 1 1])
plot(1:options_.irf,squeeze(posterior_median_irfs(shock,variable,:)),'-k','linewidth',2)
axis tight
hold off
end
if strcmpi(identification,'Cholesky')
StructuralMat = Sigma_lower_chol;
elseif strcmpi(identification,'SquareRoot')
StructuralMat = sqrtm(Sigma);
end
% Save intermediate results
DirectoryName = [ M_.fname '/bvar_irf' ];
if ~isdir(DirectoryName)
mkdir('.',DirectoryName);
% Build the IRFs...
lags_data = zeros(ny,ny*nlags) ;
sampled_irfs(:,:,1,draw) = Sigma_lower_chol ;
lags_data(:,1:ny) = Sigma_lower_chol ;
for t=2:options_.irf
sampled_irfs(:,:,t,draw) = lags_data(:,:)*Phi(1:ny*nlags,:) ;
lags_data(:,ny+1:end) = lags_data(:,1:end-ny) ;
lags_data(:,1:ny) = sampled_irfs(:,:,t,draw) ;
end
save([ DirectoryName '/simulations.mat'], 'sampled_irfs');
end
% Save results in oo_
for i=1:ny
shock_name = options_.varobs(i, :);
for j=1:ny
variable_name = options_.varobs(j, :);
eval(['oo_.bvar.irf.Mean.' variable_name '.' shock_name ' = posterior_mean_irfs(' int2str(j) ',' int2str(i) ',:);'])
eval(['oo_.bvar.irf.Median.' variable_name '.' shock_name ' = posterior_median_irfs(' int2str(j) ',' int2str(i) ',:);'])
eval(['oo_.bvar.irf.Var.' variable_name '.' shock_name ' = posterior_variance_irfs(' int2str(j) ',' int2str(i) ',:);'])
eval(['oo_.bvar.irf.Upper_bound.' variable_name '.' shock_name ' = posterior_up_conf_irfs(' int2str(j) ',' int2str(i) ',:);'])
eval(['oo_.bvar.irf.Lower_bound.' variable_name '.' shock_name ' = posterior_down_conf_irfs(' int2str(j) ',' int2str(i) ',:);'])
end
end
if p > 0
disp(' ')
disp(['Some of the VAR models sampled from the posterior distribution'])
disp(['were found to be explosive (' int2str(p) ' samples).'])
disp(' ')
end
posterior_mean_irfs = mean(sampled_irfs,4);
posterior_variance_irfs = var(sampled_irfs, 1, 4);
sorted_irfs = sort(sampled_irfs,4);
sort_idx = round((0.5 + [-options_.conf_sig, options_.conf_sig, .0]/2) * options_.bvar_replic);
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));
number_of_columns = fix(sqrt(ny));
number_of_rows = ceil(ny / number_of_columns) ;
% Plots of the IRFs
for shock=1:ny
figure('Name',['Posterior BVAR Impulse Responses (shock in equation ' int2str(shock) ').']);
for variable=1:ny
subplot(number_of_rows,number_of_columns,variable);
h1 = area(1:options_.irf,squeeze(posterior_up_conf_irfs(shock,variable,:)));
set(h1,'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))]))
set(h1,'FaceColor',[.9 .9 .9])
hold on
h2 = area(1:options_.irf,squeeze(posterior_down_conf_irfs(shock,variable,:)));
set(h2,'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))]))
set(h2,'FaceColor',[1 1 1])
plot(1:options_.irf,squeeze(posterior_median_irfs(shock,variable,:)),'-k','linewidth',2)
axis tight
hold off
end
end
% Save intermediate results
DirectoryName = [ M_.fname '/bvar_irf' ];
if ~isdir(DirectoryName)
mkdir('.',DirectoryName);
end
save([ DirectoryName '/simulations.mat'], 'sampled_irfs');
% Save results in oo_
for i=1:ny
shock_name = options_.varobs(i, :);
for j=1:ny
variable_name = options_.varobs(j, :);
eval(['oo_.bvar.irf.Mean.' variable_name '.' shock_name ' = posterior_mean_irfs(' int2str(j) ',' int2str(i) ',:);'])
eval(['oo_.bvar.irf.Median.' variable_name '.' shock_name ' = posterior_median_irfs(' int2str(j) ',' int2str(i) ',:);'])
eval(['oo_.bvar.irf.Var.' variable_name '.' shock_name ' = posterior_variance_irfs(' int2str(j) ',' int2str(i) ',:);'])
eval(['oo_.bvar.irf.Upper_bound.' variable_name '.' shock_name ' = posterior_up_conf_irfs(' int2str(j) ',' int2str(i) ',:);'])
eval(['oo_.bvar.irf.Lower_bound.' variable_name '.' shock_name ' = posterior_down_conf_irfs(' int2str(j) ',' int2str(i) ',:);'])
end
end

View File

@ -40,7 +40,7 @@ function [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags)
% This function uses the following Dynare options:
% - datafile, first_obs, varobs, xls_sheet, xls_range, nobs, presample
% - bvar_prior_{tau,decay,lambda,mu,omega,flat,train}
% Copyright (C) 2003-2007 Christopher Sims
% Copyright (C) 2007-2008 Dynare Team
%
@ -59,105 +59,105 @@ function [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_
% Load dataset
dataset = read_variables(options_.datafile, options_.varobs, [], options_.xls_sheet, options_.xls_range);
options_ = set_default_option(options_, 'nobs', size(dataset,1)-options_.first_obs+1);
% Parameters for prior
options_ = set_default_option(options_, 'bvar_prior_tau', 3);
options_ = set_default_option(options_, 'bvar_prior_decay', 0.5);
options_ = set_default_option(options_, 'bvar_prior_lambda', 5);
options_ = set_default_option(options_, 'bvar_prior_mu', 2);
options_ = set_default_option(options_, 'bvar_prior_omega', 1);
options_ = set_default_option(options_, 'bvar_prior_flat', 0);
options_ = set_default_option(options_, 'bvar_prior_train', 0);
if options_.first_obs + options_.presample <= nlags
error('first_obs+presample should be > nlags (for initializing the VAR)')
end
global options_
train = options_.bvar_prior_train;
if options_.first_obs + options_.presample - train <= nlags
error('first_obs+presample-train should be > nlags (for initializating the VAR)')
end
% Load dataset
dataset = read_variables(options_.datafile, options_.varobs, [], options_.xls_sheet, options_.xls_range);
options_ = set_default_option(options_, 'nobs', size(dataset,1)-options_.first_obs+1);
idx = options_.first_obs+options_.presample-train-nlags:options_.first_obs+options_.nobs-1;
% Prepare dataset
if options_.loglinear & ~options_.logdata
dataset = log(dataset);
end
if options_.prefilter
dataset(idx,:) = dataset(idx,:) - ones(length(idx),1)*mean(dataset(idx,:));
end
mnprior.tight = options_.bvar_prior_tau;
mnprior.decay = options_.bvar_prior_decay;
% Parameters for prior
options_ = set_default_option(options_, 'bvar_prior_tau', 3);
options_ = set_default_option(options_, 'bvar_prior_decay', 0.5);
options_ = set_default_option(options_, 'bvar_prior_lambda', 5);
options_ = set_default_option(options_, 'bvar_prior_mu', 2);
options_ = set_default_option(options_, 'bvar_prior_omega', 1);
options_ = set_default_option(options_, 'bvar_prior_flat', 0);
options_ = set_default_option(options_, 'bvar_prior_train', 0);
% Use only initializations lags for the variance prior
vprior.sig = std(dataset(options_.first_obs+options_.presample-nlags:options_.first_obs+options_.presample-1,:))';
vprior.w = options_.bvar_prior_omega;
if options_.first_obs + options_.presample <= nlags
error('first_obs+presample should be > nlags (for initializing the VAR)')
end
lambda = options_.bvar_prior_lambda;
mu = options_.bvar_prior_mu;
flat = options_.bvar_prior_flat;
ny = size(dataset, 2);
if options_.prefilter | options_.noconstant
nx = 0;
train = options_.bvar_prior_train;
if options_.first_obs + options_.presample - train <= nlags
error('first_obs+presample-train should be > nlags (for initializating the VAR)')
end
idx = options_.first_obs+options_.presample-train-nlags:options_.first_obs+options_.nobs-1;
% Prepare dataset
if options_.loglinear & ~options_.logdata
dataset = log(dataset);
end
if options_.prefilter
dataset(idx,:) = dataset(idx,:) - ones(length(idx),1)*mean(dataset(idx,:));
end
mnprior.tight = options_.bvar_prior_tau;
mnprior.decay = options_.bvar_prior_decay;
% Use only initializations lags for the variance prior
vprior.sig = std(dataset(options_.first_obs+options_.presample-nlags:options_.first_obs+options_.presample-1,:))';
vprior.w = options_.bvar_prior_omega;
lambda = options_.bvar_prior_lambda;
mu = options_.bvar_prior_mu;
flat = options_.bvar_prior_flat;
ny = size(dataset, 2);
if options_.prefilter | options_.noconstant
nx = 0;
else
nx = 1;
end
[ydum, xdum, pbreaks] = varprior(ny, nx, nlags, mnprior, vprior);
ydata = dataset(idx, :);
T = size(ydata, 1);
xdata = ones(T,nx);
% Posterior density
var = rfvar3([ydata; ydum], nlags, [xdata; xdum], [T; T+pbreaks], lambda, mu);
Tu = size(var.u, 1);
posterior.df = Tu - ny*nlags - nx - flat*(ny+1);
posterior.S = var.u' * var.u;
posterior.XXi = var.xxi;
posterior.PhiHat = var.B;
% Prior density
Tp = train + nlags;
if nx
xdata = xdata(1:Tp, :);
else
xdata = [];
end
varp = rfvar3([ydata(1:Tp, :); ydum], nlags, [xdata; xdum], [Tp; Tp + pbreaks], lambda, mu);
Tup = size(varp.u, 1);
prior.df = Tup - ny*nlags - nx - flat*(ny+1);
prior.S = varp.u' * varp.u;
prior.XXi = varp.xxi;
prior.PhiHat = varp.B;
if prior.df < ny
error('Too few degrees of freedom in the inverse-Wishart part of prior distribution. You should increase training sample size.')
end
% Add forecast informations
if nargout >= 5
forecast_data.xdata = ones(options_.forecast, nx);
forecast_data.initval = ydata(end-nlags+1:end, :);
if options_.first_obs + options_.nobs <= size(dataset, 1)
forecast_data.realized_val = dataset(options_.first_obs+options_.nobs:end, :);
forecast_data.realized_xdata = ones(size(forecast_data.realized_val, 1), nx);
else
nx = 1;
forecast_data.realized_val = [];
end
[ydum, xdum, pbreaks] = varprior(ny, nx, nlags, mnprior, vprior);
ydata = dataset(idx, :);
T = size(ydata, 1);
xdata = ones(T,nx);
end
% Posterior density
var = rfvar3([ydata; ydum], nlags, [xdata; xdum], [T; T+pbreaks], lambda, mu);
Tu = size(var.u, 1);
posterior.df = Tu - ny*nlags - nx - flat*(ny+1);
posterior.S = var.u' * var.u;
posterior.XXi = var.xxi;
posterior.PhiHat = var.B;
% Prior density
Tp = train + nlags;
if nx
xdata = xdata(1:Tp, :);
else
xdata = [];
end
varp = rfvar3([ydata(1:Tp, :); ydum], nlags, [xdata; xdum], [Tp; Tp + pbreaks], lambda, mu);
Tup = size(varp.u, 1);
prior.df = Tup - ny*nlags - nx - flat*(ny+1);
prior.S = varp.u' * varp.u;
prior.XXi = varp.xxi;
prior.PhiHat = varp.B;
if prior.df < ny
error('Too few degrees of freedom in the inverse-Wishart part of prior distribution. You should increase training sample size.')
end
% Add forecast informations
if nargout >= 5
forecast_data.xdata = ones(options_.forecast, nx);
forecast_data.initval = ydata(end-nlags+1:end, :);
if options_.first_obs + options_.nobs <= size(dataset, 1)
forecast_data.realized_val = dataset(options_.first_obs+options_.nobs:end, :);
forecast_data.realized_xdata = ones(size(forecast_data.realized_val, 1), nx);
else
forecast_data.realized_val = [];
end
end
function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior)
%function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior)
@ -185,41 +185,41 @@ function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior)
% Original file downloaded from:
% http://sims.princeton.edu/yftp/VARtools/matlab/varprior.m
if ~isempty(mnprior)
xdum = zeros(lags+1,nx,lags,nv);
ydum = zeros(lags+1,nv,lags,nv);
for il = 1:lags
ydum(il+1,:,il,:) = il^mnprior.decay*diag(vprior.sig);
end
ydum(1,:,1,:) = diag(vprior.sig);
ydum = mnprior.tight*reshape(ydum,[lags+1,nv,lags*nv]);
ydum = flipdim(ydum,1);
xdum = mnprior.tight*reshape(xdum,[lags+1,nx,lags*nv]);
xdum = flipdim(xdum,1);
breaks = (lags+1)*[1:(nv*lags)]';
if ~isempty(mnprior)
xdum = zeros(lags+1,nx,lags,nv);
ydum = zeros(lags+1,nv,lags,nv);
for il = 1:lags
ydum(il+1,:,il,:) = il^mnprior.decay*diag(vprior.sig);
end
ydum(1,:,1,:) = diag(vprior.sig);
ydum = mnprior.tight*reshape(ydum,[lags+1,nv,lags*nv]);
ydum = flipdim(ydum,1);
xdum = mnprior.tight*reshape(xdum,[lags+1,nx,lags*nv]);
xdum = flipdim(xdum,1);
breaks = (lags+1)*[1:(nv*lags)]';
lbreak = breaks(end);
else
ydum = [];
xdum = [];
breaks = [];
lbreak = 0;
end
if ~isempty(vprior) & vprior.w>0
ydum2 = zeros(lags+1,nv,nv);
xdum2 = zeros(lags+1,nx,nv);
ydum2(end,:,:) = diag(vprior.sig);
for i = 1:vprior.w
ydum = cat(3,ydum,ydum2);
xdum = cat(3,xdum,xdum2);
breaks = [breaks;(lags+1)*[1:nv]'+lbreak];
lbreak = breaks(end);
else
ydum = [];
xdum = [];
breaks = [];
lbreak = 0;
end
if ~isempty(vprior) & vprior.w>0
ydum2 = zeros(lags+1,nv,nv);
xdum2 = zeros(lags+1,nx,nv);
ydum2(end,:,:) = diag(vprior.sig);
for i = 1:vprior.w
ydum = cat(3,ydum,ydum2);
xdum = cat(3,xdum,xdum2);
breaks = [breaks;(lags+1)*[1:nv]'+lbreak];
lbreak = breaks(end);
end
end
dimy = size(ydum);
ydum = reshape(permute(ydum,[1 3 2]),dimy(1)*dimy(3),nv);
xdum = reshape(permute(xdum,[1 3 2]),dimy(1)*dimy(3),nx);
breaks = breaks(1:(end-1));
end
dimy = size(ydum);
ydum = reshape(permute(ydum,[1 3 2]),dimy(1)*dimy(3),nv);
xdum = reshape(permute(xdum,[1 3 2]),dimy(1)*dimy(3),nx);
breaks = breaks(1:(end-1));
function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)
%function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)
@ -253,74 +253,74 @@ function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)
% Original file downloaded from:
% http://sims.princeton.edu/yftp/VARtools/matlab/rfvar3.m
[T,nvar] = size(ydata);
nox = isempty(xdata);
[T,nvar] = size(ydata);
nox = isempty(xdata);
if ~nox
[T2,nx] = size(xdata);
else
T2 = T;
nx = 0;
xdata = zeros(T2,0);
end
% note that x must be same length as y, even though first part of x will not be used.
% This is so that the lags parameter can be changed without reshaping the xdata matrix.
if T2 ~= T, error('Mismatch of x and y data lengths'),end
if nargin < 4
nbreaks = 0;
breaks = [];
else
nbreaks = length(breaks);
end
breaks = [0;breaks;T];
smpl = [];
for nb = 1:nbreaks+1
smpl = [smpl;[breaks(nb)+lags+1:breaks(nb+1)]'];
end
Tsmpl = size(smpl,1);
X = zeros(Tsmpl,nvar,lags);
for is = 1:length(smpl)
X(is,:,:) = ydata(smpl(is)-(1:lags),:)';
end
X = [X(:,:) xdata(smpl,:)];
y = ydata(smpl,:);
% Everything now set up with input data for y=Xb+e
% Add persistence dummies
if lambda ~= 0 | mu > 0
ybar = mean(ydata(1:lags,:),1);
if ~nox
[T2,nx] = size(xdata);
xbar = mean(xdata(1:lags,:),1);
else
T2 = T;
nx = 0;
xdata = zeros(T2,0);
xbar = [];
end
% note that x must be same length as y, even though first part of x will not be used.
% This is so that the lags parameter can be changed without reshaping the xdata matrix.
if T2 ~= T, error('Mismatch of x and y data lengths'),end
if nargin < 4
nbreaks = 0;
breaks = [];
else
nbreaks = length(breaks);
end
breaks = [0;breaks;T];
smpl = [];
for nb = 1:nbreaks+1
smpl = [smpl;[breaks(nb)+lags+1:breaks(nb+1)]'];
end
Tsmpl = size(smpl,1);
X = zeros(Tsmpl,nvar,lags);
for is = 1:length(smpl)
X(is,:,:) = ydata(smpl(is)-(1:lags),:)';
end
X = [X(:,:) xdata(smpl,:)];
y = ydata(smpl,:);
% Everything now set up with input data for y=Xb+e
% Add persistence dummies
if lambda ~= 0 | mu > 0
ybar = mean(ydata(1:lags,:),1);
if ~nox
xbar = mean(xdata(1:lags,:),1);
if lambda ~= 0
if lambda>0
xdum = lambda*[repmat(ybar,1,lags) xbar];
else
xbar = [];
end
if lambda ~= 0
if lambda>0
xdum = lambda*[repmat(ybar,1,lags) xbar];
else
lambda = -lambda;
xdum = lambda*[repmat(ybar,1,lags) zeros(size(xbar))];
end
ydum = zeros(1,nvar);
ydum(1,:) = lambda*ybar;
y = [y;ydum];
X = [X;xdum];
end
if mu>0
xdum = [repmat(diag(ybar),1,lags) zeros(nvar,nx)]*mu;
ydum = mu*diag(ybar);
X = [X;xdum];
y = [y;ydum];
lambda = -lambda;
xdum = lambda*[repmat(ybar,1,lags) zeros(size(xbar))];
end
ydum = zeros(1,nvar);
ydum(1,:) = lambda*ybar;
y = [y;ydum];
X = [X;xdum];
end
% Compute OLS regression and residuals
[vl,d,vr] = svd(X,0);
di = 1./diag(d);
B = (vr.*repmat(di',nvar*lags+nx,1))*vl'*y;
u = y-X*B;
xxi = vr.*repmat(di',nvar*lags+nx,1);
xxi = xxi*xxi';
var.B = B;
var.u = u;
var.xxi = xxi;
if mu>0
xdum = [repmat(diag(ybar),1,lags) zeros(nvar,nx)]*mu;
ydum = mu*diag(ybar);
X = [X;xdum];
y = [y;ydum];
end
end
% Compute OLS regression and residuals
[vl,d,vr] = svd(X,0);
di = 1./diag(d);
B = (vr.*repmat(di',nvar*lags+nx,1))*vl'*y;
u = y-X*B;
xxi = vr.*repmat(di',nvar*lags+nx,1);
xxi = xxi*xxi';
var.B = B;
var.u = u;
var.xxi = xxi;

View File

@ -17,177 +17,177 @@ function M_.Sigma_e = calib(var_indices,targets,var_weights,nar,cova,M_.Sigma_e)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global oo_ M_ vx
ncstr = 0;
ni = size(var_indices,1);
for i=1:nar+3
ncstr = ncstr + size(var_indices{i},1);
end
if cova
if ncstr < M_.exo_nbr*(M_.exo_nbr+1)/2
error(['number of preset variances is smaller than number of shock' ...
' variances and covariances to be estimated !'])
end
else
if ncstr < M_.exo_nbr
error(['number of preset variances is smaller than number of shock' ...
' variances to be estimated !'])
end
end
% computes approximate solution at order 1
dr = resol(oo_.steady_state,0,0,1);
ghx = dr.ghx;
ghu = dr.ghu;
npred = dr.npred;
nstatic = dr.nstatic;
kstate = dr.kstate;
order = dr.order_var;
iv(order) = [1:M_.endo_nbr];
iv = iv';
nx = size(ghx,2);
global oo_ M_ vx
ikx = [nstatic+1:nstatic+npred];
A = zeros(nx,nx);
A(1:npred,:)=ghx(ikx,:);
offset_r = npred;
offset_c = 0;
i0 = find(kstate(:,2) == M_.maximum_lag+1);
n0 = size(i0,1);
for i=M_.maximum_lag:-1:2
ncstr = 0;
ni = size(var_indices,1);
for i=1:nar+3
ncstr = ncstr + size(var_indices{i},1);
end
if cova
if ncstr < M_.exo_nbr*(M_.exo_nbr+1)/2
error(['number of preset variances is smaller than number of shock' ...
' variances and covariances to be estimated !'])
end
else
if ncstr < M_.exo_nbr
error(['number of preset variances is smaller than number of shock' ...
' variances to be estimated !'])
end
end
% computes approximate solution at order 1
dr = resol(oo_.steady_state,0,0,1);
ghx = dr.ghx;
ghu = dr.ghu;
npred = dr.npred;
nstatic = dr.nstatic;
kstate = dr.kstate;
order = dr.order_var;
iv(order) = [1:M_.endo_nbr];
iv = iv';
nx = size(ghx,2);
ikx = [nstatic+1:nstatic+npred];
A = zeros(nx,nx);
A(1:npred,:)=ghx(ikx,:);
offset_r = npred;
offset_c = 0;
i0 = find(kstate(:,2) == M_.maximum_lag+1);
n0 = size(i0,1);
for i=M_.maximum_lag:-1:2
i1 = find(kstate(:,2) == i);
n1 = size(i1,1);
j = zeros(n1,1);
for j1 = 1:n1
j(j1) = find(kstate(i0,1)==kstate(i1(j1),1));
j(j1) = find(kstate(i0,1)==kstate(i1(j1),1));
end
A(offset_r+1:offset_r+n1,offset_c+j)=eye(n1);
offset_r = offset_r + n1;
offset_c = offset_c + n0;
i0 = i1;
n0 = n1;
end
ghu1 = [ghu(ikx,:);zeros(nx-npred,M_.exo_nbr)];
end
ghu1 = [ghu(ikx,:);zeros(nx-npred,M_.exo_nbr)];
% IA = speye(nx*nx)-kron(A,A);
% kron_ghu = kron(ghu1,ghu1);
% vx1 such that vec(sigma_x) = vx1 * vec(M_.Sigma_e) (predetermined vars)
vx1 = [];
% vx1 = IA\kron_ghu;
IA = [];
kron_ghu = [];
% computes required variables and indices among required variables
iiy = [];
for i=1:nar+3
if i ~= 3 & ~isempty(var_indices{i})
iiy = union(iiy, iv(var_indices{i}(:,1)));
end
end
if ~isempty(var_indices{2})
iiy = union(iiy, iv(var_indices{2}(:,2)));
end
ny = size(iiy,1);
for i=1:nar+3
% vx1 such that vec(sigma_x) = vx1 * vec(M_.Sigma_e) (predetermined vars)
vx1 = [];
% vx1 = IA\kron_ghu;
IA = [];
kron_ghu = [];
% computes required variables and indices among required variables
iiy = [];
for i=1:nar+3
if i ~= 3 & ~isempty(var_indices{i})
var_indices{i}(:,1) = indnv(iv(var_indices{i}(:,1)),iiy);
iiy = union(iiy, iv(var_indices{i}(:,1)));
end
end
if ~isempty(var_indices{2})
iiy = union(iiy, iv(var_indices{2}(:,2)));
end
ny = size(iiy,1);
for i=1:nar+3
if i ~= 3 & ~isempty(var_indices{i})
var_indices{i}(:,1) = indnv(iv(var_indices{i}(:,1)),iiy);
end
if i ~= 2 & i ~= 3 & ~isempty(var_indices{i})
var_indices{i} = sub2ind([ny ny],var_indices{i},var_indices{i});
var_indices{i} = sub2ind([ny ny],var_indices{i},var_indices{i});
end
end
if ~isempty(var_indices{2})
end
if ~isempty(var_indices{2})
var_indices{2}(:,2) = indnv(iv(var_indices{2}(:,2)),iiy);
var_indices{2} = sub2ind([ny ny],var_indices{2}(:,1),var_indices{2}(:,2));
end
if ~isempty(var_indices{3})
end
if ~isempty(var_indices{3})
var_indices{3} = sub2ind([M_.exo_nbr M_.exo_nbr],var_indices{3}(:,1),var_indices{3}(:,2));
end
if isempty(M_.Sigma_e)
end
if isempty(M_.Sigma_e)
M_.Sigma_e = 0.01*eye(M_.exo_nbr);
b = 0.1*ghu1*ghu1';
else
else
b = ghu1*M_.Sigma_e*ghu1';
M_.Sigma_e = chol(M_.Sigma_e+1e-14*eye(M_.exo_nbr));
end
options=optimset('LargeScale','on','MaxFunEvals',20000*ny,'TolX',1e-4, ...
'TolFun',1e-4,'Display','Iter','MaxIter',10000);
end
options=optimset('LargeScale','on','MaxFunEvals',20000*ny,'TolX',1e-4, ...
'TolFun',1e-4,'Display','Iter','MaxIter',10000);
% [M_.Sigma_e,f]=fminunc(@calib_obj,M_.Sigma_e,options,A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar);
[M_.Sigma_e,f]=fmincon(@calib_obj,diag(M_.Sigma_e).^2,-eye(M_.exo_nbr),zeros(M_.exo_nbr,1),[],[],[],[],[],options,A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar);
M_.Sigma_e = diag(M_.Sigma_e);
objective = calib_obj2(diag(M_.Sigma_e),A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar);
disp('CALIBRATION')
disp('')
if ~isempty(var_indices{1})
[M_.Sigma_e,f]=fmincon(@calib_obj,diag(M_.Sigma_e).^2,-eye(M_.exo_nbr),zeros(M_.exo_nbr,1),[],[],[],[],[],options,A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar);
M_.Sigma_e = diag(M_.Sigma_e);
objective = calib_obj2(diag(M_.Sigma_e),A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar);
disp('CALIBRATION')
disp('')
if ~isempty(var_indices{1})
disp(sprintf('%16s %14s %14s %14s %14s','Std. Dev','Target','Obtained','Diff'));
str = ' ';
for i=1:size(var_indices{1},1)
[i1,i2] = ind2sub([ny ny],var_indices{1}(i));
str = sprintf('%16s: %14.2f %14.2f %14.2f',M_.endo_names(order(iiy(i1)),:),targets{1}(i),objective{1}(i),objective{1}(i)-targets{1}(i));
disp(str);
[i1,i2] = ind2sub([ny ny],var_indices{1}(i));
str = sprintf('%16s: %14.2f %14.2f %14.2f',M_.endo_names(order(iiy(i1)),:),targets{1}(i),objective{1}(i),objective{1}(i)-targets{1}(i));
disp(str);
end
end
if ~isempty(var_indices{2})
end
if ~isempty(var_indices{2})
disp(sprintf('%32s %14s %14s','Correlations','Target','Obtained','Diff'));
str = ' ';
for i=1:size(var_indices{2},1)
[i1,i2]=ind2sub([ny ny],var_indices{2}(i));
str = sprintf('%16s,%16s: %14.2f %14.2f %14.2f',M_.endo_names(order(iiy(i1)),:), ...
M_.endo_names(order(iiy(i2)),:),targets{2}(i),objective{2}(i),objective{2}(i)-targets{2}(i));
disp(str);
[i1,i2]=ind2sub([ny ny],var_indices{2}(i));
str = sprintf('%16s,%16s: %14.2f %14.2f %14.2f',M_.endo_names(order(iiy(i1)),:), ...
M_.endo_names(order(iiy(i2)),:),targets{2}(i),objective{2}(i),objective{2}(i)-targets{2}(i));
disp(str);
end
end
if ~isempty(var_indices{3})
end
if ~isempty(var_indices{3})
disp(sprintf('%32s %16s %16s','Constrained shocks (co)variances','Target','Obtained'));
str = ' ';
for i=1:size(var_indices{3},1)
[i1,i2]=ind2sub([M_.exo_nbr M_.exo_nbr],var_indices{3}(i));
if i1 == i2
str = sprintf('%32s: %16.4f %16.4f',M_.exo_name(order(i1),:), ...
targets{3}(i),objective{3}(i));
else
str = sprintf('%16s,%16s: %16.4f %16.4f',M_.exo_name(order(i1),:), ...
M_.exo_name(order(i2), :),targets{3}(i),objective{3}(i));
end
disp(str);
[i1,i2]=ind2sub([M_.exo_nbr M_.exo_nbr],var_indices{3}(i));
if i1 == i2
str = sprintf('%32s: %16.4f %16.4f',M_.exo_name(order(i1),:), ...
targets{3}(i),objective{3}(i));
else
str = sprintf('%16s,%16s: %16.4f %16.4f',M_.exo_name(order(i1),:), ...
M_.exo_name(order(i2), :),targets{3}(i),objective{3}(i));
end
disp(str);
end
end
flag = 1;
for j=4:nar+3
end
flag = 1;
for j=4:nar+3
if ~isempty(var_indices{j})
if flag
disp(sprintf('%16s %16s %16s','Autocorrelations','Target','Obtained'));
str = ' ';
flag = 0;
end
for i=1:size(var_indices{j},1)
[i1,i2] = ind2sub([ny ny],var_indices{j}(i));
str = sprintf('%16s(%d): %16.4f %16.4f',M_.endo_names(order(iiy(i1)),:), ...
j-3,targets{j}(i),objective{j}(i));
disp(str);
end
if flag
disp(sprintf('%16s %16s %16s','Autocorrelations','Target','Obtained'));
str = ' ';
flag = 0;
end
for i=1:size(var_indices{j},1)
[i1,i2] = ind2sub([ny ny],var_indices{j}(i));
str = sprintf('%16s(%d): %16.4f %16.4f',M_.endo_names(order(iiy(i1)),:), ...
j-3,targets{j}(i),objective{j}(i));
disp(str);
end
end
end
disp('');
disp('Calibrated variances')
str = ' ';
for i=1:M_.exo_nbr
str = [str sprintf('%16s',M_.exo_name(i,:))];
end
disp(str);
disp('');
str = ' ';
for i=1:M_.exo_nbr
str = [str sprintf('%16f',M_.Sigma_e(i,i))];
end
disp(str);
end
% 10/9/02 MJ
disp('');
disp('Calibrated variances')
str = ' ';
for i=1:M_.exo_nbr
str = [str sprintf('%16s',M_.exo_name(i,:))];
end
disp(str);
disp('');
str = ' ';
for i=1:M_.exo_nbr
str = [str sprintf('%16f',M_.Sigma_e(i,i))];
end
disp(str);
% 10/9/02 MJ

View File

@ -19,67 +19,66 @@ function f=calib_obj(M_.Sigma_e,A,ghu1,ghx,ghu,targets,var_weights,iy,nar)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global vx fold options_
oo_.gamma_y = cell(nar+1,1);
global vx fold options_
oo_.gamma_y = cell(nar+1,1);
% M_.Sigma_e = M_.Sigma_e'*M_.Sigma_e;
M_.Sigma_e=diag(M_.Sigma_e);
nx = size(ghx,2);
b=ghu1*M_.Sigma_e*ghu1';
vx = [];
if isempty(vx)
M_.Sigma_e=diag(M_.Sigma_e);
nx = size(ghx,2);
b=ghu1*M_.Sigma_e*ghu1';
vx = [];
if isempty(vx)
vx = lyapunov_symm(A,b,options_.qz_criterium,options_.lyapunov_complex_threshold);
else
else
[vx,status] = bicgstab_(@f_var,b(:),vx(:),1e-8,50,A,nx);
if status
vx = lyapunov_symm(A,b,options_.qz_criterium,options_.lyapunov_complex_threshold);
vx = lyapunov_symm(A,b,options_.qz_criterium,options_.lyapunov_complex_threshold);
else
vx=reshape(vx,nx,nx);
vx=reshape(vx,nx,nx);
end
end
oo_.gamma_y{1} = ghx*vx*ghx'+ ghu*M_.Sigma_e*ghu';
f = 0;
if ~isempty(targets{1})
end
oo_.gamma_y{1} = ghx*vx*ghx'+ ghu*M_.Sigma_e*ghu';
f = 0;
if ~isempty(targets{1})
e = targets{1}-sqrt(oo_.gamma_y{1}(iy{1}));
f = e'*(var_weights{1}.*e);
end
end
sy = sqrt(diag(oo_.gamma_y{1}));
sy = sy *sy';
if ~isempty(targets{2})
sy = sqrt(diag(oo_.gamma_y{1}));
sy = sy *sy';
if ~isempty(targets{2})
e = targets{2}-oo_.gamma_y{1}(iy{2})./(sy(iy{2})+1e-10);
f = f+e'*(var_weights{2}.*e);
end
if ~isempty(targets{3})
end
if ~isempty(targets{3})
e = targets{3}-sqrt(M_.Sigma_e(iy{3}));
f = f+e'*(var_weights{3}.*e);
end
% autocorrelations
if nar > 0
end
% autocorrelations
if nar > 0
vxy = (A*vx*ghx'+ghu1*M_.Sigma_e*ghu');
oo_.gamma_y{2} = ghx*vxy./(sy+1e-10);
if ~isempty(targets{4})
e = targets{4}-oo_.gamma_y{2}(iy{4});
f = f+e'*(var_weights{4}.*e);
e = targets{4}-oo_.gamma_y{2}(iy{4});
f = f+e'*(var_weights{4}.*e);
end
for i=2:nar
vxy = A*vxy;
oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10);
if ~isempty(targets{i+3})
e = targets{i+3}-oo_.gamma_y{i+1}(iy{i+3});
f = f+e'*(var_weights{i+3}.*e);
end
vxy = A*vxy;
oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10);
if ~isempty(targets{i+3})
e = targets{i+3}-oo_.gamma_y{i+1}(iy{i+3});
f = f+e'*(var_weights{i+3}.*e);
end
end
end
if isempty(fold) | f < 2*fold
end
if isempty(fold) | f < 2*fold
fold = f;
vxold = vx;
end
% 11/04/02 MJ generalized for correlations, autocorrelations and
% constraints on M_.Sigma_e
% 01/25/03 MJ targets std. dev. instead of variances
end
% 11/04/02 MJ generalized for correlations, autocorrelations and
% constraints on M_.Sigma_e
% 01/25/03 MJ targets std. dev. instead of variances

View File

@ -19,46 +19,46 @@ function objective=calib_obj2(M_.Sigma_e,A,ghu1,ghx,ghu,targets,var_weights,iy,n
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global vx fold options_
objective = cell (nar+3);
oo_.gamma_y = cell(nar+1,1);
M_.Sigma_e=diag(M_.Sigma_e);
nx = size(ghx,2);
b=ghu1*M_.Sigma_e*ghu1';
vx = lyapunov_symm(A,b,options_.qz_criterium,options_.lyapunov_complex_threshold);
oo_.gamma_y{1} = ghx*vx*ghx'+ ghu*M_.Sigma_e*ghu';
if ~isempty(targets{1})
objective{1} = sqrt(oo_.gamma_y{1}(iy{1}));
end
global vx fold options_
sy = sqrt(diag(oo_.gamma_y{1}));
sy = sy *sy';
if ~isempty(targets{2})
objective = cell (nar+3);
oo_.gamma_y = cell(nar+1,1);
M_.Sigma_e=diag(M_.Sigma_e);
nx = size(ghx,2);
b=ghu1*M_.Sigma_e*ghu1';
vx = lyapunov_symm(A,b,options_.qz_criterium,options_.lyapunov_complex_threshold);
oo_.gamma_y{1} = ghx*vx*ghx'+ ghu*M_.Sigma_e*ghu';
if ~isempty(targets{1})
objective{1} = sqrt(oo_.gamma_y{1}(iy{1}));
end
sy = sqrt(diag(oo_.gamma_y{1}));
sy = sy *sy';
if ~isempty(targets{2})
objective{2} = oo_.gamma_y{1}(iy{2})./(sy(iy{2})+1e-10);
end
if ~isempty(targets{3})
end
if ~isempty(targets{3})
objective{3} = M_.Sigma_e(iy{3});
end
% autocorrelations
if nar > 0
end
% autocorrelations
if nar > 0
vxy = (A*vx*ghx'+ghu1*M_.Sigma_e*ghu');
oo_.gamma_y{2} = ghx*vxy./(sy+1e-10);
if ~isempty(targets{4})
objective{4} = oo_.gamma_y{2}(iy{4});
objective{4} = oo_.gamma_y{2}(iy{4});
end
for i=2:nar
vxy = A*vxy;
oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10);
if ~isempty(targets{i+3})
objecitve{i+3} = oo_.gamma_y{i+1}(iy{i+3});
end
vxy = A*vxy;
oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10);
if ~isempty(targets{i+3})
objecitve{i+3} = oo_.gamma_y{i+1}(iy{i+3});
end
end
end
end
% 11/04/02 MJ generalized for correlations, autocorrelations and
% constraints on M_.Sigma_e
% 11/04/02 MJ generalized for correlations, autocorrelations and
% constraints on M_.Sigma_e

View File

@ -30,63 +30,63 @@ function result = check
global M_ options_ oo_
if options_.block || options_.bytecode
error('CHECK: incompatibility with "block" or "bytecode" option')
if options_.block || options_.bytecode
error('CHECK: incompatibility with "block" or "bytecode" option')
end
temp_options = options_;
tempex = oo_.exo_simul;
if ~options_.initval_file & M_.exo_nbr > 1
oo_.exo_simul = ones(M_.maximum_lead+M_.maximum_lag+1,1)*oo_.exo_steady_state';
end
options_.order = 1;
[dr, info] = resol(oo_.steady_state,1);
oo_.dr = dr;
if info(1) ~= 0 & info(1) ~= 3 & info(1) ~= 4
print_info(info, options_.noprint);
end
oo_.exo_simul = tempex;
eigenvalues_ = dr.eigval;
nyf = nnz(dr.kstate(:,2)>M_.maximum_endo_lag+1);
[m_lambda,i]=sort(abs(eigenvalues_));
n_explod = nnz(abs(eigenvalues_) > options_.qz_criterium);
if options_.noprint == 0
disp(' ')
disp('EIGENVALUES:')
disp(sprintf('%16s %16s %16s\n','Modulus','Real','Imaginary'))
z=[m_lambda real(eigenvalues_(i)) imag(eigenvalues_(i))]';
disp(sprintf('%16.4g %16.4g %16.4g\n',z))
options_ = set_default_option(options_,'qz_criterium',1.000001);
disp(sprintf('\nThere are %d eigenvalue(s) larger than 1 in modulus ', ...
n_explod));
disp(sprintf('for %d forward-looking variable(s)',nyf));
disp(' ')
if dr.rank == nyf & nyf == n_explod
disp('The rank condition is verified.')
else
disp('The rank conditions ISN''T verified!')
end
disp(' ')
end
options_ = temp_options;
% 2/9/99 MJ: line 15, added test for absence of exogenous variable.
% 8/27/2000 MJ: change JACOB call. Added ...,1 to cumsum()
% 6/24/01 MJ: added count of abs(eigenvalues) > 1
% 2/21/02 MJ: count eigenvalues > 1[+1e-5]
% 01/22/03 MJ: warning(warning_state) needs parentheses for Matlab 6.5
% name conflicts with parameters
% 05/21/03 MJ: replace computation by dr1.m and add rank check
% 06/05/03 MJ: corrected bug when M_.maximum_lag > 0
temp_options = options_;
tempex = oo_.exo_simul;
if ~options_.initval_file & M_.exo_nbr > 1
oo_.exo_simul = ones(M_.maximum_lead+M_.maximum_lag+1,1)*oo_.exo_steady_state';
end
options_.order = 1;
[dr, info] = resol(oo_.steady_state,1);
oo_.dr = dr;
if info(1) ~= 0 & info(1) ~= 3 & info(1) ~= 4
print_info(info, options_.noprint);
end
oo_.exo_simul = tempex;
eigenvalues_ = dr.eigval;
nyf = nnz(dr.kstate(:,2)>M_.maximum_endo_lag+1);
[m_lambda,i]=sort(abs(eigenvalues_));
n_explod = nnz(abs(eigenvalues_) > options_.qz_criterium);
if options_.noprint == 0
disp(' ')
disp('EIGENVALUES:')
disp(sprintf('%16s %16s %16s\n','Modulus','Real','Imaginary'))
z=[m_lambda real(eigenvalues_(i)) imag(eigenvalues_(i))]';
disp(sprintf('%16.4g %16.4g %16.4g\n',z))
options_ = set_default_option(options_,'qz_criterium',1.000001);
disp(sprintf('\nThere are %d eigenvalue(s) larger than 1 in modulus ', ...
n_explod));
disp(sprintf('for %d forward-looking variable(s)',nyf));
disp(' ')
if dr.rank == nyf & nyf == n_explod
disp('The rank condition is verified.')
else
disp('The rank conditions ISN''T verified!')
end
disp(' ')
end
options_ = temp_options;
% 2/9/99 MJ: line 15, added test for absence of exogenous variable.
% 8/27/2000 MJ: change JACOB call. Added ...,1 to cumsum()
% 6/24/01 MJ: added count of abs(eigenvalues) > 1
% 2/21/02 MJ: count eigenvalues > 1[+1e-5]
% 01/22/03 MJ: warning(warning_state) needs parentheses for Matlab 6.5
% name conflicts with parameters
% 05/21/03 MJ: replace computation by dr1.m and add rank check
% 06/05/03 MJ: corrected bug when M_.maximum_lag > 0

View File

@ -31,127 +31,127 @@ function varlist = check_list_of_variables(options_, M_, varlist)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
msg = 0;
if options_.bvar_dsge && options_.bayesian_irf
if ~isempty(varlist)
for i=1:size(varlist,1)
idx = strmatch(deblank(varlist(i,:)),options_.varobs,'exact');
if isempty(idx)
disp([varlist(i,:) ' is not an observed variable!']);
msg = 1;
end
end
if size(varlist,1)~=size(options_.varobs)
msg = 1;
end
if msg
disp(' ')
disp('Posterior IRFs will be computed for all observed variables.')
disp(' ')
end
end
varlist = options_.varobs;
return
msg = 0;
if options_.bvar_dsge && options_.bayesian_irf
if ~isempty(varlist)
for i=1:size(varlist,1)
idx = strmatch(deblank(varlist(i,:)),options_.varobs,'exact');
if isempty(idx)
disp([varlist(i,:) ' is not an observed variable!']);
msg = 1;
end
end
if size(varlist,1)~=size(options_.varobs)
msg = 1;
end
if msg
disp(' ')
disp('Posterior IRFs will be computed for all observed variables.')
disp(' ')
end
end
if isempty(varlist)
disp(' ')
disp(['You did not declare endogenous variables after the estimation command.'])
cas = [];
if options_.bayesian_irf
cas = 'Posterior IRFs';
end
if options_.moments_varendo
if isempty(cas)
cas = 'Posterior moments';
else
cas = [ cas , ', posterior moments'];
end
end
if options_.smoother
if isempty(cas)
cas = 'Posterior smoothed variables';
else
cas = [ cas , ', posterior smoothed variables'];
end
end
if options_.smoother
if isempty(cas)
cas = 'Posterior smoothed variables';
else
cas = [ cas , ', posterior smoothed variables'];
end
end
if ~isempty(options_.filter_step_ahead)
if isempty(cas)
cas = 'Posterior k-step ahead filtered variables';
else
cas = [ cas , ', posterior k-step ahead filtered variables'];
end
end
if options_.forecast
if isempty(cas)
cas = 'Posterior forecasts';
else
cas = [ cas , ' and posterior forecats'];
end
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....'];
format_text(string, 10)
choice = [];
while isempty(choice)
disp(' ')
disp(' ')
disp('Choose one of the following options:')
disp(' ')
disp(' [1] Consider all the endogenous variables.')
disp(' [2] Consider all the observed endogenous variables.')
disp(' [3] Stop Dynare and change the mod file.')
disp(' ')
choice = input('options [default is 1] = ');
if isempty(choice)
choice=1;
end
if choice==1
varlist = M_.endo_names(1:M_.orig_endo_nbr, :);
elseif choice==2
varlist = options_.varobs;
elseif choice==3
varlist = NaN;
else
disp('')
disp('YOU HAVE TO ANSWER 1, 2 or 3!')
disp('')
end
end
end
if isnan(varlist)
edit([M_.fname '.mod'])
end
disp('')
varlist = options_.varobs;
return
end
if isempty(varlist)
disp(' ')
disp(['You did not declare endogenous variables after the estimation command.'])
cas = [];
if options_.bayesian_irf
cas = 'Posterior IRFs';
end
function format_text(remain, max_number_of_words_per_line)
index = 0;
line_of_text = [];
while ~isempty(remain)
[token, remain] = strtok(remain);
index = index+1;
if isempty(line_of_text)
line_of_text = token;
if options_.moments_varendo
if isempty(cas)
cas = 'Posterior moments';
else
line_of_text = [line_of_text , ' ' , token];
end
if index==max_number_of_words_per_line
disp(line_of_text)
index = 0;
line_of_text = [];
cas = [ cas , ', posterior moments'];
end
end
if index<max_number_of_words_per_line
if options_.smoother
if isempty(cas)
cas = 'Posterior smoothed variables';
else
cas = [ cas , ', posterior smoothed variables'];
end
end
if options_.smoother
if isempty(cas)
cas = 'Posterior smoothed variables';
else
cas = [ cas , ', posterior smoothed variables'];
end
end
if ~isempty(options_.filter_step_ahead)
if isempty(cas)
cas = 'Posterior k-step ahead filtered variables';
else
cas = [ cas , ', posterior k-step ahead filtered variables'];
end
end
if options_.forecast
if isempty(cas)
cas = 'Posterior forecasts';
else
cas = [ cas , ' and posterior forecats'];
end
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....'];
format_text(string, 10)
choice = [];
while isempty(choice)
disp(' ')
disp(' ')
disp('Choose one of the following options:')
disp(' ')
disp(' [1] Consider all the endogenous variables.')
disp(' [2] Consider all the observed endogenous variables.')
disp(' [3] Stop Dynare and change the mod file.')
disp(' ')
choice = input('options [default is 1] = ');
if isempty(choice)
choice=1;
end
if choice==1
varlist = M_.endo_names(1:M_.orig_endo_nbr, :);
elseif choice==2
varlist = options_.varobs;
elseif choice==3
varlist = NaN;
else
disp('')
disp('YOU HAVE TO ANSWER 1, 2 or 3!')
disp('')
end
end
end
if isnan(varlist)
edit([M_.fname '.mod'])
end
disp('')
end
function format_text(remain, max_number_of_words_per_line)
index = 0;
line_of_text = [];
while ~isempty(remain)
[token, remain] = strtok(remain);
index = index+1;
if isempty(line_of_text)
line_of_text = token;
else
line_of_text = [line_of_text , ' ' , token];
end
if index==max_number_of_words_per_line
disp(line_of_text)
end
index = 0;
line_of_text = [];
end
end
if index<max_number_of_words_per_line
disp(line_of_text)
end

View File

@ -1,36 +1,36 @@
function check_model()
% Copyright (C) 2005-2006 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/>.
global M_
xlen = M_.maximum_exo_lag+M_.maximum_exo_lead + 1;
if ~ M_.lead_lag_incidence(M_.maximum_lag+1,:) > 0
error ('RESOL: Error in model specification: some variables don"t appear as current') ;
end
if xlen > 1
error (['RESOL: stochastic exogenous variables must appear only at the' ...
' current period. Use additional endogenous variables']) ;
end
if (M_.exo_det_nbr > 0) & (M_.maximum_lag > 1 | M_.maximum_lead > 1)
error(['Exogenous deterministic variables are currently only allowed in' ...
' models with leads and lags on only one period'])
end
function check_model()
% Copyright (C) 2005-2006 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/>.
global M_
xlen = M_.maximum_exo_lag+M_.maximum_exo_lead + 1;
if ~ M_.lead_lag_incidence(M_.maximum_lag+1,:) > 0
error ('RESOL: Error in model specification: some variables don"t appear as current') ;
end
if xlen > 1
error (['RESOL: stochastic exogenous variables must appear only at the' ...
' current period. Use additional endogenous variables']) ;
end
if (M_.exo_det_nbr > 0) & (M_.maximum_lag > 1 | M_.maximum_lead > 1)
error(['Exogenous deterministic variables are currently only allowed in' ...
' models with leads and lags on only one period'])
end

View File

@ -17,4 +17,4 @@ function n = check_name(vartan,varname)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
n = strmatch(varname,vartan,'exact');
n = strmatch(varname,vartan,'exact');

View File

@ -16,85 +16,85 @@ function [info,description] = check_posterior_analysis_data(type,M_)
%
% 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;
info = 0;
if nargout>1
description = '';
end
%% Get informations about mcmc files.
if ~exist([ M_.dname '/metropolis'],'dir')
disp('check_posterior_analysis_data:: Can''t find any mcmc file!')
return
end
mhname = get_name_of_the_last_mh_file(M_);
mhdate = get_date_of_a_file(mhname);
%% Get informations about _posterior_draws files.
drawsinfo = dir([ M_.dname '/metropolis/' M_.fname '_posterior_draws*.mat']);
if isempty(drawsinfo)
info = 1; % select_posterior_draws has to be called first.
if nargout>1
description = '';
description = 'select_posterior_draws has to be called.';
end
%% Get informations about mcmc files.
if ~exist([ M_.dname '/metropolis'],'dir')
disp('check_posterior_analysis_data:: Can''t find any mcmc file!')
return
end
mhname = get_name_of_the_last_mh_file(M_);
mhdate = get_date_of_a_file(mhname);
%% Get informations about _posterior_draws files.
drawsinfo = dir([ M_.dname '/metropolis/' M_.fname '_posterior_draws*.mat']);
if isempty(drawsinfo)
info = 1; % select_posterior_draws has to be called first.
return
else
number_of_last_posterior_draws_file = length(drawsinfo);
pddate = get_date_of_a_file([ M_.dname '/metropolis/' M_.fname '_posterior_draws'...
int2str(number_of_last_posterior_draws_file) '.mat']);
if pddate<mhdate
info = 2; % _posterior_draws files have to be updated.
if nargout>1
description = 'select_posterior_draws has to be called.';
description = 'posterior draws files have to be updated.';
end
return
else
number_of_last_posterior_draws_file = length(drawsinfo);
pddate = get_date_of_a_file([ M_.dname '/metropolis/' M_.fname '_posterior_draws'...
int2str(number_of_last_posterior_draws_file) '.mat']);
if pddate<mhdate
info = 2; % _posterior_draws files have to be updated.
if nargout>1
description = 'posterior draws files have to be updated.';
end
return
else
info = 3; % Ok!
if nargout>1
description = 'posterior draws files are up to date.';
end
end
end
%% Get informations about posterior data files.
switch type
case 'variance'
generic_post_data_file_name = 'Posterior2ndOrderMoments';
case 'decomposition'
generic_post_data_file_name = 'PosteriorVarianceDecomposition';
case 'correlation'
generic_post_data_file_name = 'PosteriorCorrelations';
case 'conditional decomposition'
generic_post_data_file_name = 'PosteriorConditionalVarianceDecomposition';
otherwise
disp('This feature is not yest implemented!')
end
pdfinfo = dir([ M_.dname '/metropolis/' M_.fname '_' generic_post_data_file_name '*']);
if isempty(pdfinfo)
info = 4; % posterior draws have to be processed.
info = 3; % Ok!
if nargout>1
description = 'posterior draws files have to be processed.';
description = 'posterior draws files are up to date.';
end
return
end
end
%% Get informations about posterior data files.
switch type
case 'variance'
generic_post_data_file_name = 'Posterior2ndOrderMoments';
case 'decomposition'
generic_post_data_file_name = 'PosteriorVarianceDecomposition';
case 'correlation'
generic_post_data_file_name = 'PosteriorCorrelations';
case 'conditional decomposition'
generic_post_data_file_name = 'PosteriorConditionalVarianceDecomposition';
otherwise
disp('This feature is not yest implemented!')
end
pdfinfo = dir([ M_.dname '/metropolis/' M_.fname '_' generic_post_data_file_name '*']);
if isempty(pdfinfo)
info = 4; % posterior draws have to be processed.
if nargout>1
description = 'posterior draws files have to be processed.';
end
return
else
number_of_the_last_post_data_file = length(pdfinfo);
name_of_the_last_post_data_file = ...
[ './' M_.dname ...
'/metropolis/' ...
M_.fname '_' ...
generic_post_data_file_name ...
int2str(number_of_the_last_post_data_file) ...
'.mat' ];
pdfdate = get_date_of_a_file(name_of_the_last_post_data_file);
if pdfdate<pddate
info = 5; % posterior data files have to be updated.
if nargout>1
description = 'posterior data files have to be updated.';
end
else
number_of_the_last_post_data_file = length(pdfinfo);
name_of_the_last_post_data_file = ...
[ './' M_.dname ...
'/metropolis/' ...
M_.fname '_' ...
generic_post_data_file_name ...
int2str(number_of_the_last_post_data_file) ...
'.mat' ];
pdfdate = get_date_of_a_file(name_of_the_last_post_data_file);
if pdfdate<pddate
info = 5; % posterior data files have to be updated.
if nargout>1
description = 'posterior data files have to be updated.';
end
else
info = 6; % Ok (nothing to do ;-)
if nargout>1
description = 'There is nothing to do';
end
end
end
info = 6; % Ok (nothing to do ;-)
if nargout>1
description = 'There is nothing to do';
end
end
end

View File

@ -15,84 +15,84 @@ function [info,description] = check_prior_analysis_data(type,M_)
%
% 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;
if nargout>1
description = '';
end
%% 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
end
prior_draws_info = dir([ M_.dname '/prior/draws/prior_draws*.mat']);
name_of_the_last_prior_draw_file = prior_draws_info(end).name;
date_of_the_last_prior_draw_file = prior_draws_info(end).datenum;
%% Get informations about _posterior_draws files.
if isempty(prior_draws_info)
info = 1;
info = 0;
if nargout>1
description = '';
end
%% 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
end
prior_draws_info = dir([ M_.dname '/prior/draws/prior_draws*.mat']);
name_of_the_last_prior_draw_file = prior_draws_info(end).name;
date_of_the_last_prior_draw_file = prior_draws_info(end).datenum;
%% Get informations about _posterior_draws files.
if isempty(prior_draws_info)
info = 1;
if nargout>1
description = 'prior_sampler has to be called.';
end
return
else
number_of_last_prior_draws_file = length(prior_draws_info);
date_of_the_prior_definition = get_date_of_a_file([ M_.dname '/prior/definition.mat']);
if date_of_the_prior_definition>date_of_the_last_prior_draw_file
info = 2;
if nargout>1
description = 'prior_sampler has to be called.';
description = 'prior draws files have to be updated.';
end
return
else
number_of_last_prior_draws_file = length(prior_draws_info);
date_of_the_prior_definition = get_date_of_a_file([ M_.dname '/prior/definition.mat']);
if date_of_the_prior_definition>date_of_the_last_prior_draw_file
info = 2;
if nargout>1
description = 'prior draws files have to be updated.';
end
return
else
info = 3; % Nothing to do!
if nargout>1
description = 'prior draws files are up to date.';
end
end
end
%% Get informations about prior data files.
switch type
case 'variance'
generic_prior_data_file_name = 'Prior2ndOrderMoments';
case 'decomposition'
generic_prior_data_file_name = 'PriorVarianceDecomposition';
case 'correlation'
generic_prior_data_file_name = 'PriorCorrelations';
case 'conditional decomposition'
generic_prior_data_file_name = 'PriorConditionalVarianceDecomposition';
otherwise
disp(['This feature is not yet implemented!'])
end
CheckPath('prior/moments');
pdfinfo = dir([ M_.dname '/prior/' generic_prior_data_file_name '*']);
if isempty(pdfinfo)
info = 4;
info = 3; % Nothing to do!
if nargout>1
description = 'prior draws files have to be processed.';
description = 'prior draws files are up to date.';
end
end
end
%% Get informations about prior data files.
switch type
case 'variance'
generic_prior_data_file_name = 'Prior2ndOrderMoments';
case 'decomposition'
generic_prior_data_file_name = 'PriorVarianceDecomposition';
case 'correlation'
generic_prior_data_file_name = 'PriorCorrelations';
case 'conditional decomposition'
generic_prior_data_file_name = 'PriorConditionalVarianceDecomposition';
otherwise
disp(['This feature is not yet implemented!'])
end
CheckPath('prior/moments');
pdfinfo = dir([ M_.dname '/prior/' generic_prior_data_file_name '*']);
if isempty(pdfinfo)
info = 4;
if nargout>1
description = 'prior draws files have to be processed.';
end
return
else
number_of_the_last_prior_data_file = length(pdfinfo);
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!!!
if pdfdate<date_of_the_last_prior_draw_file
info = 5; % prior data files have to be updated.
if nargout>1
description = 'prior data files have to be updated.';
end
return
else
number_of_the_last_prior_data_file = length(pdfinfo);
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!!!
if pdfdate<date_of_the_last_prior_draw_file
info = 5; % prior data files have to be updated.
if nargout>1
description = 'prior data files have to be updated.';
end
else
info = 6; % Ok (nothing to do ;-)
if nargout>1
description = 'prior data files are up to date.';
end
info = 6; % Ok (nothing to do ;-)
if nargout>1
description = 'prior data files are up to date.';
end
end
end
end

View File

@ -36,10 +36,10 @@ global M_ options_ estim_params_
n = estim_params_.np + ...
estim_params_.nvn+ ...
estim_params_.ncx+ ...
estim_params_.ncn+ ...
estim_params_.nvx;
estim_params_.nvn+ ...
estim_params_.ncx+ ...
estim_params_.ncn+ ...
estim_params_.nvx;
nblck = options_.mh_nblck;
MhDirectoryName = CheckPath('metropolis');

View File

@ -1,31 +1,31 @@
function moments=compute_model_moments(dr,M_,options_)
%
% INPUTS
% dr: structure describing model solution
% M_: structure of Dynare options
% options_
%
% OUTPUTS
% moments: a cell array containing requested moments
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2008 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/>.
moments = th_autocovariances(dr,options_.varlist,M_,options_);
function moments=compute_model_moments(dr,M_,options_)
%
% INPUTS
% dr: structure describing model solution
% M_: structure of Dynare options
% options_
%
% OUTPUTS
% moments: a cell array containing requested moments
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2008 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/>.
moments = th_autocovariances(dr,options_.varlist,M_,options_);

View File

@ -32,88 +32,88 @@ function oo_ = compute_moments_varendo(type,options_,M_,oo_,var_list_)
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if strcmpi(type,'posterior')
posterior = 1;
if nargin==4
var_list_ = options_.varobs;
end
elseif strcmpi(type,'prior')
posterior = 0;
if nargin==4
var_list_ = options_.prior_analysis_endo_var_list;
if isempty(var_list_)
options_.prior_analysis_var_list = options_.varobs;
end
end
else
disp('compute_moments_varendo:: Unknown type!')
error()
end
NumberOfEndogenousVariables = rows(var_list_);
NumberOfExogenousVariables = M_.exo_nbr;
list_of_exogenous_variables = M_.exo_names;
NumberOfLags = options_.ar;
Steps = options_.conditional_variance_decomposition;
if strcmpi(type,'posterior')
posterior = 1;
if nargin==4
var_list_ = options_.varobs;
end
elseif strcmpi(type,'prior')
posterior = 0;
if nargin==4
var_list_ = options_.prior_analysis_endo_var_list;
if isempty(var_list_)
options_.prior_analysis_var_list = options_.varobs;
end
end
else
disp('compute_moments_varendo:: Unknown type!')
error()
end
% COVARIANCE MATRIX.
if posterior
for i=1:NumberOfEndogenousVariables
for j=i:NumberOfEndogenousVariables
oo_ = posterior_analysis('variance',var_list_(i,:),var_list_(j,:),[],options_,M_,oo_);
end
NumberOfEndogenousVariables = rows(var_list_);
NumberOfExogenousVariables = M_.exo_nbr;
list_of_exogenous_variables = M_.exo_names;
NumberOfLags = options_.ar;
Steps = options_.conditional_variance_decomposition;
% COVARIANCE MATRIX.
if posterior
for i=1:NumberOfEndogenousVariables
for j=i:NumberOfEndogenousVariables
oo_ = posterior_analysis('variance',var_list_(i,:),var_list_(j,:),[],options_,M_,oo_);
end
else
end
else
for i=1:NumberOfEndogenousVariables
for j=i:NumberOfEndogenousVariables
oo_ = prior_analysis('variance',var_list_(i,:),var_list_(j,:),[],options_,M_,oo_);
end
end
end
% CORRELATION FUNCTION.
if posterior
for h=NumberOfLags:-1:1
for i=1:NumberOfEndogenousVariables
for j=i:NumberOfEndogenousVariables
oo_ = prior_analysis('variance',var_list_(i,:),var_list_(j,:),[],options_,M_,oo_);
for j=1:NumberOfEndogenousVariables
oo_ = posterior_analysis('correlation',var_list_(i,:),var_list_(j,:),h,options_,M_,oo_);
end
end
end
% CORRELATION FUNCTION.
if posterior
for h=NumberOfLags:-1:1
for i=1:NumberOfEndogenousVariables
for j=1:NumberOfEndogenousVariables
oo_ = posterior_analysis('correlation',var_list_(i,:),var_list_(j,:),h,options_,M_,oo_);
end
end
end
else
for h=NumberOfLags:-1:1
for i=1:NumberOfEndogenousVariables
for j=1:NumberOfEndogenousVariables
oo_ = prior_analysis('correlation',var_list_(i,:),var_list_(j,:),h,options_,M_,oo_);
end
else
for h=NumberOfLags:-1:1
for i=1:NumberOfEndogenousVariables
for j=1:NumberOfEndogenousVariables
oo_ = prior_analysis('correlation',var_list_(i,:),var_list_(j,:),h,options_,M_,oo_);
end
end
end
% VARIANCE DECOMPOSITION.
if posterior
for i=1:NumberOfEndogenousVariables
for j=1:NumberOfExogenousVariables
oo_ = posterior_analysis('decomposition',var_list_(i,:),M_.exo_names(j,:),[],options_,M_,oo_);
end
end
% VARIANCE DECOMPOSITION.
if posterior
for i=1:NumberOfEndogenousVariables
for j=1:NumberOfExogenousVariables
oo_ = posterior_analysis('decomposition',var_list_(i,:),M_.exo_names(j,:),[],options_,M_,oo_);
end
else
for i=1:NumberOfEndogenousVariables
for j=1:NumberOfExogenousVariables
oo_ = prior_analysis('decomposition',var_list_(i,:),M_.exo_names(j,:),[],options_,M_,oo_);
end
end
end
% CONDITIONAL VARIANCE DECOMPOSITION.
if posterior
for i=1:NumberOfEndogenousVariables
for j=1:NumberOfExogenousVariables
oo_ = posterior_analysis('conditional decomposition',var_list_(i,:),M_.exo_names(j,:),Steps,options_,M_,oo_);
end
else
for i=1:NumberOfEndogenousVariables
for j=1:NumberOfExogenousVariables
oo_ = prior_analysis('decomposition',var_list_(i,:),M_.exo_names(j,:),[],options_,M_,oo_);
end
else
for i=1:NumberOfEndogenousVariables
for j=1:NumberOfExogenousVariables
oo_ = prior_analysis('conditional decomposition',var_list_(i,:),M_.exo_names(j,:),Steps,options_,M_,oo_);
end
end
end
% CONDITIONAL VARIANCE DECOMPOSITION.
if posterior
for i=1:NumberOfEndogenousVariables
for j=1:NumberOfExogenousVariables
oo_ = posterior_analysis('conditional decomposition',var_list_(i,:),M_.exo_names(j,:),Steps,options_,M_,oo_);
end
end
end
else
for i=1:NumberOfEndogenousVariables
for j=1:NumberOfExogenousVariables
oo_ = prior_analysis('conditional decomposition',var_list_(i,:),M_.exo_names(j,:),Steps,options_,M_,oo_);
end
end
end

View File

@ -31,43 +31,43 @@ function PackedConditionalVarianceDecomposition = conditional_variance_decomposi
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
number_of_state_innovations = ...
StateSpaceModel.number_of_state_innovations;
transition_matrix = StateSpaceModel.transition_matrix;
number_of_state_equations = ...
StateSpaceModel.number_of_state_equations;
nSteps = length(Steps);
ConditionalVariance = zeros(number_of_state_equations,number_of_state_equations);
ConditionalVariance = repmat(ConditionalVariance,[1 1 nSteps ...
number_of_state_innovations]);
number_of_state_innovations = ...
StateSpaceModel.number_of_state_innovations;
transition_matrix = StateSpaceModel.transition_matrix;
number_of_state_equations = ...
StateSpaceModel.number_of_state_equations;
nSteps = length(Steps);
if StateSpaceModel.sigma_e_is_diagonal
B = StateSpaceModel.impulse_matrix.* ...
repmat(sqrt(diag(StateSpaceModel.state_innovations_covariance_matrix)'),...
number_of_state_equations,1);
else
B = StateSpaceModel.impulse_matrix*chol(StateSpaceModel.state_innovations_covariance_matrix)';
end
for i=1:number_of_state_innovations
BB = B(:,i)*B(:,i)';
V = zeros(number_of_state_equations,number_of_state_equations);
m = 1;
for h = 1:max(Steps)
V = transition_matrix*V*transition_matrix'+BB;
if h == Steps(m)
ConditionalVariance(:,:,m,i) = V;
m = m+1;
end
ConditionalVariance = zeros(number_of_state_equations,number_of_state_equations);
ConditionalVariance = repmat(ConditionalVariance,[1 1 nSteps ...
number_of_state_innovations]);
if StateSpaceModel.sigma_e_is_diagonal
B = StateSpaceModel.impulse_matrix.* ...
repmat(sqrt(diag(StateSpaceModel.state_innovations_covariance_matrix)'),...
number_of_state_equations,1);
else
B = StateSpaceModel.impulse_matrix*chol(StateSpaceModel.state_innovations_covariance_matrix)';
end
for i=1:number_of_state_innovations
BB = B(:,i)*B(:,i)';
V = zeros(number_of_state_equations,number_of_state_equations);
m = 1;
for h = 1:max(Steps)
V = transition_matrix*V*transition_matrix'+BB;
if h == Steps(m)
ConditionalVariance(:,:,m,i) = V;
m = m+1;
end
end
ConditionalVariance = ConditionalVariance(SubsetOfVariables,SubsetOfVariables,:,:);
NumberOfVariables = length(SubsetOfVariables);
PackedConditionalVarianceDecomposition = zeros(NumberOfVariables*(NumberOfVariables+1)/2,length(Steps),StateSpaceModel.number_of_state_innovations);
for i=1:number_of_state_innovations
for h = 1:length(Steps)
PackedConditionalVarianceDecomposition(:,h,i) = vech(ConditionalVariance(:,:,h,i));
end
end
end
ConditionalVariance = ConditionalVariance(SubsetOfVariables,SubsetOfVariables,:,:);
NumberOfVariables = length(SubsetOfVariables);
PackedConditionalVarianceDecomposition = zeros(NumberOfVariables*(NumberOfVariables+1)/2,length(Steps),StateSpaceModel.number_of_state_innovations);
for i=1:number_of_state_innovations
for h = 1:length(Steps)
PackedConditionalVarianceDecomposition(:,h,i) = vech(ConditionalVariance(:,:,h,i));
end
end

View File

@ -19,78 +19,78 @@ function oo_ = conditional_variance_decomposition_mc_analysis(NumberOfSimulation
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if strcmpi(type,'posterior')
TYPE = 'Posterior';
PATH = [dname '/metropolis/'];
else
TYPE = 'Prior';
PATH = [dname '/prior/moments/'];
end
if strcmpi(type,'posterior')
TYPE = 'Posterior';
PATH = [dname '/metropolis/'];
else
TYPE = 'Prior';
PATH = [dname '/prior/moments/'];
end
indx = check_name(vartan,var);
if isempty(indx)
disp([ type '_analysis:: ' var ' is not a stationary endogenous variable!'])
return
end
endogenous_variable_index = sum(1:indx);
exogenous_variable_index = check_name(exonames,exo);
if isempty(exogenous_variable_index)
disp([ type '_analysis:: ' exo ' is not a declared exogenous variable!'])
return
end
indx = check_name(vartan,var);
if isempty(indx)
disp([ type '_analysis:: ' var ' is not a stationary endogenous variable!'])
return
end
endogenous_variable_index = sum(1:indx);
exogenous_variable_index = check_name(exonames,exo);
if isempty(exogenous_variable_index)
disp([ type '_analysis:: ' exo ' is not a declared exogenous variable!'])
return
end
name = [ var '.' exo ];
if isfield(oo_, [ TYPE 'TheoreticalMoments' ])
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'ConditionalVarianceDecomposition')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean;'])
if isfield(temporary_structure,name)
if sum(Steps-temporary_structure.(name)(1,:)) == 0
% Nothing (new) to do here...
return
end
name = [ var '.' exo ];
if isfield(oo_, [ TYPE 'TheoreticalMoments' ])
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'ConditionalVarianceDecomposition')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean;'])
if isfield(temporary_structure,name)
if sum(Steps-temporary_structure.(name)(1,:)) == 0
% Nothing (new) to do here...
return
end
end
end
end
ListOfFiles = dir([ PATH fname '_' TYPE 'ConditionalVarianceDecomposition*.mat']);
i1 = 1; tmp = zeros(NumberOfSimulations,length(Steps));
for file = 1:length(ListOfFiles)
load([ PATH ListOfFiles(file).name ]);
% 4D-array (endovar,time,exovar,simul)
i2 = i1 + size(Conditional_decomposition_array,4) - 1;
tmp(i1:i2,:) = transpose(dynare_squeeze(Conditional_decomposition_array(endogenous_variable_index,:,exogenous_variable_index,:)));
i1 = i2+1;
end
end
p_mean = NaN(2,length(Steps));
p_mean(1,:) = Steps;
p_median = NaN(1,length(Steps));
p_variance = NaN(1,length(Steps));
p_deciles = NaN(9,length(Steps));
p_density = NaN(2^9,2,length(Steps));
p_hpdinf = NaN(1,length(Steps));
p_hpdsup = NaN(1,length(Steps));
for i=1:length(Steps)
if ~isconst(tmp(:,i))
[pp_mean, pp_median, pp_var, hpd_interval, pp_deciles, pp_density] = ...
posterior_moments(tmp(:,i),1,mh_conf_sig);
p_mean(2,i) = pp_mean;
p_median(i) = pp_median;
p_variance(i) = pp_var;
p_deciles(:,i) = pp_deciles;
p_hpdinf(i) = hpd_interval(1);
p_hpdinf(i) = hpd_interval(2);
p_density(:,:,i) = pp_density;
end
ListOfFiles = dir([ PATH fname '_' TYPE 'ConditionalVarianceDecomposition*.mat']);
i1 = 1; tmp = zeros(NumberOfSimulations,length(Steps));
for file = 1:length(ListOfFiles)
load([ PATH ListOfFiles(file).name ]);
% 4D-array (endovar,time,exovar,simul)
i2 = i1 + size(Conditional_decomposition_array,4) - 1;
tmp(i1:i2,:) = transpose(dynare_squeeze(Conditional_decomposition_array(endogenous_variable_index,:,exogenous_variable_index,:)));
i1 = i2+1;
end
p_mean = NaN(2,length(Steps));
p_mean(1,:) = Steps;
p_median = NaN(1,length(Steps));
p_variance = NaN(1,length(Steps));
p_deciles = NaN(9,length(Steps));
p_density = NaN(2^9,2,length(Steps));
p_hpdinf = NaN(1,length(Steps));
p_hpdsup = NaN(1,length(Steps));
for i=1:length(Steps)
if ~isconst(tmp(:,i))
[pp_mean, pp_median, pp_var, hpd_interval, pp_deciles, pp_density] = ...
posterior_moments(tmp(:,i),1,mh_conf_sig);
p_mean(2,i) = pp_mean;
p_median(i) = pp_median;
p_variance(i) = pp_var;
p_deciles(:,i) = pp_deciles;
p_hpdinf(i) = hpd_interval(1);
p_hpdinf(i) = hpd_interval(2);
p_density(:,:,i) = pp_density;
end
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean.' name ' = p_mean;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.median.' name ' = p_median;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.variance.' name ' = p_variance;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdinf.' name ' = p_hpdinf;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdsup.' name ' = p_hpdsup;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.deciles.' name ' = p_deciles;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.density.' name ' = p_density;']);
end
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean.' name ' = p_mean;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.median.' name ' = p_median;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.variance.' name ' = p_variance;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdinf.' name ' = p_hpdinf;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdsup.' name ' = p_hpdsup;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.deciles.' name ' = p_deciles;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.density.' name ' = p_density;']);

View File

@ -19,55 +19,52 @@ function oo_ = correlation_mc_analysis(SampleSize,type,dname,fname,vartan,nvar,v
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if strcmpi(type,'posterior')
TYPE = 'Posterior';
PATH = [dname '/metropolis/'];
else
TYPE = 'Prior';
PATH = [dname '/prior/moments/'];
end
if strcmpi(type,'posterior')
TYPE = 'Posterior';
PATH = [dname '/metropolis/'];
else
TYPE = 'Prior';
PATH = [dname '/prior/moments/'];
end
indx1 = check_name(vartan,var1);
if isempty(indx1)
disp([ type '_analysis:: ' var1 ' is not a stationary endogenous variable!'])
indx1 = check_name(vartan,var1);
if isempty(indx1)
disp([ type '_analysis:: ' var1 ' is not a stationary endogenous variable!'])
return
end
if ~isempty(var2)
indx2 = check_name(vartan,var2);
if isempty(indx2)
disp([ type '_analysis:: ' var2 ' is not a stationary endogenous variable!'])
return
end
if ~isempty(var2)
indx2 = check_name(vartan,var2);
if isempty(indx2)
disp([ type '_analysis:: ' var2 ' is not a stationary endogenous variable!'])
return
end
else
indx2 = indx1;
var2 = var1;
end
else
indx2 = indx1;
var2 = var1;
end
if isfield(oo_,[TYPE 'TheoreticalMoments'])
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'correlation')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean;'])
if isfield(temporary_structure,var1)
eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean.' var1 ';'])
if isfield(temporary_structure_1,var2)
eval(['temporary_structure_2 = temporary_structure_1.' var2 ';'])
l1 = length(temporary_structure_2);
if l1<nar
% INITIALIZATION:
oo_ = initialize_output_structure(var1,var2,nar,type,oo_);
delete([PATH fname '_' TYPE 'Correlations*'])
[nvar,vartan,NumberOfFiles] = ...
dsge_simulated_theoretical_correlation(SampleSize,nar,M_,options_,oo_,type);
else
if ~isnan(temporary_structure_2(nar))
%Nothing to do.
return
end
end
if isfield(oo_,[TYPE 'TheoreticalMoments'])
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'correlation')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean;'])
if isfield(temporary_structure,var1)
eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean.' var1 ';'])
if isfield(temporary_structure_1,var2)
eval(['temporary_structure_2 = temporary_structure_1.' var2 ';'])
l1 = length(temporary_structure_2);
if l1<nar
% INITIALIZATION:
oo_ = initialize_output_structure(var1,var2,nar,type,oo_);
delete([PATH fname '_' TYPE 'Correlations*'])
[nvar,vartan,NumberOfFiles] = ...
dsge_simulated_theoretical_correlation(SampleSize,nar,M_,options_,oo_,type);
else
oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_);
if ~isnan(temporary_structure_2(nar))
%Nothing to do.
return
end
end
else
oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_);
@ -81,72 +78,75 @@ function oo_ = correlation_mc_analysis(SampleSize,type,dname,fname,vartan,nvar,v
else
oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_);
end
ListOfFiles = dir([ PATH fname '_' TYPE 'Correlations*.mat']);
i1 = 1; tmp = zeros(SampleSize,1);
for file = 1:length(ListOfFiles)
load([ PATH ListOfFiles(file).name ]);
i2 = i1 + rows(Correlation_array) - 1;
tmp(i1:i2) = Correlation_array(:,indx1,indx2,nar);
i1 = i2+1;
end
name = [ var1 '.' var2 ];
if ~isconst(tmp)
[p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ...
posterior_moments(tmp,1,mh_conf_sig);
if isfield(oo_,[ TYPE 'TheoreticalMoments'])
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'correlation')
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'mean',nar,p_mean);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'median',nar,p_median);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'variance',nar,p_var);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdinf',nar,hpd_interval(1));
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdsup',nar,hpd_interval(2));
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'deciles',nar,p_deciles);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'density',nar,density);
end
end
end
else
if isfield(oo_,'PosteriorTheoreticalMoments')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'correlation')
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'mean',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'median',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'variance',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdinf',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdsup',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'deciles',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'density',nar,NaN);
end
else
oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_);
end
ListOfFiles = dir([ PATH fname '_' TYPE 'Correlations*.mat']);
i1 = 1; tmp = zeros(SampleSize,1);
for file = 1:length(ListOfFiles)
load([ PATH ListOfFiles(file).name ]);
i2 = i1 + rows(Correlation_array) - 1;
tmp(i1:i2) = Correlation_array(:,indx1,indx2,nar);
i1 = i2+1;
end
name = [ var1 '.' var2 ];
if ~isconst(tmp)
[p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ...
posterior_moments(tmp,1,mh_conf_sig);
if isfield(oo_,[ TYPE 'TheoreticalMoments'])
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'correlation')
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'mean',nar,p_mean);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'median',nar,p_median);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'variance',nar,p_var);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdinf',nar,hpd_interval(1));
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdsup',nar,hpd_interval(2));
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'deciles',nar,p_deciles);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'density',nar,density);
end
end
end
else
if isfield(oo_,'PosteriorTheoreticalMoments')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'correlation')
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'mean',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'median',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'variance',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdinf',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdsup',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'deciles',nar,NaN);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'density',nar,NaN);
end
end
end
end
function oo_ = initialize_output_structure(var1,var2,nar,type,oo_)
name = [ var1 '.' var2 ];
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.mean.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.median.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.variance.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.hpdinf.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.hpdsup.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.deciles.' name ' = cell(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name ' = cell(' int2str(nar) ',1);']);
for i=1:nar
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name '(' int2str(i) ',1) = {NaN};']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.deciles.' name '(' int2str(i) ',1) = {NaN};']);
end
name = [ var1 '.' var2 ];
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.mean.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.median.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.variance.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.hpdinf.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.hpdsup.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.deciles.' name ' = cell(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name ' = cell(' int2str(nar) ',1);']);
for i=1:nar
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name '(' int2str(i) ',1) = {NaN};']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.deciles.' name '(' int2str(i) ',1) = {NaN};']);
end
function oo_ = fill_output_structure(var1,var2,type,oo_,moment,lag,result)
name = [ var1 '.' var2 ];
switch moment
case {'mean','median','variance','hpdinf','hpdsup'}
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = result;']);
case {'deciles','density'}
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = {result};']);
otherwise
disp('fill_output_structure:: Unknown field!')
end
name = [ var1 '.' var2 ];
switch moment
case {'mean','median','variance','hpdinf','hpdsup'}
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = result;']);
case {'deciles','density'}
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = {result};']);
otherwise
disp('fill_output_structure:: Unknown field!')
end

View File

@ -1,41 +1,41 @@
function co = cosn(H);
% function co = cosn(H);
% computes the cosine of the angle between the H(:,1) and its
% projection onto the span of H(:,2:end)
%
% Not the same as multiple correlation coefficient since the means are not
% zero
%
% Copyright (C) 2008 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/>.
y = H(:,1);
X = H(:,2:end);
% y = H(:,1);
% X = H(:,2:end);
yhat = X*(X\y);
if rank(yhat),
co = y'*yhat/sqrt((y'*y)*(yhat'*yhat));
else
co=0;
end
function co = cosn(H);
% function co = cosn(H);
% computes the cosine of the angle between the H(:,1) and its
% projection onto the span of H(:,2:end)
%
% Not the same as multiple correlation coefficient since the means are not
% zero
%
% Copyright (C) 2008 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/>.
y = H(:,1);
X = H(:,2:end);
% y = H(:,1);
% X = H(:,2:end);
yhat = X*(X\y);
if rank(yhat),
co = y'*yhat/sqrt((y'*y)*(yhat'*yhat));
else
co=0;
end

View File

@ -19,80 +19,80 @@ function oo_ = covariance_mc_analysis(NumberOfSimulations,type,dname,fname,varta
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if strcmpi(type,'posterior')
TYPE = 'Posterior';
PATH = [dname '/metropolis/'];
else
TYPE = 'Prior';
PATH = [dname '/prior/moments/'];
end
if strcmpi(type,'posterior')
TYPE = 'Posterior';
PATH = [dname '/metropolis/'];
else
TYPE = 'Prior';
PATH = [dname '/prior/moments/'];
end
indx1 = check_name(vartan,var1);
if isempty(indx1)
disp([ type '_analysis:: ' var1 ' is not a stationary endogenous variable!'])
indx1 = check_name(vartan,var1);
if isempty(indx1)
disp([ type '_analysis:: ' var1 ' is not a stationary endogenous variable!'])
return
end
if ~isempty(var2)
indx2 = check_name(vartan,var2);
if isempty(indx2)
disp([ type '_analysis:: ' var2 ' is not a stationary endogenous variable!'])
return
end
if ~isempty(var2)
indx2 = check_name(vartan,var2);
if isempty(indx2)
disp([ type '_analysis:: ' var2 ' is not a stationary endogenous variable!'])
return
end
else
indx2 = indx1;
var2 = var1;
end
else
indx2 = indx1;
var2 = var1;
end
if isfield(oo_,[ TYPE 'TheoreticalMoments'])
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'covariance')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean;'])
if isfield(temporary_structure,var1)
eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' var1 ';'])
if isfield(temporary_structure_1,var2)
if isfield(oo_,[ TYPE 'TheoreticalMoments'])
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'covariance')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean;'])
if isfield(temporary_structure,var1)
eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' var1 ';'])
if isfield(temporary_structure_1,var2)
% Nothing to do (the covariance matrix is symmetric!).
return
end
else
if isfield(temporary_structure,var2)
eval(['temporary_structure_2 = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' var2 ';'])
if isfield(temporary_structure_2,var1)
% Nothing to do (the covariance matrix is symmetric!).
return
end
else
if isfield(temporary_structure,var2)
eval(['temporary_structure_2 = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' var2 ';'])
if isfield(temporary_structure_2,var1)
% Nothing to do (the covariance matrix is symmetric!).
return
end
end
end
end
end
end
end
ListOfFiles = dir([ PATH fname '_' TYPE '2ndOrderMoments*.mat']);
i1 = 1; tmp = zeros(NumberOfSimulations,1);
for file = 1:length(ListOfFiles)
load([ PATH ListOfFiles(file).name ]);
i2 = i1 + rows(Covariance_matrix) - 1;
tmp(i1:i2) = Covariance_matrix(:,symmetric_matrix_index(indx1,indx2,nvar));
i1 = i2+1;
end
name = [var1 '.' var2];
if ~isconst(tmp)
[p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ...
posterior_moments(tmp,1,mh_conf_sig);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' name ' = p_mean;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.median.' name ' = p_median;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.variance.' name ' = p_var;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdinf.' name ' = hpd_interval(1);']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdsup.' name ' = hpd_interval(2);']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.deciles.' name ' = p_deciles;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = density;']);
else
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.median.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.variance.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdinf.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdsup.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.deciles.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = NaN;']);
end
ListOfFiles = dir([ PATH fname '_' TYPE '2ndOrderMoments*.mat']);
i1 = 1; tmp = zeros(NumberOfSimulations,1);
for file = 1:length(ListOfFiles)
load([ PATH ListOfFiles(file).name ]);
i2 = i1 + rows(Covariance_matrix) - 1;
tmp(i1:i2) = Covariance_matrix(:,symmetric_matrix_index(indx1,indx2,nvar));
i1 = i2+1;
end
name = [var1 '.' var2];
if ~isconst(tmp)
[p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ...
posterior_moments(tmp,1,mh_conf_sig);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' name ' = p_mean;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.median.' name ' = p_median;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.variance.' name ' = p_var;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdinf.' name ' = hpd_interval(1);']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdsup.' name ' = hpd_interval(2);']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.deciles.' name ' = p_deciles;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = density;']);
else
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.median.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.variance.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdinf.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdsup.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.deciles.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = NaN;']);
end

View File

@ -60,152 +60,152 @@ g = g0;
gnorm = norm(g);
%
if (gnorm < 1.e-12) & ~badg % put ~badg 8/4/94
retcode =1;
dxnorm=0;
% gradient convergence
retcode =1;
dxnorm=0;
% gradient convergence
else
% with badg true, we don't try to match rate of improvement to directional
% derivative. We're satisfied just to get some improvement in f.
%
%if(badg)
% dx = -g*FCHANGE/(gnorm*gnorm);
% dxnorm = norm(dx);
% if dxnorm > 1e12
% disp('Bad, small gradient problem.')
% dx = dx*FCHANGE/dxnorm;
% end
%else
% Gauss-Newton step;
%---------- Start of 7/19/93 mod ---------------
%[v d] = eig(H0);
%toc
%d=max(1e-10,abs(diag(d)));
%d=abs(diag(d));
%dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g);
% toc
dx = -H0*g;
% toc
dxnorm = norm(dx);
if dxnorm > 1e12
disp('Near-singular H problem.')
dx = dx*FCHANGE/dxnorm;
end
dfhat = dx'*g0;
%end
%
%
if ~badg
% test for alignment of dx with gradient and fix if necessary
a = -dfhat/(gnorm*dxnorm);
if a<ANGLE
dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g;
dfhat = dx'*g;
dxnorm = norm(dx);
disp(sprintf('Correct for low angle: %g',a))
end
end
disp(sprintf('Predicted improvement: %18.9f',-dfhat/2))
%
% Have OK dx, now adjust length of step (lambda) until min and
% max improvement rate criteria are met.
done=0;
factor=3;
shrink=1;
lambdaMin=0;
lambdaMax=inf;
lambdaPeak=0;
fPeak=f0;
lambdahat=0;
while ~done
if size(x0,2)>1
dxtest=x0+dx'*lambda;
else
dxtest=x0+dx*lambda;
end
% home
f = feval(fcn,dxtest,varargin{:});
%ARGLIST
%f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13);
% f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8);
disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f ))
%debug
%disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda))
if f<fhat
fhat=f;
xhat=dxtest;
lambdahat = lambda;
end
fcount=fcount+1;
shrinkSignal = (~badg & (f0-f < max([-THETA*dfhat*lambda 0]))) | (badg & (f0-f) < 0) ;
growSignal = ~badg & ( (lambda > 0) & (f0-f > -(1-THETA)*dfhat*lambda) );
if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) )
if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak))
shrink=1;
factor=factor^.6;
while lambda/factor <= lambdaPeak
factor=factor^.6;
% with badg true, we don't try to match rate of improvement to directional
% derivative. We're satisfied just to get some improvement in f.
%
%if(badg)
% dx = -g*FCHANGE/(gnorm*gnorm);
% dxnorm = norm(dx);
% if dxnorm > 1e12
% disp('Bad, small gradient problem.')
% dx = dx*FCHANGE/dxnorm;
% end
%else
% Gauss-Newton step;
%---------- Start of 7/19/93 mod ---------------
%[v d] = eig(H0);
%toc
%d=max(1e-10,abs(diag(d)));
%d=abs(diag(d));
%dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g);
% toc
dx = -H0*g;
% toc
dxnorm = norm(dx);
if dxnorm > 1e12
disp('Near-singular H problem.')
dx = dx*FCHANGE/dxnorm;
end
dfhat = dx'*g0;
%end
%
%
if ~badg
% test for alignment of dx with gradient and fix if necessary
a = -dfhat/(gnorm*dxnorm);
if a<ANGLE
dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g;
dfhat = dx'*g;
dxnorm = norm(dx);
disp(sprintf('Correct for low angle: %g',a))
end
end
disp(sprintf('Predicted improvement: %18.9f',-dfhat/2))
%
% Have OK dx, now adjust length of step (lambda) until min and
% max improvement rate criteria are met.
done=0;
factor=3;
shrink=1;
lambdaMin=0;
lambdaMax=inf;
lambdaPeak=0;
fPeak=f0;
lambdahat=0;
while ~done
if size(x0,2)>1
dxtest=x0+dx'*lambda;
else
dxtest=x0+dx*lambda;
end
% home
f = feval(fcn,dxtest,varargin{:});
%ARGLIST
%f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13);
% f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8);
disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f ))
%debug
%disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda))
if f<fhat
fhat=f;
xhat=dxtest;
lambdahat = lambda;
end
fcount=fcount+1;
shrinkSignal = (~badg & (f0-f < max([-THETA*dfhat*lambda 0]))) | (badg & (f0-f) < 0) ;
growSignal = ~badg & ( (lambda > 0) & (f0-f > -(1-THETA)*dfhat*lambda) );
if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) )
if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak))
shrink=1;
factor=factor^.6;
while lambda/factor <= lambdaPeak
factor=factor^.6;
end
%if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB)
if abs(factor-1)<MINDFAC
if abs(lambda)<4
retcode=2;
else
retcode=7;
end
done=1;
end
end
%if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB)
if abs(factor-1)<MINDFAC
if abs(lambda)<4
retcode=2;
else
retcode=7;
end
done=1;
if (lambda<lambdaMax) & (lambda>lambdaPeak)
lambdaMax=lambda;
end
end
if (lambda<lambdaMax) & (lambda>lambdaPeak)
lambdaMax=lambda;
end
lambda=lambda/factor;
if abs(lambda) < MINLAMB
if (lambda > 0) & (f0 <= fhat)
% try going against gradient, which may be inaccurate
lambda = -lambda*factor^6
lambda=lambda/factor;
if abs(lambda) < MINLAMB
if (lambda > 0) & (f0 <= fhat)
% try going against gradient, which may be inaccurate
lambda = -lambda*factor^6
else
if lambda < 0
retcode = 6;
else
retcode = 3;
end
done = 1;
end
end
elseif (growSignal & lambda>0) | (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0)))
if shrink
shrink=0;
factor = factor^.6;
%if ( abs(lambda)*(factor-1)*dxnorm< MINDX ) | ( abs(lambda)*(factor-1)< MINLAMB)
if abs(factor-1)<MINDFAC
if abs(lambda)<4
retcode=4;
else
retcode=7;
end
done=1;
end
end
if ( f<fPeak ) & (lambda>0)
fPeak=f;
lambdaPeak=lambda;
if lambdaMax<=lambdaPeak
lambdaMax=lambdaPeak*factor*factor;
end
end
lambda=lambda*factor;
if abs(lambda) > 1e20;
retcode = 5;
done =1;
end
else
done=1;
if factor < 1.2
retcode=7;
else
if lambda < 0
retcode = 6;
else
retcode = 3;
end
done = 1;
retcode=0;
end
end
elseif (growSignal & lambda>0) | (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0)))
if shrink
shrink=0;
factor = factor^.6;
%if ( abs(lambda)*(factor-1)*dxnorm< MINDX ) | ( abs(lambda)*(factor-1)< MINLAMB)
if abs(factor-1)<MINDFAC
if abs(lambda)<4
retcode=4;
else
retcode=7;
end
done=1;
end
end
if ( f<fPeak ) & (lambda>0)
fPeak=f;
lambdaPeak=lambda;
if lambdaMax<=lambdaPeak
lambdaMax=lambdaPeak*factor*factor;
end
end
lambda=lambda*factor;
if abs(lambda) > 1e20;
retcode = 5;
done =1;
end
else
done=1;
if factor < 1.2
retcode=7;
else
retcode=0;
end
end
end
end
end
end
disp(sprintf('Norm of dx %10.5g', dxnorm))

View File

@ -1,309 +1,309 @@
function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel(fcn,x0,H0,grad,crit,nit,method,varargin)
%[fhat,xhat,ghat,Hhat,itct,fcount,retcodehat] = csminwel(fcn,x0,H0,grad,crit,nit,method,varargin)
% fcn: string naming the objective function to be minimized
% x0: initial value of the parameter vector
% H0: initial value for the inverse Hessian. Must be positive definite.
% grad: Either a string naming a function that calculates the gradient, or the null matrix.
% If it's null, the program calculates a numerical gradient. In this case fcn must
% be written so that it can take a matrix argument and produce a row vector of values.
% crit: Convergence criterion. Iteration will cease when it proves impossible to improve the
% function value by more than crit.
% nit: Maximum number of iterations.
% method: integer scalar, 2, 3 or 5 points formula.
% penalty: scalar double, size of the penality.
% varargin: A list of optional length of additional parameters that get handed off to fcn each
% time it is called.
% Note that if the program ends abnormally, it is possible to retrieve the current x,
% f, and H from the files g1.mat and H.mat that are written at each iteration and at each
% hessian update, respectively. (When the routine hits certain kinds of difficulty, it
% write g2.mat and g3.mat as well. If all were written at about the same time, any of them
% may be a decent starting point. One can also start from the one with best function value.)
% Original file downloaded from:
% http://sims.princeton.edu/yftp/optimize/mfiles/csminwel.m
% Copyright (C) 1993-2007 Christopher Sims
% Copyright (C) 2006-2008 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/>.
global bayestopt_
fh = [];
xh = [];
[nx,no]=size(x0);
nx=max(nx,no);
Verbose=1;
NumGrad= isempty(grad);
done=0;
itct=0;
fcount=0;
snit=100;
%tailstr = ')';
%stailstr = [];
% Lines below make the number of Pi's optional. This is inefficient, though, and precludes
% use of the matlab compiler. Without them, we use feval and the number of Pi's must be
% changed with the editor for each application. Places where this is required are marked
% with ARGLIST comments
%for i=nargin-6:-1:1
% tailstr=[ ',P' num2str(i) tailstr];
% stailstr=[' P' num2str(i) stailstr];
%end
[f0,cost_flag] = feval(fcn,x0,varargin{:});
if ~cost_flag
disp('Bad initial parameter.')
return
end
if NumGrad
switch method
case 2
[g,badg] = numgrad(fcn,x0, varargin{:});
case 3
[g,badg] = numgrad3(fcn,x0, varargin{:});
case 5
[g,badg] = numgrad5(fcn,x0, varargin{:});
end
else
[g,badg] = feval(grad,x0,varargin{:});
end
retcode3=101;
x=x0;
f=f0;
H=H0;
cliff=0;
while ~done
bayestopt_.penalty = f;
g1=[]; g2=[]; g3=[];
%addition fj. 7/6/94 for control
disp('-----------------')
disp('-----------------')
%disp('f and x at the beginning of new iteration')
disp(sprintf('f at the beginning of new iteration, %20.10f',f))
%-----------Comment out this line if the x vector is long----------------
% disp([sprintf('x = ') sprintf('%15.8g %15.8g %15.8g %15.8g\n',x)]);
%-------------------------
itct=itct+1;
[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,varargin{:});
%ARGLIST
%[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,P1,P2,P3,P4,P5,P6,P7,...
% P8,P9,P10,P11,P12,P13);
% itct=itct+1;
fcount = fcount+fc;
% erased on 8/4/94
% if (retcode == 1) | (abs(f1-f) < crit)
% done=1;
% end
% if itct > nit
% done = 1;
% retcode = -retcode;
% end
if retcode1 ~= 1
if retcode1==2 | retcode1==4
wall1=1; badg1=1;
else
if NumGrad
switch method
case 2
[g1 badg1] = numgrad(fcn, x1,varargin{:});
case 3
[g1 badg1] = numgrad3(fcn, x1,varargin{:});
case 5
[g1,badg1] = numgrad5(fcn,x0, varargin{:});
end
else
[g1 badg1] = feval(grad,x1,varargin{:});
end
wall1=badg1;
% g1
save g1.mat g1 x1 f1 varargin;
%ARGLIST
%save g1 g1 x1 f1 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end
if wall1 % & (~done) by Jinill
% Bad gradient or back and forth on step length. Possibly at
% cliff edge. Try perturbing search direction.
%
%fcliff=fh;xcliff=xh;
Hcliff=H+diag(diag(H).*rand(nx,1));
disp('Cliff. Perturbing search direction.')
[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,varargin{:});
%ARGLIST
%[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,P1,P2,P3,P4,...
% P5,P6,P7,P8,P9,P10,P11,P12,P13);
fcount = fcount+fc; % put by Jinill
if f2 < f
if retcode2==2 | retcode2==4
wall2=1; badg2=1;
else
if NumGrad
switch method
case 2
[g2 badg2] = numgrad(fcn, x2,varargin{:});
case 3
[g2 badg2] = numgrad3(fcn, x2,varargin{:});
case 5
[g2,badg2] = numgrad5(fcn,x0, varargin{:});
end
else
[g2 badg2] = feval(grad,x2,varargin{:});
end
wall2=badg2;
% g2
badg2
save g2.mat g2 x2 f2 varargin
%ARGLIST
%save g2 g2 x2 f2 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end
if wall2
disp('Cliff again. Try traversing')
if norm(x2-x1) < 1e-13
f3=f; x3=x; badg3=1;retcode3=101;
else
gcliff=((f2-f1)/((norm(x2-x1))^2))*(x2-x1);
if(size(x0,2)>1), gcliff=gcliff', end
[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),varargin{:});
%ARGLIST
%[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),P1,P2,P3,...
% P4,P5,P6,P7,P8,...
% P9,P10,P11,P12,P13);
fcount = fcount+fc; % put by Jinill
if retcode3==2 | retcode3==4
wall3=1; badg3=1;
else
if NumGrad
switch method
case 2
[g3 badg3] = numgrad(fcn, x3,varargin{:});
case 3
[g3 badg3] = numgrad3(fcn, x3,varargin{:});
case 5
[g3,badg3] = numgrad5(fcn,x0, varargin{:});
end
else
[g3 badg3] = feval(grad,x3,varargin{:});
end
wall3=badg3;
% g3
save g3.mat g3 x3 f3 varargin;
%ARGLIST
%save g3 g3 x3 f3 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end
end
else
f3=f; x3=x; badg3=1; retcode3=101;
end
else
f3=f; x3=x; badg3=1;retcode3=101;
end
else
% normal iteration, no walls, or else we're finished here.
f2=f; f3=f; badg2=1; badg3=1; retcode2=101; retcode3=101;
end
else
f2=f;f3=f;f1=f;retcode2=retcode1;retcode3=retcode1;
end
%how to pick gh and xh
if f3 < f - crit & badg3==0 & f3 < f2 & f3 < f1
ih=3;
fh=f3;xh=x3;gh=g3;badgh=badg3;retcodeh=retcode3;
elseif f2 < f - crit & badg2==0 & f2 < f1
ih=2;
fh=f2;xh=x2;gh=g2;badgh=badg2;retcodeh=retcode2;
elseif f1 < f - crit & badg1==0
ih=1;
fh=f1;xh=x1;gh=g1;badgh=badg1;retcodeh=retcode1;
else
[fh,ih] = min([f1,f2,f3]);
%disp(sprintf('ih = %d',ih))
%eval(['xh=x' num2str(ih) ';'])
switch ih
case 1
xh=x1;
case 2
xh=x2;
case 3
xh=x3;
end %case
%eval(['gh=g' num2str(ih) ';'])
%eval(['retcodeh=retcode' num2str(ih) ';'])
retcodei=[retcode1,retcode2,retcode3];
retcodeh=retcodei(ih);
if exist('gh')
nogh=isempty(gh);
else
nogh=1;
end
if nogh
if NumGrad
switch method
case 2
[gh,badgh] = numgrad(fcn,xh,varargin{:});
case 3
[gh,badgh] = numgrad3(fcn,xh,varargin{:});
case 5
[gh,badgh] = numgrad5(fcn,xh,varargin{:});
end
else
[gh badgh] = feval(grad, xh,varargin{:});
end
end
badgh=1;
end
%end of picking
%ih
%fh
%xh
%gh
%badgh
stuck = (abs(fh-f) < crit);
if (~badg)&(~badgh)&(~stuck)
H = bfgsi(H,gh-g,xh-x);
end
if Verbose
disp('----')
disp(sprintf('Improvement on iteration %d = %18.9f',itct,f-fh))
end
% if Verbose
if itct > nit
disp('iteration count termination')
done = 1;
elseif stuck
disp('improvement < crit termination')
done = 1;
end
rc=retcodeh;
if rc == 1
disp('zero gradient')
elseif rc == 6
disp('smallest step still improving too slow, reversed gradient')
elseif rc == 5
disp('largest step still improving too fast')
elseif (rc == 4) | (rc==2)
disp('back and forth on step length never finished')
elseif rc == 3
disp('smallest step still improving too slow')
elseif rc == 7
disp('warning: possible inaccuracy in H matrix')
end
% end
f=fh;
x=xh;
g=gh;
badg=badgh;
end
% what about making an m-file of 10 lines including numgrad.m
function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel(fcn,x0,H0,grad,crit,nit,method,varargin)
%[fhat,xhat,ghat,Hhat,itct,fcount,retcodehat] = csminwel(fcn,x0,H0,grad,crit,nit,method,varargin)
% fcn: string naming the objective function to be minimized
% x0: initial value of the parameter vector
% H0: initial value for the inverse Hessian. Must be positive definite.
% grad: Either a string naming a function that calculates the gradient, or the null matrix.
% If it's null, the program calculates a numerical gradient. In this case fcn must
% be written so that it can take a matrix argument and produce a row vector of values.
% crit: Convergence criterion. Iteration will cease when it proves impossible to improve the
% function value by more than crit.
% nit: Maximum number of iterations.
% method: integer scalar, 2, 3 or 5 points formula.
% penalty: scalar double, size of the penality.
% varargin: A list of optional length of additional parameters that get handed off to fcn each
% time it is called.
% Note that if the program ends abnormally, it is possible to retrieve the current x,
% f, and H from the files g1.mat and H.mat that are written at each iteration and at each
% hessian update, respectively. (When the routine hits certain kinds of difficulty, it
% write g2.mat and g3.mat as well. If all were written at about the same time, any of them
% may be a decent starting point. One can also start from the one with best function value.)
% Original file downloaded from:
% http://sims.princeton.edu/yftp/optimize/mfiles/csminwel.m
% Copyright (C) 1993-2007 Christopher Sims
% Copyright (C) 2006-2008 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/>.
global bayestopt_
fh = [];
xh = [];
[nx,no]=size(x0);
nx=max(nx,no);
Verbose=1;
NumGrad= isempty(grad);
done=0;
itct=0;
fcount=0;
snit=100;
%tailstr = ')';
%stailstr = [];
% Lines below make the number of Pi's optional. This is inefficient, though, and precludes
% use of the matlab compiler. Without them, we use feval and the number of Pi's must be
% changed with the editor for each application. Places where this is required are marked
% with ARGLIST comments
%for i=nargin-6:-1:1
% tailstr=[ ',P' num2str(i) tailstr];
% stailstr=[' P' num2str(i) stailstr];
%end
[f0,cost_flag] = feval(fcn,x0,varargin{:});
if ~cost_flag
disp('Bad initial parameter.')
return
end
if NumGrad
switch method
case 2
[g,badg] = numgrad(fcn,x0, varargin{:});
case 3
[g,badg] = numgrad3(fcn,x0, varargin{:});
case 5
[g,badg] = numgrad5(fcn,x0, varargin{:});
end
else
[g,badg] = feval(grad,x0,varargin{:});
end
retcode3=101;
x=x0;
f=f0;
H=H0;
cliff=0;
while ~done
bayestopt_.penalty = f;
g1=[]; g2=[]; g3=[];
%addition fj. 7/6/94 for control
disp('-----------------')
disp('-----------------')
%disp('f and x at the beginning of new iteration')
disp(sprintf('f at the beginning of new iteration, %20.10f',f))
%-----------Comment out this line if the x vector is long----------------
% disp([sprintf('x = ') sprintf('%15.8g %15.8g %15.8g %15.8g\n',x)]);
%-------------------------
itct=itct+1;
[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,varargin{:});
%ARGLIST
%[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,P1,P2,P3,P4,P5,P6,P7,...
% P8,P9,P10,P11,P12,P13);
% itct=itct+1;
fcount = fcount+fc;
% erased on 8/4/94
% if (retcode == 1) | (abs(f1-f) < crit)
% done=1;
% end
% if itct > nit
% done = 1;
% retcode = -retcode;
% end
if retcode1 ~= 1
if retcode1==2 | retcode1==4
wall1=1; badg1=1;
else
if NumGrad
switch method
case 2
[g1 badg1] = numgrad(fcn, x1,varargin{:});
case 3
[g1 badg1] = numgrad3(fcn, x1,varargin{:});
case 5
[g1,badg1] = numgrad5(fcn,x0, varargin{:});
end
else
[g1 badg1] = feval(grad,x1,varargin{:});
end
wall1=badg1;
% g1
save g1.mat g1 x1 f1 varargin;
%ARGLIST
%save g1 g1 x1 f1 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end
if wall1 % & (~done) by Jinill
% Bad gradient or back and forth on step length. Possibly at
% cliff edge. Try perturbing search direction.
%
%fcliff=fh;xcliff=xh;
Hcliff=H+diag(diag(H).*rand(nx,1));
disp('Cliff. Perturbing search direction.')
[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,varargin{:});
%ARGLIST
%[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,P1,P2,P3,P4,...
% P5,P6,P7,P8,P9,P10,P11,P12,P13);
fcount = fcount+fc; % put by Jinill
if f2 < f
if retcode2==2 | retcode2==4
wall2=1; badg2=1;
else
if NumGrad
switch method
case 2
[g2 badg2] = numgrad(fcn, x2,varargin{:});
case 3
[g2 badg2] = numgrad3(fcn, x2,varargin{:});
case 5
[g2,badg2] = numgrad5(fcn,x0, varargin{:});
end
else
[g2 badg2] = feval(grad,x2,varargin{:});
end
wall2=badg2;
% g2
badg2
save g2.mat g2 x2 f2 varargin
%ARGLIST
%save g2 g2 x2 f2 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end
if wall2
disp('Cliff again. Try traversing')
if norm(x2-x1) < 1e-13
f3=f; x3=x; badg3=1;retcode3=101;
else
gcliff=((f2-f1)/((norm(x2-x1))^2))*(x2-x1);
if(size(x0,2)>1), gcliff=gcliff', end
[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),varargin{:});
%ARGLIST
%[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),P1,P2,P3,...
% P4,P5,P6,P7,P8,...
% P9,P10,P11,P12,P13);
fcount = fcount+fc; % put by Jinill
if retcode3==2 | retcode3==4
wall3=1; badg3=1;
else
if NumGrad
switch method
case 2
[g3 badg3] = numgrad(fcn, x3,varargin{:});
case 3
[g3 badg3] = numgrad3(fcn, x3,varargin{:});
case 5
[g3,badg3] = numgrad5(fcn,x0, varargin{:});
end
else
[g3 badg3] = feval(grad,x3,varargin{:});
end
wall3=badg3;
% g3
save g3.mat g3 x3 f3 varargin;
%ARGLIST
%save g3 g3 x3 f3 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end
end
else
f3=f; x3=x; badg3=1; retcode3=101;
end
else
f3=f; x3=x; badg3=1;retcode3=101;
end
else
% normal iteration, no walls, or else we're finished here.
f2=f; f3=f; badg2=1; badg3=1; retcode2=101; retcode3=101;
end
else
f2=f;f3=f;f1=f;retcode2=retcode1;retcode3=retcode1;
end
%how to pick gh and xh
if f3 < f - crit & badg3==0 & f3 < f2 & f3 < f1
ih=3;
fh=f3;xh=x3;gh=g3;badgh=badg3;retcodeh=retcode3;
elseif f2 < f - crit & badg2==0 & f2 < f1
ih=2;
fh=f2;xh=x2;gh=g2;badgh=badg2;retcodeh=retcode2;
elseif f1 < f - crit & badg1==0
ih=1;
fh=f1;xh=x1;gh=g1;badgh=badg1;retcodeh=retcode1;
else
[fh,ih] = min([f1,f2,f3]);
%disp(sprintf('ih = %d',ih))
%eval(['xh=x' num2str(ih) ';'])
switch ih
case 1
xh=x1;
case 2
xh=x2;
case 3
xh=x3;
end %case
%eval(['gh=g' num2str(ih) ';'])
%eval(['retcodeh=retcode' num2str(ih) ';'])
retcodei=[retcode1,retcode2,retcode3];
retcodeh=retcodei(ih);
if exist('gh')
nogh=isempty(gh);
else
nogh=1;
end
if nogh
if NumGrad
switch method
case 2
[gh,badgh] = numgrad(fcn,xh,varargin{:});
case 3
[gh,badgh] = numgrad3(fcn,xh,varargin{:});
case 5
[gh,badgh] = numgrad5(fcn,xh,varargin{:});
end
else
[gh badgh] = feval(grad, xh,varargin{:});
end
end
badgh=1;
end
%end of picking
%ih
%fh
%xh
%gh
%badgh
stuck = (abs(fh-f) < crit);
if (~badg)&(~badgh)&(~stuck)
H = bfgsi(H,gh-g,xh-x);
end
if Verbose
disp('----')
disp(sprintf('Improvement on iteration %d = %18.9f',itct,f-fh))
end
% if Verbose
if itct > nit
disp('iteration count termination')
done = 1;
elseif stuck
disp('improvement < crit termination')
done = 1;
end
rc=retcodeh;
if rc == 1
disp('zero gradient')
elseif rc == 6
disp('smallest step still improving too slow, reversed gradient')
elseif rc == 5
disp('largest step still improving too fast')
elseif (rc == 4) | (rc==2)
disp('back and forth on step length never finished')
elseif rc == 3
disp('smallest step still improving too slow')
elseif rc == 7
disp('warning: possible inaccuracy in H matrix')
end
% end
f=fh;
x=xh;
g=gh;
badg=badgh;
end
% what about making an m-file of 10 lines including numgrad.m
% since it appears three times in csminwel.m

View File

@ -49,121 +49,121 @@ alpha=1e-3;
%---------------------------------------
%------------ verbose ----------------
verbose=0;% if this is set to zero, all screen output is suppressed
%-------------------------------------
%------------ analyticg --------------
%-------------------------------------
%------------ analyticg --------------
analyticg=1-isempty(gradfun); %if the grad argument is [], numerical derivatives are used.
%-------------------------------------
%-------------------------------------
nv=length(x);
tvec=delta*eye(nv);
done=0;
if isempty(varargin)
f0=feval(FUN,x);
f0=feval(FUN,x);
else
f0=feval(FUN,x,varargin{:});
f0=feval(FUN,x,varargin{:});
end
af0=sum(abs(f0));
af00=af0;
itct=0;
while ~done
% disp([af00-af0 crit*max(1,af0)])
if itct>3 & af00-af0<crit*max(1,af0) & rem(itct,2)==1
randomize=1;
else
if ~analyticg
% disp([af00-af0 crit*max(1,af0)])
if itct>3 & af00-af0<crit*max(1,af0) & rem(itct,2)==1
randomize=1;
else
if ~analyticg
% $$$ if isempty(varargin)
% $$$ grad = (feval(FUN,x*ones(1,nv)+tvec)-f0*ones(1,nv))/delta;
% $$$ else
% $$$ grad = (feval(FUN,x*ones(1,nv)+tvec,varargin{:})-f0*ones(1,nv))/delta;
% $$$ end
grad = zeros(nv,nv);
for i=1:nv
grad(:,i) = (feval(FUN,x+tvec(:,i),varargin{:})-f0)/delta;
end
else % use analytic gradient
% grad=feval(gradfun,x,varargin{:});
[f0,grad] = feval(gradfun,x,varargin{:});
end
if isreal(grad)
if rcond(grad)<1e-12
grad=grad+tvec;
end
dx0=-grad\f0;
randomize=0;
else
if(verbose),disp('gradient imaginary'),end
randomize=1;
end
end
if randomize
if(verbose),fprintf(1,'\n Random Search'),end
dx0=norm(x)./randn(size(x));
end
lambda=1;
lambdamin=1;
fmin=f0;
xmin=x;
afmin=af0;
dxSize=norm(dx0);
factor=.6;
shrink=1;
subDone=0;
while ~subDone
dx=lambda*dx0;
f=feval(FUN,x+dx,varargin{:});
af=sum(abs(f));
if af<afmin
afmin=af;
fmin=f;
lambdamin=lambda;
xmin=x+dx;
end
if ((lambda >0) & (af0-af < alpha*lambda*af0)) | ((lambda<0) & (af0-af < 0) )
if ~shrink
factor=factor^.6;
shrink=1;
end
if abs(lambda*(1-factor))*dxSize > .1*delta;
lambda = factor*lambda;
elseif (lambda > 0) & (factor==.6) %i.e., we've only been shrinking
lambda=-.3;
else %
subDone=1;
if lambda > 0
if factor==.6
rc = 2;
else
rc = 1;
end
else
rc=3;
grad = zeros(nv,nv);
for i=1:nv
grad(:,i) = (feval(FUN,x+tvec(:,i),varargin{:})-f0)/delta;
end
end
elseif (lambda >0) & (af-af0 > (1-alpha)*lambda*af0)
if shrink
factor=factor^.6;
shrink=0;
end
lambda=lambda/factor;
else % good value found
subDone=1;
rc=0;
end
end % while ~subDone
itct=itct+1;
if(verbose)
fprintf(1,'\nitct %d, af %g, lambda %g, rc %g',itct,afmin,lambdamin,rc)
fprintf(1,'\n x %10g %10g %10g %10g',xmin);
fprintf(1,'\n f %10g %10g %10g %10g',fmin);
end
x=xmin;
f0=fmin;
af00=af0;
af0=afmin;
if itct >= itmax
done=1;
rc=4;
elseif af0<crit;
done=1;
rc=0;
end
else % use analytic gradient
% grad=feval(gradfun,x,varargin{:});
[f0,grad] = feval(gradfun,x,varargin{:});
end
if isreal(grad)
if rcond(grad)<1e-12
grad=grad+tvec;
end
dx0=-grad\f0;
randomize=0;
else
if(verbose),disp('gradient imaginary'),end
randomize=1;
end
end
if randomize
if(verbose),fprintf(1,'\n Random Search'),end
dx0=norm(x)./randn(size(x));
end
lambda=1;
lambdamin=1;
fmin=f0;
xmin=x;
afmin=af0;
dxSize=norm(dx0);
factor=.6;
shrink=1;
subDone=0;
while ~subDone
dx=lambda*dx0;
f=feval(FUN,x+dx,varargin{:});
af=sum(abs(f));
if af<afmin
afmin=af;
fmin=f;
lambdamin=lambda;
xmin=x+dx;
end
if ((lambda >0) & (af0-af < alpha*lambda*af0)) | ((lambda<0) & (af0-af < 0) )
if ~shrink
factor=factor^.6;
shrink=1;
end
if abs(lambda*(1-factor))*dxSize > .1*delta;
lambda = factor*lambda;
elseif (lambda > 0) & (factor==.6) %i.e., we've only been shrinking
lambda=-.3;
else %
subDone=1;
if lambda > 0
if factor==.6
rc = 2;
else
rc = 1;
end
else
rc=3;
end
end
elseif (lambda >0) & (af-af0 > (1-alpha)*lambda*af0)
if shrink
factor=factor^.6;
shrink=0;
end
lambda=lambda/factor;
else % good value found
subDone=1;
rc=0;
end
end % while ~subDone
itct=itct+1;
if(verbose)
fprintf(1,'\nitct %d, af %g, lambda %g, rc %g',itct,afmin,lambdamin,rc)
fprintf(1,'\n x %10g %10g %10g %10g',xmin);
fprintf(1,'\n f %10g %10g %10g %10g',fmin);
end
x=xmin;
f0=fmin;
af00=af0;
af0=afmin;
if itct >= itmax
done=1;
rc=4;
elseif af0<crit;
done=1;
rc=0;
end
end

View File

@ -1,63 +1,63 @@
function datatomfile (s,var_list)
% function datatomfile (s,var_list)
% This optional command saves the simulation results in a text file. The name of each
% variable preceeds the corresponding results. This command must follow SIMUL.
%
% INPUTS
% s: data file name
% var_list: vector of selected endogenous variables
%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2001-2009 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/>.
global M_ oo_
sm=[s,'.m'];
fid=fopen(sm,'w') ;
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr,:);
end
n = size(var_list,1);
ivar=zeros(n,1);
for i=1:n
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact');
if isempty(i_tmp)
error (['One of the specified variables does not exist']) ;
else
ivar(i) = i_tmp;
end
end
for i = 1:n
fprintf(fid,[M_.endo_names(ivar(i),:), '=['],'\n') ;
fprintf(fid,'\n') ;
fprintf(fid,'%15.8g\n',oo_.endo_simul(ivar(i),:)') ;
fprintf(fid,'\n') ;
fprintf(fid,'];\n') ;
fprintf(fid,'\n') ;
end
fclose(fid) ;
function datatomfile (s,var_list)
% function datatomfile (s,var_list)
% This optional command saves the simulation results in a text file. The name of each
% variable preceeds the corresponding results. This command must follow SIMUL.
%
% INPUTS
% s: data file name
% var_list: vector of selected endogenous variables
%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2001-2009 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/>.
global M_ oo_
sm=[s,'.m'];
fid=fopen(sm,'w') ;
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr,:);
end
n = size(var_list,1);
ivar=zeros(n,1);
for i=1:n
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact');
if isempty(i_tmp)
error (['One of the specified variables does not exist']) ;
else
ivar(i) = i_tmp;
end
end
for i = 1:n
fprintf(fid,[M_.endo_names(ivar(i),:), '=['],'\n') ;
fprintf(fid,'\n') ;
fprintf(fid,'%15.8g\n',oo_.endo_simul(ivar(i),:)') ;
fprintf(fid,'\n') ;
fprintf(fid,'];\n') ;
fprintf(fid,'\n') ;
end
fclose(fid) ;

View File

@ -24,27 +24,27 @@ ftest(s1,0) ;
i = [lag1(1):size(x,2)-lag1(2)+1]' ;
if size(options_.smpl,1) == 1
error(['DSAMPLE not specified.']) ;
error(['DSAMPLE not specified.']) ;
end
if options_.smpl(3) > 0
if options_.smpl(3) == 2
if options_.smpl(1)<0 | options_.smpl(2)>size(x,2)-lag1(2)
error ('Wrong sample.') ;
end
i = [options_.smpl(1)+lag1(1):options_.smpl(2)+lag1(1)]' ;
elseif options_.smpl(3) == 1
if options_.smpl(1)>size(x,2)-lag1(2)
error ('Wrong sample.') ;
end
i = [lag1(1):options_.smpl(1)+lag1(1)]' ;
end
if options_.smpl(3) == 2
if options_.smpl(1)<0 | options_.smpl(2)>size(x,2)-lag1(2)
error ('Wrong sample.') ;
end
i = [options_.smpl(1)+lag1(1):options_.smpl(2)+lag1(1)]' ;
elseif options_.smpl(3) == 1
if options_.smpl(1)>size(x,2)-lag1(2)
error ('Wrong sample.') ;
end
i = [lag1(1):options_.smpl(1)+lag1(1)]' ;
end
end
j = bseastr(nvx,nvy) ;
if stop
return ;
return ;
end
z = mean(mean(abs(x(j,i)-y(j,i)))) ;

View File

@ -25,7 +25,7 @@ function d = diag_vech(Vector)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
m = length(Vector);
n = (sqrt(1+8*m)-1)/2;
k = cumsum(1:n);
d = Vector(k);
m = length(Vector);
n = (sqrt(1+8*m)-1)/2;
k = cumsum(1:n);
d = Vector(k);

View File

@ -6,7 +6,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-2009 Dynare Team
%
% This file is part of Dynare.
@ -24,190 +24,190 @@ function disp_dr(dr,order,var_list)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_
nx =size(dr.ghx,2);
nu =size(dr.ghu,2);
k = find(dr.kstate(:,2) <= M_.maximum_lag+1);
klag = dr.kstate(k,[1 2]);
k1 = dr.order_var;
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
global M_
nvar = size(var_list,1);
nx =size(dr.ghx,2);
nu =size(dr.ghu,2);
k = find(dr.kstate(:,2) <= M_.maximum_lag+1);
klag = dr.kstate(k,[1 2]);
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names(k1,:),'exact');
if isempty(i_tmp)
k1 = dr.order_var;
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
nvar = size(var_list,1);
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names(k1,:),'exact');
if isempty(i_tmp)
disp(var_list(i,:));
error (['One of the variable specified does not exist']) ;
else
else
ivar(i) = i_tmp;
end
end
end
disp('POLICY AND TRANSITION FUNCTIONS')
% variable names
str = ' ';
for i=1:nvar
disp('POLICY AND TRANSITION FUNCTIONS')
% variable names
str = ' ';
for i=1:nvar
str = [str sprintf('%16s',M_.endo_names(k1(ivar(i)),:))];
end
disp(str);
%
% constant
%
str = 'Constant ';
flag = 0;
for i=1:nvar
end
disp(str);
%
% constant
%
str = 'Constant ';
flag = 0;
for i=1:nvar
x = dr.ys(k1(ivar(i)));
if order > 1
x = x + dr.ghs2(ivar(i))/2;
x = x + dr.ghs2(ivar(i))/2;
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
str = [str ' 0'];
end
end
if flag
end
if flag
disp(str)
end
if order > 1
end
if order > 1
str = '(correction) ';
flag = 0;
for i=1:nvar
x = dr.ghs2(ivar(i))/2;
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
x = dr.ghs2(ivar(i))/2;
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
disp(str)
end
end
%
% ghx
%
for k=1:nx
end
%
% ghx
%
for k=1:nx
flag = 0;
str1 = subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2);
str = sprintf('%-20s',str1);
for i=1:nvar
x = dr.ghx(ivar(i),k);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
x = dr.ghx(ivar(i),k);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
disp(str)
end
end
%
% ghu
%
for k=1:nu
end
%
% ghu
%
for k=1:nu
flag = 0;
str = sprintf('%-20s',M_.exo_names(k,:));
for i=1:nvar
x = dr.ghu(ivar(i),k);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
x = dr.ghu(ivar(i),k);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
disp(str)
end
end
end
if order > 1
if order > 1
% ghxx
for k = 1:nx
for j = 1:k
flag = 0;
str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
subst_auxvar(k1(klag(j,1)),klag(j,2)-M_.maximum_lag-2));
str = sprintf('%-20s',str1);
for i=1:nvar
if k == j
x = dr.ghxx(ivar(i),(k-1)*nx+j)/2;
else
x = dr.ghxx(ivar(i),(k-1)*nx+j);
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
for j = 1:k
flag = 0;
str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
subst_auxvar(k1(klag(j,1)),klag(j,2)-M_.maximum_lag-2));
str = sprintf('%-20s',str1);
for i=1:nvar
if k == j
x = dr.ghxx(ivar(i),(k-1)*nx+j)/2;
else
x = dr.ghxx(ivar(i),(k-1)*nx+j);
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
end
%
% ghuu
%
for k = 1:nu
for j = 1:k
flag = 0;
str = sprintf('%-20s',[M_.exo_names(k,:) ',' M_.exo_names(j,:)] );
for i=1:nvar
if k == j
x = dr.ghuu(ivar(i),(k-1)*nu+j)/2;
else
x = dr.ghuu(ivar(i),(k-1)*nu+j);
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
for j = 1:k
flag = 0;
str = sprintf('%-20s',[M_.exo_names(k,:) ',' M_.exo_names(j,:)] );
for i=1:nvar
if k == j
x = dr.ghuu(ivar(i),(k-1)*nu+j)/2;
else
x = dr.ghuu(ivar(i),(k-1)*nu+j);
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
end
%
% ghxu
%
for k = 1:nx
for j = 1:nu
flag = 0;
str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
M_.exo_names(j,:));
str = sprintf('%-20s',str1);
for i=1:nvar
x = dr.ghxu(ivar(i),(k-1)*nu+j);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
for j = 1:nu
flag = 0;
str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
M_.exo_names(j,:));
str = sprintf('%-20s',str1);
for i=1:nvar
x = dr.ghxu(ivar(i),(k-1)*nu+j);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
end
end
end
end
% Given the index of an endogenous (possibly an auxiliary var), and a
@ -215,25 +215,25 @@ end
% In the case of auxiliary vars for lags, replace by the original variable
% name, and compute the lead/lag accordingly.
function str = subst_auxvar(aux_index, aux_lead_lag)
global M_
if aux_index <= M_.orig_endo_nbr
str = sprintf('%s(%d)', deblank(M_.endo_names(aux_index,:)), aux_lead_lag);
global M_
if aux_index <= M_.orig_endo_nbr
str = sprintf('%s(%d)', deblank(M_.endo_names(aux_index,:)), aux_lead_lag);
return
end
for i = 1:length(M_.aux_vars)
if M_.aux_vars(i).endo_index == aux_index
switch M_.aux_vars(i).type
case 1
orig_name = deblank(M_.endo_names(M_.aux_vars(i).orig_index, :));
case 3
orig_name = deblank(M_.exo_names(M_.aux_vars(i).orig_index, :));
otherwise
error(sprintf('Invalid auxiliary type: %s', M_.endo_names(aux_index, :)))
end
str = sprintf('%s(%d)', orig_name, M_.aux_vars(i).orig_lead_lag+aux_lead_lag);
return
end
for i = 1:length(M_.aux_vars)
if M_.aux_vars(i).endo_index == aux_index
switch M_.aux_vars(i).type
case 1
orig_name = deblank(M_.endo_names(M_.aux_vars(i).orig_index, :));
case 3
orig_name = deblank(M_.exo_names(M_.aux_vars(i).orig_index, :));
otherwise
error(sprintf('Invalid auxiliary type: %s', M_.endo_names(aux_index, :)))
end
str = sprintf('%s(%d)', orig_name, M_.aux_vars(i).orig_lead_lag+aux_lead_lag);
return
end
end
error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :)))
end
error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :)))
end

View File

@ -25,209 +25,209 @@ function disp_dr_sparse(dr,order,var_list)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_
nx = 0;
nu = 0;
k = [];
klag = [];
k1 = [];
nspred = 0;
for i=1:length(M_.block_structure.block)
nspred = nspred + M_.block_structure.block(i).dr.nspred;
end;
ghu = zeros(M_.endo_nbr, M_.exo_nbr*(M_.maximum_exo_lag+M_.maximum_exo_lead+1));
ghx = zeros(M_.endo_nbr, nspred);
for i=1:length(M_.block_structure.block)
nx = nx + size(M_.block_structure.block(i).dr.ghx,2);
% M_.block_structure.block(i).dr.ghx
% M_.block_structure.block(i).equation
% M_.block_structure.block(i).variable
ghx(M_.block_structure.block(i).equation, M_.block_structure.block(i).variable(find(M_.block_structure.block(i).lead_lag_incidence(1: M_.block_structure.block(i).maximum_endo_lag,:))) ) = M_.block_structure.block(i).dr.ghx;
if(M_.block_structure.block(i).exo_nbr)
global M_
nx = 0;
nu = 0;
k = [];
klag = [];
k1 = [];
nspred = 0;
for i=1:length(M_.block_structure.block)
nspred = nspred + M_.block_structure.block(i).dr.nspred;
end;
ghu = zeros(M_.endo_nbr, M_.exo_nbr*(M_.maximum_exo_lag+M_.maximum_exo_lead+1));
ghx = zeros(M_.endo_nbr, nspred);
for i=1:length(M_.block_structure.block)
nx = nx + size(M_.block_structure.block(i).dr.ghx,2);
% M_.block_structure.block(i).dr.ghx
% M_.block_structure.block(i).equation
% M_.block_structure.block(i).variable
ghx(M_.block_structure.block(i).equation, M_.block_structure.block(i).variable(find(M_.block_structure.block(i).lead_lag_incidence(1: M_.block_structure.block(i).maximum_endo_lag,:))) ) = M_.block_structure.block(i).dr.ghx;
if(M_.block_structure.block(i).exo_nbr)
nu = nu + size(M_.block_structure.block(i).dr.ghu,2);
ghu(M_.block_structure.block(i).equation, M_.block_structure.block(i).exogenous) = M_.block_structure.block(i).dr.ghu;
end
k_tmp = find(M_.block_structure.block(i).dr.kstate(:,2) <= M_.block_structure.block(i).maximum_lag+1);
k = [k ; k_tmp];
klag = [klag ; M_.block_structure.block(i).dr.kstate(k_tmp,[1 2])];
k1 = [k1 ; M_.block_structure.block(i).variable(M_.block_structure.block(i).dr.order_var)'];
end
end
k_tmp = find(M_.block_structure.block(i).dr.kstate(:,2) <= M_.block_structure.block(i).maximum_lag+1);
k = [k ; k_tmp];
klag = [klag ; M_.block_structure.block(i).dr.kstate(k_tmp,[1 2])];
k1 = [k1 ; M_.block_structure.block(i).variable(M_.block_structure.block(i).dr.order_var)'];
end
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
nvar = size(var_list,1);
nvar = size(var_list,1);
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names(k1,:),'exact');
if isempty(i_tmp)
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names(k1,:),'exact');
if isempty(i_tmp)
disp(var_list(i,:));
error (['One of the variable specified does not exist']) ;
else
else
ivar(i) = i_tmp;
end
end
end
disp('POLICY AND TRANSITION FUNCTIONS')
% variable names
str = ' ';
for i=1:nvar
disp('POLICY AND TRANSITION FUNCTIONS')
% variable names
str = ' ';
for i=1:nvar
str = [str sprintf('%16s',M_.endo_names(k1(ivar(i)),:))];
end
disp(str);
%
% constant
%
str = 'Constant ';
flag = 0;
for i=1:nvar
end
disp(str);
%
% constant
%
str = 'Constant ';
flag = 0;
for i=1:nvar
x = dr.ys(k1(ivar(i)));
if order > 1
x = x + dr.ghs2(ivar(i))/2;
x = x + dr.ghs2(ivar(i))/2;
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
str = [str ' 0'];
end
end
if flag
end
if flag
disp(str)
end
if order > 1
end
if order > 1
str = '(correction) ';
flag = 0;
for i=1:nvar
x = dr.ghs2(ivar(i))/2;
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
x = dr.ghs2(ivar(i))/2;
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
disp(str)
end
end
%
% ghx
%
for k=1:nx
end
%
% ghx
%
for k=1:nx
flag = 0;
str1 = subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2);
str = sprintf('%-20s',str1);
for i=1:nvar
x = ghx(ivar(i),k);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
x = ghx(ivar(i),k);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
disp(str)
end
end
%
% ghu
%
for k=1:nu
end
%
% ghu
%
for k=1:nu
flag = 0;
str = sprintf('%-20s',M_.exo_names(k,:));
for i=1:nvar
x = ghu(ivar(i),k);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
x = ghu(ivar(i),k);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
disp(str)
end
end
end
if order > 1
if order > 1
% ghxx
for k = 1:nx
for j = 1:k
flag = 0;
str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
subst_auxvar(k1(klag(j,1)),klag(j,2)-M_.maximum_lag-2));
str = sprintf('%-20s',str1);
for i=1:nvar
if k == j
x = dr.ghxx(ivar(i),(k-1)*nx+j)/2;
else
x = dr.ghxx(ivar(i),(k-1)*nx+j);
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
for j = 1:k
flag = 0;
str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
subst_auxvar(k1(klag(j,1)),klag(j,2)-M_.maximum_lag-2));
str = sprintf('%-20s',str1);
for i=1:nvar
if k == j
x = dr.ghxx(ivar(i),(k-1)*nx+j)/2;
else
x = dr.ghxx(ivar(i),(k-1)*nx+j);
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
end
%
% ghuu
%
for k = 1:nu
for j = 1:k
flag = 0;
str = sprintf('%-20s',[M_.exo_names(k,:) ',' M_.exo_names(j,:)] );
for i=1:nvar
if k == j
x = dr.ghuu(ivar(i),(k-1)*nu+j)/2;
else
x = dr.ghuu(ivar(i),(k-1)*nu+j);
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
for j = 1:k
flag = 0;
str = sprintf('%-20s',[M_.exo_names(k,:) ',' M_.exo_names(j,:)] );
for i=1:nvar
if k == j
x = dr.ghuu(ivar(i),(k-1)*nu+j)/2;
else
x = dr.ghuu(ivar(i),(k-1)*nu+j);
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
end
%
% ghxu
%
for k = 1:nx
for j = 1:nu
flag = 0;
str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
M_.exo_names(j,:));
str = sprintf('%-20s',str1);
for i=1:nvar
x = dr.ghxu(ivar(i),(k-1)*nu+j);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
for j = 1:nu
flag = 0;
str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
M_.exo_names(j,:));
str = sprintf('%-20s',str1);
for i=1:nvar
x = dr.ghxu(ivar(i),(k-1)*nu+j);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
end
if flag
disp(str)
end
end
end
end
end
end
% Given the index of an endogenous (possibly an auxiliary var), and a
@ -235,25 +235,25 @@ end
% In the case of auxiliary vars for lags, replace by the original variable
% name, and compute the lead/lag accordingly.
function str = subst_auxvar(aux_index, aux_lead_lag)
global M_
if aux_index <= M_.orig_endo_nbr
str = sprintf('%s(%d)', deblank(M_.endo_names(aux_index,:)), aux_lead_lag);
global M_
if aux_index <= M_.orig_endo_nbr
str = sprintf('%s(%d)', deblank(M_.endo_names(aux_index,:)), aux_lead_lag);
return
end
for i = 1:length(M_.aux_vars)
if M_.aux_vars(i).endo_index == aux_index
switch M_.aux_vars(i).type
case 1
orig_name = deblank(M_.endo_names(M_.aux_vars(i).orig_index, :));
case 3
orig_name = deblank(M_.exo_names(M_.aux_vars(i).orig_index, :));
otherwise
error(sprintf('Invalid auxiliary type: %s', M_.endo_names(aux_index, :)))
end
str = sprintf('%s(%d)', orig_name, M_.aux_vars(i).orig_lead_lag+aux_lead_lag);
return
end
for i = 1:length(M_.aux_vars)
if M_.aux_vars(i).endo_index == aux_index
switch M_.aux_vars(i).type
case 1
orig_name = deblank(M_.endo_names(M_.aux_vars(i).orig_index, :));
case 3
orig_name = deblank(M_.exo_names(M_.aux_vars(i).orig_index, :));
otherwise
error(sprintf('Invalid auxiliary type: %s', M_.endo_names(aux_index, :)))
end
str = sprintf('%s(%d)', orig_name, M_.aux_vars(i).orig_lead_lag+aux_lead_lag);
return
end
end
error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :)))
end
error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :)))
end

View File

@ -1,107 +1,107 @@
function disp_identification(pdraws, idemodel, idemoments, disp_pcorr)
% Copyright (C) 2008 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/>.
global bayestopt_
if nargin<4 | isempty(disp_pcorr),
disp_pcorr=0;
end
[SampleSize, npar] = size(pdraws);
jok = 0;
jokP = 0;
jokJ = 0;
jokPJ = 0;
if ~any(any(idemodel.ind==0))
disp(['All parameters are identified in the model in the MC sample (rank of H).' ]),
disp(' ')
end
if ~any(any(idemoments.ind==0))
disp(['All parameters are identified by J moments in the MC sample (rank of J)' ]),
end
for j=1:npar,
if any(idemodel.ind(j,:)==0),
pno = 100*length(find(idemodel.ind(j,:)==0))/SampleSize;
disp(['Parameter ',bayestopt_.name{j},' is not identified in the model for ',num2str(pno),'% of MC runs!' ])
disp(' ')
end
if any(idemoments.ind(j,:)==0),
pno = 100*length(find(idemoments.ind(j,:)==0))/SampleSize;
disp(['Parameter ',bayestopt_.name{j},' is not identified by J moments for ',num2str(pno),'% of MC runs!' ])
disp(' ')
end
if any(idemodel.ind(j,:)==1),
iok = find(idemodel.ind(j,:)==1);
jok = jok+1;
kok(jok) = j;
mmin(jok,1) = min(idemodel.Mco(j,iok));
mmean(jok,1) = mean(idemodel.Mco(j,iok));
mmax(jok,1) = max(idemodel.Mco(j,iok));
[ipmax, jpmax] = find(abs(squeeze(idemodel.Pco(j,[1:j-1,j+1:end],iok)))>0.95);
if ~isempty(ipmax)
jokP = jokP+1;
kokP(jokP) = j;
ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1;
[N,X]=hist(ipmax,[1:npar]);
jpM(jokP)={find(N)};
NPM(jokP)={N(find(N))./SampleSize.*100};
pmeanM(jokP)={mean(squeeze(idemodel.Pco(j,find(N),iok))')};
pminM(jokP)={min(squeeze(idemodel.Pco(j,find(N),iok))')};
pmaxM(jokP)={max(squeeze(idemodel.Pco(j,find(N),iok))')};
end
end
if any(idemoments.ind(j,:)==1),
iok = find(idemoments.ind(j,:)==1);
jokJ = jokJ+1;
kokJ(jokJ) = j;
mminJ(jokJ,1) = min(idemoments.Mco(j,iok));
mmeanJ(jokJ,1) = mean(idemoments.Mco(j,iok));
mmaxJ(jokJ,1) = max(idemoments.Mco(j,iok));
[ipmax, jpmax] = find(abs(squeeze(idemoments.Pco(j,[1:j-1,j+1:end],iok)))>0.95);
if ~isempty(ipmax)
jokPJ = jokPJ+1;
kokPJ(jokPJ) = j;
ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1;
[N,X]=hist(ipmax,[1:npar]);
jpJ(jokPJ)={find(N)};
NPJ(jokPJ)={N(find(N))./SampleSize.*100};
pmeanJ(jokPJ)={mean(squeeze(idemoments.Pco(j,find(N),iok))')};
pminJ(jokPJ)={min(squeeze(idemoments.Pco(j,find(N),iok))')};
pmaxJ(jokPJ)={max(squeeze(idemoments.Pco(j,find(N),iok))')};
end
end
end
dyntable('Multi collinearity in the model:',strvcat('param','min','mean','max'), ...
strvcat(bayestopt_.name(kok)),[mmin, mmean, mmax],10,10,6);
dyntable('Multi collinearity for moments in J:',strvcat('param','min','mean','max'), ...
strvcat(bayestopt_.name(kokJ)),[mminJ, mmeanJ, mmaxJ],10,10,6);
if disp_pcorr,
for j=1:length(kokP),
dyntable([bayestopt_.name{kokP(j)},' pairwise correlations in the model'],strvcat(' ','min','mean','max'), ...
strvcat(bayestopt_.name{jpM{j}}),[pminM{j}' pmeanM{j}' pmaxM{j}'],10,10,3);
end
for j=1:length(kokPJ),
dyntable([bayestopt_.name{kokPJ(j)},' pairwise correlations in J moments'],strvcat(' ','min','mean','max'), ...
strvcat(bayestopt_.name{jpJ{j}}),[pminJ{j}' pmeanJ{j}' pmaxJ{j}'],10,10,3);
end
end
function disp_identification(pdraws, idemodel, idemoments, disp_pcorr)
% Copyright (C) 2008 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/>.
global bayestopt_
if nargin<4 | isempty(disp_pcorr),
disp_pcorr=0;
end
[SampleSize, npar] = size(pdraws);
jok = 0;
jokP = 0;
jokJ = 0;
jokPJ = 0;
if ~any(any(idemodel.ind==0))
disp(['All parameters are identified in the model in the MC sample (rank of H).' ]),
disp(' ')
end
if ~any(any(idemoments.ind==0))
disp(['All parameters are identified by J moments in the MC sample (rank of J)' ]),
end
for j=1:npar,
if any(idemodel.ind(j,:)==0),
pno = 100*length(find(idemodel.ind(j,:)==0))/SampleSize;
disp(['Parameter ',bayestopt_.name{j},' is not identified in the model for ',num2str(pno),'% of MC runs!' ])
disp(' ')
end
if any(idemoments.ind(j,:)==0),
pno = 100*length(find(idemoments.ind(j,:)==0))/SampleSize;
disp(['Parameter ',bayestopt_.name{j},' is not identified by J moments for ',num2str(pno),'% of MC runs!' ])
disp(' ')
end
if any(idemodel.ind(j,:)==1),
iok = find(idemodel.ind(j,:)==1);
jok = jok+1;
kok(jok) = j;
mmin(jok,1) = min(idemodel.Mco(j,iok));
mmean(jok,1) = mean(idemodel.Mco(j,iok));
mmax(jok,1) = max(idemodel.Mco(j,iok));
[ipmax, jpmax] = find(abs(squeeze(idemodel.Pco(j,[1:j-1,j+1:end],iok)))>0.95);
if ~isempty(ipmax)
jokP = jokP+1;
kokP(jokP) = j;
ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1;
[N,X]=hist(ipmax,[1:npar]);
jpM(jokP)={find(N)};
NPM(jokP)={N(find(N))./SampleSize.*100};
pmeanM(jokP)={mean(squeeze(idemodel.Pco(j,find(N),iok))')};
pminM(jokP)={min(squeeze(idemodel.Pco(j,find(N),iok))')};
pmaxM(jokP)={max(squeeze(idemodel.Pco(j,find(N),iok))')};
end
end
if any(idemoments.ind(j,:)==1),
iok = find(idemoments.ind(j,:)==1);
jokJ = jokJ+1;
kokJ(jokJ) = j;
mminJ(jokJ,1) = min(idemoments.Mco(j,iok));
mmeanJ(jokJ,1) = mean(idemoments.Mco(j,iok));
mmaxJ(jokJ,1) = max(idemoments.Mco(j,iok));
[ipmax, jpmax] = find(abs(squeeze(idemoments.Pco(j,[1:j-1,j+1:end],iok)))>0.95);
if ~isempty(ipmax)
jokPJ = jokPJ+1;
kokPJ(jokPJ) = j;
ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1;
[N,X]=hist(ipmax,[1:npar]);
jpJ(jokPJ)={find(N)};
NPJ(jokPJ)={N(find(N))./SampleSize.*100};
pmeanJ(jokPJ)={mean(squeeze(idemoments.Pco(j,find(N),iok))')};
pminJ(jokPJ)={min(squeeze(idemoments.Pco(j,find(N),iok))')};
pmaxJ(jokPJ)={max(squeeze(idemoments.Pco(j,find(N),iok))')};
end
end
end
dyntable('Multi collinearity in the model:',strvcat('param','min','mean','max'), ...
strvcat(bayestopt_.name(kok)),[mmin, mmean, mmax],10,10,6);
dyntable('Multi collinearity for moments in J:',strvcat('param','min','mean','max'), ...
strvcat(bayestopt_.name(kokJ)),[mminJ, mmeanJ, mmaxJ],10,10,6);
if disp_pcorr,
for j=1:length(kokP),
dyntable([bayestopt_.name{kokP(j)},' pairwise correlations in the model'],strvcat(' ','min','mean','max'), ...
strvcat(bayestopt_.name{jpM{j}}),[pminM{j}' pmeanM{j}' pmaxM{j}'],10,10,3);
end
for j=1:length(kokPJ),
dyntable([bayestopt_.name{kokPJ(j)},' pairwise correlations in J moments'],strvcat(' ','min','mean','max'), ...
strvcat(bayestopt_.name{jpJ{j}}),[pminJ{j}' pmeanJ{j}' pmaxJ{j}'],10,10,3);
end
end

View File

@ -24,19 +24,19 @@ function disp_model_summary(M,dr)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
disp(' ')
disp('MODEL SUMMARY')
disp(' ')
disp([' Number of variables: ' int2str(M.endo_nbr)])
disp([' Number of stochastic shocks: ' int2str(M.exo_nbr)])
disp([' Number of state variables: ' ...
int2str(length(find(dr.kstate(:,2) <= M.maximum_lag+1)))])
disp([' Number of jumpers: ' ...
int2str(length(find(dr.kstate(:,2) == M.maximum_lag+2)))])
disp([' Number of static variables: ' int2str(dr.nstatic)])
my_title='MATRIX OF COVARIANCE OF EXOGENOUS SHOCKS';
labels = deblank(M.exo_names);
headers = strvcat('Variables',labels);
lh = size(labels,2)+2;
dyntable(my_title,headers,labels,M.Sigma_e,lh,10,6);
disp(' ')
disp('MODEL SUMMARY')
disp(' ')
disp([' Number of variables: ' int2str(M.endo_nbr)])
disp([' Number of stochastic shocks: ' int2str(M.exo_nbr)])
disp([' Number of state variables: ' ...
int2str(length(find(dr.kstate(:,2) <= M.maximum_lag+1)))])
disp([' Number of jumpers: ' ...
int2str(length(find(dr.kstate(:,2) == M.maximum_lag+2)))])
disp([' Number of static variables: ' int2str(dr.nstatic)])
my_title='MATRIX OF COVARIANCE OF EXOGENOUS SHOCKS';
labels = deblank(M.exo_names);
headers = strvcat('Variables',labels);
lh = size(labels,2)+2;
dyntable(my_title,headers,labels,M.Sigma_e,lh,10,6);

View File

@ -18,81 +18,81 @@ function disp_moments(y,var_list)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ oo_
warning_old_state = warning;
warning off
global M_ options_ oo_
if options_.hp_filter
error('STOCH_SIMUL: HP filter is not yet implemented for empirical moments')
end
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
nvar = size(var_list,1);
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact');
if isempty(i_tmp)
warning_old_state = warning;
warning off
if options_.hp_filter
error('STOCH_SIMUL: HP filter is not yet implemented for empirical moments')
end
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
nvar = size(var_list,1);
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact');
if isempty(i_tmp)
error (['One of the variable specified does not exist']) ;
else
else
ivar(i) = i_tmp;
end
end
end
y = y(ivar,options_.drop+M_.maximum_lag+1:end)';
m = mean(y);
y = y - repmat(m,size(y,1),1);
s2 = mean(y.*y);
s = sqrt(s2);
oo_.mean = transpose(m);
oo_.var = y'*y/size(y,1);
y = y(ivar,options_.drop+M_.maximum_lag+1:end)';
labels = deblank(M_.endo_names(ivar,:));
if options_.nomoments == 0
m = mean(y);
y = y - repmat(m,size(y,1),1);
s2 = mean(y.*y);
s = sqrt(s2);
oo_.mean = transpose(m);
oo_.var = y'*y/size(y,1);
labels = deblank(M_.endo_names(ivar,:));
if options_.nomoments == 0
z = [ m' s' s2' (mean(y.^3)./s2.^1.5)' (mean(y.^4)./(s2.*s2)-3)' ];
title='MOMENTS OF SIMULATED VARIABLES';
if options_.hp_filter
title = [title ' (HP filter, lambda = ' ...
int2str(options_.hp_filter) ')'];
title = [title ' (HP filter, lambda = ' ...
int2str(options_.hp_filter) ')'];
end
headers=strvcat('VARIABLE','MEAN','STD. DEV.','VARIANCE','SKEWNESS', ...
'KURTOSIS');
dyntable(title,headers,labels,z,size(labels,2)+2,16,6);
end
if options_.nocorr == 0
end
if options_.nocorr == 0
corr = (y'*y/size(y,1))./(s'*s);
title = 'CORRELATION OF SIMULATED VARIABLES';
if options_.hp_filter
title = [title ' (HP filter, lambda = ' ...
int2str(options_.hp_filter) ')'];
title = [title ' (HP filter, lambda = ' ...
int2str(options_.hp_filter) ')'];
end
headers = strvcat('VARIABLE',M_.endo_names(ivar,:));
dyntable(title,headers,labels,corr,size(labels,2)+2,8,4);
end
ar = options_.ar;
options_ = set_default_option(options_,'ar',5);
ar = options_.ar;
if ar > 0
end
ar = options_.ar;
options_ = set_default_option(options_,'ar',5);
ar = options_.ar;
if ar > 0
autocorr = [];
for i=1:ar
oo_.autocorr{i} = y(ar+1:end,:)'*y(ar+1-i:end-i,:)./((size(y,1)-ar)*s'*s);
autocorr = [ autocorr diag(oo_.autocorr{i}) ];
oo_.autocorr{i} = y(ar+1:end,:)'*y(ar+1-i:end-i,:)./((size(y,1)-ar)*s'*s);
autocorr = [ autocorr diag(oo_.autocorr{i}) ];
end
title = 'AUTOCORRELATION OF SIMULATED VARIABLES';
if options_.hp_filter
title = [title ' (HP filter, lambda = ' ...
int2str(options_.hp_filter) ')'];
title = [title ' (HP filter, lambda = ' ...
int2str(options_.hp_filter) ')'];
end
headers = strvcat('VARIABLE',int2str([1:ar]'));
dyntable(title,headers,labels,autocorr,size(labels,2)+2,8,4);
end
warning(warning_old_state);
end
warning(warning_old_state);

View File

@ -1,6 +1,6 @@
function disp_th_moments(dr,var_list)
% Display theoretical moments of variables
% Copyright (C) 2001-2009 Dynare Team
%
% This file is part of Dynare.
@ -18,62 +18,62 @@ function disp_th_moments(dr,var_list)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ options_
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
nvar = size(var_list,1);
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact');
if isempty(i_tmp)
error (['One of the variable specified does not exist']) ;
else
ivar(i) = i_tmp;
end
end
[oo_.gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_);
m = dr.ys(ivar);
non_stationary_vars = setdiff(1:length(ivar),stationary_vars);
ivar1 = intersect(non_stationary_vars,ivar);
m(ivar1) = NaN;
global M_ oo_ options_
i1 = find(abs(diag(oo_.gamma_y{1})) > 1e-12);
s2 = diag(oo_.gamma_y{1});
sd = sqrt(s2);
if options_.order == 2
if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
nvar = size(var_list,1);
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact');
if isempty(i_tmp)
error (['One of the variable specified does not exist']) ;
else
ivar(i) = i_tmp;
end
end
[oo_.gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_);
m = dr.ys(ivar);
non_stationary_vars = setdiff(1:length(ivar),stationary_vars);
ivar1 = intersect(non_stationary_vars,ivar);
m(ivar1) = NaN;
i1 = find(abs(diag(oo_.gamma_y{1})) > 1e-12);
s2 = diag(oo_.gamma_y{1});
sd = sqrt(s2);
if options_.order == 2
m = m+oo_.gamma_y{options_.ar+3};
end
z = [ m sd s2 ];
oo_.mean = m;
oo_.var = oo_.gamma_y{1};
if options_.nomoments == 0
end
z = [ m sd s2 ];
oo_.mean = m;
oo_.var = oo_.gamma_y{1};
if options_.nomoments == 0
title='THEORETICAL MOMENTS';
if options_.hp_filter
title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')'];
title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')'];
end
headers=strvcat('VARIABLE','MEAN','STD. DEV.','VARIANCE');
labels = deblank(M_.endo_names(ivar,:));
lh = size(labels,2)+2;
dyntable(title,headers,labels,z,lh,11,4);
if M_.exo_nbr > 1
disp(' ')
title='VARIANCE DECOMPOSITION (in percent)';
if options_.hp_filter
title = [title ' (HP filter, lambda = ' ...
int2str(options_.hp_filter) ')'];
end
headers = M_.exo_names;
headers(M_.exo_names_orig_ord,:) = headers;
headers = strvcat(' ',headers);
lh = size(deblank(M_.endo_names(ivar(stationary_vars),:)),2)+2;
dyntable(title,headers,deblank(M_.endo_names(ivar(stationary_vars), ...
:)),100*oo_.gamma_y{options_.ar+2}(stationary_vars,:),lh,8,2);
disp(' ')
title='VARIANCE DECOMPOSITION (in percent)';
if options_.hp_filter
title = [title ' (HP filter, lambda = ' ...
int2str(options_.hp_filter) ')'];
end
headers = M_.exo_names;
headers(M_.exo_names_orig_ord,:) = headers;
headers = strvcat(' ',headers);
lh = size(deblank(M_.endo_names(ivar(stationary_vars),:)),2)+2;
dyntable(title,headers,deblank(M_.endo_names(ivar(stationary_vars), ...
:)),100*oo_.gamma_y{options_.ar+2}(stationary_vars,:),lh,8,2);
end
conditional_variance_steps = options_.conditional_variance_decomposition;
@ -82,34 +82,34 @@ function disp_th_moments(dr,var_list)
ivar,dr,M_, ...
options_,oo_);
end
end
if options_.nocorr == 0
end
if options_.nocorr == 0
disp(' ')
title='MATRIX OF CORRELATIONS';
if options_.hp_filter
title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')'];
title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')'];
end
labels = deblank(M_.endo_names(ivar(i1),:));
headers = strvcat('Variables',labels);
corr = oo_.gamma_y{1}(i1,i1)./(sd(i1)*sd(i1)');
lh = size(labels,2)+2;
dyntable(title,headers,labels,corr,lh,8,4);
end
if options_.ar > 0
end
if options_.ar > 0
disp(' ')
title='COEFFICIENTS OF AUTOCORRELATION';
if options_.hp_filter
title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')'];
title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')'];
end
labels = deblank(M_.endo_names(ivar(i1),:));
headers = strvcat('Order ',int2str([1:options_.ar]'));
z=[];
for i=1:options_.ar
oo_.autocorr{i} = oo_.gamma_y{i+1};
z(:,i) = diag(oo_.gamma_y{i+1}(i1,i1));
oo_.autocorr{i} = oo_.gamma_y{i+1};
z(:,i) = diag(oo_.gamma_y{i+1}(i1,i1));
end
lh = size(labels,2)+2;
dyntable(title,headers,labels,z,lh,8,4);
end
end

View File

@ -32,45 +32,45 @@ function oo_ = display_conditional_variance_decomposition(Steps, SubsetOfVariabl
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
endo_nbr = M_.endo_nbr;
exo_nbr = M_.exo_nbr;
StateSpaceModel.number_of_state_equations = M_.endo_nbr;
StateSpaceModel.number_of_state_innovations = exo_nbr;
StateSpaceModel.sigma_e_is_diagonal = M_.sigma_e_is_diagonal;
iv = (1:endo_nbr)';
ic = dr.nstatic+(1:dr.npred)';
[StateSpaceModel.transition_matrix,StateSpaceModel.impulse_matrix] = kalman_transition_matrix(dr,iv,ic,[],exo_nbr);
StateSpaceModel.state_innovations_covariance_matrix = M_.Sigma_e;
conditional_decomposition_array = conditional_variance_decomposition(StateSpaceModel,Steps,dr.inv_order_var(SubsetOfVariables ));
endo_nbr = M_.endo_nbr;
exo_nbr = M_.exo_nbr;
StateSpaceModel.number_of_state_equations = M_.endo_nbr;
StateSpaceModel.number_of_state_innovations = exo_nbr;
StateSpaceModel.sigma_e_is_diagonal = M_.sigma_e_is_diagonal;
iv = (1:endo_nbr)';
ic = dr.nstatic+(1:dr.npred)';
[StateSpaceModel.transition_matrix,StateSpaceModel.impulse_matrix] = kalman_transition_matrix(dr,iv,ic,[],exo_nbr);
StateSpaceModel.state_innovations_covariance_matrix = M_.Sigma_e;
conditional_decomposition_array = conditional_variance_decomposition(StateSpaceModel,Steps,dr.inv_order_var(SubsetOfVariables ));
if options_.noprint == 0
disp(' ')
disp('CONDITIONAL VARIANCE DECOMPOSITION (in percent)')
end
vardec_i = zeros(length(SubsetOfVariables),exo_nbr);
for i=1:length(Steps)
disp(['Period ' int2str(Steps(i)) ':'])
for j=1:exo_nbr
vardec_i(:,j) = diag_vech(conditional_decomposition_array(:, ...
i,j));
end
vardec_i = 100*vardec_i./repmat(sum(vardec_i,2),1,exo_nbr);
if options_.noprint == 0
disp(' ')
disp('CONDITIONAL VARIANCE DECOMPOSITION (in percent)')
headers = M_.exo_names;
headers(M_.exo_names_orig_ord,:) = headers;
headers = strvcat(' ',headers);
lh = size(deblank(M_.endo_names(SubsetOfVariables,:)),2)+2;
dyntable('',headers,...
deblank(M_.endo_names(SubsetOfVariables,:)),...
vardec_i,lh,8,2);
end
vardec_i = zeros(length(SubsetOfVariables),exo_nbr);
for i=1:length(Steps)
disp(['Period ' int2str(Steps(i)) ':'])
for j=1:exo_nbr
vardec_i(:,j) = diag_vech(conditional_decomposition_array(:, ...
i,j));
end
vardec_i = 100*vardec_i./repmat(sum(vardec_i,2),1,exo_nbr);
if options_.noprint == 0
headers = M_.exo_names;
headers(M_.exo_names_orig_ord,:) = headers;
headers = strvcat(' ',headers);
lh = size(deblank(M_.endo_names(SubsetOfVariables,:)),2)+2;
dyntable('',headers,...
deblank(M_.endo_names(SubsetOfVariables,:)),...
vardec_i,lh,8,2);
end
end
oo_.conditional_variance_decomposition = conditional_decomposition_array;
end
oo_.conditional_variance_decomposition = conditional_decomposition_array;

View File

@ -38,50 +38,50 @@ function m = compute_prior_mode(hyperparameters,shape)
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
m = NaN ;
switch shape
case 1
if (hyperparameters(1)>1 && hyperparameters(2)>1)
m = (hyperparameters(1)-1)/(hyperparameters(1)+hyperparameters(2)-2) ;
elseif (hyperparameters(1)<1 && hyperparameters(2)<1)
m = [ 0 ; 1 ] ;
elseif ( hyperparameters(1)<1 && hyperparameters(2)>1-eps ) || ( abs(hyperparameters(1)-1)<2*eps && hyperparameters(2)>1 )
m = 0;
elseif ( hyperparameters(1)>1 && hyperparameters(2)<1+eps ) || ( abs(hyperparameters(1)-1)<2*eps && hyperparameters(2)<1 )
m = 1;
elseif ( abs(hyperparameters(1)-1)<2*eps && abs(hyperparameters(2)-1)<2*eps )% Uniform distribution!
m = .5 ;
end
if length(hyperparameters)==4
m = m*(hyperparameters(4)-hyperparameters(3)) + hyperparameters(3) ;
end
case 2
if hyperparameters(1)<1
m = 0;
else
m = (hyperparameters(1)-1)*hyperparameters(2);
end
if length(hyperparameters)>2
m = m + hyperparameters(3);
end
case 3
m = hyperparameters(1);
case 4
% s = hyperparameters(1)
% nu = hyperparameters(2)
m = 1/sqrt((hyperparameters(2)+1)/hyperparameters(1));%sqrt((hyperparameters(2)-1)/hyperparameters(1))
if length(hyperparameters)>2
m = m + hyperparameters(3);
end
case 5
m = .5*(hyperparameters(2)-hyperparameters(1)) ;
case 6
% s = hyperparameters(1)
% nu = hyperparameters(2)
m = hyperparameters(1)/(hyperparameters(2)+2) ;
if length(hyperparameters)>2
m = m + hyperparameters(3) ;
end
otherwise
error('Unknown prior shape!')
end
m = NaN ;
switch shape
case 1
if (hyperparameters(1)>1 && hyperparameters(2)>1)
m = (hyperparameters(1)-1)/(hyperparameters(1)+hyperparameters(2)-2) ;
elseif (hyperparameters(1)<1 && hyperparameters(2)<1)
m = [ 0 ; 1 ] ;
elseif ( hyperparameters(1)<1 && hyperparameters(2)>1-eps ) || ( abs(hyperparameters(1)-1)<2*eps && hyperparameters(2)>1 )
m = 0;
elseif ( hyperparameters(1)>1 && hyperparameters(2)<1+eps ) || ( abs(hyperparameters(1)-1)<2*eps && hyperparameters(2)<1 )
m = 1;
elseif ( abs(hyperparameters(1)-1)<2*eps && abs(hyperparameters(2)-1)<2*eps )% Uniform distribution!
m = .5 ;
end
if length(hyperparameters)==4
m = m*(hyperparameters(4)-hyperparameters(3)) + hyperparameters(3) ;
end
case 2
if hyperparameters(1)<1
m = 0;
else
m = (hyperparameters(1)-1)*hyperparameters(2);
end
if length(hyperparameters)>2
m = m + hyperparameters(3);
end
case 3
m = hyperparameters(1);
case 4
% s = hyperparameters(1)
% nu = hyperparameters(2)
m = 1/sqrt((hyperparameters(2)+1)/hyperparameters(1));%sqrt((hyperparameters(2)-1)/hyperparameters(1))
if length(hyperparameters)>2
m = m + hyperparameters(3);
end
case 5
m = .5*(hyperparameters(2)-hyperparameters(1)) ;
case 6
% s = hyperparameters(1)
% nu = hyperparameters(2)
m = hyperparameters(1)/(hyperparameters(2)+2) ;
if length(hyperparameters)>2
m = m + hyperparameters(3) ;
end
otherwise
error('Unknown prior shape!')
end

View File

@ -38,37 +38,37 @@ sigma2 = sigma^2;
mu2 = mu^2;
if type == 2; % Inverse Gamma 2
nu = 2*(2+mu2/sigma2);
s = 2*mu*(1+mu2/sigma2);
nu = 2*(2+mu2/sigma2);
s = 2*mu*(1+mu2/sigma2);
elseif type == 1; % Inverse Gamma 1
if sigma2 < Inf;
nu = sqrt(2*(2+mu2/sigma2));
nu2 = 2*nu;
nu1 = 2;
err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2;
while abs(nu2-nu1) > 1e-12
if err > 0
nu1 = nu;
if nu < nu2
nu = nu2;
else
nu = 2*nu;
nu2 = nu;
end
else
nu2 = nu;
end
nu = (nu1+nu2)/2;
err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2;
end
s = (sigma2+mu2)*(nu-2);
nu = sqrt(2*(2+mu2/sigma2));
nu2 = 2*nu;
nu1 = 2;
err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2;
while abs(nu2-nu1) > 1e-12
if err > 0
nu1 = nu;
if nu < nu2
nu = nu2;
else
nu = 2*nu;
nu2 = nu;
end
else
nu2 = nu;
end
nu = (nu1+nu2)/2;
err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2;
end
s = (sigma2+mu2)*(nu-2);
else;
nu = 2;
s = 2*mu2/pi;
end;
else;
s = -1;
nu = -1;
s = -1;
nu = -1;
end;
% 01/18/2004 MJ replaced fsolve with secant

View File

@ -34,156 +34,156 @@ 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.
if ~(nargin==3 || nargin==5 || nargin==4 )
error('mode_and_variance_to mean:: 3 or 5 input arguments are needed!')
% Check input aruments.
if ~(nargin==3 || nargin==5 || nargin==4 )
error('mode_and_variance_to mean:: 3 or 5 input arguments are needed!')
end
% Set defaults bounds.
if nargin==3
switch distribution
case 1
lower_bound = 0;
upper_bound = Inf;
case 3
lower_bound = 0;
upper_bound = Inf;
case 2
lower_bound = 0;
upper_bound = Inf;
case 4
lower_bound = 0;
upper_bound = 1;
otherwise
error('Unknown distribution!')
end
% Set defaults bounds.
if nargin==3
switch distribution
case 1
lower_bound = 0;
upper_bound = Inf;
case 3
lower_bound = 0;
upper_bound = Inf;
case 2
lower_bound = 0;
upper_bound = Inf;
case 4
lower_bound = 0;
upper_bound = 1;
otherwise
error('Unknown distribution!')
end
end
if nargin==4
switch distribution
case 1
upper_bound = Inf;
case 3
upper_bound = Inf;
case 2
upper_bound = Inf;
case 4
upper_bound = 1;
otherwise
error('Unknown distribution!')
end
if nargin==4
switch distribution
case 1
upper_bound = Inf;
case 3
upper_bound = Inf;
case 2
upper_bound = Inf;
case 4
upper_bound = 1;
otherwise
error('Unknown distribution!')
end
end
if (distribution==1)% Gamma distribution
if m<lower_bound
error('The mode has to be greater than the lower bound!')
end
if (distribution==1)% Gamma distribution
if m<lower_bound
error('The mode has to be greater than the lower bound!')
end
if (m-lower_bound)<1e-12
error('The gamma distribution should be specified with the mean and variance.')
end
m = m - lower_bound ;
beta = -.5*m*(1-sqrt(1+4*s2/(m*m))) ;
alpha = (m+beta)/beta ;
parameters(1) = alpha;
parameters(2) = beta;
mu = alpha*beta + lower_bound ;
return
if (m-lower_bound)<1e-12
error('The gamma distribution should be specified with the mean and variance.')
end
m = m - lower_bound ;
beta = -.5*m*(1-sqrt(1+4*s2/(m*m))) ;
alpha = (m+beta)/beta ;
parameters(1) = alpha;
parameters(2) = beta;
mu = alpha*beta + lower_bound ;
return
end
if (distribution==2)% Inverse Gamma - 2 distribution
if m<lower_bound+2*eps
error('The mode has to be greater than the lower bound!')
end
if (distribution==2)% Inverse Gamma - 2 distribution
if m<lower_bound+2*eps
error('The mode has to be greater than the lower bound!')
end
m = m - lower_bound ;
if isinf(s2)
nu = 4;
s = 2*m;
else
delta = 2*(m*m/s2);
poly = [ 1 , -(8+delta) , 20-4*delta , -(16+4*delta) ];
all_roots = roots(poly);
real_roots = all_roots(find(abs(imag(all_roots))<2*eps));
nu = real_roots(find(real_roots>2));
s = m*(nu+2);
end
parameters(1) = nu;
parameters(2) = s;
mu = s/(nu-2) + lower_bound;
return
m = m - lower_bound ;
if isinf(s2)
nu = 4;
s = 2*m;
else
delta = 2*(m*m/s2);
poly = [ 1 , -(8+delta) , 20-4*delta , -(16+4*delta) ];
all_roots = roots(poly);
real_roots = all_roots(find(abs(imag(all_roots))<2*eps));
nu = real_roots(find(real_roots>2));
s = m*(nu+2);
end
if (distribution==3)% Inverted Gamma 1 distribution
if m<lower_bound+2*eps
error('The mode has to be greater than the lower bound!')
end
m = m - lower_bound ;
if isinf(s2)
nu = 2;
s = 3*(m*m);
else
[mu, parameters] = mode_and_variance_to_mean(m,s2,2);
nu = sqrt(parameters(1));
nu2 = 2*nu;
nu1 = 2;
err = s2/(m*m) - (nu+1)/(nu-2) + .5*(nu+1)*(gamma((nu-1)/2)/gamma(nu/2))^2;
while abs(nu2-nu1) > 1e-12
if err < 0
nu1 = nu;
if nu < nu2
nu = nu2;
else
nu = 2*nu;
nu2 = nu;
end
parameters(1) = nu;
parameters(2) = s;
mu = s/(nu-2) + lower_bound;
return
end
if (distribution==3)% Inverted Gamma 1 distribution
if m<lower_bound+2*eps
error('The mode has to be greater than the lower bound!')
end
m = m - lower_bound ;
if isinf(s2)
nu = 2;
s = 3*(m*m);
else
[mu, parameters] = mode_and_variance_to_mean(m,s2,2);
nu = sqrt(parameters(1));
nu2 = 2*nu;
nu1 = 2;
err = s2/(m*m) - (nu+1)/(nu-2) + .5*(nu+1)*(gamma((nu-1)/2)/gamma(nu/2))^2;
while abs(nu2-nu1) > 1e-12
if err < 0
nu1 = nu;
if nu < nu2
nu = nu2;
else
nu = 2*nu;
nu2 = nu;
end
nu = (nu1+nu2)/2;
err = s2/(m*m) - (nu+1)/(nu-2) + .5*(nu+1)*(gamma((nu-1)/2)/gamma(nu/2))^2;
else
nu2 = nu;
end
s = (nu+1)*(m*m) ;
nu = (nu1+nu2)/2;
err = s2/(m*m) - (nu+1)/(nu-2) + .5*(nu+1)*(gamma((nu-1)/2)/gamma(nu/2))^2;
end
parameters(1) = nu;
parameters(2) = s;
mu = sqrt(.5*s)*gamma(.5*(nu-1))/gamma(.5*nu) + lower_bound ;
return
s = (nu+1)*(m*m) ;
end
if (distribution==4)% Beta distribution
if m<lower_bound
error('The mode has to be greater than the lower bound!')
end
if m>upper_bound
error('The mode has to be less than the upper bound!')
end
if (m-lower_bound)<1e-12
error('The beta distribution should be specified with the mean and variance.')
end
if (upper_bound-m)<1e-12
error('The beta distribution should be specified with the mean and variance.')
end
ll = upper_bound-lower_bound;
m = (m-lower_bound)/ll;
s2 = s2/(ll*ll);
delta = m^2/s2;
poly = NaN(1,4);
poly(1) = 1;
poly(2) = 7*m-(1-m)*delta-3;
poly(3) = 16*m^2-14*m+3-2*m*delta+delta;
poly(4) = 12*m^3-16*m^2+7*m-1;
all_roots = roots(poly);
real_roots = all_roots(find(abs(imag(all_roots))<2*eps));
idx = find(real_roots>1);
if length(idx)>1
error('Multiplicity of solutions for the beta distribution specification.')
elseif isempty(idx)
disp('No solution for the beta distribution specification. You should reduce the variance.')
error();
end
alpha = real_roots(idx);
beta = ((1-m)*alpha+2*m-1)/m;
parameters(1) = alpha;
parameters(2) = beta;
mu = alpha/(alpha+beta)*(upper_bound-lower_bound)+lower_bound;
return
end
parameters(1) = nu;
parameters(2) = s;
mu = sqrt(.5*s)*gamma(.5*(nu-1))/gamma(.5*nu) + lower_bound ;
return
end
if (distribution==4)% Beta distribution
if m<lower_bound
error('The mode has to be greater than the lower bound!')
end
if m>upper_bound
error('The mode has to be less than the upper bound!')
end
if (m-lower_bound)<1e-12
error('The beta distribution should be specified with the mean and variance.')
end
if (upper_bound-m)<1e-12
error('The beta distribution should be specified with the mean and variance.')
end
ll = upper_bound-lower_bound;
m = (m-lower_bound)/ll;
s2 = s2/(ll*ll);
delta = m^2/s2;
poly = NaN(1,4);
poly(1) = 1;
poly(2) = 7*m-(1-m)*delta-3;
poly(3) = 16*m^2-14*m+3-2*m*delta+delta;
poly(4) = 12*m^3-16*m^2+7*m-1;
all_roots = roots(poly);
real_roots = all_roots(find(abs(imag(all_roots))<2*eps));
idx = find(real_roots>1);
if length(idx)>1
error('Multiplicity of solutions for the beta distribution specification.')
elseif isempty(idx)
disp('No solution for the beta distribution specification. You should reduce the variance.')
error();
end
alpha = real_roots(idx);
beta = ((1-m)*alpha+2*m-1)/m;
parameters(1) = alpha;
parameters(2) = beta;
mu = alpha/(alpha+beta)*(upper_bound-lower_bound)+lower_bound;
return
end

View File

@ -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) * ...
prod(diag(Sigma_upper_chol))^(-1) * ...
exp(-.5*(X-Mean)*(Sigma_upper_chol\(transpose(Sigma_upper_chol)\transpose(X-Mean))));
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))));

View File

@ -30,7 +30,7 @@ function density = multivariate_student_pdf(X,Mean,Sigma_upper_chol,df);
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
nn = length(X);
t1 = gamma( .5*(nn+df) ) / ( gamma( .5*nn ) * (df*pi)^(.5*nn) ) ;
t2 = t1 / prod(diag(Sigma_upper_chol)) ;
density = t2 / ( 1 + (X-Mean)*(Sigma_upper_chol\(transpose(Sigma_upper_chol)\transpose(X-Mean)))/df )^(.5*(nn+df));
nn = length(X);
t1 = gamma( .5*(nn+df) ) / ( gamma( .5*nn ) * (df*pi)^(.5*nn) ) ;
t2 = t1 / prod(diag(Sigma_upper_chol)) ;
density = t2 / ( 1 + (X-Mean)*(Sigma_upper_chol\(transpose(Sigma_upper_chol)\transpose(X-Mean)))/df )^(.5*(nn+df));

View File

@ -41,13 +41,13 @@ 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;
% At this point, X'*X is Wishart distributed
% G = inv(X'*X);
X = randn(v, m) * H_inv_upper_chol;
% Rather compute inv(X'*X) using the SVD
[U,S,V] = svd(X, 0);
SSi = 1 ./ (diag(S) .^ 2);
G = (V .* repmat(SSi', m, 1)) * V';
% At this point, X'*X is Wishart distributed
% G = inv(X'*X);
% Rather compute inv(X'*X) using the SVD
[U,S,V] = svd(X, 0);
SSi = 1 ./ (diag(S) .^ 2);
G = (V .* repmat(SSi', m, 1)) * V';

View File

@ -37,7 +37,7 @@ function B = rand_matrix_normal(n, p, M, Omega_lower_chol, Sigma_lower_chol)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
B1 = randn(n * p, 1);
B2 = kron(Omega_lower_chol, Sigma_lower_chol) * B1;
B3 = reshape(B2, n, p);
B = B3 + M;
B1 = randn(n * p, 1);
B2 = kron(Omega_lower_chol, Sigma_lower_chol) * B1;
B3 = reshape(B2, n, p);
B = B3 + M;

View File

@ -31,4 +31,4 @@ function draw = rand_multivariate_normal(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/>.
draw = Mean + randn(1,n) * Sigma_upper_chol;
draw = Mean + randn(1,n) * Sigma_upper_chol;

View File

@ -35,5 +35,5 @@ function draw = rand_multivariate_student(Mean,Sigma_upper_chol,df)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
n = length(Mean);
draw = Mean + randn(1,n) * Sigma_upper_chol * sqrt(df/sum(randn(df,1).^2));
n = length(Mean);
draw = Mean + randn(1,n) * Sigma_upper_chol * sqrt(df/sum(randn(df,1).^2));

File diff suppressed because it is too large Load Diff

View File

@ -1,489 +1,489 @@
function [dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian)
%function [dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian)
% Copyright (C) 2008 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/>.
%task
info = 0;
klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1;
kstate = dr.kstate;
kad = dr.kad;
kae = dr.kae;
nstatic = dr.nstatic;
nfwrd = dr.nfwrd;
npred = dr.npred;
nboth = dr.nboth;
order_var = dr.order_var;
nd = size(kstate,1);
nz = nnz(M_.lead_lag_incidence);
sdyn = M_.endo_nbr - nstatic;
k0 = M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var);
k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:);
b = jacobia_(:,k0);
if M_.maximum_endo_lead == 0; % backward models
a = jacobia_(:,nonzeros(k1'));
dr.ghx = zeros(size(a));
m = 0;
for i=M_.maximum_endo_lag:-1:1
k = nonzeros(M_.lead_lag_incidence(i,order_var));
dr.ghx(:,m+[1:length(k)]) = -b\a(:,k);
m = m+length(k);
end
if M_.exo_nbr & task~=1
jacobia_
jacobia_(:,nz+1:end)
b
dr.ghu = -b\jacobia_(:,nz+1:end);
disp(['nz=' int2str(nz) ]);
dr.ghu
end
dr.eigval = eig(transition_matrix(dr,M_));
dr.rank = 0;
if any(abs(dr.eigval) > options_.qz_criterium)
temp = sort(abs(dr.eigval));
nba = nnz(abs(dr.eigval) > options_.qz_criterium);
temp = temp(nd-nba+1:nd)-1-options_.qz_criterium;
info(1) = 3;
info(2) = temp'*temp;
end
return;
end
%forward--looking models
if nstatic > 0
[Q,R] = qr(b(:,1:nstatic));
aa = Q'*jacobia_;
else
aa = jacobia_;
end
a = aa(:,nonzeros(k1'));
b = aa(:,k0);
b10 = b(1:nstatic,1:nstatic);
b11 = b(1:nstatic,nstatic+1:end);
b2 = b(nstatic+1:end,nstatic+1:end);
if any(isinf(a(:)))
info = 1;
return
end
% buildind D and E
%nd
d = zeros(nd,nd) ;
e = d ;
k = find(kstate(:,2) >= M_.maximum_endo_lag+2 & kstate(:,3));
d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ;
k1 = find(kstate(:,2) == M_.maximum_endo_lag+2);
e(1:sdyn,k1) = -b2(:,kstate(k1,1)-nstatic);
k = find(kstate(:,2) <= M_.maximum_endo_lag+1 & kstate(:,4));
e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ;
k2 = find(kstate(:,2) == M_.maximum_endo_lag+1);
k2 = k2(~ismember(kstate(k2,1),kstate(k1,1)));
d(1:sdyn,k2) = b2(:,kstate(k2,1)-nstatic);
if ~isempty(kad)
for j = 1:size(kad,1)
d(sdyn+j,kad(j)) = 1 ;
e(sdyn+j,kae(j)) = 1 ;
end
end
%e
%d
[ss,tt,w,sdim,dr.eigval,info1] = mjdgges(e,d,options_.qz_criterium);
if info1
info(1) = 2;
info(2) = info1;
return
end
nba = nd-sdim;
nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1);
if task == 1
dr.rank = rank(w(1:nyf,nd-nyf+1:end));
% Under Octave, eig(A,B) doesn't exist, and
% lambda = qz(A,B) won't return infinite eigenvalues
if ~exist('OCTAVE_VERSION')
dr.eigval = eig(e,d);
end
return
end
if nba ~= nyf
temp = sort(abs(dr.eigval));
if nba > nyf
temp = temp(nd-nba+1:nd-nyf)-1-options_.qz_criterium;
info(1) = 3;
elseif nba < nyf;
temp = temp(nd-nyf+1:nd-nba)-1-options_.qz_criterium;
info(1) = 4;
end
info(2) = temp'*temp;
return
end
np = nd - nyf;
n2 = np + 1;
n3 = nyf;
n4 = n3 + 1;
% derivatives with respect to dynamic state variables
% forward variables
w1 =w(1:n3,n2:nd);
if condest(w1) > 1e9;
info(1) = 5;
info(2) = condest(w1);
return;
else
gx = -w1'\w(n4:nd,n2:nd)';
end
% predetermined variables
hx = w(1:n3,1:np)'*gx+w(n4:nd,1:np)';
hx = (tt(1:np,1:np)*hx)\(ss(1:np,1:np)*hx);
k1 = find(kstate(n4:nd,2) == M_.maximum_endo_lag+1);
k2 = find(kstate(1:n3,2) == M_.maximum_endo_lag+2);
hx(k1,:)
gx(k2(nboth+1:end),:)
dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)];
dr.ghx
%lead variables actually present in the model
j3 = nonzeros(kstate(:,3));
j4 = find(kstate(:,3));
% derivatives with respect to exogenous variables
disp(['M_.exo_nbr=' int2str(M_.exo_nbr)]);
if M_.exo_nbr
fu = aa(:,nz+(1:M_.exo_nbr));
a1 = b;
aa1 = [];
if nstatic > 0
aa1 = a1(:,1:nstatic);
end
dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ...
npred) a1(:,nstatic+npred+1:end)]\fu;
else
dr.ghu = [];
end
% static variables
if nstatic > 0
temp = -a(1:nstatic,j3)*gx(j4,:)*hx;
j5 = find(kstate(n4:nd,4));
temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4)));
temp = b10\(temp-b11*dr.ghx);
dr.ghx = [temp; dr.ghx];
temp = [];
end
if options_.loglinear == 1
k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1);
klag = dr.kstate(k,[1 2]);
k1 = dr.order_var;
dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ...
repmat(dr.ys(k1(klag(:,1)))',size(dr.ghx,1),1);
dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu;
end
%% Necessary when using Sims' routines for QZ
if options_.use_qzdiv
gx = real(gx);
hx = real(hx);
dr.ghx = real(dr.ghx);
dr.ghu = real(dr.ghu);
end
%exogenous deterministic variables
if M_.exo_det_nbr > 0
f1 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var))));
f0 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var))));
fudet = sparse(jacobia_(:,nz+M_.exo_nbr+1:end));
M1 = inv(f0+[zeros(M_.endo_nbr,nstatic) f1*gx zeros(M_.endo_nbr,nyf-nboth)]);
M2 = M1*f1;
dr.ghud = cell(M_.exo_det_length,1);
dr.ghud{1} = -M1*fudet;
for i = 2:M_.exo_det_length
dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:);
end
end
if options_.order == 1
return
end
% Second order
%tempex = oo_.exo_simul ;
%hessian = real(hessext('ff1_',[z; oo_.exo_steady_state]))' ;
kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1));
if M_.maximum_endo_lag > 0
kk = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); kk];
end
kk = kk';
kk = find(kk(:));
nk = size(kk,1) + M_.exo_nbr + M_.exo_det_nbr;
k1 = M_.lead_lag_incidence(:,order_var);
k1 = k1';
k1 = k1(:);
k1 = k1(kk);
k2 = find(k1);
kk1(k1(k2)) = k2;
kk1 = [kk1 length(k1)+1:length(k1)+M_.exo_nbr+M_.exo_det_nbr];
kk = reshape([1:nk^2],nk,nk);
kk1 = kk(kk1,kk1);
%[junk,junk,hessian] = feval([M_.fname '_dynamic'],z, oo_.exo_steady_state);
hessian(:,kk1(:)) = hessian;
%oo_.exo_simul = tempex ;
%clear tempex
n1 = 0;
n2 = np;
zx = zeros(np,np);
zu=zeros(np,M_.exo_nbr);
for i=2:M_.maximum_endo_lag+1
k1 = sum(kstate(:,2) == i);
zx(n1+1:n1+k1,n2-k1+1:n2)=eye(k1);
n1 = n1+k1;
n2 = n2-k1;
end
kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1));
k0 = [1:M_.endo_nbr];
gx1 = dr.ghx;
hu = dr.ghu(nstatic+[1:npred],:);
zx = [zx; gx1];
zu = [zu; dr.ghu];
for i=1:M_.maximum_endo_lead
k1 = find(kk(i+1,k0) > 0);
zu = [zu; gx1(k1,1:npred)*hu];
gx1 = gx1(k1,:)*hx;
zx = [zx; gx1];
kk = kk(:,k0);
k0 = k1;
end
zx=[zx; zeros(M_.exo_nbr,np);zeros(M_.exo_det_nbr,np)];
zu=[zu; eye(M_.exo_nbr);zeros(M_.exo_det_nbr,M_.exo_nbr)];
[nrzx,nczx] = size(zx);
rhs = -sparse_hessian_times_B_kronecker_C(hessian,zx);
%lhs
n = M_.endo_nbr+sum(kstate(:,2) > M_.maximum_endo_lag+1 & kstate(:,2) < M_.maximum_endo_lag+M_.maximum_endo_lead+1);
A = zeros(n,n);
B = zeros(n,n);
A(1:M_.endo_nbr,1:M_.endo_nbr) = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var));
% variables with the highest lead
k1 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead+1);
if M_.maximum_endo_lead > 1
k2 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead);
[junk,junk,k3] = intersect(kstate(k1,1),kstate(k2,1));
else
k2 = [1:M_.endo_nbr];
k3 = kstate(k1,1);
end
% Jacobian with respect to the variables with the highest lead
B(1:M_.endo_nbr,end-length(k2)+k3) = jacobia_(:,kstate(k1,3)+M_.endo_nbr);
offset = M_.endo_nbr;
k0 = [1:M_.endo_nbr];
gx1 = dr.ghx;
for i=1:M_.maximum_endo_lead-1
k1 = find(kstate(:,2) == M_.maximum_endo_lag+i+1);
[k2,junk,k3] = find(kstate(k1,3));
A(1:M_.endo_nbr,offset+k2) = jacobia_(:,k3+M_.endo_nbr);
n1 = length(k1);
A(offset+[1:n1],nstatic+[1:npred]) = -gx1(kstate(k1,1),1:npred);
gx1 = gx1*hx;
A(offset+[1:n1],offset+[1:n1]) = eye(n1);
n0 = length(k0);
E = eye(n0);
if i == 1
[junk,junk,k4]=intersect(kstate(k1,1),[1:M_.endo_nbr]);
else
[junk,junk,k4]=intersect(kstate(k1,1),kstate(k0,1));
end
i1 = offset-n0+n1;
B(offset+[1:n1],offset-n0+[1:n0]) = -E(k4,:);
k0 = k1;
offset = offset + n1;
end
[junk,k1,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+M_.maximum_endo_lead+1,order_var));
A(1:M_.endo_nbr,nstatic+1:nstatic+npred)=...
A(1:M_.endo_nbr,nstatic+[1:npred])+jacobia_(:,k2)*gx1(k1,1:npred);
C = hx;
D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))];
dr.ghxx = gensylv(2,A,B,C,D);
%ghxu
%rhs
hu = dr.ghu(nstatic+1:nstatic+npred,:);
%kk = reshape([1:np*np],np,np);
%kk = kk(1:npred,1:npred);
%rhs = -hessian*kron(zx,zu)-f1*dr.ghxx(end-nyf+1:end,kk(:))*kron(hx(1:npred,:),hu(1:npred,:));
rhs = sparse_hessian_times_B_kronecker_C(hessian,zx,zu);
nyf1 = sum(kstate(:,2) == M_.maximum_endo_lag+2);
hu1 = [hu;zeros(np-npred,M_.exo_nbr)];
%B1 = [B(1:M_.endo_nbr,:);zeros(size(A,1)-M_.endo_nbr,size(B,2))];
[nrhx,nchx] = size(hx);
[nrhu1,nchu1] = size(hu1);
B1 = B*A_times_B_kronecker_C(dr.ghxx,hx,hu1);
rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;
%lhs
dr.ghxu = A\rhs;
%ghuu
%rhs
kk = reshape([1:np*np],np,np);
kk = kk(1:npred,1:npred);
rhs = sparse_hessian_times_B_kronecker_C(hessian,zu);
B1 = A_times_B_kronecker_C(B*dr.ghxx,hu1);
rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;
%lhs
dr.ghuu = A\rhs;
dr.ghxx = dr.ghxx(1:M_.endo_nbr,:);
dr.ghxu = dr.ghxu(1:M_.endo_nbr,:);
dr.ghuu = dr.ghuu(1:M_.endo_nbr,:);
% dr.ghs2
% derivatives of F with respect to forward variables
% reordering predetermined variables in diminishing lag order
O1 = zeros(M_.endo_nbr,nstatic);
O2 = zeros(M_.endo_nbr,M_.endo_nbr-nstatic-npred);
LHS = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var));
RHS = zeros(M_.endo_nbr,M_.exo_nbr^2);
kk = find(kstate(:,2) == M_.maximum_endo_lag+2);
gu = dr.ghu;
guu = dr.ghuu;
Gu = [dr.ghu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr)];
Guu = [dr.ghuu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr*M_.exo_nbr)];
E = eye(M_.endo_nbr);
M_.lead_lag_incidenceordered = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1));
if M_.maximum_endo_lag > 0
M_.lead_lag_incidenceordered = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); M_.lead_lag_incidenceordered];
end
M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered';
M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered(:);
k1 = find(M_.lead_lag_incidenceordered);
M_.lead_lag_incidenceordered(k1) = [1:length(k1)]';
M_.lead_lag_incidenceordered =reshape(M_.lead_lag_incidenceordered,M_.endo_nbr,M_.maximum_endo_lag+M_.maximum_endo_lead+1)';
kh = reshape([1:nk^2],nk,nk);
kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1);
E1 = [eye(npred); zeros(kp-npred,npred)];
H = E1;
hxx = dr.ghxx(nstatic+[1:npred],:);
for i=1:M_.maximum_endo_lead
for j=i:M_.maximum_endo_lead
[junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+j+1,order_var));
[junk,k3a,k3] = ...
find(M_.lead_lag_incidenceordered(M_.maximum_endo_lag+j+1,:));
nk3a = length(k3a);
B1 = sparse_hessian_times_B_kronecker_C(hessian(:,kh(k3,k3)),gu(k3a,:));
RHS = RHS + jacobia_(:,k2)*guu(k2a,:)+B1;
end
% LHS
[junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+i+1,order_var));
LHS = LHS + jacobia_(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]);
if i == M_.maximum_endo_lead
break
end
kk = find(kstate(:,2) == M_.maximum_endo_lag+i+1);
gu = dr.ghx*Gu;
[nrGu,ncGu] = size(Gu);
G1 = A_times_B_kronecker_C(dr.ghxx,Gu);
G2 = A_times_B_kronecker_C(hxx,Gu);
guu = dr.ghx*Guu+G1;
Gu = hx*Gu;
Guu = hx*Guu;
Guu(end-npred+1:end,:) = Guu(end-npred+1:end,:) + G2;
H = E1 + hx*H;
end
RHS = RHS*M_.Sigma_e(:);
dr.fuu = RHS;
%RHS = -RHS-dr.fbias;
RHS = -RHS;
dr.ghs2 = LHS\RHS;
% deterministic exogenous variables
if M_.exo_det_nbr > 0
hud = dr.ghud{1}(nstatic+1:nstatic+npred,:);
zud=[zeros(np,M_.exo_det_nbr);dr.ghud{1};gx(:,1:npred)*hud;zeros(M_.exo_nbr,M_.exo_det_nbr);eye(M_.exo_det_nbr)];
R1 = hessian*kron(zx,zud);
dr.ghxud = cell(M_.exo_det_length,1);
kf = [M_.endo_nbr-nyf+1:M_.endo_nbr];
kp = nstatic+[1:npred];
dr.ghxud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{1}(kp,:)));
Eud = eye(M_.exo_det_nbr);
for i = 2:M_.exo_det_length
hudi = dr.ghud{i}(kp,:);
zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
R2 = hessian*kron(zx,zudi);
dr.ghxud{i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hx,Eud)+dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{i}(kp,:)))-M1*R2;
end
R1 = hessian*kron(zu,zud);
dr.ghudud = cell(M_.exo_det_length,1);
kf = [M_.endo_nbr-nyf+1:M_.endo_nbr];
dr.ghuud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghu(kp,:),dr.ghud{1}(kp,:)));
Eud = eye(M_.exo_det_nbr);
for i = 2:M_.exo_det_length
hudi = dr.ghud{i}(kp,:);
zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
R2 = hessian*kron(zu,zudi);
dr.ghuud{i} = -M2*dr.ghxud{i-1}(kf,:)*kron(hu,Eud)-M1*R2;
end
R1 = hessian*kron(zud,zud);
dr.ghudud = cell(M_.exo_det_length,M_.exo_det_length);
dr.ghudud{1,1} = -M1*R1-M2*dr.ghxx(kf,:)*kron(hud,hud);
for i = 2:M_.exo_det_length
hudi = dr.ghud{i}(nstatic+1:nstatic+npred,:);
zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi+dr.ghud{i-1}(kf,:);zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
R2 = hessian*kron(zudi,zudi);
dr.ghudud{i,i} = -M2*(dr.ghudud{i-1,i-1}(kf,:)+...
2*dr.ghxud{i-1}(kf,:)*kron(hudi,Eud) ...
+dr.ghxx(kf,:)*kron(hudi,hudi))-M1*R2;
R2 = hessian*kron(zud,zudi);
dr.ghudud{1,i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hud,Eud)+...
dr.ghxx(kf,:)*kron(hud,hudi))...
-M1*R2;
for j=2:i-1
hudj = dr.ghud{j}(kp,:);
zudj=[zeros(np,M_.exo_det_nbr);dr.ghud{j};gx(:,1:npred)*hudj;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
R2 = hessian*kron(zudj,zudi);
dr.ghudud{j,i} = -M2*(dr.ghudud{j-1,i-1}(kf,:)+dr.ghxud{j-1}(kf,:)* ...
kron(hudi,Eud)+dr.ghxud{i-1}(kf,:)* ...
kron(hudj,Eud)+dr.ghxx(kf,:)*kron(hudj,hudi))-M1*R2;
end
end
end
function [dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian)
%function [dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian)
% Copyright (C) 2008 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/>.
%task
info = 0;
klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1;
kstate = dr.kstate;
kad = dr.kad;
kae = dr.kae;
nstatic = dr.nstatic;
nfwrd = dr.nfwrd;
npred = dr.npred;
nboth = dr.nboth;
order_var = dr.order_var;
nd = size(kstate,1);
nz = nnz(M_.lead_lag_incidence);
sdyn = M_.endo_nbr - nstatic;
k0 = M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var);
k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:);
b = jacobia_(:,k0);
if M_.maximum_endo_lead == 0; % backward models
a = jacobia_(:,nonzeros(k1'));
dr.ghx = zeros(size(a));
m = 0;
for i=M_.maximum_endo_lag:-1:1
k = nonzeros(M_.lead_lag_incidence(i,order_var));
dr.ghx(:,m+[1:length(k)]) = -b\a(:,k);
m = m+length(k);
end
if M_.exo_nbr & task~=1
jacobia_
jacobia_(:,nz+1:end)
b
dr.ghu = -b\jacobia_(:,nz+1:end);
disp(['nz=' int2str(nz) ]);
dr.ghu
end
dr.eigval = eig(transition_matrix(dr,M_));
dr.rank = 0;
if any(abs(dr.eigval) > options_.qz_criterium)
temp = sort(abs(dr.eigval));
nba = nnz(abs(dr.eigval) > options_.qz_criterium);
temp = temp(nd-nba+1:nd)-1-options_.qz_criterium;
info(1) = 3;
info(2) = temp'*temp;
end
return;
end
%forward--looking models
if nstatic > 0
[Q,R] = qr(b(:,1:nstatic));
aa = Q'*jacobia_;
else
aa = jacobia_;
end
a = aa(:,nonzeros(k1'));
b = aa(:,k0);
b10 = b(1:nstatic,1:nstatic);
b11 = b(1:nstatic,nstatic+1:end);
b2 = b(nstatic+1:end,nstatic+1:end);
if any(isinf(a(:)))
info = 1;
return
end
% buildind D and E
%nd
d = zeros(nd,nd) ;
e = d ;
k = find(kstate(:,2) >= M_.maximum_endo_lag+2 & kstate(:,3));
d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ;
k1 = find(kstate(:,2) == M_.maximum_endo_lag+2);
e(1:sdyn,k1) = -b2(:,kstate(k1,1)-nstatic);
k = find(kstate(:,2) <= M_.maximum_endo_lag+1 & kstate(:,4));
e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ;
k2 = find(kstate(:,2) == M_.maximum_endo_lag+1);
k2 = k2(~ismember(kstate(k2,1),kstate(k1,1)));
d(1:sdyn,k2) = b2(:,kstate(k2,1)-nstatic);
if ~isempty(kad)
for j = 1:size(kad,1)
d(sdyn+j,kad(j)) = 1 ;
e(sdyn+j,kae(j)) = 1 ;
end
end
%e
%d
[ss,tt,w,sdim,dr.eigval,info1] = mjdgges(e,d,options_.qz_criterium);
if info1
info(1) = 2;
info(2) = info1;
return
end
nba = nd-sdim;
nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1);
if task == 1
dr.rank = rank(w(1:nyf,nd-nyf+1:end));
% Under Octave, eig(A,B) doesn't exist, and
% lambda = qz(A,B) won't return infinite eigenvalues
if ~exist('OCTAVE_VERSION')
dr.eigval = eig(e,d);
end
return
end
if nba ~= nyf
temp = sort(abs(dr.eigval));
if nba > nyf
temp = temp(nd-nba+1:nd-nyf)-1-options_.qz_criterium;
info(1) = 3;
elseif nba < nyf;
temp = temp(nd-nyf+1:nd-nba)-1-options_.qz_criterium;
info(1) = 4;
end
info(2) = temp'*temp;
return
end
np = nd - nyf;
n2 = np + 1;
n3 = nyf;
n4 = n3 + 1;
% derivatives with respect to dynamic state variables
% forward variables
w1 =w(1:n3,n2:nd);
if condest(w1) > 1e9;
info(1) = 5;
info(2) = condest(w1);
return;
else
gx = -w1'\w(n4:nd,n2:nd)';
end
% predetermined variables
hx = w(1:n3,1:np)'*gx+w(n4:nd,1:np)';
hx = (tt(1:np,1:np)*hx)\(ss(1:np,1:np)*hx);
k1 = find(kstate(n4:nd,2) == M_.maximum_endo_lag+1);
k2 = find(kstate(1:n3,2) == M_.maximum_endo_lag+2);
hx(k1,:)
gx(k2(nboth+1:end),:)
dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)];
dr.ghx
%lead variables actually present in the model
j3 = nonzeros(kstate(:,3));
j4 = find(kstate(:,3));
% derivatives with respect to exogenous variables
disp(['M_.exo_nbr=' int2str(M_.exo_nbr)]);
if M_.exo_nbr
fu = aa(:,nz+(1:M_.exo_nbr));
a1 = b;
aa1 = [];
if nstatic > 0
aa1 = a1(:,1:nstatic);
end
dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ...
npred) a1(:,nstatic+npred+1:end)]\fu;
else
dr.ghu = [];
end
% static variables
if nstatic > 0
temp = -a(1:nstatic,j3)*gx(j4,:)*hx;
j5 = find(kstate(n4:nd,4));
temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4)));
temp = b10\(temp-b11*dr.ghx);
dr.ghx = [temp; dr.ghx];
temp = [];
end
if options_.loglinear == 1
k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1);
klag = dr.kstate(k,[1 2]);
k1 = dr.order_var;
dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ...
repmat(dr.ys(k1(klag(:,1)))',size(dr.ghx,1),1);
dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu;
end
%% Necessary when using Sims' routines for QZ
if options_.use_qzdiv
gx = real(gx);
hx = real(hx);
dr.ghx = real(dr.ghx);
dr.ghu = real(dr.ghu);
end
%exogenous deterministic variables
if M_.exo_det_nbr > 0
f1 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var))));
f0 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var))));
fudet = sparse(jacobia_(:,nz+M_.exo_nbr+1:end));
M1 = inv(f0+[zeros(M_.endo_nbr,nstatic) f1*gx zeros(M_.endo_nbr,nyf-nboth)]);
M2 = M1*f1;
dr.ghud = cell(M_.exo_det_length,1);
dr.ghud{1} = -M1*fudet;
for i = 2:M_.exo_det_length
dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:);
end
end
if options_.order == 1
return
end
% Second order
%tempex = oo_.exo_simul ;
%hessian = real(hessext('ff1_',[z; oo_.exo_steady_state]))' ;
kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1));
if M_.maximum_endo_lag > 0
kk = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); kk];
end
kk = kk';
kk = find(kk(:));
nk = size(kk,1) + M_.exo_nbr + M_.exo_det_nbr;
k1 = M_.lead_lag_incidence(:,order_var);
k1 = k1';
k1 = k1(:);
k1 = k1(kk);
k2 = find(k1);
kk1(k1(k2)) = k2;
kk1 = [kk1 length(k1)+1:length(k1)+M_.exo_nbr+M_.exo_det_nbr];
kk = reshape([1:nk^2],nk,nk);
kk1 = kk(kk1,kk1);
%[junk,junk,hessian] = feval([M_.fname '_dynamic'],z, oo_.exo_steady_state);
hessian(:,kk1(:)) = hessian;
%oo_.exo_simul = tempex ;
%clear tempex
n1 = 0;
n2 = np;
zx = zeros(np,np);
zu=zeros(np,M_.exo_nbr);
for i=2:M_.maximum_endo_lag+1
k1 = sum(kstate(:,2) == i);
zx(n1+1:n1+k1,n2-k1+1:n2)=eye(k1);
n1 = n1+k1;
n2 = n2-k1;
end
kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1));
k0 = [1:M_.endo_nbr];
gx1 = dr.ghx;
hu = dr.ghu(nstatic+[1:npred],:);
zx = [zx; gx1];
zu = [zu; dr.ghu];
for i=1:M_.maximum_endo_lead
k1 = find(kk(i+1,k0) > 0);
zu = [zu; gx1(k1,1:npred)*hu];
gx1 = gx1(k1,:)*hx;
zx = [zx; gx1];
kk = kk(:,k0);
k0 = k1;
end
zx=[zx; zeros(M_.exo_nbr,np);zeros(M_.exo_det_nbr,np)];
zu=[zu; eye(M_.exo_nbr);zeros(M_.exo_det_nbr,M_.exo_nbr)];
[nrzx,nczx] = size(zx);
rhs = -sparse_hessian_times_B_kronecker_C(hessian,zx);
%lhs
n = M_.endo_nbr+sum(kstate(:,2) > M_.maximum_endo_lag+1 & kstate(:,2) < M_.maximum_endo_lag+M_.maximum_endo_lead+1);
A = zeros(n,n);
B = zeros(n,n);
A(1:M_.endo_nbr,1:M_.endo_nbr) = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var));
% variables with the highest lead
k1 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead+1);
if M_.maximum_endo_lead > 1
k2 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead);
[junk,junk,k3] = intersect(kstate(k1,1),kstate(k2,1));
else
k2 = [1:M_.endo_nbr];
k3 = kstate(k1,1);
end
% Jacobian with respect to the variables with the highest lead
B(1:M_.endo_nbr,end-length(k2)+k3) = jacobia_(:,kstate(k1,3)+M_.endo_nbr);
offset = M_.endo_nbr;
k0 = [1:M_.endo_nbr];
gx1 = dr.ghx;
for i=1:M_.maximum_endo_lead-1
k1 = find(kstate(:,2) == M_.maximum_endo_lag+i+1);
[k2,junk,k3] = find(kstate(k1,3));
A(1:M_.endo_nbr,offset+k2) = jacobia_(:,k3+M_.endo_nbr);
n1 = length(k1);
A(offset+[1:n1],nstatic+[1:npred]) = -gx1(kstate(k1,1),1:npred);
gx1 = gx1*hx;
A(offset+[1:n1],offset+[1:n1]) = eye(n1);
n0 = length(k0);
E = eye(n0);
if i == 1
[junk,junk,k4]=intersect(kstate(k1,1),[1:M_.endo_nbr]);
else
[junk,junk,k4]=intersect(kstate(k1,1),kstate(k0,1));
end
i1 = offset-n0+n1;
B(offset+[1:n1],offset-n0+[1:n0]) = -E(k4,:);
k0 = k1;
offset = offset + n1;
end
[junk,k1,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+M_.maximum_endo_lead+1,order_var));
A(1:M_.endo_nbr,nstatic+1:nstatic+npred)=...
A(1:M_.endo_nbr,nstatic+[1:npred])+jacobia_(:,k2)*gx1(k1,1:npred);
C = hx;
D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))];
dr.ghxx = gensylv(2,A,B,C,D);
%ghxu
%rhs
hu = dr.ghu(nstatic+1:nstatic+npred,:);
%kk = reshape([1:np*np],np,np);
%kk = kk(1:npred,1:npred);
%rhs = -hessian*kron(zx,zu)-f1*dr.ghxx(end-nyf+1:end,kk(:))*kron(hx(1:npred,:),hu(1:npred,:));
rhs = sparse_hessian_times_B_kronecker_C(hessian,zx,zu);
nyf1 = sum(kstate(:,2) == M_.maximum_endo_lag+2);
hu1 = [hu;zeros(np-npred,M_.exo_nbr)];
%B1 = [B(1:M_.endo_nbr,:);zeros(size(A,1)-M_.endo_nbr,size(B,2))];
[nrhx,nchx] = size(hx);
[nrhu1,nchu1] = size(hu1);
B1 = B*A_times_B_kronecker_C(dr.ghxx,hx,hu1);
rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;
%lhs
dr.ghxu = A\rhs;
%ghuu
%rhs
kk = reshape([1:np*np],np,np);
kk = kk(1:npred,1:npred);
rhs = sparse_hessian_times_B_kronecker_C(hessian,zu);
B1 = A_times_B_kronecker_C(B*dr.ghxx,hu1);
rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;
%lhs
dr.ghuu = A\rhs;
dr.ghxx = dr.ghxx(1:M_.endo_nbr,:);
dr.ghxu = dr.ghxu(1:M_.endo_nbr,:);
dr.ghuu = dr.ghuu(1:M_.endo_nbr,:);
% dr.ghs2
% derivatives of F with respect to forward variables
% reordering predetermined variables in diminishing lag order
O1 = zeros(M_.endo_nbr,nstatic);
O2 = zeros(M_.endo_nbr,M_.endo_nbr-nstatic-npred);
LHS = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var));
RHS = zeros(M_.endo_nbr,M_.exo_nbr^2);
kk = find(kstate(:,2) == M_.maximum_endo_lag+2);
gu = dr.ghu;
guu = dr.ghuu;
Gu = [dr.ghu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr)];
Guu = [dr.ghuu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr*M_.exo_nbr)];
E = eye(M_.endo_nbr);
M_.lead_lag_incidenceordered = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1));
if M_.maximum_endo_lag > 0
M_.lead_lag_incidenceordered = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); M_.lead_lag_incidenceordered];
end
M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered';
M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered(:);
k1 = find(M_.lead_lag_incidenceordered);
M_.lead_lag_incidenceordered(k1) = [1:length(k1)]';
M_.lead_lag_incidenceordered =reshape(M_.lead_lag_incidenceordered,M_.endo_nbr,M_.maximum_endo_lag+M_.maximum_endo_lead+1)';
kh = reshape([1:nk^2],nk,nk);
kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1);
E1 = [eye(npred); zeros(kp-npred,npred)];
H = E1;
hxx = dr.ghxx(nstatic+[1:npred],:);
for i=1:M_.maximum_endo_lead
for j=i:M_.maximum_endo_lead
[junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+j+1,order_var));
[junk,k3a,k3] = ...
find(M_.lead_lag_incidenceordered(M_.maximum_endo_lag+j+1,:));
nk3a = length(k3a);
B1 = sparse_hessian_times_B_kronecker_C(hessian(:,kh(k3,k3)),gu(k3a,:));
RHS = RHS + jacobia_(:,k2)*guu(k2a,:)+B1;
end
% LHS
[junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+i+1,order_var));
LHS = LHS + jacobia_(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]);
if i == M_.maximum_endo_lead
break
end
kk = find(kstate(:,2) == M_.maximum_endo_lag+i+1);
gu = dr.ghx*Gu;
[nrGu,ncGu] = size(Gu);
G1 = A_times_B_kronecker_C(dr.ghxx,Gu);
G2 = A_times_B_kronecker_C(hxx,Gu);
guu = dr.ghx*Guu+G1;
Gu = hx*Gu;
Guu = hx*Guu;
Guu(end-npred+1:end,:) = Guu(end-npred+1:end,:) + G2;
H = E1 + hx*H;
end
RHS = RHS*M_.Sigma_e(:);
dr.fuu = RHS;
%RHS = -RHS-dr.fbias;
RHS = -RHS;
dr.ghs2 = LHS\RHS;
% deterministic exogenous variables
if M_.exo_det_nbr > 0
hud = dr.ghud{1}(nstatic+1:nstatic+npred,:);
zud=[zeros(np,M_.exo_det_nbr);dr.ghud{1};gx(:,1:npred)*hud;zeros(M_.exo_nbr,M_.exo_det_nbr);eye(M_.exo_det_nbr)];
R1 = hessian*kron(zx,zud);
dr.ghxud = cell(M_.exo_det_length,1);
kf = [M_.endo_nbr-nyf+1:M_.endo_nbr];
kp = nstatic+[1:npred];
dr.ghxud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{1}(kp,:)));
Eud = eye(M_.exo_det_nbr);
for i = 2:M_.exo_det_length
hudi = dr.ghud{i}(kp,:);
zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
R2 = hessian*kron(zx,zudi);
dr.ghxud{i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hx,Eud)+dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{i}(kp,:)))-M1*R2;
end
R1 = hessian*kron(zu,zud);
dr.ghudud = cell(M_.exo_det_length,1);
kf = [M_.endo_nbr-nyf+1:M_.endo_nbr];
dr.ghuud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghu(kp,:),dr.ghud{1}(kp,:)));
Eud = eye(M_.exo_det_nbr);
for i = 2:M_.exo_det_length
hudi = dr.ghud{i}(kp,:);
zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
R2 = hessian*kron(zu,zudi);
dr.ghuud{i} = -M2*dr.ghxud{i-1}(kf,:)*kron(hu,Eud)-M1*R2;
end
R1 = hessian*kron(zud,zud);
dr.ghudud = cell(M_.exo_det_length,M_.exo_det_length);
dr.ghudud{1,1} = -M1*R1-M2*dr.ghxx(kf,:)*kron(hud,hud);
for i = 2:M_.exo_det_length
hudi = dr.ghud{i}(nstatic+1:nstatic+npred,:);
zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi+dr.ghud{i-1}(kf,:);zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
R2 = hessian*kron(zudi,zudi);
dr.ghudud{i,i} = -M2*(dr.ghudud{i-1,i-1}(kf,:)+...
2*dr.ghxud{i-1}(kf,:)*kron(hudi,Eud) ...
+dr.ghxx(kf,:)*kron(hudi,hudi))-M1*R2;
R2 = hessian*kron(zud,zudi);
dr.ghudud{1,i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hud,Eud)+...
dr.ghxx(kf,:)*kron(hud,hudi))...
-M1*R2;
for j=2:i-1
hudj = dr.ghud{j}(kp,:);
zudj=[zeros(np,M_.exo_det_nbr);dr.ghud{j};gx(:,1:npred)*hudj;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
R2 = hessian*kron(zudj,zudi);
dr.ghudud{j,i} = -M2*(dr.ghudud{j-1,i-1}(kf,:)+dr.ghxud{j-1}(kf,:)* ...
kron(hudi,Eud)+dr.ghxud{i-1}(kf,:)* ...
kron(hudj,Eud)+dr.ghxx(kf,:)*kron(hudj,hudi))-M1*R2;
end
end
end

View File

@ -47,47 +47,47 @@ function [dr,info,M_,options_,oo_] = dr1_sparse(dr,task,M_,options_,oo_)
% 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;
options_ = set_default_option(options_,'loglinear',0);
options_ = set_default_option(options_,'noprint',0);
options_ = set_default_option(options_,'olr',0);
options_ = set_default_option(options_,'olr_beta',1);
options_ = set_default_option(options_,'qz_criterium',1.000001);
xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1;
klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1;
iyv = M_.lead_lag_incidence';
iyv = iyv(:);
iyr0 = find(iyv) ;
it_ = M_.maximum_lag + 1 ;
if M_.exo_nbr == 0
oo_.exo_steady_state = [] ;
info = 0;
options_ = set_default_option(options_,'loglinear',0);
options_ = set_default_option(options_,'noprint',0);
options_ = set_default_option(options_,'olr',0);
options_ = set_default_option(options_,'olr_beta',1);
options_ = set_default_option(options_,'qz_criterium',1.000001);
xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1;
klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1;
iyv = M_.lead_lag_incidence';
iyv = iyv(:);
iyr0 = find(iyv) ;
it_ = M_.maximum_lag + 1 ;
if M_.exo_nbr == 0
oo_.exo_steady_state = [] ;
end
% expanding system for Optimal Linear Regulator
if options_.ramsey_policy
if isfield(M_,'orig_model')
orig_model = M_.orig_model;
M_.endo_nbr = orig_model.endo_nbr;
M_.orig_endo_nbr = orig_model.orig_endo_nbr;
M_.aux_vars = orig_model.aux_vars;
M_.endo_names = orig_model.endo_names;
M_.lead_lag_incidence = orig_model.lead_lag_incidence;
M_.maximum_lead = orig_model.maximum_lead;
M_.maximum_endo_lead = orig_model.maximum_endo_lead;
M_.maximum_lag = orig_model.maximum_lag;
M_.maximum_endo_lag = orig_model.maximum_endo_lag;
end
% expanding system for Optimal Linear Regulator
if options_.ramsey_policy
if isfield(M_,'orig_model')
orig_model = M_.orig_model;
M_.endo_nbr = orig_model.endo_nbr;
M_.orig_endo_nbr = orig_model.orig_endo_nbr;
M_.aux_vars = orig_model.aux_vars;
M_.endo_names = orig_model.endo_names;
M_.lead_lag_incidence = orig_model.lead_lag_incidence;
M_.maximum_lead = orig_model.maximum_lead;
M_.maximum_endo_lead = orig_model.maximum_endo_lead;
M_.maximum_lag = orig_model.maximum_lag;
M_.maximum_endo_lag = orig_model.maximum_endo_lag;
end
old_solve_algo = options_.solve_algo;
% options_.solve_algo = 1;
oo_.steady_state = dynare_solve('dyn_ramsey_static_',oo_.steady_state,0,M_,options_,oo_,it_);
options_.solve_algo = old_solve_algo;
[junk,junk,multbar] = dyn_ramsey_static_(oo_.steady_state,M_,options_,oo_,it_);
[jacobia_,M_] = dyn_ramsey_dynamic_(oo_.steady_state,multbar,M_,options_,oo_,it_);
klen = M_.maximum_lag + M_.maximum_lead + 1;
dr.ys = [oo_.steady_state;zeros(M_.exo_nbr,1);multbar];
old_solve_algo = options_.solve_algo;
% options_.solve_algo = 1;
oo_.steady_state = dynare_solve('dyn_ramsey_static_',oo_.steady_state,0,M_,options_,oo_,it_);
options_.solve_algo = old_solve_algo;
[junk,junk,multbar] = dyn_ramsey_static_(oo_.steady_state,M_,options_,oo_,it_);
[jacobia_,M_] = dyn_ramsey_dynamic_(oo_.steady_state,multbar,M_,options_,oo_,it_);
klen = M_.maximum_lag + M_.maximum_lead + 1;
dr.ys = [oo_.steady_state;zeros(M_.exo_nbr,1);multbar];
% $$$ if options_.ramsey_policy == 2
% $$$ mask = M_.orig_model.lead_lag_incidence ~= 0;
% $$$ incidence_submatrix = M_.lead_lag_incidence(M_.orig_model.maximum_lead+(1:size(mask,1)),1:M_.orig_model.endo_nbr);
@ -178,91 +178,91 @@ function [dr,info,M_,options_,oo_] = dr1_sparse(dr,task,M_,options_,oo_)
% $$$ M_.endo_names = strvcat(M_.orig_model.endo_names, M_.endo_names(endo_nbr1+k,:));
% $$$ M_.endo_nbr = endo_nbr1+length(k);
% $$$ end
else
klen = M_.maximum_lag + M_.maximum_lead + 1;
iyv = M_.lead_lag_incidence';
iyv = iyv(:);
iyr0 = find(iyv) ;
it_ = M_.maximum_lag + 1 ;
if M_.exo_nbr == 0
oo_.exo_steady_state = [] ;
end
it_ = M_.maximum_lag + 1;
z = repmat(dr.ys,1,klen);
z = z(iyr0) ;
if options_.model_mode==0 || options_.model_mode == 2
if options_.order == 1
[junk,jacobia_] = feval([M_.fname '_dynamic'],z,[oo_.exo_simul ...
oo_.exo_det_simul], M_.params, it_);
hessian = 0;
elseif options_.order == 2
[junk,jacobia_,hessian] = feval([M_.fname '_dynamic'],z,...
[oo_.exo_simul ...
oo_.exo_det_simul], M_.params, it_);
end
dr=set_state_space(dr,M_);
if options_.debug
save([M_.fname '_debug.mat'],'jacobia_')
end
[dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian);
dr.nyf = nnz(dr.kstate(:,2)>M_.maximum_lag+1);
elseif options_.model_mode==1
if options_.order == 1
[junk,derivate] = feval([M_.fname '_dynamic'],ones(M_.maximum_lag+M_.maximum_lead+1,1)*dr.ys',[oo_.exo_simul ...
oo_.exo_det_simul], M_.params, it_);
%full(jacobia_)
dr.eigval = [];
dr.nyf = 0;
dr.rank = 0;
first_col_exo = M_.endo_nbr * (M_.maximum_endo_lag + M_.maximum_endo_lead + 1);
for i=1:length(M_.block_structure.block)
%disp(['block = ' int2str(i)]);
M_.block_structure.block(i).dr.Null=0;
M_.block_structure.block(i).dr=set_state_space(M_.block_structure.block(i).dr,M_.block_structure.block(i));
col_selector=repmat(M_.block_structure.block(i).variable,1,M_.block_structure.block(i).maximum_endo_lag+M_.block_structure.block(i).maximum_endo_lead+1)+kron([M_.maximum_endo_lag-M_.block_structure.block(i).maximum_endo_lag:M_.maximum_endo_lag+M_.block_structure.block(i).maximum_endo_lead],M_.endo_nbr*ones(1,M_.block_structure.block(i).endo_nbr));
row_selector = M_.block_structure.block(i).equation;
%jcb_=jacobia_(row_selector,col_selector);
jcb_=derivate(i).g1;
%disp('jcb_');
%full(jcb_)
%M_.block_structure.block(i).lead_lag_incidence'
jcb_ = jcb_(:,find(M_.block_structure.block(i).lead_lag_incidence')) ;
if M_.block_structure.block(i).exo_nbr>0
col_selector = [ first_col_exo + ...
repmat(M_.block_structure.block(i).exogenous,1,M_.block_structure.block(i).maximum_exo_lag+M_.block_structure.block(i).maximum_exo_lead+1)+kron([M_.maximum_exo_lag-M_.block_structure.block(i).maximum_exo_lag:M_.maximum_exo_lag+M_.block_structure.block(i).maximum_exo_lead],M_.exo_nbr*ones(1,M_.block_structure.block(i).exo_nbr))];
end
%derivate(i).g1
%derivate(i).g1_x
%col_selector
%jcb_ = [ jcb_ jacobia_(row_selector,col_selector)];
jcb_ = [ jcb_ derivate(i).g1_x];
%full(jcb_)
hss_=0; %hessian(M_.block_structure.block(i).equation,M_.block_structure.block(i).variable);
dra = M_.block_structure.block(i).dr;
%M_.block_structure.block(i).exo_nbr=M_.exo_nbr;
[dra ,info,M_.block_structure.block(i),options_,oo_] = dr11_sparse(dra ,task,M_.block_structure.block(i),options_,oo_, jcb_, hss_);
M_.block_structure.block(i).dr = dra;
dr.eigval = [dr.eigval; dra.eigval];
nyf = nnz(dra.kstate(:,2)>M_.block_structure.block(i).maximum_endo_lag+1);
n_explod = nnz(abs(dra.eigval) > options_.qz_criterium);
if nyf ~= n_explod
disp(['EIGENVALUES in block ' int2str(i) ':']);
[m_lambda,ii]=sort(abs(dra.eigval));
disp(sprintf('%16s %16s %16s\n','Modulus','Real','Imaginary'))
z=[m_lambda real(dra.eigval(ii)) imag(dra.eigval(ii))]';
disp(sprintf('%16.4g %16.4g %16.4g\n',z))
disp(['The rank condition is not satisfy in block ' int2str(i) ' :']);
disp([' ' int2str(nyf) ' forward-looking variable(s) for ' ...
int2str(n_explod) ' eigenvalue(s) larger than 1 in modulus']);
end
dr.nyf = dr.nyf + nyf;
dr.rank = dr.rank + dra.rank;
end;
end
end
else
klen = M_.maximum_lag + M_.maximum_lead + 1;
iyv = M_.lead_lag_incidence';
iyv = iyv(:);
iyr0 = find(iyv) ;
it_ = M_.maximum_lag + 1 ;
if M_.exo_nbr == 0
oo_.exo_steady_state = [] ;
end
it_ = M_.maximum_lag + 1;
z = repmat(dr.ys,1,klen);
z = z(iyr0) ;
if options_.model_mode==0 || options_.model_mode == 2
if options_.order == 1
[junk,jacobia_] = feval([M_.fname '_dynamic'],z,[oo_.exo_simul ...
oo_.exo_det_simul], M_.params, it_);
hessian = 0;
elseif options_.order == 2
[junk,jacobia_,hessian] = feval([M_.fname '_dynamic'],z,...
[oo_.exo_simul ...
oo_.exo_det_simul], M_.params, it_);
end
dr=set_state_space(dr,M_);
if options_.debug
save([M_.fname '_debug.mat'],'jacobia_')
end
[dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian);
dr.nyf = nnz(dr.kstate(:,2)>M_.maximum_lag+1);
elseif options_.model_mode==1
if options_.order == 1
[junk,derivate] = feval([M_.fname '_dynamic'],ones(M_.maximum_lag+M_.maximum_lead+1,1)*dr.ys',[oo_.exo_simul ...
oo_.exo_det_simul], M_.params, it_);
%full(jacobia_)
dr.eigval = [];
dr.nyf = 0;
dr.rank = 0;
first_col_exo = M_.endo_nbr * (M_.maximum_endo_lag + M_.maximum_endo_lead + 1);
for i=1:length(M_.block_structure.block)
%disp(['block = ' int2str(i)]);
M_.block_structure.block(i).dr.Null=0;
M_.block_structure.block(i).dr=set_state_space(M_.block_structure.block(i).dr,M_.block_structure.block(i));
col_selector=repmat(M_.block_structure.block(i).variable,1,M_.block_structure.block(i).maximum_endo_lag+M_.block_structure.block(i).maximum_endo_lead+1)+kron([M_.maximum_endo_lag-M_.block_structure.block(i).maximum_endo_lag:M_.maximum_endo_lag+M_.block_structure.block(i).maximum_endo_lead],M_.endo_nbr*ones(1,M_.block_structure.block(i).endo_nbr));
row_selector = M_.block_structure.block(i).equation;
%jcb_=jacobia_(row_selector,col_selector);
jcb_=derivate(i).g1;
%disp('jcb_');
%full(jcb_)
%M_.block_structure.block(i).lead_lag_incidence'
jcb_ = jcb_(:,find(M_.block_structure.block(i).lead_lag_incidence')) ;
if M_.block_structure.block(i).exo_nbr>0
col_selector = [ first_col_exo + ...
repmat(M_.block_structure.block(i).exogenous,1,M_.block_structure.block(i).maximum_exo_lag+M_.block_structure.block(i).maximum_exo_lead+1)+kron([M_.maximum_exo_lag-M_.block_structure.block(i).maximum_exo_lag:M_.maximum_exo_lag+M_.block_structure.block(i).maximum_exo_lead],M_.exo_nbr*ones(1,M_.block_structure.block(i).exo_nbr))];
end
%derivate(i).g1
%derivate(i).g1_x
%col_selector
%jcb_ = [ jcb_ jacobia_(row_selector,col_selector)];
jcb_ = [ jcb_ derivate(i).g1_x];
%full(jcb_)
hss_=0; %hessian(M_.block_structure.block(i).equation,M_.block_structure.block(i).variable);
dra = M_.block_structure.block(i).dr;
%M_.block_structure.block(i).exo_nbr=M_.exo_nbr;
[dra ,info,M_.block_structure.block(i),options_,oo_] = dr11_sparse(dra ,task,M_.block_structure.block(i),options_,oo_, jcb_, hss_);
M_.block_structure.block(i).dr = dra;
dr.eigval = [dr.eigval; dra.eigval];
nyf = nnz(dra.kstate(:,2)>M_.block_structure.block(i).maximum_endo_lag+1);
n_explod = nnz(abs(dra.eigval) > options_.qz_criterium);
if nyf ~= n_explod
disp(['EIGENVALUES in block ' int2str(i) ':']);
[m_lambda,ii]=sort(abs(dra.eigval));
disp(sprintf('%16s %16s %16s\n','Modulus','Real','Imaginary'))
z=[m_lambda real(dra.eigval(ii)) imag(dra.eigval(ii))]';
disp(sprintf('%16.4g %16.4g %16.4g\n',z))
disp(['The rank condition is not satisfy in block ' int2str(i) ' :']);
disp([' ' int2str(nyf) ' forward-looking variable(s) for ' ...
int2str(n_explod) ' eigenvalue(s) larger than 1 in modulus']);
end
dr.nyf = dr.nyf + nyf;
dr.rank = dr.rank + dra.rank;
end;
end
end
end

View File

@ -37,20 +37,20 @@ global options_
options_.smpl = zeros(2,1) ;
if nargin == 0
options_.smpl(1) = 1 ;
options_.smpl(2) = options_.periods ;
options_.smpl(1) = 1 ;
options_.smpl(2) = options_.periods ;
elseif nargin == 1
if s1 > options_.periods
error('DSAMPLE: argument greater than number of periods');
end
options_.smpl(1) = 1 ;
options_.smpl(2) = s1 ;
if s1 > options_.periods
error('DSAMPLE: argument greater than number of periods');
end
options_.smpl(1) = 1 ;
options_.smpl(2) = s1 ;
else
if s1 > options_.periods || s2 > options_.periods
error('DSAMPLE: one of the arguments is greater than number of periods');
end
options_.smpl(1) = s1 ;
options_.smpl(2) = s2 ;
if s1 > options_.periods || s2 > options_.periods
error('DSAMPLE: one of the arguments is greater than number of periods');
end
options_.smpl(1) = s1 ;
options_.smpl(2) = s2 ;
end
% 02/23/01 MJ added error checking

View File

@ -38,274 +38,274 @@ function [fval,cost_flag,ys,trend_coeff,info] = dsge_posterior_kernel(xparam1,ge
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_
fval = [];
ys = [];
trend_coeff = [];
cost_flag = 1;
nobs = size(options_.varobs,1);
%------------------------------------------------------------------------------
% 1. Get the structural parameters & define penalties
%------------------------------------------------------------------------------
if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
k = find(xparam1 < bayestopt_.lb);
fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
cost_flag = 0;
info = 41;
return;
end
if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
k = find(xparam1 > bayestopt_.ub);
fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
cost_flag = 0;
info = 42;
return;
end
Q = M_.Sigma_e;
H = M_.H;
for i=1:estim_params_.nvx
global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_
fval = [];
ys = [];
trend_coeff = [];
cost_flag = 1;
nobs = size(options_.varobs,1);
%------------------------------------------------------------------------------
% 1. Get the structural parameters & define penalties
%------------------------------------------------------------------------------
if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
k = find(xparam1 < bayestopt_.lb);
fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
cost_flag = 0;
info = 41;
return;
end
if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
k = find(xparam1 > bayestopt_.ub);
fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
cost_flag = 0;
info = 42;
return;
end
Q = M_.Sigma_e;
H = M_.H;
for i=1:estim_params_.nvx
k =estim_params_.var_exo(i,1);
Q(k,k) = xparam1(i)*xparam1(i);
end
offset = estim_params_.nvx;
if estim_params_.nvn
end
offset = estim_params_.nvx;
if estim_params_.nvn
for i=1:estim_params_.nvn
k = estim_params_.var_endo(i,1);
H(k,k) = xparam1(i+offset)*xparam1(i+offset);
k = estim_params_.var_endo(i,1);
H(k,k) = xparam1(i+offset)*xparam1(i+offset);
end
offset = offset+estim_params_.nvn;
end
if estim_params_.ncx
end
if estim_params_.ncx
for i=1:estim_params_.ncx
k1 =estim_params_.corrx(i,1);
k2 =estim_params_.corrx(i,2);
Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
Q(k2,k1) = Q(k1,k2);
k1 =estim_params_.corrx(i,1);
k2 =estim_params_.corrx(i,2);
Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
Q(k2,k1) = Q(k1,k2);
end
[CholQ,testQ] = chol(Q);
if testQ %% The variance-covariance matrix of the structural innovations is not definite positive.
%% We have to compute the eigenvalues of this matrix in order to build the penalty.
a = diag(eig(Q));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 43;
return
end
%% We have to compute the eigenvalues of this matrix in order to build the penalty.
a = diag(eig(Q));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 43;
return
end
end
offset = offset+estim_params_.ncx;
end
if estim_params_.ncn
end
if estim_params_.ncn
for i=1:estim_params_.ncn
k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
H(k2,k1) = H(k1,k2);
k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
H(k2,k1) = H(k1,k2);
end
[CholH,testH] = chol(H);
if testH
a = diag(eig(H));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 44;
return
end
a = diag(eig(H));
k = find(a < 0);
if k > 0
fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0;
info = 44;
return
end
end
offset = offset+estim_params_.ncn;
end
if estim_params_.np > 0
M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
end
M_.Sigma_e = Q;
M_.H = H;
%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------
[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
bayestopt_.restrict_columns,...
bayestopt_.restrict_aux);
if info(1) == 1 | info(1) == 2 | info(1) == 5
end
if estim_params_.np > 0
M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
end
M_.Sigma_e = Q;
M_.H = H;
%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------
[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
bayestopt_.restrict_columns,...
bayestopt_.restrict_aux);
if info(1) == 1 | info(1) == 2 | info(1) == 5
fval = bayestopt_.penalty+1;
cost_flag = 0;
return
elseif info(1) == 3 | info(1) == 4 | info(1) == 20
elseif info(1) == 3 | info(1) == 4 | info(1) == 20
fval = bayestopt_.penalty+info(2);%^2; % penalty power raised in DR1.m and resol already. GP July'08
cost_flag = 0;
return
end
bayestopt_.mf = bayestopt_.mf1;
if ~options_.noconstant
end
bayestopt_.mf = bayestopt_.mf1;
if ~options_.noconstant
if options_.loglinear == 1
constant = log(SteadyState(bayestopt_.mfys));
constant = log(SteadyState(bayestopt_.mfys));
else
constant = SteadyState(bayestopt_.mfys);
constant = SteadyState(bayestopt_.mfys);
end
else
else
constant = zeros(nobs,1);
end
if bayestopt_.with_trend == 1
end
if bayestopt_.with_trend == 1
trend_coeff = zeros(nobs,1);
t = options_.trend_coeffs;
for i=1:length(t)
if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i});
end
if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i});
end
end
trend = repmat(constant,1,gend)+trend_coeff*[1:gend];
else
else
trend = repmat(constant,1,gend);
end
start = options_.presample+1;
np = size(T,1);
mf = bayestopt_.mf;
no_missing_data_flag = (number_of_observations==gend*nobs);
%------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter
%------------------------------------------------------------------------------
kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = 10*eye(np);
Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4
kalman_algo = 3;
end
[QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k);
nk1 = nk+1;
Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2
if ST(i,i-1) == 0
if i == np
c = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else
if i == np
c = zeros(np-nk,1);
c1 = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+...
ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1);
c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+...
ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+...
ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);...
-ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)];
z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1];
Pstar(nk1:i,i) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1;
end
end
if i == nk+2
c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1);
Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end
Z = QT(mf,:);
R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag(RR)) < 1e-8);
if length(k) > 0
k1 = EE(:,k);
dd =ones(nk,1);
dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd);
end
end
if kalman_algo == 2
no_correlation_flag = 1;
if length(H)==1
H = zeros(nobs,1);
else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H);
else
no_correlation_flag = 0;
end
end
end
kalman_tol = options_.kalman_tol;
riccati_tol = options_.riccati_tol;
mf = bayestopt_.mf1;
Y = data-trend;
%------------------------------------------------------------------------------
% 4. Likelihood evaluation
%------------------------------------------------------------------------------
if (kalman_algo==1)% Multivariate Kalman Filter
if no_missing_data_flag
LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol);
else
LIK = ...
missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ...
data_index,number_of_observations,no_more_missing_observations);
end
if isinf(LIK)
kalman_algo = 2;
end
end
if (kalman_algo==2)% Univariate Kalman Filter
if no_correlation_flag
LIK = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
else
LIK = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
end
end
if (kalman_algo==3)% Multivariate Diffuse Kalman Filter
if no_missing_data_flag
LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol);
else
LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,no_more_missing_observations);
end
if isinf(LIK)
kalman_algo = 4;
end
end
if (kalman_algo==4)% Univariate Diffuse Kalman Filter
if no_correlation_flag
LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,no_more_missing_observations);
else
LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,no_more_missing_observations);
end
end
if imag(LIK) ~= 0
likelihood = bayestopt_.penalty;
else
likelihood = LIK;
end
% ------------------------------------------------------------------------------
% Adds prior if necessary
% ------------------------------------------------------------------------------
lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
fval = (likelihood-lnprior);
options_.kalman_algo = kalman_algo;
end
start = options_.presample+1;
np = size(T,1);
mf = bayestopt_.mf;
no_missing_data_flag = (number_of_observations==gend*nobs);
%------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter
%------------------------------------------------------------------------------
kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2
kalman_algo = 1;
end
Pstar = 10*eye(np);
Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4
kalman_algo = 3;
end
[QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k);
nk1 = nk+1;
Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2
if ST(i,i-1) == 0
if i == np
c = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else
if i == np
c = zeros(np-nk,1);
c1 = zeros(np-nk,1);
else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+...
ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1);
c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+...
ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+...
ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);...
-ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)];
z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1];
Pstar(nk1:i,i) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1;
end
end
if i == nk+2
c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1);
Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end
Z = QT(mf,:);
R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag(RR)) < 1e-8);
if length(k) > 0
k1 = EE(:,k);
dd =ones(nk,1);
dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd);
end
end
if kalman_algo == 2
no_correlation_flag = 1;
if length(H)==1
H = zeros(nobs,1);
else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H);
else
no_correlation_flag = 0;
end
end
end
kalman_tol = options_.kalman_tol;
riccati_tol = options_.riccati_tol;
mf = bayestopt_.mf1;
Y = data-trend;
%------------------------------------------------------------------------------
% 4. Likelihood evaluation
%------------------------------------------------------------------------------
if (kalman_algo==1)% Multivariate Kalman Filter
if no_missing_data_flag
LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol);
else
LIK = ...
missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ...
data_index,number_of_observations,no_more_missing_observations);
end
if isinf(LIK)
kalman_algo = 2;
end
end
if (kalman_algo==2)% Univariate Kalman Filter
if no_correlation_flag
LIK = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
else
LIK = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
end
end
if (kalman_algo==3)% Multivariate Diffuse Kalman Filter
if no_missing_data_flag
LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol);
else
LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,no_more_missing_observations);
end
if isinf(LIK)
kalman_algo = 4;
end
end
if (kalman_algo==4)% Univariate Diffuse Kalman Filter
if no_correlation_flag
LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,no_more_missing_observations);
else
LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,no_more_missing_observations);
end
end
if imag(LIK) ~= 0
likelihood = bayestopt_.penalty;
else
likelihood = LIK;
end
% ------------------------------------------------------------------------------
% Adds prior if necessary
% ------------------------------------------------------------------------------
lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
fval = (likelihood-lnprior);
options_.kalman_algo = kalman_algo;

View File

@ -1,5 +1,5 @@
function [nvar,vartan,NumberOfConditionalDecompFiles] = ...
dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,Steps,M_,options_,oo_,type)
dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,Steps,M_,options_,oo_,type)
% This function computes the posterior or prior distribution of the conditional variance
% decomposition of the endogenous variables (or a subset of the endogenous variables).
%

View File

@ -47,7 +47,7 @@ else
error()
end
NumberOfDrawsFiles = length(DrawsFiles);
% Set varlist (vartan)
if ~posterior
if isfield(options_,'varlist')

View File

@ -1,5 +1,5 @@
function [nvar,vartan,NumberOfDecompFiles] = ...
dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,type)
dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,type)
% This function computes the posterior or prior distribution of the variance
% decomposition of the observed endogenous variables.
%

View File

@ -17,8 +17,7 @@ function y=dy_date(year,period)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_
y = M_.freq*(year-M_.start_date(1))+period-M_.start_date(2)+1;
global M_
y = M_.freq*(year-M_.start_date(1))+period-M_.start_date(2)+1;

View File

@ -31,54 +31,54 @@ function [z,zss]=dyn2vec(s1,s2)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ options_
global M_ oo_ options_
if options_.smpl == 0
if options_.smpl == 0
k = [1:size(oo_.endo_simul,2)];
else
else
k = [M_.maximum_lag+options_.smpl(1):M_.maximum_lag+options_.smpl(2)];
end
end
if nargin == 0
if nargin == 0
if nargout > 0
t = ['DYNARE dyn2vec error: the function doesn''t return values when' ...
' used without input argument'];
error(t);
t = ['DYNARE dyn2vec error: the function doesn''t return values when' ...
' used without input argument'];
error(t);
end
for i=1:size(oo_.endo_simul,1)
assignin('base',deblank(M_.endo_names(i,:)),oo_.endo_simul(i,k)');
assignin('base',deblank(M_.endo_names(i,:)),oo_.endo_simul(i,k)');
end
return
else
else
j = strmatch(s1,M_.endo_names,'exact');
if ~ isempty(j)
z = oo_.endo_simul(j,k)';
z = oo_.endo_simul(j,k)';
else
j = strmatch(s1,M_.exo_names,'exact');
if ~ isempty(j)
if options_.smpl == 0
z = oo_.exo_simul(:,j);
else
z = oo_.exo_simul(M_.maximum_lag+options_.smpl(1):M_.maximum_lag+options_.smpl(2));
end
else
t = ['DYNARE dyn2vec error: variable ' deblank(s1(i,:)) ' doesn''t' ...
' exist.'] ;
error (t) ;
end
j = strmatch(s1,M_.exo_names,'exact');
if ~ isempty(j)
if options_.smpl == 0
z = oo_.exo_simul(:,j);
else
z = oo_.exo_simul(M_.maximum_lag+options_.smpl(1):M_.maximum_lag+options_.smpl(2));
end
else
t = ['DYNARE dyn2vec error: variable ' deblank(s1(i,:)) ' doesn''t' ...
' exist.'] ;
error (t) ;
end
end
end
end
if nargout == 0
if nargout == 0
if nargin == 1
assignin('base',s1,z);
assignin('base',s1,z);
elseif nargin == 2
assignin('base',s2,z);
assignin('base',s2,z);
end
else
else
zss=oo_.steady_state(j);
end
end
% 02/23/01 MJ redone, incorporating FC's improvements
% 08/24/01 MJ replaced globlize by internal assignin
% 08/24/01 MJ added 'exact' to strmatch (thanks to David Vavra)

View File

@ -1,239 +1,239 @@
function [J,M_] = dyn_ramsey_dynamic_(ys,lbar,M_,options_,oo_,it_)
% function J = dyn_ramsey_dynamic_(ys,lbar)
% dyn_ramsey_dynamic_ sets up the Jacobian of the expanded model for optimal
% policies. It modifies several fields of M_
%
% INPUTS:
% ys: steady state of original endogenous variables
% lbar: steady state of Lagrange multipliers
%
% OUPTUTS:
% J: jaocobian of expanded model
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2009 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/>.
% retrieving model parameters
endo_nbr = M_.endo_nbr;
i_endo_nbr = 1:endo_nbr;
endo_names = M_.endo_names;
% exo_nbr = M_.exo_nbr+M_.exo_det_nbr;
% exo_names = vertcat(M_.exo_names,M_.exo_det_names);
exo_nbr = M_.exo_nbr;
exo_names = M_.exo_names;
i_leadlag = M_.lead_lag_incidence;
max_lead = M_.maximum_lead;
max_endo_lead = M_.maximum_endo_lead;
max_lag = M_.maximum_lag;
max_endo_lag = M_.maximum_endo_lag;
leadlag_nbr = max_lead+max_lag+1;
fname = M_.fname;
% instr_names = options_.olr_inst;
% instr_nbr = size(options_.olr_inst,1);
% discount factor
beta = options_.planner_discount;
% storing original values
orig_model.endo_nbr = endo_nbr;
orig_model.orig_endo_nbr = M_.orig_endo_nbr;
orig_model.aux_vars = M_.aux_vars;
orig_model.endo_names = endo_names;
orig_model.lead_lag_incidence = i_leadlag;
orig_model.maximum_lead = max_lead;
orig_model.maximum_endo_lead = max_endo_lead;
orig_model.maximum_lag = max_lag;
orig_model.maximum_endo_lag = max_endo_lag;
y = repmat(ys,1,max_lag+max_lead+1);
k = find(i_leadlag');
% retrieving derivatives of the objective function
[U,Uy,Uyy] = feval([fname '_objective_static'],ys,zeros(1,exo_nbr), M_.params);
Uy = Uy';
Uyy = reshape(Uyy,endo_nbr,endo_nbr);
% retrieving derivatives of original model
[f,fJ,fH] = feval([fname '_dynamic'],y(k),[oo_.exo_simul oo_.exo_det_simul], M_.params, it_);
instr_nbr = endo_nbr - size(f,1);
mult_nbr = endo_nbr-instr_nbr;
% parameters for expanded model
endo_nbr1 = 2*endo_nbr-instr_nbr+exo_nbr;
max_lead1 = max_lead + max_lag;
max_lag1 = max_lead1;
max_leadlag1 = max_lead1;
% adding new variables names
endo_names1 = endo_names;
% adding shocks to endogenous variables
endo_names1 = strvcat(endo_names1, exo_names);
% adding multipliers names
for i=1:mult_nbr;
endo_names1 = strvcat(endo_names1,['mult_' int2str(i)]);
end
% expanding matrix of lead/lag incidence
%
% multipliers lead/lag incidence
i_mult = [];
for i=1:leadlag_nbr
i_mult = [any(fJ(:,nonzeros(i_leadlag(i,:))) ~= 0,2)' ; i_mult];
end
% putting it all together:
% original variables, exogenous variables made endogenous, multipliers
%
% number of original dynamic variables
n_dyn = nnz(i_leadlag);
% numbering columns of dynamic multipliers to be put in the last columns
% of the new Jacobian
i_leadlag1 = [cumsum(i_leadlag(1:max_lag,:),1); ...
repmat(i_leadlag(max_lag+1,:),leadlag_nbr,1); ...
flipud(cumsum(flipud(i_leadlag(max_lag+2:end,:)),1))];
i_leadlag1 = i_leadlag1';
k = find(i_leadlag1 > 0);
n = length(k);
i_leadlag1(k) = 1:n;
i_leadlag1 = i_leadlag1';
i_mult = i_mult';
k = find(i_mult > 0);
i_mult(k) = n+leadlag_nbr*exo_nbr+(1:length(k));
i_mult = i_mult';
i_leadlag1 = [ i_leadlag1 ...
[zeros(max_lag,exo_nbr);...
reshape(n+(1:leadlag_nbr*exo_nbr),exo_nbr,leadlag_nbr)'; ...
zeros(max_lead,exo_nbr)] ...
[zeros(max_lag,mult_nbr);...
i_mult;...
zeros(max_lead,mult_nbr)]];
i_leadlag1 = i_leadlag1';
k = find(i_leadlag1 > 0);
n = length(k);
i_leadlag1(k) = 1:n;
i_leadlag1 = i_leadlag1';
% building Jacobian of expanded model
jacobian = zeros(endo_nbr+mult_nbr,nnz(i_leadlag1)+exo_nbr);
% derivatives of f.o.c. w.r. to endogenous variables
% to be rearranged further down
lbarfH = lbar'*fH;
% indices of Hessian columns
n1 = nnz(i_leadlag)+exo_nbr;
iH = reshape(1:n1^2,n1,n1);
J = zeros(endo_nbr1,nnz(i_leadlag1)+exo_nbr);
% second order derivatives of objective function
J(1:endo_nbr,i_leadlag1(max_leadlag1+1,1:endo_nbr)) = Uyy;
% loop on lead/lags in expanded model
for i=1:2*max_leadlag1 + 1
% index of variables at the current lag in expanded model
kc = find(i_leadlag1(i,i_endo_nbr) > 0);
t1 = max(1,i-max_leadlag1);
t2 = min(i,max_leadlag1+1);
% loop on lead/lag blocks of relevant 1st order derivatives
for j = t1:t2
% derivatives w.r. endogenous variables
ic = find(i_leadlag(i-j+1,:) > 0 );
kc1 = i_leadlag(i-j+1,ic);
[junk,ic1,ic2] = intersect(ic,kc);
kc2 = i_leadlag1(i,kc(ic2));
ir = find(i_leadlag(max_leadlag1+2-j,:) > 0 );
kr1 = i_leadlag(max_leadlag1+2-j,ir);
J(ir,kc2) = J(ir,kc2) + beta^(j-max_lead-1)...
*reshape(lbarfH(iH(kr1,kc1)),length(kr1),length(kc1));
end
end
% derivatives w.r. aux. variables for lead/lag exogenous shocks
for i=1:leadlag_nbr
kc = i_leadlag1(max_lag+i,endo_nbr+(1:exo_nbr));
ir = find(i_leadlag(leadlag_nbr+1-i,:) > 0);
kr1 = i_leadlag(leadlag_nbr+1-i,ir);
J(ir,kc) = beta^(i-max_lead-1)...
*reshape(lbarfH(iH(kr1,n_dyn+(1:exo_nbr))),length(kr1), ...
exo_nbr);
end
% derivatives w.r. Lagrange multipliers
for i=1:leadlag_nbr
ic1 = find(i_leadlag(leadlag_nbr+1-i,:) > 0);
kc1 = i_leadlag(leadlag_nbr+1-i,ic1);
ic2 = find(i_leadlag1(max_lag+i,endo_nbr+exo_nbr+(1:mult_nbr)) > 0);
kc2 = i_leadlag1(max_lag+i,endo_nbr+exo_nbr+ic2);
J(ic1,kc2) = beta^(i-max_lead-1)*fJ(ic2,kc1)';
end
% Jacobian of original equations
%
% w.r. endogenous variables
ir = endo_nbr+(1:endo_nbr-instr_nbr);
for i=1:leadlag_nbr
ic1 = find(i_leadlag(i,:) > 0);
kc1 = i_leadlag(i,ic1);
ic2 = find(i_leadlag1(max_lead+i,:) > 0);
kc2 = i_leadlag1(max_lead+i,ic2);
[junk,junk,ic3] = intersect(ic1,ic2);
J(ir,kc2(ic3)) = fJ(:,kc1);
end
% w.r. exogenous variables
J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = fJ(:,nnz(i_leadlag)+(1:exo_nbr));
% auxiliary variable for exogenous shocks
ir = 2*endo_nbr-instr_nbr+(1:exo_nbr);
kc = i_leadlag1(leadlag_nbr,endo_nbr+(1:exo_nbr));
J(ir,kc) = eye(exo_nbr);
J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = -eye(exo_nbr);
% eliminating empty columns
% getting indices of nonzero entries
m = find(i_leadlag1');
n1 = max_lag1*endo_nbr1+1;
n2 = n1+endo_nbr-1;
n = length(m);
k = 1:size(J,2);
for i=1:n
if sum(abs(J(:,i))) < 1e-8
if m(i) < n1 | m(i) > n2
k(i) = 0;
m(i) = 0;
end
end
end
J = J(:,nonzeros(k));
i_leadlag1 = zeros(size(i_leadlag1))';
i_leadlag1(nonzeros(m)) = 1:nnz(m);
i_leadlag1 = i_leadlag1';
% setting expanded model parameters
% storing original values
M_.endo_nbr = endo_nbr1;
% Consider that there is no auxiliary variable, because otherwise it
% interacts badly with the auxiliary variables from the preprocessor.
M_.orig_endo_nbr = endo_nbr1;
M_.aux_vars = [];
M_.endo_names = endo_names1;
M_.lead_lag_incidence = i_leadlag1;
M_.maximum_lead = max_lead1;
M_.maximum_endo_lead = max_lead1;
M_.maximum_lag = max_lag1;
M_.maximum_endo_lag = max_lag1;
M_.orig_model = orig_model;
function [J,M_] = dyn_ramsey_dynamic_(ys,lbar,M_,options_,oo_,it_)
% function J = dyn_ramsey_dynamic_(ys,lbar)
% dyn_ramsey_dynamic_ sets up the Jacobian of the expanded model for optimal
% policies. It modifies several fields of M_
%
% INPUTS:
% ys: steady state of original endogenous variables
% lbar: steady state of Lagrange multipliers
%
% OUPTUTS:
% J: jaocobian of expanded model
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2009 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/>.
% retrieving model parameters
endo_nbr = M_.endo_nbr;
i_endo_nbr = 1:endo_nbr;
endo_names = M_.endo_names;
% exo_nbr = M_.exo_nbr+M_.exo_det_nbr;
% exo_names = vertcat(M_.exo_names,M_.exo_det_names);
exo_nbr = M_.exo_nbr;
exo_names = M_.exo_names;
i_leadlag = M_.lead_lag_incidence;
max_lead = M_.maximum_lead;
max_endo_lead = M_.maximum_endo_lead;
max_lag = M_.maximum_lag;
max_endo_lag = M_.maximum_endo_lag;
leadlag_nbr = max_lead+max_lag+1;
fname = M_.fname;
% instr_names = options_.olr_inst;
% instr_nbr = size(options_.olr_inst,1);
% discount factor
beta = options_.planner_discount;
% storing original values
orig_model.endo_nbr = endo_nbr;
orig_model.orig_endo_nbr = M_.orig_endo_nbr;
orig_model.aux_vars = M_.aux_vars;
orig_model.endo_names = endo_names;
orig_model.lead_lag_incidence = i_leadlag;
orig_model.maximum_lead = max_lead;
orig_model.maximum_endo_lead = max_endo_lead;
orig_model.maximum_lag = max_lag;
orig_model.maximum_endo_lag = max_endo_lag;
y = repmat(ys,1,max_lag+max_lead+1);
k = find(i_leadlag');
% retrieving derivatives of the objective function
[U,Uy,Uyy] = feval([fname '_objective_static'],ys,zeros(1,exo_nbr), M_.params);
Uy = Uy';
Uyy = reshape(Uyy,endo_nbr,endo_nbr);
% retrieving derivatives of original model
[f,fJ,fH] = feval([fname '_dynamic'],y(k),[oo_.exo_simul oo_.exo_det_simul], M_.params, it_);
instr_nbr = endo_nbr - size(f,1);
mult_nbr = endo_nbr-instr_nbr;
% parameters for expanded model
endo_nbr1 = 2*endo_nbr-instr_nbr+exo_nbr;
max_lead1 = max_lead + max_lag;
max_lag1 = max_lead1;
max_leadlag1 = max_lead1;
% adding new variables names
endo_names1 = endo_names;
% adding shocks to endogenous variables
endo_names1 = strvcat(endo_names1, exo_names);
% adding multipliers names
for i=1:mult_nbr;
endo_names1 = strvcat(endo_names1,['mult_' int2str(i)]);
end
% expanding matrix of lead/lag incidence
%
% multipliers lead/lag incidence
i_mult = [];
for i=1:leadlag_nbr
i_mult = [any(fJ(:,nonzeros(i_leadlag(i,:))) ~= 0,2)' ; i_mult];
end
% putting it all together:
% original variables, exogenous variables made endogenous, multipliers
%
% number of original dynamic variables
n_dyn = nnz(i_leadlag);
% numbering columns of dynamic multipliers to be put in the last columns
% of the new Jacobian
i_leadlag1 = [cumsum(i_leadlag(1:max_lag,:),1); ...
repmat(i_leadlag(max_lag+1,:),leadlag_nbr,1); ...
flipud(cumsum(flipud(i_leadlag(max_lag+2:end,:)),1))];
i_leadlag1 = i_leadlag1';
k = find(i_leadlag1 > 0);
n = length(k);
i_leadlag1(k) = 1:n;
i_leadlag1 = i_leadlag1';
i_mult = i_mult';
k = find(i_mult > 0);
i_mult(k) = n+leadlag_nbr*exo_nbr+(1:length(k));
i_mult = i_mult';
i_leadlag1 = [ i_leadlag1 ...
[zeros(max_lag,exo_nbr);...
reshape(n+(1:leadlag_nbr*exo_nbr),exo_nbr,leadlag_nbr)'; ...
zeros(max_lead,exo_nbr)] ...
[zeros(max_lag,mult_nbr);...
i_mult;...
zeros(max_lead,mult_nbr)]];
i_leadlag1 = i_leadlag1';
k = find(i_leadlag1 > 0);
n = length(k);
i_leadlag1(k) = 1:n;
i_leadlag1 = i_leadlag1';
% building Jacobian of expanded model
jacobian = zeros(endo_nbr+mult_nbr,nnz(i_leadlag1)+exo_nbr);
% derivatives of f.o.c. w.r. to endogenous variables
% to be rearranged further down
lbarfH = lbar'*fH;
% indices of Hessian columns
n1 = nnz(i_leadlag)+exo_nbr;
iH = reshape(1:n1^2,n1,n1);
J = zeros(endo_nbr1,nnz(i_leadlag1)+exo_nbr);
% second order derivatives of objective function
J(1:endo_nbr,i_leadlag1(max_leadlag1+1,1:endo_nbr)) = Uyy;
% loop on lead/lags in expanded model
for i=1:2*max_leadlag1 + 1
% index of variables at the current lag in expanded model
kc = find(i_leadlag1(i,i_endo_nbr) > 0);
t1 = max(1,i-max_leadlag1);
t2 = min(i,max_leadlag1+1);
% loop on lead/lag blocks of relevant 1st order derivatives
for j = t1:t2
% derivatives w.r. endogenous variables
ic = find(i_leadlag(i-j+1,:) > 0 );
kc1 = i_leadlag(i-j+1,ic);
[junk,ic1,ic2] = intersect(ic,kc);
kc2 = i_leadlag1(i,kc(ic2));
ir = find(i_leadlag(max_leadlag1+2-j,:) > 0 );
kr1 = i_leadlag(max_leadlag1+2-j,ir);
J(ir,kc2) = J(ir,kc2) + beta^(j-max_lead-1)...
*reshape(lbarfH(iH(kr1,kc1)),length(kr1),length(kc1));
end
end
% derivatives w.r. aux. variables for lead/lag exogenous shocks
for i=1:leadlag_nbr
kc = i_leadlag1(max_lag+i,endo_nbr+(1:exo_nbr));
ir = find(i_leadlag(leadlag_nbr+1-i,:) > 0);
kr1 = i_leadlag(leadlag_nbr+1-i,ir);
J(ir,kc) = beta^(i-max_lead-1)...
*reshape(lbarfH(iH(kr1,n_dyn+(1:exo_nbr))),length(kr1), ...
exo_nbr);
end
% derivatives w.r. Lagrange multipliers
for i=1:leadlag_nbr
ic1 = find(i_leadlag(leadlag_nbr+1-i,:) > 0);
kc1 = i_leadlag(leadlag_nbr+1-i,ic1);
ic2 = find(i_leadlag1(max_lag+i,endo_nbr+exo_nbr+(1:mult_nbr)) > 0);
kc2 = i_leadlag1(max_lag+i,endo_nbr+exo_nbr+ic2);
J(ic1,kc2) = beta^(i-max_lead-1)*fJ(ic2,kc1)';
end
% Jacobian of original equations
%
% w.r. endogenous variables
ir = endo_nbr+(1:endo_nbr-instr_nbr);
for i=1:leadlag_nbr
ic1 = find(i_leadlag(i,:) > 0);
kc1 = i_leadlag(i,ic1);
ic2 = find(i_leadlag1(max_lead+i,:) > 0);
kc2 = i_leadlag1(max_lead+i,ic2);
[junk,junk,ic3] = intersect(ic1,ic2);
J(ir,kc2(ic3)) = fJ(:,kc1);
end
% w.r. exogenous variables
J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = fJ(:,nnz(i_leadlag)+(1:exo_nbr));
% auxiliary variable for exogenous shocks
ir = 2*endo_nbr-instr_nbr+(1:exo_nbr);
kc = i_leadlag1(leadlag_nbr,endo_nbr+(1:exo_nbr));
J(ir,kc) = eye(exo_nbr);
J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = -eye(exo_nbr);
% eliminating empty columns
% getting indices of nonzero entries
m = find(i_leadlag1');
n1 = max_lag1*endo_nbr1+1;
n2 = n1+endo_nbr-1;
n = length(m);
k = 1:size(J,2);
for i=1:n
if sum(abs(J(:,i))) < 1e-8
if m(i) < n1 | m(i) > n2
k(i) = 0;
m(i) = 0;
end
end
end
J = J(:,nonzeros(k));
i_leadlag1 = zeros(size(i_leadlag1))';
i_leadlag1(nonzeros(m)) = 1:nnz(m);
i_leadlag1 = i_leadlag1';
% setting expanded model parameters
% storing original values
M_.endo_nbr = endo_nbr1;
% Consider that there is no auxiliary variable, because otherwise it
% interacts badly with the auxiliary variables from the preprocessor.
M_.orig_endo_nbr = endo_nbr1;
M_.aux_vars = [];
M_.endo_names = endo_names1;
M_.lead_lag_incidence = i_leadlag1;
M_.maximum_lead = max_lead1;
M_.maximum_endo_lead = max_lead1;
M_.maximum_lag = max_lag1;
M_.maximum_endo_lag = max_lag1;
M_.orig_model = orig_model;

View File

@ -1,138 +1,137 @@
function [resids, rJ,mult] = dyn_ramsey_static_(x,M_,options_,oo_,it_)
% function [resids, rJ,mult] = dyn_ramsey_static_(x)
% Computes the static first order conditions for optimal policy
%
% INPUTS
% x: vector of endogenous variables
%
% OUTPUTS
% resids: residuals of non linear equations
% rJ: Jacobian
% mult: Lagrangian multipliers
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2007 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/>.
% recovering usefull fields
endo_nbr = M_.endo_nbr;
exo_nbr = M_.exo_nbr;
fname = M_.fname;
% inst_nbr = M_.inst_nbr;
% i_endo_no_inst = M_.endogenous_variables_without_instruments;
max_lead = M_.maximum_lead;
max_lag = M_.maximum_lag;
beta = options_.planner_discount;
% indices of all endogenous variables
i_endo = [1:endo_nbr]';
% indices of endogenous variable except instruments
% i_inst = M_.instruments;
% lead_lag incidence matrix for endogenous variables
i_lag = M_.lead_lag_incidence;
if options_.steadystate_flag
k_inst = [];
instruments = options_.instruments;
for i = 1:size(instruments,1)
k_inst = [k_inst; strmatch(options_.instruments(i,:), ...
M_.endo_names,'exact')];
end
oo_.steady_state(k_inst) = x;
[x,check] = feval([M_.fname '_steadystate'],...
oo_.steady_state,...
[oo_.exo_steady_state; ...
oo_.exo_det_steady_state]);
if size(x,1) < M_.endo_nbr
if length(M_.aux_vars) > 0
x = add_auxiliary_variables_to_steadystate(x,M_.aux_vars,...
M_.fname,...
oo_.exo_steady_state,...
oo_.exo_det_steady_state,...
M_.params);
else
error([M_.fname '_steadystate.m doesn''t match the model']);
end
end
end
% value and Jacobian of objective function
ex = zeros(1,M_.exo_nbr);
[U,Uy,Uyy] = feval([fname '_objective_static'],x(i_endo),ex, M_.params);
Uy = Uy';
Uyy = reshape(Uyy,endo_nbr,endo_nbr);
y = repmat(x(i_endo),1,max_lag+max_lead+1);
% value and Jacobian of dynamic function
k = find(i_lag');
it_ = 1;
% [f,fJ,fH] = feval([fname '_dynamic'],y(k),ex);
[f,fJ] = feval([fname '_dynamic'],y(k),[oo_.exo_simul oo_.exo_det_simul], M_.params, it_);
% indices of Lagrange multipliers
inst_nbr = endo_nbr - size(f,1);
i_mult = [endo_nbr+1:2*endo_nbr-inst_nbr]';
% derivatives of Lagrangian with respect to endogenous variables
% res1 = Uy;
A = zeros(endo_nbr,endo_nbr-inst_nbr);
for i=1:max_lag+max_lead+1
% select variables present in the model at a given lag
[junk,k1,k2] = find(i_lag(i,:));
% res1(k1) = res1(k1) + beta^(max_lag-i+1)*fJ(:,k2)'*x(i_mult);
A(k1,:) = A(k1,:) + beta^(max_lag-i+1)*fJ(:,k2)';
end
% i_inst = var_index(options_.olr_inst);
% k = setdiff(1:size(A,1),i_inst);
% mult = -A(k,:)\Uy(k);
mult = -A\Uy;
% resids = [f; Uy(i_inst)+A(i_inst,:)*mult];
resids1 = Uy+A*mult;
% resids = [f; sqrt(resids1'*resids1/endo_nbr)];
[q,r,e] = qr([A Uy]');
if options_.steadystate_flag
resids = [r(end,(endo_nbr-inst_nbr+1:end))'];
else
resids = [f; r(end,(endo_nbr-inst_nbr+1:end))'];
end
rJ = [];
return;
% Jacobian of first order conditions
n = nnz(i_lag)+exo_nbr;
iH = reshape(1:n^2,n,n);
rJ = zeros(2*endo_nbr-inst_nbr,2*endo_nbr-inst_nbr);
rJ(i_endo,i_endo) = Uyy;
for i=1:max_lag+max_lead+1
% select variables present in the model at a given lag
[junk,k1,k2] = find(i_lag(i,:));
k3 = length(k2);
rJ(k1,k1) = rJ(k1,k1) + beta^(max_lag-i+1)*reshape(fH(:,iH(k2,k2))'*x(i_mult),k3,k3);
rJ(k1,i_mult) = rJ(k1,i_mult) + beta^(max_lag-1+1)*fJ(:,k2)';
rJ(i_mult,k1) = rJ(i_mult,k1) + fJ(:,k2);
end
% rJ = 1e-3*rJ;
% rJ(209,210) = rJ(209,210)+1-1e-3;
function [resids, rJ,mult] = dyn_ramsey_static_(x,M_,options_,oo_,it_)
% function [resids, rJ,mult] = dyn_ramsey_static_(x)
% Computes the static first order conditions for optimal policy
%
% INPUTS
% x: vector of endogenous variables
%
% OUTPUTS
% resids: residuals of non linear equations
% rJ: Jacobian
% mult: Lagrangian multipliers
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2007 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/>.
% recovering usefull fields
endo_nbr = M_.endo_nbr;
exo_nbr = M_.exo_nbr;
fname = M_.fname;
% inst_nbr = M_.inst_nbr;
% i_endo_no_inst = M_.endogenous_variables_without_instruments;
max_lead = M_.maximum_lead;
max_lag = M_.maximum_lag;
beta = options_.planner_discount;
% indices of all endogenous variables
i_endo = [1:endo_nbr]';
% indices of endogenous variable except instruments
% i_inst = M_.instruments;
% lead_lag incidence matrix for endogenous variables
i_lag = M_.lead_lag_incidence;
if options_.steadystate_flag
k_inst = [];
instruments = options_.instruments;
for i = 1:size(instruments,1)
k_inst = [k_inst; strmatch(options_.instruments(i,:), ...
M_.endo_names,'exact')];
end
oo_.steady_state(k_inst) = x;
[x,check] = feval([M_.fname '_steadystate'],...
oo_.steady_state,...
[oo_.exo_steady_state; ...
oo_.exo_det_steady_state]);
if size(x,1) < M_.endo_nbr
if length(M_.aux_vars) > 0
x = add_auxiliary_variables_to_steadystate(x,M_.aux_vars,...
M_.fname,...
oo_.exo_steady_state,...
oo_.exo_det_steady_state,...
M_.params);
else
error([M_.fname '_steadystate.m doesn''t match the model']);
end
end
end
% value and Jacobian of objective function
ex = zeros(1,M_.exo_nbr);
[U,Uy,Uyy] = feval([fname '_objective_static'],x(i_endo),ex, M_.params);
Uy = Uy';
Uyy = reshape(Uyy,endo_nbr,endo_nbr);
y = repmat(x(i_endo),1,max_lag+max_lead+1);
% value and Jacobian of dynamic function
k = find(i_lag');
it_ = 1;
% [f,fJ,fH] = feval([fname '_dynamic'],y(k),ex);
[f,fJ] = feval([fname '_dynamic'],y(k),[oo_.exo_simul oo_.exo_det_simul], M_.params, it_);
% indices of Lagrange multipliers
inst_nbr = endo_nbr - size(f,1);
i_mult = [endo_nbr+1:2*endo_nbr-inst_nbr]';
% derivatives of Lagrangian with respect to endogenous variables
% res1 = Uy;
A = zeros(endo_nbr,endo_nbr-inst_nbr);
for i=1:max_lag+max_lead+1
% select variables present in the model at a given lag
[junk,k1,k2] = find(i_lag(i,:));
% res1(k1) = res1(k1) + beta^(max_lag-i+1)*fJ(:,k2)'*x(i_mult);
A(k1,:) = A(k1,:) + beta^(max_lag-i+1)*fJ(:,k2)';
end
% i_inst = var_index(options_.olr_inst);
% k = setdiff(1:size(A,1),i_inst);
% mult = -A(k,:)\Uy(k);
mult = -A\Uy;
% resids = [f; Uy(i_inst)+A(i_inst,:)*mult];
resids1 = Uy+A*mult;
% resids = [f; sqrt(resids1'*resids1/endo_nbr)];
[q,r,e] = qr([A Uy]');
if options_.steadystate_flag
resids = [r(end,(endo_nbr-inst_nbr+1:end))'];
else
resids = [f; r(end,(endo_nbr-inst_nbr+1:end))'];
end
rJ = [];
return;
% Jacobian of first order conditions
n = nnz(i_lag)+exo_nbr;
iH = reshape(1:n^2,n,n);
rJ = zeros(2*endo_nbr-inst_nbr,2*endo_nbr-inst_nbr);
rJ(i_endo,i_endo) = Uyy;
for i=1:max_lag+max_lead+1
% select variables present in the model at a given lag
[junk,k1,k2] = find(i_lag(i,:));
k3 = length(k2);
rJ(k1,k1) = rJ(k1,k1) + beta^(max_lag-i+1)*reshape(fH(:,iH(k2,k2))'*x(i_mult),k3,k3);
rJ(k1,i_mult) = rJ(k1,i_mult) + beta^(max_lag-1+1)*fJ(:,k2)';
rJ(i_mult,k1) = rJ(i_mult,k1) + fJ(:,k2);
end
% rJ = 1e-3*rJ;
% rJ(209,210) = rJ(209,210)+1-1e-3;

View File

@ -59,13 +59,13 @@ end
warning_config()
if exist('OCTAVE_VERSION')
if octave_ver_less_than('3.0.0')
warning('This version of Dynare has only been tested on Octave 3.0.0 and above. Since your Octave version is older than that, Dynare may fail to run, or give unexpected results. Consider upgrading your Octave installation.');
end
if octave_ver_less_than('3.0.0')
warning('This version of Dynare has only been tested on Octave 3.0.0 and above. Since your Octave version is older than that, Dynare may fail to run, or give unexpected results. Consider upgrading your Octave installation.');
end
else
if matlab_ver_less_than('6.5')
warning('This version of Dynare has only been tested on Matlab 6.5 and above. Since your Matlab version is older than that, Dynare may fail to run, or give unexpected results. Consider upgrading your Matlab installation (or switch to Octave).');
end
if matlab_ver_less_than('6.5')
warning('This version of Dynare has only been tested on Matlab 6.5 and above. Since your Matlab version is older than that, Dynare may fail to run, or give unexpected results. Consider upgrading your Matlab installation (or switch to Octave).');
end
end
% disable output paging (it is on by default on Octave)
@ -73,44 +73,44 @@ more off
% sets default format for save() command
if exist('OCTAVE_VERSION')
default_save_options('-mat')
default_save_options('-mat')
end
% detect if MEX files are present; if not, use alternative M-files
dynareroot = dynare_config;
if nargin < 1
error('DYNARE: you must provide the name of the MOD file in argument')
error('DYNARE: you must provide the name of the MOD file in argument')
end
if ~ischar(fname)
error('DYNARE: argument of dynare must be a text string')
error('DYNARE: argument of dynare must be a text string')
end
% Testing if file have extension
% If no extension default .mod is added
if isempty(strfind(fname,'.'))
fname1 = [fname '.dyn'];
d = dir(fname1);
if length(d) == 0
fname1 = [fname '.mod'];
end
fname = fname1;
% Checking file extension
fname1 = [fname '.dyn'];
d = dir(fname1);
if length(d) == 0
fname1 = [fname '.mod'];
end
fname = fname1;
% Checking file extension
else
if ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.MOD') ...
&& ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.DYN')
error('DYNARE: argument must be a filename with .mod or .dyn extension')
end;
if ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.MOD') ...
&& ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.DYN')
error('DYNARE: argument must be a filename with .mod or .dyn extension')
end;
end;
d = dir(fname);
if length(d) == 0
error(['DYNARE: can''t open ' fname])
error(['DYNARE: can''t open ' fname])
end
command = ['"' dynareroot 'dynare_m" ' fname] ;
for i=2:nargin
command = [command ' ' varargin{i-1}];
command = [command ' ' varargin{i-1}];
end
% Workaround for bug in Octave >= 3.2
@ -122,11 +122,11 @@ end
[status, result] = system(command);
disp(result)
if status
% Should not use "error(result)" since message will be truncated if too long
error('DYNARE: preprocessing failed')
% Should not use "error(result)" since message will be truncated if too long
error('DYNARE: preprocessing failed')
end
if ~ isempty(find(abs(fname) == 46))
fname = fname(:,1:find(abs(fname) == 46)-1) ;
fname = fname(:,1:find(abs(fname) == 46)-1) ;
end
evalin('base',fname) ;

View File

@ -189,29 +189,29 @@ end
% Test if bytecode DLL is present
if exist('bytecode') == 3
if ~multithread_flag
message = '[mex] ';
else
message = [ '[mex][multithread version, ' int2str(multithread_flag+1) ' threads are used] ' ];
end
if ~multithread_flag
message = '[mex] ';
else
message = [ '[mex][multithread version, ' int2str(multithread_flag+1) ' threads are used] ' ];
end
else
message = '[no] ';
message = '[no] ';
end
disp([ message 'Bytecode evaluation.' ])
% Test if k-order perturbation DLL is present
if exist('k_order_perturbation') == 3
message = '[mex] ';
message = '[mex] ';
else
message = '[no] ';
message = '[no] ';
end
disp([ message 'k-order perturbation solver.' ])
% Test if dynare_simul_ DLL is present
if exist('dynare_simul_') == 3
message = '[mex] ';
message = '[mex] ';
else
message = '[no] ';
message = '[no] ';
end
disp([ message 'k-order solution simulation.' ])

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More