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,rts]=dynAIMsolver1(jacobia_,M_,dr)
% function [dr,aimcode]=dynAIMsolver1(jacobia_,M_,dr) % function [dr,aimcode]=dynAIMsolver1(jacobia_,M_,dr)
% Maps Dynare jacobia to AIM 1st order model solver designed and developed by Gary ANderson % Maps Dynare jacobia to AIM 1st order model solver designed and developed by Gary ANderson
% and derives the solution for gy=dr.hgx and gu=dr.hgu from the AIM outputs % and derives the solution for gy=dr.hgx and gu=dr.hgu from the AIM outputs
% AIM System is given as a sum: % AIM System is given as a sum:
% i.e. for i=-$...+& SUM(Hi*xt+i)= £*zt, t = 0, . . . ,? % i.e. for i=-$...+& SUM(Hi*xt+i)= £*zt, t = 0, . . . ,?
% and its input as single array of matrices: [H-$... Hi ... H+&] % and its input as single array of matrices: [H-$... Hi ... H+&]
% and its solution as xt=SUM( Bi*xt+i) + @*£*zt for i=-$...-1 % 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) % with the output in form bb=[B-$... Bi ... B-1] and @=inv(Ho+H1*B-1)
% Dynare jacobian = [fy'-$... fy'i ... fy'+& fu'] % Dynare jacobian = [fy'-$... fy'i ... fy'+& fu']
% where [fy'-$... fy'i ... fy'+&]=[H-$... Hi ... H+&] and fu'= £ % where [fy'-$... fy'i ... fy'+&]=[H-$... Hi ... H+&] and fu'= £
% %
% INPUTS % INPUTS
% jacobia_ [matrix] 1st order derivative of the model % jacobia_ [matrix] 1st order derivative of the model
% dr [matlab structure] Decision rules for stochastic simulations. % dr [matlab structure] Decision rules for stochastic simulations.
% M_ [matlab structure] Definition of the model. % M_ [matlab structure] Definition of the model.
% %
% OUTPUTS % OUTPUTS
% dr [matlab structure] Decision rules for stochastic simulations. % dr [matlab structure] Decision rules for stochastic simulations.
% aimcode [integer] 1: the model defines variables uniquely % aimcode [integer] 1: the model defines variables uniquely
% aimcode is resolved in AIMerr as % aimcode is resolved in AIMerr as
% (c==1) e='Aim: unique solution.'; % (c==1) e='Aim: unique solution.';
% (c==2) e='Aim: roots not correctly computed by real_schur.'; % (c==2) e='Aim: roots not correctly computed by real_schur.';
% (c==3) e='Aim: too many big roots.'; % (c==3) e='Aim: too many big roots.';
% (c==35) e='Aim: too many big roots, and q(:,right) is singular.'; % (c==35) e='Aim: too many big roots, and q(:,right) is singular.';
% (c==4) e='Aim: too few big roots.'; % (c==4) e='Aim: too few big roots.';
% (c==45) e='Aim: too few big roots, and q(:,right) is singular.'; % (c==45) e='Aim: too few big roots, and q(:,right) is singular.';
% (c==5) e='Aim: q(:,right) is singular.'; % (c==5) e='Aim: q(:,right) is singular.';
% (c==61) e='Aim: too many exact shiftrights.'; % (c==61) e='Aim: too many exact shiftrights.';
% (c==62) e='Aim: too many numeric shiftrights.'; % (c==62) e='Aim: too many numeric shiftrights.';
% else e='Aimerr: return code not properly specified'; % else e='Aimerr: return code not properly specified';
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% Dynare use: % Dynare use:
% 1) the lognormal block in DR1 is being invoked for some models and changing % 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 of ghx and ghy. We need to return the AIM output
% values before that block and run the block with the current returned values % values before that block and run the block with the current returned values
% of gy (i.e. dr.ghx) and gu (dr.ghu) if it is needed even when the AIM is used % of gy (i.e. dr.ghx) and gu (dr.ghu) if it is needed even when the AIM is used
% (it does not depend on mjdgges output). % (it does not depend on mjdgges output).
% %
% 2) passing in aa={Q'|1}*jacobia_ can produce ~ one order closer % 2) passing in aa={Q'|1}*jacobia_ can produce ~ one order closer
% results to the Dynare solutiion then when if plain jacobia_ is passed, % 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. % i.e. diff < e-14 for aa and diff < *e-13 for jacobia_ if Q' is used.
% %
% GP July 2008 % GP July 2008
% Copyright (C) 2008 Dynare Team % Copyright (C) 2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
aimcode=-1; aimcode=-1;
neq= size(jacobia_,1); % no of equations neq= size(jacobia_,1); % no of equations
lags=M_.maximum_endo_lag; % no of lags and leads lags=M_.maximum_endo_lag; % no of lags and leads
leads=M_.maximum_endo_lead; leads=M_.maximum_endo_lead;
klen=(leads+lags+1); % total lenght klen=(leads+lags+1); % total lenght
theAIM_H=zeros(neq, neq*klen); % alloc space theAIM_H=zeros(neq, neq*klen); % alloc space
lli=M_.lead_lag_incidence'; lli=M_.lead_lag_incidence';
% "sparse" the compact jacobia into AIM H aray of matrices % "sparse" the compact jacobia into AIM H aray of matrices
% without exogenous shoc % without exogenous shoc
theAIM_H(:,find(lli(:)))=jacobia_(:,nonzeros(lli(:))); theAIM_H(:,find(lli(:)))=jacobia_(:,nonzeros(lli(:)));
condn = 1.e-10;%SPAmalg uses this in zero tests condn = 1.e-10;%SPAmalg uses this in zero tests
uprbnd = 1 + 1.e-6;%allow unit roots uprbnd = 1 + 1.e-6;%allow unit roots
% forward only models - AIM must have at least 1 lead and 1 lag. % forward only models - AIM must have at least 1 lead and 1 lag.
if lags ==0 if lags ==0
theAIM_H =[zeros(neq) theAIM_H]; theAIM_H =[zeros(neq) theAIM_H];
lags=1; lags=1;
klen=(leads+lags+1); klen=(leads+lags+1);
end end
% backward looking only models % backward looking only models
if leads ==0 if leads ==0
theAIM_H =[theAIM_H zeros(neq)]; theAIM_H =[theAIM_H zeros(neq)];
leads=1; leads=1;
klen=(leads+lags+1); klen=(leads+lags+1);
end end
%disp('gensysToAMA:running ama'); %disp('gensysToAMA:running ama');
try % try to run AIM try % try to run AIM
[bb,rts,ia,nexact,nnumeric,lgroots,aimcode] =... [bb,rts,ia,nexact,nnumeric,lgroots,aimcode] =...
SPAmalg(theAIM_H,neq, lags,leads,condn,uprbnd); SPAmalg(theAIM_H,neq, lags,leads,condn,uprbnd);
catch catch
err = lasterror; err = lasterror;
disp(['Dynare AIM Solver error:' sprintf('%s; ID:%s',err.message, err.identifier)]); disp(['Dynare AIM Solver error:' sprintf('%s; ID:%s',err.message, err.identifier)]);
rethrow(lasterror); rethrow(lasterror);
end end
if aimcode==1 %if OK if aimcode==1 %if OK
col_order=[]; col_order=[];
for i =1:lags for i =1:lags
col_order=[((i-1)*neq)+dr.order_var' col_order]; col_order=[((i-1)*neq)+dr.order_var' col_order];
end end
bb_ord= bb(dr.order_var,col_order); % derive ordered gy bb_ord= bb(dr.order_var,col_order); % derive ordered gy
% variables are present in the state space at the lag at which they % 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 % appear and at all smaller lags. The are ordered from smaller to
% higher lag (reversed order of M_.lead_lag_incidence rows for lagged % higher lag (reversed order of M_.lead_lag_incidence rows for lagged
% variables) % variables)
i_lagged_vars = flipud(cumsum(M_.lead_lag_incidence(1:M_.maximum_lag,dr.order_var),1))'; 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 dr.ghx= bb_ord(:,find(i_lagged_vars(:))); % get columns reported in
% Dynare solution % Dynare solution
if M_.exo_nbr % if there are exogenous shocks then derive gu for the shocks: if M_.exo_nbr % if there are exogenous shocks then derive gu for the shocks:
% get H0 and H+1=HM % get H0 and H+1=HM
% theH0= theAIM_H (:,M_.maximum_endo_lag*neq+1: (M_.maximum_endo_lag+1)*neq); % theH0= theAIM_H (:,M_.maximum_endo_lag*neq+1: (M_.maximum_endo_lag+1)*neq);
%theH0= theAIM_H (:,lags*neq+1: (lags+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 (:,(M_.maximum_endo_lag+1)*neq+1: (M_.maximum_endo_lag+2)*neq);
%theHP= theAIM_H (:,(lags+1)*neq+1: (lags+2)*neq); %theHP= theAIM_H (:,(lags+1)*neq+1: (lags+2)*neq);
theAIM_Psi= - jacobia_(:, size(nonzeros(lli(:)))+1:end);% theAIM_Psi= - jacobia_(:, size(nonzeros(lli(:)))+1:end);%
%? = inv(H0 + H1B1) %? = inv(H0 + H1B1)
%phi= (theH0+theHP*sparse(bb(:,(lags-1)*neq+1:end)))\eye( neq); %phi= (theH0+theHP*sparse(bb(:,(lags-1)*neq+1:end)))\eye( neq);
%AIM_ghu=phi*theAIM_Psi; %AIM_ghu=phi*theAIM_Psi;
%dr.ghu =AIM_ghu(dr.order_var,:); % order gu %dr.ghu =AIM_ghu(dr.order_var,:); % order gu
% Using AIM SPObstruct % Using AIM SPObstruct
scof = SPObstruct(theAIM_H,bb,neq,lags,leads); scof = SPObstruct(theAIM_H,bb,neq,lags,leads);
scof1= scof(:,(lags)*neq+1:end); scof1= scof(:,(lags)*neq+1:end);
scof1= scof1(:,dr.order_var); scof1= scof1(:,dr.order_var);
dr.ghu =scof1\theAIM_Psi; dr.ghu =scof1\theAIM_Psi;
else else
dr.ghu = []; dr.ghu = [];
end end
else else
err=SPAimerr(aimcode); err=SPAimerr(aimcode);
%warning('Error in AIM: aimcode=%d, erro=%s', aimcode, err);; %warning('Error in AIM: aimcode=%d, erro=%s', aimcode, err);;
disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]); disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]);
if aimcode < 1 || aimcode > 5 % too big exception, use mjdgges if aimcode < 1 || aimcode > 5 % too big exception, use mjdgges
error('Error in AIM: aimcode=%d ; %s', aimcode, err); error('Error in AIM: aimcode=%d ; %s', aimcode, err);
end end
% if aimcode > 5 % if aimcode > 5
% disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]); % disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]);
% aimcode=5; % aimcode=5;
% end % end
end end

View File

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

View File

@ -1,44 +1,44 @@
function DirectoryName = CheckPath(type) function DirectoryName = CheckPath(type)
% Creates the subfolder "./M_.dname/type" if it does not exist yet. % Creates the subfolder "./M_.dname/type" if it does not exist yet.
% %
% INPUTS % INPUTS
% type [string] Name of the subfolder. % type [string] Name of the subfolder.
% %
% OUTPUTS % OUTPUTS
% none. % none.
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2005-2009 Dynare Team % Copyright (C) 2005-2009 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ global M_
DirectoryName = [ M_.dname '/' type ]; DirectoryName = [ M_.dname '/' type ];
if ~isdir(M_.dname) if ~isdir(M_.dname)
% Make sure there isn't a file with the same name, see trac ticket #47 % Make sure there isn't a file with the same name, see trac ticket #47
delete(M_.dname) delete(M_.dname)
mkdir('.', M_.dname); mkdir('.', M_.dname);
end end
if ~isdir(DirectoryName) if ~isdir(DirectoryName)
% Make sure there isn't a file with the same name, see trac ticket #47 % Make sure there isn't a file with the same name, see trac ticket #47
delete(DirectoryName) delete(DirectoryName)
mkdir('.',DirectoryName); mkdir('.',DirectoryName);
end 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,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) % 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 % Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix
% %
% INPUTS % INPUTS
% T: mm*mm matrix % T: mm*mm matrix
% R: mm*rr matrix % R: mm*rr matrix
% Q: rr*rr matrix % Q: rr*rr matrix
% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros % Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar1: mm*mm variance-covariance matrix with stationary variables % Pstar1: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector % Y: pp*1 vector
% trend % trend
% pp: number of observed variables % pp: number of observed variables
% mm: number of state variables % mm: number of state variables
% smpl: sample size % smpl: sample size
% mf: observed variables index in the state vector % mf: observed variables index in the state vector
% %
% OUTPUTS % OUTPUTS
% alphahat: smoothed state variables (a_{t|T}) % alphahat: smoothed state variables (a_{t|T})
% etahat: smoothed shocks % etahat: smoothed shocks
% atilde: matrix of updated variables (a_{t|t}) % atilde: matrix of updated variables (a_{t|t})
% aK: 3D array of k step ahead filtered state variables (a_{t+k|t}) % aK: 3D array of k step ahead filtered state variables (a_{t+k|t})
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space % See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 Dynare Team % Copyright (C) 2004-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% modified by M. Ratto: % modified by M. Ratto:
% new output argument aK (1-step to k-step predictions) % new output argument aK (1-step to k-step predictions)
% new options_.nk: the max step ahed prediction in aK (default is 4) % new options_.nk: the max step ahed prediction in aK (default is 4)
% new crit1 value for rank of Pinf % new crit1 value for rank of Pinf
% it is assured that P is symmetric % it is assured that P is symmetric
global options_ global options_
nk = options_.nk; nk = options_.nk;
spinf = size(Pinf1); spinf = size(Pinf1);
spstar = size(Pstar1); spstar = size(Pstar1);
v = zeros(pp,smpl); v = zeros(pp,smpl);
a = zeros(mm,smpl+1); a = zeros(mm,smpl+1);
atilde = zeros(mm,smpl); atilde = zeros(mm,smpl);
aK = zeros(nk,mm,smpl+1); aK = zeros(nk,mm,smpl+1);
iF = zeros(pp,pp,smpl); iF = zeros(pp,pp,smpl);
Fstar = zeros(pp,pp,smpl); Fstar = zeros(pp,pp,smpl);
iFinf = zeros(pp,pp,smpl); iFinf = zeros(pp,pp,smpl);
K = zeros(mm,pp,smpl); K = zeros(mm,pp,smpl);
L = zeros(mm,mm,smpl); L = zeros(mm,mm,smpl);
Linf = zeros(mm,mm,smpl); Linf = zeros(mm,mm,smpl);
Kstar = zeros(mm,pp,smpl); Kstar = zeros(mm,pp,smpl);
P = zeros(mm,mm,smpl+1); P = zeros(mm,mm,smpl+1);
Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
crit = options_.kalman_tol; crit = options_.kalman_tol;
crit1 = 1.e-8; crit1 = 1.e-8;
steady = smpl; steady = smpl;
rr = size(Q,1); rr = size(Q,1);
QQ = R*Q*transpose(R); QQ = R*Q*transpose(R);
QRt = Q*transpose(R); QRt = Q*transpose(R);
alphahat = zeros(mm,smpl); alphahat = zeros(mm,smpl);
etahat = zeros(rr,smpl); etahat = zeros(rr,smpl);
r = zeros(mm,smpl+1); r = zeros(mm,smpl+1);
Z = zeros(pp,mm); Z = zeros(pp,mm);
for i=1:pp; for i=1:pp;
Z(i,mf(i)) = 1; Z(i,mf(i)) = 1;
end end
t = 0; t = 0;
while rank(Pinf(:,:,t+1),crit1) & t<smpl while rank(Pinf(:,:,t+1),crit1) & t<smpl
t = t+1; t = t+1;
v(:,t) = Y(:,t) - a(mf,t) - trend(:,t); v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
if rcond(Pinf(mf,mf,t)) < crit if rcond(Pinf(mf,mf,t)) < crit
return return
end end
iFinf(:,:,t) = inv(Pinf(mf,mf,t)); iFinf(:,:,t) = inv(Pinf(mf,mf,t));
PZI = Pinf(:,mf,t)*iFinf(:,:,t); PZI = Pinf(:,mf,t)*iFinf(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t); atilde(:,t) = a(:,t) + PZI*v(:,t);
Kinf(:,:,t) = T*PZI; Kinf(:,:,t) = T*PZI;
a(:,t+1) = T*atilde(:,t); a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1); aK(1,:,t+1) = a(:,t+1);
for jnk=2:nk, for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end end
Linf(:,:,t) = T - Kinf(:,:,t)*Z; Linf(:,:,t) = T - Kinf(:,:,t)*Z;
Fstar(:,:,t) = Pstar(mf,mf,t); Fstar(:,:,t) = Pstar(mf,mf,t);
Kstar(:,:,t) = (T*Pstar(:,mf,t)-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,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; 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)); Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T)-T*Pinf(:,mf,t)*transpose(Kinf(:,:,t));
end end
d = t; d = t;
P(:,:,d+1) = Pstar(:,:,d+1); P(:,:,d+1) = Pstar(:,:,d+1);
iFinf = iFinf(:,:,1:d); iFinf = iFinf(:,:,1:d);
Linf = Linf(:,:,1:d); Linf = Linf(:,:,1:d);
Fstar = Fstar(:,:,1:d); Fstar = Fstar(:,:,1:d);
Kstar = Kstar(:,:,1:d); Kstar = Kstar(:,:,1:d);
Pstar = Pstar(:,:,1:d); Pstar = Pstar(:,:,1:d);
Pinf = Pinf(:,:,1:d); Pinf = Pinf(:,:,1:d);
notsteady = 1; notsteady = 1;
while notsteady & t<smpl while notsteady & t<smpl
t = t+1; t = t+1;
v(:,t) = Y(:,t) - a(mf,t) - trend(:,t); v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
if rcond(P(mf,mf,t)) < crit if rcond(P(mf,mf,t)) < crit
return return
end end
iF(:,:,t) = inv(P(mf,mf,t)); iF(:,:,t) = inv(P(mf,mf,t));
PZI = P(:,mf,t)*iF(:,:,t); PZI = P(:,mf,t)*iF(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t); atilde(:,t) = a(:,t) + PZI*v(:,t);
K(:,:,t) = T*PZI; K(:,:,t) = T*PZI;
L(:,:,t) = T-K(:,:,t)*Z; L(:,:,t) = T-K(:,:,t)*Z;
a(:,t+1) = T*atilde(:,t); a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1); aK(1,:,t+1) = a(:,t+1);
for jnk=2:nk, for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end end
P(:,:,t+1) = T*P(:,:,t)*transpose(T)-T*P(:,mf,t)*transpose(K(:,:,t)) + QQ; 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); notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end end
if t<smpl if t<smpl
PZI_s = PZI; PZI_s = PZI;
K_s = K(:,:,t); K_s = K(:,:,t);
iF_s = iF(:,:,t); iF_s = iF(:,:,t);
P_s = P(:,:,t+1); P_s = P(:,:,t+1);
t_steady = t+1; t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+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])); 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])); 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])); K = cat(3,K(:,:,1:t),repmat(T*P_s(:,mf)*iF_s,[1 1 smpl-t_steady+1]));
end end
while t<smpl while t<smpl
t=t+1; t=t+1;
v(:,t) = Y(:,t) - a(mf,t) - trend(:,t); v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t); atilde(:,t) = a(:,t) + PZI*v(:,t);
a(:,t+1) = T*a(:,t) + K_s*v(:,t); a(:,t+1) = T*a(:,t) + K_s*v(:,t);
aK(1,:,t+1) = a(:,t+1); aK(1,:,t+1) = a(:,t+1);
for jnk=2:nk, for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end end
end end
t = smpl+1; t = smpl+1;
while t>d+1 while t>d+1
t = t-1; t = t-1;
r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1); r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1);
alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t); etahat(:,t) = QRt*r(:,t);
end end
if d if d
r0 = zeros(mm,d+1); r0 = zeros(mm,d+1);
r0(:,d+1) = r(:,d+1); r0(:,d+1) = r(:,d+1);
r1 = zeros(mm,d+1); r1 = zeros(mm,d+1);
for t = d:-1:1 for t = d:-1:1
r0(:,t) = Linf(:,:,t)'*r0(:,t+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); 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); alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t);
etahat(:,t) = QRt*r0(:,t); etahat(:,t) = QRt*r0(:,t);
end end
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,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) % 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 % Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix
% %
% INPUTS % INPUTS
% T: mm*mm matrix % T: mm*mm matrix
% Z: pp*mm matrix % Z: pp*mm matrix
% R: mm*rr matrix % R: mm*rr matrix
% Q: rr*rr matrix % Q: rr*rr matrix
% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros % Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar1: mm*mm variance-covariance matrix with stationary variables % Pstar1: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector % Y: pp*1 vector
% pp: number of observed variables % pp: number of observed variables
% mm: number of state variables % mm: number of state variables
% smpl: sample size % smpl: sample size
% %
% OUTPUTS % OUTPUTS
% alphahat: smoothed variables (a_{t|T}) % alphahat: smoothed variables (a_{t|T})
% etahat: smoothed shocks % etahat: smoothed shocks
% atilde: matrix of updated variables (a_{t|t}) % atilde: matrix of updated variables (a_{t|t})
% aK: 3D array of k step ahead filtered state variables (a_{t+k|t) % aK: 3D array of k step ahead filtered state variables (a_{t+k|t)
% (meaningless for periods 1:d) % (meaningless for periods 1:d)
% P: 3D array of one-step ahead forecast error variance % P: 3D array of one-step ahead forecast error variance
% matrices % matrices
% PK: 4D array of k-step ahead forecast error variance % PK: 4D array of k-step ahead forecast error variance
% matrices (meaningless for periods 1:d) % matrices (meaningless for periods 1:d)
% d: number of periods where filter remains in diffuse part % d: number of periods where filter remains in diffuse part
% (should be equal to the order of integration of the model) % (should be equal to the order of integration of the model)
% decomp: decomposition of the effect of shocks on filtered values % decomp: decomposition of the effect of shocks on filtered values
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space % See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 Dynare Team % Copyright (C) 2004-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% modified by M. Ratto: % modified by M. Ratto:
% new output argument aK (1-step to k-step predictions) % new output argument aK (1-step to k-step predictions)
% new options_.nk: the max step ahed prediction in aK (default is 4) % new options_.nk: the max step ahed prediction in aK (default is 4)
% new crit1 value for rank of Pinf % new crit1 value for rank of Pinf
% it is assured that P is symmetric % it is assured that P is symmetric
global options_ global options_
d = 0; d = 0;
decomp = []; decomp = [];
nk = options_.nk; nk = options_.nk;
spinf = size(Pinf1); spinf = size(Pinf1);
spstar = size(Pstar1); spstar = size(Pstar1);
v = zeros(pp,smpl); v = zeros(pp,smpl);
a = zeros(mm,smpl+1); a = zeros(mm,smpl+1);
atilde = zeros(mm,smpl); atilde = zeros(mm,smpl);
aK = zeros(nk,mm,smpl+nk); aK = zeros(nk,mm,smpl+nk);
PK = zeros(nk,mm,mm,smpl+nk); PK = zeros(nk,mm,mm,smpl+nk);
iF = zeros(pp,pp,smpl); iF = zeros(pp,pp,smpl);
Fstar = zeros(pp,pp,smpl); Fstar = zeros(pp,pp,smpl);
iFinf = zeros(pp,pp,smpl); iFinf = zeros(pp,pp,smpl);
K = zeros(mm,pp,smpl); K = zeros(mm,pp,smpl);
L = zeros(mm,mm,smpl); L = zeros(mm,mm,smpl);
Linf = zeros(mm,mm,smpl); Linf = zeros(mm,mm,smpl);
Kstar = zeros(mm,pp,smpl); Kstar = zeros(mm,pp,smpl);
P = zeros(mm,mm,smpl+1); P = zeros(mm,mm,smpl+1);
Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
crit = options_.kalman_tol; crit = options_.kalman_tol;
crit1 = 1.e-8; crit1 = 1.e-8;
steady = smpl; steady = smpl;
rr = size(Q,1); rr = size(Q,1);
QQ = R*Q*transpose(R); QQ = R*Q*transpose(R);
QRt = Q*transpose(R); QRt = Q*transpose(R);
alphahat = zeros(mm,smpl); alphahat = zeros(mm,smpl);
etahat = zeros(rr,smpl); etahat = zeros(rr,smpl);
r = zeros(mm,smpl+1); r = zeros(mm,smpl+1);
t = 0; t = 0;
while rank(Pinf(:,:,t+1),crit1) & t<smpl while rank(Pinf(:,:,t+1),crit1) & t<smpl
t = t+1; t = t+1;
v(:,t)= Y(:,t) - Z*a(:,t); v(:,t)= Y(:,t) - Z*a(:,t);
F = Z*Pinf(:,:,t)*Z'; F = Z*Pinf(:,:,t)*Z';
if rcond(F) < crit if rcond(F) < crit
return return
end end
iFinf(:,:,t) = inv(F); iFinf(:,:,t) = inv(F);
PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t); PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t); atilde(:,t) = a(:,t) + PZI*v(:,t);
Kinf(:,:,t) = T*PZI; Kinf(:,:,t) = T*PZI;
a(:,t+1) = T*atilde(:,t); a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1); aK(1,:,t+1) = a(:,t+1);
% isn't a meaningless as long as we are in the diffuse part? MJ % isn't a meaningless as long as we are in the diffuse part? MJ
for jnk=2:nk, for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end end
Linf(:,:,t) = T - Kinf(:,:,t)*Z; Linf(:,:,t) = T - Kinf(:,:,t)*Z;
Fstar(:,:,t) = Z*Pstar(:,:,t)*Z'; Fstar(:,:,t) = Z*Pstar(:,:,t)*Z';
Kstar(:,:,t) = (T*Pstar(:,:,t)*Z'-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t); 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; 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)'; Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*Z'*Kinf(:,:,t)';
end end
d = t; d = t;
P(:,:,d+1) = Pstar(:,:,d+1); P(:,:,d+1) = Pstar(:,:,d+1);
iFinf = iFinf(:,:,1:d); iFinf = iFinf(:,:,1:d);
Linf = Linf(:,:,1:d); Linf = Linf(:,:,1:d);
Fstar = Fstar(:,:,1:d); Fstar = Fstar(:,:,1:d);
Kstar = Kstar(:,:,1:d); Kstar = Kstar(:,:,1:d);
Pstar = Pstar(:,:,1:d); Pstar = Pstar(:,:,1:d);
Pinf = Pinf(:,:,1:d); Pinf = Pinf(:,:,1:d);
notsteady = 1; notsteady = 1;
while notsteady & t<smpl while notsteady & t<smpl
t = t+1; t = t+1;
v(:,t) = Y(:,t) - Z*a(:,t); v(:,t) = Y(:,t) - Z*a(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
F = Z*P(:,:,t)*Z'; F = Z*P(:,:,t)*Z';
if rcond(F) < crit if rcond(F) < crit
return return
end end
iF(:,:,t) = inv(F); iF(:,:,t) = inv(F);
PZI = P(:,:,t)*Z'*iF(:,:,t); PZI = P(:,:,t)*Z'*iF(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t); atilde(:,t) = a(:,t) + PZI*v(:,t);
K(:,:,t) = T*PZI; K(:,:,t) = T*PZI;
L(:,:,t) = T-K(:,:,t)*Z; L(:,:,t) = T-K(:,:,t)*Z;
a(:,t+1) = T*atilde(:,t); a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t); Pf = P(:,:,t);
for jnk=1:nk, for jnk=1:nk,
Pf = T*Pf*T' + QQ; Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf; PK(jnk,:,:,t+jnk) = Pf;
end end
P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ; P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end end
if t<smpl if t<smpl
PZI_s = PZI; PZI_s = PZI;
K_s = K(:,:,t); K_s = K(:,:,t);
iF_s = iF(:,:,t); iF_s = iF(:,:,t);
P_s = P(:,:,t+1); P_s = P(:,:,t+1);
P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); 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])); 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])); 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])); K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t]));
end end
while t<smpl while t<smpl
t=t+1; t=t+1;
v(:,t) = Y(:,t) - Z*a(:,t); v(:,t) = Y(:,t) - Z*a(:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t); atilde(:,t) = a(:,t) + PZI*v(:,t);
a(:,t+1) = T*atilde(:,t); a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t); Pf = P(:,:,t);
for jnk=1:nk, for jnk=1:nk,
Pf = T*Pf*T' + QQ; Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf; PK(jnk,:,:,t+jnk) = Pf;
end end
end end
t = smpl+1; t = smpl+1;
while t>d+1 while t>d+1
t = t-1; t = t-1;
r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1); r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1);
alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t); etahat(:,t) = QRt*r(:,t);
end end
if d if d
r0 = zeros(mm,d+1); r0 = zeros(mm,d+1);
r0(:,d+1) = r(:,d+1); r0(:,d+1) = r(:,d+1);
r1 = zeros(mm,d+1); r1 = zeros(mm,d+1);
for t = d:-1:1 for t = d:-1:1
r0(:,t) = Linf(:,:,t)'*r0(:,t+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); 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); alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t);
etahat(:,t) = QRt*r0(:,t); etahat(:,t) = QRt*r0(:,t);
end end
end end
if nargout > 7 if nargout > 7
decomp = zeros(nk,mm,rr,smpl+nk); decomp = zeros(nk,mm,rr,smpl+nk);
ZRQinv = inv(Z*QQ*Z'); ZRQinv = inv(Z*QQ*Z');
for t = max(d,1):smpl for t = max(d,1):smpl
ri_d = Z'*iF(:,:,t)*v(:,t); ri_d = Z'*iF(:,:,t)*v(:,t);
% calculate eta_tm1t % calculate eta_tm1t
eta_tm1t = QRt*ri_d; eta_tm1t = QRt*ri_d;
% calculate decomposition % calculate decomposition
Ttok = eye(mm,mm); Ttok = eye(mm,mm);
for h = 1:nk for h = 1:nk
for j=1:rr for j=1:rr
eta=zeros(rr,1); eta=zeros(rr,1);
eta(j) = eta_tm1t(j); eta(j) = eta_tm1t(j);
decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta; decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta;
end end
end end
end end
end end

View File

@ -70,9 +70,9 @@ aK = zeros(nk,mm,smpl+nk);
PK = zeros(nk,mm,mm,smpl+nk); PK = zeros(nk,mm,mm,smpl+nk);
if isempty(options_.diffuse_d), if isempty(options_.diffuse_d),
smpl_diff = 1; smpl_diff = 1;
else else
smpl_diff=rank(Pinf1); smpl_diff=rank(Pinf1);
end end
Fstar = zeros(pp,smpl_diff); Fstar = zeros(pp,smpl_diff);
@ -101,81 +101,81 @@ r = zeros(mm,smpl+1);
Z = zeros(pp,mm); Z = zeros(pp,mm);
for i=1:pp; for i=1:pp;
Z(i,mf(i)) = 1; Z(i,mf(i)) = 1;
end end
t = 0; t = 0;
icc=0; icc=0;
newRank = rank(Pinf(:,:,1),crit1); newRank = rank(Pinf(:,:,1),crit1);
while newRank & t < smpl while newRank & t < smpl
t = t+1; t = t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
Pstar1(:,:,t) = Pstar(:,:,t); Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t); Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp for i=1:pp
v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t); v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t);
Fstar(i,t) = Pstar(mf(i),mf(i),t); Fstar(i,t) = Pstar(mf(i),mf(i),t);
Finf(i,t) = Pinf(mf(i),mf(i),t); Finf(i,t) = Pinf(mf(i),mf(i),t);
Kstar(:,i,t) = Pstar(:,mf(i),t); Kstar(:,i,t) = Pstar(:,mf(i),t);
if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit
icc=icc+1; icc=icc+1;
Kinf(:,i,t) = Pinf(:,mf(i),t); Kinf(:,i,t) = Pinf(:,mf(i),t);
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(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); 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); a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ... Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*transpose(Kinf(:,i,t)) +... (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +...
Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(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); Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
% new terminiation criteria by M. Ratto % new terminiation criteria by M. Ratto
P0=Pinf(:,:,t); P0=Pinf(:,:,t);
% newRank = any(diag(P0(mf,mf))>crit); % newRank = any(diag(P0(mf,mf))>crit);
% if newRank==0, id = i; end, % if newRank==0, id = i; end,
if ~isempty(options_.diffuse_d), if ~isempty(options_.diffuse_d),
newRank = (icc<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;
if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0); if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc; options_.diffuse_d = icc;
newRank=0; 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 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
end a1(:,t+1) = T*a(:,t);
a1(:,t+1) = T*a(:,t); for jnk=1:nk,
for jnk=1:nk, aK(jnk,:,t+jnk) = T^jnk*a(:,t);
aK(jnk,:,t+jnk) = T^jnk*a(:,t); end
end Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ;
Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ; Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T);
Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T); P0=Pinf(:,:,t+1);
P0=Pinf(:,:,t+1); if newRank,
if newRank, %newRank = any(diag(P0(mf,mf))>crit);
%newRank = any(diag(P0(mf,mf))>crit); newRank = rank(P0,crit1);
newRank = rank(P0,crit1); end
end
end end
@ -192,96 +192,96 @@ Pstar1 = Pstar1(:,:,1:d);
Pinf1 = Pinf1(:,:,1:d); Pinf1 = Pinf1(:,:,1:d);
notsteady = 1; notsteady = 1;
while notsteady & t<smpl while notsteady & t<smpl
t = t+1; t = t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
P1(:,:,t) = P(:,:,t); P1(:,:,t) = P(:,:,t);
for i=1:pp for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t);
Fi(i,t) = P(mf(i),mf(i),t); Fi(i,t) = P(mf(i),mf(i),t);
Ki(:,i,t) = P(:,mf(i),t); Ki(:,i,t) = P(:,mf(i),t);
if Fi(i,t) > crit if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); 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); 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) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
end
end end
end a1(:,t+1) = T*a(:,t);
a1(:,t+1) = T*a(:,t); Pf = P(:,:,t);
Pf = P(:,:,t); for jnk=1:nk,
for jnk=1:nk, Pf = T*Pf*T' + QQ;
Pf = T*Pf*T' + QQ; aK(jnk,:,t+jnk) = T^jnk*a(:,t);
aK(jnk,:,t+jnk) = T^jnk*a(:,t); PK(jnk,:,:,t+jnk) = Pf;
PK(jnk,:,:,t+jnk) = Pf; end
end P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ;
P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ; notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end end
P_s=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); P_s=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
Fi_s = Fi(:,t); Fi_s = Fi(:,t);
Ki_s = Ki(:,:,t); Ki_s = Ki(:,:,t);
L_s =Li(:,:,:,t); L_s =Li(:,:,:,t);
if t<smpl if t<smpl
t_steady = t+1; t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+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])); 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])); 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])); Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1]));
end end
while t<smpl while t<smpl
t=t+1; t=t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
for i=1:pp for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t);
if Fi_s(i) > crit if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); 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
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 end
ri=zeros(mm,1); ri=zeros(mm,1);
t = smpl+1; t = smpl+1;
while t>d+1 while t>d+1
t = t-1; t = t-1;
for i=pp:-1:1 for i=pp:-1:1
if Fi(i,t) > crit if Fi(i,t) > crit
ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
end
end end
end r(:,t) = ri;
r(:,t) = ri; alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); etahat(:,t) = QRt*r(:,t);
etahat(:,t) = QRt*r(:,t); ri = T'*ri;
ri = T'*ri;
end end
if d if d
r0 = zeros(mm,d); r0 = zeros(mm,d);
r0(:,d) = ri; r0(:,d) = ri;
r1 = zeros(mm,d); r1 = zeros(mm,d);
for t = d:-1:1 for t = d:-1:1
for i=pp:-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 & ~(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) = transpose(Z)*v(:,t)/Finf(i,t) + ... BUG HERE in transpose(Z)
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t); r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0 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); r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end 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
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 end
if nargout > 7 if nargout > 7

View File

@ -76,9 +76,9 @@ a1 = zeros(mm,smpl+1);
aK = zeros(nk,mm,smpl+nk); aK = zeros(nk,mm,smpl+nk);
if isempty(options_.diffuse_d), if isempty(options_.diffuse_d),
smpl_diff = 1; smpl_diff = 1;
else else
smpl_diff=rank(Pinf1); smpl_diff=rank(Pinf1);
end end
Fstar = zeros(pp,smpl_diff); Fstar = zeros(pp,smpl_diff);
@ -111,67 +111,67 @@ t = 0;
icc=0; icc=0;
newRank = rank(Pinf(:,:,1),crit1); newRank = rank(Pinf(:,:,1),crit1);
while newRank & t < smpl while newRank & t < smpl
t = t+1; t = t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
Pstar1(:,:,t) = Pstar(:,:,t); Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t); Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i,t) = Y(i,t)-Zi*a(:,t); v(i,t) = Y(i,t)-Zi*a(:,t);
Fstar(i,t) = Zi*Pstar(:,:,t)*Zi'; Fstar(i,t) = Zi*Pstar(:,:,t)*Zi';
Finf(i,t) = Zi*Pinf(:,:,t)*Zi'; Finf(i,t) = Zi*Pinf(:,:,t)*Zi';
Kstar(:,i,t) = Pstar(:,:,t)*Zi'; Kstar(:,i,t) = Pstar(:,:,t)*Zi';
if Finf(i,t) > crit & newRank if Finf(i,t) > crit & newRank
icc=icc+1; icc=icc+1;
Kinf(:,i,t) = Pinf(:,:,t)*Zi'; Kinf(:,i,t) = Pinf(:,:,t)*Zi';
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(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))*Zi/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); a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ... Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*Kinf(:,i,t)' +... (Kstar(:,i,t)*Kinf(:,i,t)' +...
Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t); Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,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)'; Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
% new terminiation criteria by M. Ratto % new terminiation criteria by M. Ratto
P0=Pinf(:,:,t); P0=Pinf(:,:,t);
if ~isempty(options_.diffuse_d), if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d); newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0); if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc; options_.diffuse_d = icc;
newRank=0; 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 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
end a1(:,t+1) = T*a(:,t);
a1(:,t+1) = T*a(:,t); for jnk=1:nk,
for jnk=1:nk, aK(jnk,:,t+jnk) = T^jnk*a(:,t);
aK(jnk,:,t+jnk) = T^jnk*a(:,t); end
end Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ;
Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ; Pinf(:,:,t+1) = T*Pinf(:,:,t)*T';
Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; P0=Pinf(:,:,t+1);
P0=Pinf(:,:,t+1); if newRank,
if newRank, newRank = rank(P0,crit1);
newRank = rank(P0,crit1); end
end
end end
@ -188,31 +188,31 @@ Pstar1 = Pstar1(:,:,1:d);
Pinf1 = Pinf1(:,:,1:d); Pinf1 = Pinf1(:,:,1:d);
notsteady = 1; notsteady = 1;
while notsteady & t<smpl while notsteady & t<smpl
t = t+1; t = t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
P1(:,:,t) = P(:,:,t); P1(:,:,t) = P(:,:,t);
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t); v(i,t) = Y(i,t) - Zi*a(:,t);
Fi(i,t) = Zi*P(:,:,t)*Zi'; Fi(i,t) = Zi*P(:,:,t)*Zi';
Ki(:,i,t) = P(:,:,t)*Zi'; Ki(:,i,t) = P(:,:,t)*Zi';
if Fi(i,t) > crit if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); 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); 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) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
end
end end
end a1(:,t+1) = T*a(:,t);
a1(:,t+1) = T*a(:,t); Pf = P(:,:,t);
Pf = P(:,:,t); for jnk=1:nk,
for jnk=1:nk, Pf = T*Pf*T' + QQ;
Pf = T*Pf*T' + QQ; aK(jnk,:,t+jnk) = T^jnk*a(:,t);
aK(jnk,:,t+jnk) = T^jnk*a(:,t); PK(jnk,:,:,t+jnk) = Pf;
PK(jnk,:,:,t+jnk) = Pf; end
end P(:,:,t+1) = T*P(:,:,t)*T' + QQ;
P(:,:,t+1) = T*P(:,:,t)*T' + QQ; notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end end
P_s=tril(P(:,:,t))+tril(P(:,:,t),-1)'; P_s=tril(P(:,:,t))+tril(P(:,:,t),-1)';
P1_s=tril(P1(:,:,t))+tril(P1(:,:,t),-1)'; P1_s=tril(P1(:,:,t))+tril(P1(:,:,t),-1)';
@ -220,67 +220,67 @@ Fi_s = Fi(:,t);
Ki_s = Ki(:,:,t); Ki_s = Ki(:,:,t);
L_s =Li(:,:,:,t); L_s =Li(:,:,:,t);
if t<smpl if t<smpl
P = cat(3,P(:,:,1:t),repmat(P_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])); 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])); 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])); 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])); Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t]));
end end
while t<smpl while t<smpl
t=t+1; t=t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t); v(i,t) = Y(i,t) - Zi*a(:,t);
if Fi_s(i) > crit if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); 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
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 end
ri=zeros(mm,1); ri=zeros(mm,1);
t = smpl+1; t = smpl+1;
while t > d+1 while t > d+1
t = t-1; t = t-1;
for i=pp:-1:1 for i=pp:-1:1
if Fi(i,t) > crit if Fi(i,t) > crit
ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
end
end end
end r(:,t) = ri;
r(:,t) = ri; alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); etahat(:,t) = QRt*r(:,t);
etahat(:,t) = QRt*r(:,t); ri = T'*ri;
ri = T'*ri;
end end
if d if d
r0 = zeros(mm,d); r0 = zeros(mm,d);
r0(:,d) = ri; r0(:,d) = ri;
r1 = zeros(mm,d); r1 = zeros(mm,d);
for t = d:-1:1 for t = d:-1:1
for i=pp:-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 & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination
if Finf(i,t) > crit if Finf(i,t) > crit
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t); r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0 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); r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end 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
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 end
if nargout > 7 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,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) % 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 % Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix
% %
% INPUTS % INPUTS
% T: mm*mm matrix % T: mm*mm matrix
% Z: pp*mm matrix % Z: pp*mm matrix
% R: mm*rr matrix % R: mm*rr matrix
% Q: rr*rr matrix % Q: rr*rr matrix
% H: pp*pp matrix variance of measurement errors % H: pp*pp matrix variance of measurement errors
% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros % Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar1: mm*mm variance-covariance matrix with stationary variables % Pstar1: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector % Y: pp*1 vector
% pp: number of observed variables % pp: number of observed variables
% mm: number of state variables % mm: number of state variables
% smpl: sample size % smpl: sample size
% %
% OUTPUTS % OUTPUTS
% alphahat: smoothed variables (a_{t|T}) % alphahat: smoothed variables (a_{t|T})
% epsilonhat:smoothed measurement errors % epsilonhat:smoothed measurement errors
% etahat: smoothed shocks % etahat: smoothed shocks
% atilde: matrix of updated variables (a_{t|t}) % atilde: matrix of updated variables (a_{t|t})
% aK: 3D array of k step ahead filtered state variables (a_{t+k|t) % aK: 3D array of k step ahead filtered state variables (a_{t+k|t)
% (meaningless for periods 1:d) % (meaningless for periods 1:d)
% P: 3D array of one-step ahead forecast error variance % P: 3D array of one-step ahead forecast error variance
% matrices % matrices
% PK: 4D array of k-step ahead forecast error variance % PK: 4D array of k-step ahead forecast error variance
% matrices (meaningless for periods 1:d) % matrices (meaningless for periods 1:d)
% d: number of periods where filter remains in diffuse part % d: number of periods where filter remains in diffuse part
% (should be equal to the order of integration of the model) % (should be equal to the order of integration of the model)
% decomp: decomposition of the effect of shocks on filtered values % decomp: decomposition of the effect of shocks on filtered values
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space % See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 Dynare Team % Copyright (C) 2004-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% modified by M. Ratto: % modified by M. Ratto:
% new output argument aK (1-step to k-step predictions) % new output argument aK (1-step to k-step predictions)
% new options_.nk: the max step ahed prediction in aK (default is 4) % new options_.nk: the max step ahed prediction in aK (default is 4)
% new crit1 value for rank of Pinf % new crit1 value for rank of Pinf
% it is assured that P is symmetric % it is assured that P is symmetric
global options_ global options_
d = 0; d = 0;
decomp = []; decomp = [];
nk = options_.nk; nk = options_.nk;
spinf = size(Pinf1); spinf = size(Pinf1);
spstar = size(Pstar1); spstar = size(Pstar1);
v = zeros(pp,smpl); v = zeros(pp,smpl);
a = zeros(mm,smpl+1); a = zeros(mm,smpl+1);
atilde = zeros(mm,smpl); atilde = zeros(mm,smpl);
aK = zeros(nk,mm,smpl+nk); aK = zeros(nk,mm,smpl+nk);
PK = zeros(nk,mm,mm,smpl+nk); PK = zeros(nk,mm,mm,smpl+nk);
iF = zeros(pp,pp,smpl); iF = zeros(pp,pp,smpl);
Fstar = zeros(pp,pp,smpl); Fstar = zeros(pp,pp,smpl);
iFinf = zeros(pp,pp,smpl); iFinf = zeros(pp,pp,smpl);
K = zeros(mm,pp,smpl); K = zeros(mm,pp,smpl);
L = zeros(mm,mm,smpl); L = zeros(mm,mm,smpl);
Linf = zeros(mm,mm,smpl); Linf = zeros(mm,mm,smpl);
Kstar = zeros(mm,pp,smpl); Kstar = zeros(mm,pp,smpl);
P = zeros(mm,mm,smpl+1); P = zeros(mm,mm,smpl+1);
Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
crit = options_.kalman_tol; crit = options_.kalman_tol;
crit1 = 1.e-8; crit1 = 1.e-8;
steady = smpl; steady = smpl;
rr = size(Q,1); rr = size(Q,1);
QQ = R*Q*transpose(R); QQ = R*Q*transpose(R);
QRt = Q*transpose(R); QRt = Q*transpose(R);
alphahat = zeros(mm,smpl); alphahat = zeros(mm,smpl);
etahat = zeros(rr,smpl); etahat = zeros(rr,smpl);
epsilonhat = zeros(size(Y)); epsilonhat = zeros(size(Y));
r = zeros(mm,smpl+1); r = zeros(mm,smpl+1);
t = 0; t = 0;
while rank(Pinf(:,:,t+1),crit1) & t<smpl while rank(Pinf(:,:,t+1),crit1) & t<smpl
t = t+1; t = t+1;
v(:,t)= Y(:,t) - Z*a(:,t); v(:,t)= Y(:,t) - Z*a(:,t);
F = Z*Pinf(:,:,t)*Z'; F = Z*Pinf(:,:,t)*Z';
if rcond(F) < crit if rcond(F) < crit
return return
end end
iFinf(:,:,t) = inv(F); iFinf(:,:,t) = inv(F);
PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t); PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t); atilde(:,t) = a(:,t) + PZI*v(:,t);
Kinf(:,:,t) = T*PZI; Kinf(:,:,t) = T*PZI;
a(:,t+1) = T*atilde(:,t); a(:,t+1) = T*atilde(:,t);
aK(1,:,t+1) = a(:,t+1); aK(1,:,t+1) = a(:,t+1);
% isn't a meaningless as long as we are in the diffuse part? MJ % isn't a meaningless as long as we are in the diffuse part? MJ
for jnk=2:nk, for jnk=2:nk,
aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1);
end end
Linf(:,:,t) = T - Kinf(:,:,t)*Z; Linf(:,:,t) = T - Kinf(:,:,t)*Z;
Fstar(:,:,t) = Z*Pstar(:,:,t)*Z' + H; Fstar(:,:,t) = Z*Pstar(:,:,t)*Z' + H;
Kstar(:,:,t) = (T*Pstar(:,:,t)*Z'-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t); 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; 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)'; Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*Z'*Kinf(:,:,t)';
end end
d = t; d = t;
P(:,:,d+1) = Pstar(:,:,d+1); P(:,:,d+1) = Pstar(:,:,d+1);
iFinf = iFinf(:,:,1:d); iFinf = iFinf(:,:,1:d);
Linf = Linf(:,:,1:d); Linf = Linf(:,:,1:d);
Fstar = Fstar(:,:,1:d); Fstar = Fstar(:,:,1:d);
Kstar = Kstar(:,:,1:d); Kstar = Kstar(:,:,1:d);
Pstar = Pstar(:,:,1:d); Pstar = Pstar(:,:,1:d);
Pinf = Pinf(:,:,1:d); Pinf = Pinf(:,:,1:d);
notsteady = 1; notsteady = 1;
while notsteady & t<smpl while notsteady & t<smpl
t = t+1; t = t+1;
v(:,t) = Y(:,t) - Z*a(:,t); v(:,t) = Y(:,t) - Z*a(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
F = Z*P(:,:,t)*Z' + H; F = Z*P(:,:,t)*Z' + H;
if rcond(F) < crit if rcond(F) < crit
return return
end end
iF(:,:,t) = inv(F); iF(:,:,t) = inv(F);
PZI = P(:,:,t)*Z'*iF(:,:,t); PZI = P(:,:,t)*Z'*iF(:,:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t); atilde(:,t) = a(:,t) + PZI*v(:,t);
K(:,:,t) = T*PZI; K(:,:,t) = T*PZI;
L(:,:,t) = T-K(:,:,t)*Z; L(:,:,t) = T-K(:,:,t)*Z;
a(:,t+1) = T*atilde(:,t); a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t); Pf = P(:,:,t);
for jnk=1:nk, for jnk=1:nk,
Pf = T*Pf*T' + QQ; Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf; PK(jnk,:,:,t+jnk) = Pf;
end end
P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ; P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ;
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end end
if t<smpl if t<smpl
PZI_s = PZI; PZI_s = PZI;
K_s = K(:,:,t); K_s = K(:,:,t);
iF_s = iF(:,:,t); iF_s = iF(:,:,t);
P_s = P(:,:,t+1); P_s = P(:,:,t+1);
P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); 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])); 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])); 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])); K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t]));
end end
while t<smpl while t<smpl
t=t+1; t=t+1;
v(:,t) = Y(:,t) - Z*a(:,t); v(:,t) = Y(:,t) - Z*a(:,t);
atilde(:,t) = a(:,t) + PZI*v(:,t); atilde(:,t) = a(:,t) + PZI*v(:,t);
a(:,t+1) = T*atilde(:,t); a(:,t+1) = T*atilde(:,t);
Pf = P(:,:,t); Pf = P(:,:,t);
for jnk=1:nk, for jnk=1:nk,
Pf = T*Pf*T' + QQ; Pf = T*Pf*T' + QQ;
aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); aK(jnk,:,t+jnk) = T^jnk*atilde(:,t);
PK(jnk,:,:,t+jnk) = Pf; PK(jnk,:,:,t+jnk) = Pf;
end end
end end
t = smpl+1; t = smpl+1;
while t>d+1 while t>d+1
t = t-1; t = t-1;
r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1); r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1);
alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t); etahat(:,t) = QRt*r(:,t);
end end
if d if d
r0 = zeros(mm,d+1); r0 = zeros(mm,d+1);
r0(:,d+1) = r(:,d+1); r0(:,d+1) = r(:,d+1);
r1 = zeros(mm,d+1); r1 = zeros(mm,d+1);
for t = d:-1:1 for t = d:-1:1
r0(:,t) = Linf(:,:,t)'*r0(:,t+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); 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); alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t);
etahat(:,t) = QRt*r0(:,t); etahat(:,t) = QRt*r0(:,t);
end end
end end
if nargout > 7 if nargout > 7
decomp = zeros(nk,mm,rr,smpl+nk); decomp = zeros(nk,mm,rr,smpl+nk);
ZRQinv = inv(Z*QQ*Z'); ZRQinv = inv(Z*QQ*Z');
for t = max(d,1):smpl for t = max(d,1):smpl
ri_d = Z'*iF(:,:,t)*v(:,t); ri_d = Z'*iF(:,:,t)*v(:,t);
% calculate eta_tm1t % calculate eta_tm1t
eta_tm1t = QRt*ri_d; eta_tm1t = QRt*ri_d;
% calculate decomposition % calculate decomposition
Ttok = eye(mm,mm); Ttok = eye(mm,mm);
for h = 1:nk for h = 1:nk
for j=1:rr for j=1:rr
eta=zeros(rr,1); eta=zeros(rr,1);
eta(j) = eta_tm1t(j); eta(j) = eta_tm1t(j);
decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta; decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta;
end end
end end
end end
end end
epsilonhat = Y-Z*alphahat; epsilonhat = Y-Z*alphahat;

View File

@ -68,9 +68,9 @@ a1 = zeros(mm,smpl+1);
aK = zeros(nk,mm,smpl+nk); aK = zeros(nk,mm,smpl+nk);
if isempty(options_.diffuse_d), if isempty(options_.diffuse_d),
smpl_diff = 1; smpl_diff = 1;
else else
smpl_diff=rank(Pinf1); smpl_diff=rank(Pinf1);
end end
Fstar = zeros(pp,smpl_diff); Fstar = zeros(pp,smpl_diff);
@ -99,81 +99,81 @@ r = zeros(mm,smpl+1);
Z = zeros(pp,mm); Z = zeros(pp,mm);
for i=1:pp; for i=1:pp;
Z(i,mf(i)) = 1; Z(i,mf(i)) = 1;
end end
t = 0; t = 0;
icc=0; icc=0;
newRank = rank(Pinf(:,:,1),crit1); newRank = rank(Pinf(:,:,1),crit1);
while newRank & t < smpl while newRank & t < smpl
t = t+1; t = t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
Pstar1(:,:,t) = Pstar(:,:,t); Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t); Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp for i=1:pp
v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t); 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); Fstar(i,t) = Pstar(mf(i),mf(i),t) + H(i,i);
Finf(i,t) = Pinf(mf(i),mf(i),t); Finf(i,t) = Pinf(mf(i),mf(i),t);
Kstar(:,i,t) = Pstar(:,mf(i),t); Kstar(:,i,t) = Pstar(:,mf(i),t);
if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit
icc=icc+1; icc=icc+1;
Kinf(:,i,t) = Pinf(:,mf(i),t); Kinf(:,i,t) = Pinf(:,mf(i),t);
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(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); 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); a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ... Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*transpose(Kinf(:,i,t)) +... (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +...
Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(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); Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
% new terminiation criteria by M. Ratto % new terminiation criteria by M. Ratto
P0=Pinf(:,:,t); P0=Pinf(:,:,t);
% newRank = any(diag(P0(mf,mf))>crit); % newRank = any(diag(P0(mf,mf))>crit);
% if newRank==0, options_.diffuse_d = i; end, % if newRank==0, options_.diffuse_d = i; end,
if ~isempty(options_.diffuse_d), if ~isempty(options_.diffuse_d),
newRank = (icc<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;
if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0); if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc; options_.diffuse_d = icc;
newRank=0; newRank=0;
end end
else else
%newRank = any(diag(P0(mf,mf))>crit); %newRank = any(diag(P0(mf,mf))>crit);
newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1));
if newRank==0, if newRank==0,
options_.diffuse_d = icc; options_.diffuse_d = icc;
end end
end, end,
% if newRank==0, % if newRank==0,
% options_.diffuse_d=i; % this line is buggy! % options_.diffuse_d=i; % this line is buggy!
% end % end
% end new terminiation criteria by M. Ratto % end new terminiation criteria by M. Ratto
elseif Fstar(i,t) > crit 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 %% 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 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]. %% 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 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); 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) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); 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
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 end
@ -190,89 +190,89 @@ Pstar1 = Pstar1(:,:,1:d);
Pinf1 = Pinf1(:,:,1:d); Pinf1 = Pinf1(:,:,1:d);
notsteady = 1; notsteady = 1;
while notsteady & t<smpl while notsteady & t<smpl
t = t+1; t = t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
P1(:,:,t) = P(:,:,t); P1(:,:,t) = P(:,:,t);
for i=1:pp for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); 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); Fi(i,t) = P(mf(i),mf(i),t)+H(i,i);
Ki(:,i,t) = P(:,mf(i),t); Ki(:,i,t) = P(:,mf(i),t);
if Fi(i,t) > crit if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); 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); 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) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
end
end end
end a1(:,t+1) = T*a(:,t);
a1(:,t+1) = T*a(:,t); for jnk=1:nk,
for jnk=1:nk, aK(jnk,:,t+jnk) = T^jnk*a(:,t);
aK(jnk,:,t+jnk) = T^jnk*a(:,t); end
end P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ;
P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ; notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end end
P_s=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); P_s=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
Fi_s = Fi(:,t); Fi_s = Fi(:,t);
Ki_s = Ki(:,:,t); Ki_s = Ki(:,:,t);
L_s =Li(:,:,:,t); L_s =Li(:,:,:,t);
if t<smpl if t<smpl
t_steady = t+1; t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+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])); 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])); 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])); Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1]));
end end
while t<smpl while t<smpl
t=t+1; t=t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
for i=1:pp for i=1:pp
v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t);
if Fi_s(i) > crit if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); 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
end
a1(:,t+1) = T*a(:,t);
for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t);
end
end end
ri=zeros(mm,1); ri=zeros(mm,1);
t = smpl+1; t = smpl+1;
while t>d+1 while t>d+1
t = t-1; t = t-1;
for i=pp:-1:1 for i=pp:-1:1
if Fi(i,t) > crit if Fi(i,t) > crit
ri=Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; ri=Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
end
end end
end r(:,t) = ri;
r(:,t) = ri; alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); etahat(:,t) = QRt*r(:,t);
etahat(:,t) = QRt*r(:,t); ri = T'*ri;
ri = T'*ri;
end end
if d if d
r0 = zeros(mm,d); r0 = zeros(mm,d);
r0(:,d) = ri; r0(:,d) = ri;
r1 = zeros(mm,d); r1 = zeros(mm,d);
for t = d:-1:1 for t = d:-1:1
for i=pp:-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 & ~(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) + ... r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t); r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0 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); r0(:,t)=Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end 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
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 end
epsilonhat = Y-alphahat(mf,:)-trend; epsilonhat = Y-alphahat(mf,:)-trend;

View File

@ -77,9 +77,9 @@ a1 = zeros(mm,smpl+1);
aK = zeros(nk,mm,smpl+nk); aK = zeros(nk,mm,smpl+nk);
if isempty(options_.diffuse_d), if isempty(options_.diffuse_d),
smpl_diff = 1; smpl_diff = 1;
else else
smpl_diff=rank(Pinf1); smpl_diff=rank(Pinf1);
end end
Fstar = zeros(pp,smpl_diff); Fstar = zeros(pp,smpl_diff);
@ -112,67 +112,67 @@ t = 0;
icc=0; icc=0;
newRank = rank(Pinf(:,:,1),crit1); newRank = rank(Pinf(:,:,1),crit1);
while newRank & t < smpl while newRank & t < smpl
t = t+1; t = t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
Pstar1(:,:,t) = Pstar(:,:,t); Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t); Pinf1(:,:,t) = Pinf(:,:,t);
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i,t) = Y(i,t)-Zi*a(:,t); v(i,t) = Y(i,t)-Zi*a(:,t);
Fstar(i,t) = Zi*Pstar(:,:,t)*Zi' +H(i,i); Fstar(i,t) = Zi*Pstar(:,:,t)*Zi' +H(i,i);
Finf(i,t) = Zi*Pinf(:,:,t)*Zi'; Finf(i,t) = Zi*Pinf(:,:,t)*Zi';
Kstar(:,i,t) = Pstar(:,:,t)*Zi'; Kstar(:,i,t) = Pstar(:,:,t)*Zi';
if Finf(i,t) > crit & newRank if Finf(i,t) > crit & newRank
icc=icc+1; icc=icc+1;
Kinf(:,i,t) = Pinf(:,:,t)*Zi'; Kinf(:,i,t) = Pinf(:,:,t)*Zi';
Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(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))*Zi/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); a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ... Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*Kinf(:,i,t)' +... (Kstar(:,i,t)*Kinf(:,i,t)' +...
Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t); Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t);
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,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)'; Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)';
Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)';
% new terminiation criteria by M. Ratto % new terminiation criteria by M. Ratto
P0=Pinf(:,:,t); P0=Pinf(:,:,t);
if ~isempty(options_.diffuse_d), if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d); newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0); if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0);
disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
options_.diffuse_d = icc; options_.diffuse_d = icc;
newRank=0; 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 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
end a1(:,t+1) = T*a(:,t);
a1(:,t+1) = T*a(:,t); for jnk=1:nk,
for jnk=1:nk, aK(jnk,:,t+jnk) = T^jnk*a(:,t);
aK(jnk,:,t+jnk) = T^jnk*a(:,t); end
end Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ;
Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ; Pinf(:,:,t+1) = T*Pinf(:,:,t)*T';
Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; P0=Pinf(:,:,t+1);
P0=Pinf(:,:,t+1); if newRank,
if newRank, newRank = rank(P0,crit1);
newRank = rank(P0,crit1); end
end
end end
@ -189,31 +189,31 @@ Pstar1 = Pstar1(:,:,1:d);
Pinf1 = Pinf1(:,:,1:d); Pinf1 = Pinf1(:,:,1:d);
notsteady = 1; notsteady = 1;
while notsteady & t<smpl while notsteady & t<smpl
t = t+1; t = t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
P1(:,:,t) = P(:,:,t); P1(:,:,t) = P(:,:,t);
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t); v(i,t) = Y(i,t) - Zi*a(:,t);
Fi(i,t) = Zi*P(:,:,t)*Zi' + H(i,i); Fi(i,t) = Zi*P(:,:,t)*Zi' + H(i,i);
Ki(:,i,t) = P(:,:,t)*Zi'; Ki(:,i,t) = P(:,:,t)*Zi';
if Fi(i,t) > crit if Fi(i,t) > crit
Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); 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); 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) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t);
P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)';
end
end end
end a1(:,t+1) = T*a(:,t);
a1(:,t+1) = T*a(:,t); Pf = P(:,:,t);
Pf = P(:,:,t); for jnk=1:nk,
for jnk=1:nk, Pf = T*Pf*T' + QQ;
Pf = T*Pf*T' + QQ; aK(jnk,:,t+jnk) = T^jnk*a(:,t);
aK(jnk,:,t+jnk) = T^jnk*a(:,t); PK(jnk,:,:,t+jnk) = Pf;
PK(jnk,:,:,t+jnk) = Pf; end
end P(:,:,t+1) = T*P(:,:,t)*T' + QQ;
P(:,:,t+1) = T*P(:,:,t)*T' + QQ; notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
end end
P_s=tril(P(:,:,t))+tril(P(:,:,t),-1)'; P_s=tril(P(:,:,t))+tril(P(:,:,t),-1)';
P1_s=tril(P1(:,:,t))+tril(P1(:,:,t),-1)'; P1_s=tril(P1(:,:,t))+tril(P1(:,:,t),-1)';
@ -221,67 +221,67 @@ Fi_s = Fi(:,t);
Ki_s = Ki(:,:,t); Ki_s = Ki(:,:,t);
L_s =Li(:,:,:,t); L_s =Li(:,:,:,t);
if t<smpl if t<smpl
P = cat(3,P(:,:,1:t),repmat(P_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])); 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])); 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])); 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])); Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t]));
end end
while t<smpl while t<smpl
t=t+1; t=t+1;
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i,t) = Y(i,t) - Zi*a(:,t); v(i,t) = Y(i,t) - Zi*a(:,t);
if Fi_s(i) > crit if Fi_s(i) > crit
a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); 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
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 end
ri=zeros(mm,1); ri=zeros(mm,1);
t = smpl+1; t = smpl+1;
while t>d+1 while t>d+1
t = t-1; t = t-1;
for i=pp:-1:1 for i=pp:-1:1
if Fi(i,t) > crit if Fi(i,t) > crit
ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri;
end
end end
end r(:,t) = ri;
r(:,t) = ri; alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); etahat(:,t) = QRt*r(:,t);
etahat(:,t) = QRt*r(:,t); ri = T'*ri;
ri = T'*ri;
end end
if d if d
r0 = zeros(mm,d); r0 = zeros(mm,d);
r0(:,d) = ri; r0(:,d) = ri;
r1 = zeros(mm,d); r1 = zeros(mm,d);
for t = d:-1:2 for t = d:-1:2
for i=pp:-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 & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination
if Finf(i,t) > crit if Finf(i,t) > crit
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = Linf(:,:,i,t)'*r0(:,t); r0(:,t) = Linf(:,:,i,t)'*r0(:,t);
elseif Fstar(i,t) > crit % step needed whe Finf == 0 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); r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
end 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
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 end
if nargout > 7 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))); 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)); 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) 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 end
Pstar1 = cat(1,cat(2,Pstar1,zeros(mm,pp)),cat(2,zeros(pp,mm),H)); Pstar1 = cat(1,cat(2,Pstar1,zeros(mm,pp)),cat(2,zeros(pp,mm),H));
spinf = size(Pinf1); spinf = size(Pinf1);
@ -88,8 +88,8 @@ epsilonhat = zeros(pp,smpl);
r = zeros(mm+pp,smpl+1); r = zeros(mm+pp,smpl+1);
Z = zeros(pp,mm+pp); Z = zeros(pp,mm+pp);
for i=1:pp; for i=1:pp;
Z(i,mf(i)) = 1; Z(i,mf(i)) = 1;
Z(i,mm+i) = 1; Z(i,mm+i) = 1;
end end
%% [1] Kalman filter... %% [1] Kalman filter...
t = 0; t = 0;
@ -99,28 +99,28 @@ while newRank & t < smpl
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
Pstar1(:,:,t) = Pstar(:,:,t); Pstar1(:,:,t) = Pstar(:,:,t);
Pinf1(:,:,t) = Pinf(:,:,t); Pinf1(:,:,t) = Pinf(:,:,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); 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); Fstar(i,t) = Pstar(mf(i),mf(i),t)+Pstar(mm+i,mm+i,t);
Finf(i,t) = Pinf(mf(i),mf(i),t); Finf(i,t) = Pinf(mf(i),mf(i),t);
Kstar(:,i,t) = Pstar(:,mf(i),t)+Pstar(:,mm+i,t); Kstar(:,i,t) = Pstar(:,mf(i),t)+Pstar(:,mm+i,t);
if Finf(i,t) > crit if Finf(i,t) > crit
Kinf(:,i,t) = Pinf(:,mf(i),t); Kinf(:,i,t) = Pinf(:,mf(i),t);
Linf(:,:,i,t) = eye(mm+pp) - Kinf(:,i,t)*Z(i,:)/Finf(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); 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); a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
Pstar(:,:,t) = Pstar(:,:,t) + ... Pstar(:,:,t) = Pstar(:,:,t) + ...
Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
(Kstar(:,i,t)*transpose(Kinf(:,i,t)) +... (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +...
Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(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); 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 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 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]. %% rank(Pinf)=0. [stéphane,11-03-2004].
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); 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) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t);
end end
end end
a1(:,t+1) = T*a(:,t); a1(:,t+1) = T*a(:,t);
for jnk=1:nk, for jnk=1:nk,
aK(jnk,:,t+jnk) = T^jnk*a(:,t); aK(jnk,:,t+jnk) = T^jnk*a(:,t);
@ -147,11 +147,11 @@ while notsteady & t<smpl
a(:,t) = a1(:,t); a(:,t) = a1(:,t);
P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
P1(:,:,t) = P(:,:,t); 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); 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); 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); 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); 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) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t);
@ -170,11 +170,11 @@ Fi_s = Fi(:,t);
Ki_s = Ki(:,:,t); Ki_s = Ki(:,:,t);
L_s =Li(:,:,:,t); L_s =Li(:,:,:,t);
if t<smpl if t<smpl
t_steady = t+1; t_steady = t+1;
P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+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])); 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])); 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])); Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1]));
end end
while t<smpl while t<smpl
t=t+1; t=t+1;
@ -219,16 +219,16 @@ if d
L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t);
r0(:,t) = transpose(Linf(:,:,i,t))*r0(:,t); r0(:,t) = transpose(Linf(:,:,i,t))*r0(:,t);
end end
end end
alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
r(:,t-1) = r0(:,t); r(:,t-1) = r0(:,t);
tmp = QRt*r(:,t); tmp = QRt*r(:,t);
etahat(:,t) = tmp(1:rr); etahat(:,t) = tmp(1:rr);
epsilonhat(:,t) = tmp(rr+(1:pp)); epsilonhat(:,t) = tmp(rr+(1:pp));
if t > 1 if t > 1
r0(:,t-1) = T'*r0(:,t); r0(:,t-1) = T'*r0(:,t);
r1(:,t-1) = T'*r1(:,t); r1(:,t-1) = T'*r1(:,t);
end end
end end
end end
alphahat = alphahat(1:mm,:); 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)
% 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 % Computes the diffuse likelihood without measurement error, in the case of a non-singular var-cov matrix
% %
% INPUTS % INPUTS
% T: mm*mm matrix % T: mm*mm matrix
% R: mm*rr matrix % R: mm*rr matrix
% Q: rr*rr matrix % Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros % Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables % Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector % Y: pp*1 vector
% trend % trend
% start: likelihood evaluation at 'start' % start: likelihood evaluation at 'start'
% %
% OUTPUTS % OUTPUTS
% LIK: likelihood % LIK: likelihood
% lik: density vector in each period % lik: density vector in each period
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space % See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 Dynare Team % Copyright (C) 2004-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% M. Ratto added lik in output % M. Ratto added lik in output
global bayestopt_ options_ global bayestopt_ options_
mf = bayestopt_.mf; mf = bayestopt_.mf;
smpl = size(Y,2); smpl = size(Y,2);
mm = size(T,2); mm = size(T,2);
pp = size(Y,1); pp = size(Y,1);
a = zeros(mm,1); a = zeros(mm,1);
dF = 1; dF = 1;
QQ = R*Q*transpose(R); QQ = R*Q*transpose(R);
t = 0; t = 0;
lik = zeros(smpl,1); lik = zeros(smpl,1);
LIK = Inf; LIK = Inf;
notsteady = 1; notsteady = 1;
crit = options_.kalman_tol; crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl while rank(Pinf,crit) & t < smpl
t = t+1; t = t+1;
v = Y(:,t)-a(mf)-trend(:,t); v = Y(:,t)-a(mf)-trend(:,t);
Finf = Pinf(mf,mf); Finf = Pinf(mf,mf);
if rcond(Finf) < crit if rcond(Finf) < crit
if ~all(abs(Finf(:)) < crit) if ~all(abs(Finf(:)) < crit)
return return
else else
iFstar = inv(Pstar(mf,mf)); iFstar = inv(Pstar(mf,mf));
dFstar = det(Pstar(mf,mf)); dFstar = det(Pstar(mf,mf));
Kstar = Pstar(:,mf)*iFstar; Kstar = Pstar(:,mf)*iFstar;
lik(t) = log(dFstar) + transpose(v)*iFstar*v; lik(t) = log(dFstar) + transpose(v)*iFstar*v;
Pinf = T*Pinf*transpose(T); Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ; Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ;
a = T*(a+Kstar*v); a = T*(a+Kstar*v);
end end
else else
lik(t) = log(det(Finf)); lik(t) = log(det(Finf));
iFinf = inv(Finf); iFinf = inv(Finf);
Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane)
Fstar = Pstar(mf,mf); Fstar = Pstar(mf,mf);
Kstar = (Pstar(:,mf)-Kinf*Fstar)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) 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; Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ;
Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T); Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T);
a = T*(a+Kinf*v); a = T*(a+Kinf*v);
end end
end end
if t == smpl if t == smpl
error(['There isn''t enough information to estimate the initial' ... error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']); ' conditions of the nonstationary variables']);
end end
F_singular = 1; F_singular = 1;
while notsteady & t < smpl while notsteady & t < smpl
t = t+1; t = t+1;
v = Y(:,t)-a(mf)-trend(:,t); v = Y(:,t)-a(mf)-trend(:,t);
F = Pstar(mf,mf); F = Pstar(mf,mf);
oldPstar = Pstar; oldPstar = Pstar;
dF = det(F); dF = det(F);
if rcond(F) < crit if rcond(F) < crit
if ~all(abs(F(:))<crit) if ~all(abs(F(:))<crit)
return return
else else
a = T*a; a = T*a;
Pstar = T*Pstar*transpose(T)+QQ; Pstar = T*Pstar*transpose(T)+QQ;
end end
else else
F_singular = 0; F_singular = 0;
iF = inv(F); iF = inv(F);
lik(t) = log(dF)+transpose(v)*iF*v; lik(t) = log(dF)+transpose(v)*iF*v;
K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane) K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane)
a = T*(a+K*v); %% --> factorization of the transition matrix... a = T*(a+K*v); %% --> factorization of the transition matrix...
Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane) Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane)
end end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end end
if F_singular == 1 if F_singular == 1
error(['The variance of the forecast error remains singular until the' ... error(['The variance of the forecast error remains singular until the' ...
'end of the sample']) 'end of the sample'])
end end
if t < smpl if t < smpl
t0 = t+1; t0 = t+1;
while t < smpl while t < smpl
t = t+1; t = t+1;
v = Y(:,t)-a(mf)-trend(:,t); v = Y(:,t)-a(mf)-trend(:,t);
a = T*(a+K*v); a = T*(a+K*v);
lik(t) = transpose(v)*iF*v; lik(t) = transpose(v)*iF*v;
end end
lik(t0:smpl) = lik(t0:smpl) + log(dF); lik(t0:smpl) = lik(t0:smpl) + log(dF);
end end
% adding log-likelihhod constants % adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2; lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood. 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)
% 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 % Computes the diffuse likelihood without measurement error, in the case of a non-singular var-cov matrix
% %
% INPUTS % INPUTS
% T: mm*mm matrix % T: mm*mm matrix
% Z: pp,mm matrix % Z: pp,mm matrix
% R: mm*rr matrix % R: mm*rr matrix
% Q: rr*rr matrix % Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros % Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables % Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector % Y: pp*1 vector
% start: likelihood evaluation at 'start' % start: likelihood evaluation at 'start'
% %
% OUTPUTS % OUTPUTS
% LIK: likelihood % LIK: likelihood
% lik: density vector in each period % lik: density vector in each period
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space % See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 Dynare Team % Copyright (C) 2004-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% M. Ratto added lik in output % M. Ratto added lik in output
global bayestopt_ options_ global bayestopt_ options_
smpl = size(Y,2); smpl = size(Y,2);
mm = size(T,2); mm = size(T,2);
pp = size(Y,1); pp = size(Y,1);
a = zeros(mm,1); a = zeros(mm,1);
dF = 1; dF = 1;
QQ = R*Q*transpose(R); QQ = R*Q*transpose(R);
t = 0; t = 0;
lik = zeros(smpl,1); lik = zeros(smpl,1);
LIK = Inf; LIK = Inf;
notsteady = 1; notsteady = 1;
crit = options_.kalman_tol; crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl while rank(Pinf,crit) & t < smpl
t = t+1; t = t+1;
v = Y(:,t)-Z*a; v = Y(:,t)-Z*a;
Finf = Z*Pinf*Z'; Finf = Z*Pinf*Z';
if rcond(Finf) < crit if rcond(Finf) < crit
if ~all(abs(Finf(:)) < crit) if ~all(abs(Finf(:)) < crit)
return return
else else
Fstar = Z*Pstar*Z'; Fstar = Z*Pstar*Z';
iFstar = inv(Fstar); iFstar = inv(Fstar);
dFstar = det(Fstar); dFstar = det(Fstar);
Kstar = Pstar*Z'*iFstar; Kstar = Pstar*Z'*iFstar;
lik(t) = log(dFstar) + v'*iFstar*v; lik(t) = log(dFstar) + v'*iFstar*v;
Pinf = T*Pinf*transpose(T); Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ; Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ;
a = T*(a+Kstar*v); a = T*(a+Kstar*v);
end end
else else
lik(t) = log(det(Finf)); lik(t) = log(det(Finf));
iFinf = inv(Finf); iFinf = inv(Finf);
Kinf = Pinf*Z'*iFinf; Kinf = Pinf*Z'*iFinf;
Fstar = Z*Pstar*Z'; Fstar = Z*Pstar*Z';
Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf; Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf;
Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ; Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ;
Pinf = T*(Pinf-Pinf*Z'*Kinf')*T'; Pinf = T*(Pinf-Pinf*Z'*Kinf')*T';
a = T*(a+Kinf*v); a = T*(a+Kinf*v);
end end
end end
if t == smpl if t == smpl
error(['There isn''t enough information to estimate the initial' ... error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']); ' conditions of the nonstationary variables']);
end end
F_singular = 1; F_singular = 1;
while notsteady & t < smpl while notsteady & t < smpl
t = t+1; t = t+1;
v = Y(:,t)-Z*a; v = Y(:,t)-Z*a;
F = Z*Pstar*Z'; F = Z*Pstar*Z';
oldPstar = Pstar; oldPstar = Pstar;
dF = det(F); dF = det(F);
if rcond(F) < crit if rcond(F) < crit
if ~all(abs(F(:))<crit) if ~all(abs(F(:))<crit)
return return
else else
a = T*a; a = T*a;
Pstar = T*Pstar*T'+QQ; Pstar = T*Pstar*T'+QQ;
end end
else else
F_singular = 0; F_singular = 0;
iF = inv(F); iF = inv(F);
lik(t) = log(dF)+v'*iF*v; lik(t) = log(dF)+v'*iF*v;
K = Pstar*Z'*iF; K = Pstar*Z'*iF;
a = T*(a+K*v); a = T*(a+K*v);
Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ; Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ;
end end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end end
if F_singular == 1 if F_singular == 1
error(['The variance of the forecast error remains singular until the' ... error(['The variance of the forecast error remains singular until the' ...
'end of the sample']) 'end of the sample'])
end end
if t < smpl if t < smpl
t0 = t+1; t0 = t+1;
while t < smpl while t < smpl
t = t+1; t = t+1;
v = Y(:,t)-Z*a; v = Y(:,t)-Z*a;
a = T*(a+K*v); a = T*(a+K*v);
lik(t) = v'*iF*v; lik(t) = v'*iF*v;
end end
lik(t0:smpl) = lik(t0:smpl) + log(dF); lik(t0:smpl) = lik(t0:smpl) + log(dF);
end end
% adding log-likelihhod constants % adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2; lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood. 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)%//Z,T,R,Q,Pinf,Pstar,Y)
% function [LIK, lik] = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,Y,trend,start) % function [LIK, lik] = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,Y,trend,start)
% Computes the diffuse likelihood without measurement error, in the case of % Computes the diffuse likelihood without measurement error, in the case of
% a singular var-cov matrix. % a singular var-cov matrix.
% Univariate treatment of multivariate time series. % Univariate treatment of multivariate time series.
% %
% INPUTS % INPUTS
% T: mm*mm matrix % T: mm*mm matrix
% R: mm*rr matrix % R: mm*rr matrix
% Q: rr*rr matrix % Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros % Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables % Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector % Y: pp*1 vector
% trend % trend
% start: likelihood evaluation at 'start' % start: likelihood evaluation at 'start'
% %
% OUTPUTS % OUTPUTS
% LIK: likelihood % LIK: likelihood
% lik: density vector in each period % lik: density vector in each period
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space % See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 Dynare Team % Copyright (C) 2004-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% M. Ratto added lik in output [October 2005] % M. Ratto added lik in output [October 2005]
% changes by M. Ratto [April 2005] % changes by M. Ratto [April 2005]
% introduced new options options_.diffuse_d for termination of DKF % introduced new options options_.diffuse_d for termination of DKF
% new icc counter for Finf steps in DKF % new icc counter for Finf steps in DKF
% new termination for DKF % new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non % likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero. % zero.
% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf % [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf
% introduced a specific crit1 for the DKF termination % introduced a specific crit1 for the DKF termination
global bayestopt_ options_ global bayestopt_ options_
mf = bayestopt_.mf; mf = bayestopt_.mf;
pp = size(Y,1); pp = size(Y,1);
mm = size(T,1); mm = size(T,1);
smpl = size(Y,2); smpl = size(Y,2);
a = zeros(mm,1); a = zeros(mm,1);
QQ = R*Q*transpose(R); QQ = R*Q*transpose(R);
t = 0; t = 0;
lik = zeros(smpl,1); lik = zeros(smpl,1);
notsteady = 1; notsteady = 1;
crit = options_.kalman_tol; crit = options_.kalman_tol;
crit1 = 1.e-6; crit1 = 1.e-6;
newRank = rank(Pinf,crit1); newRank = rank(Pinf,crit1);
icc=0; icc=0;
while newRank & t < smpl while newRank & t < smpl
t = t+1; t = t+1;
for i=1:pp for i=1:pp
v(i) = Y(i,t)-a(mf(i))-trend(i,t); v(i) = Y(i,t)-a(mf(i))-trend(i,t);
Fstar = Pstar(mf(i),mf(i)); Fstar = Pstar(mf(i),mf(i));
Finf = Pinf(mf(i),mf(i)); Finf = Pinf(mf(i),mf(i));
Kstar = Pstar(:,mf(i)); Kstar = Pstar(:,mf(i));
if Finf > crit & newRank, %added newRank criterion if Finf > crit & newRank, %added newRank criterion
icc=icc+1; icc=icc+1;
Kinf = Pinf(:,mf(i)); Kinf = Pinf(:,mf(i));
a = a + Kinf*v(i)/Finf; a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ... Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ...
(Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf; (Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf;
Pinf = Pinf - Kinf*transpose(Kinf)/Finf; Pinf = Pinf - Kinf*transpose(Kinf)/Finf;
lik(t) = lik(t) + log(Finf); lik(t) = lik(t) + log(Finf);
% start new termination criterion for DKF % start new termination criterion for DKF
if ~isempty(options_.diffuse_d), if ~isempty(options_.diffuse_d),
newRank = (icc<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; % M. Ratto this line is BUGGY
if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0); if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc; options_.diffuse_d = icc;
newRank=0; newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation') disp('You may have to reset the optimisation')
end end
else else
%newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY %newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY
newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1)); newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1));
if newRank==0, if newRank==0,
P0= T*Pinf*transpose(T); 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); % M. Ratto this line is BUGGY
newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005 newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005
if newRank==0, if newRank==0,
options_.diffuse_d = icc; options_.diffuse_d = icc;
end end
end end
end, end,
% end new termination and checks for DKF % end new termination and checks for DKF
elseif Fstar > crit 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 %% 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 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]. %% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf,crit) == 0 %if rank(Pinf,crit) == 0
% the likelihood terms should alwasy be cumulated, not only % the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering % when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables % of observed variables
% presample options can be used to ignore initial time points % presample options can be used to ignore initial time points
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
%end %end
a = a + Kstar*v(i)/Fstar; a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*transpose(Kstar)/Fstar; Pstar = Pstar - Kstar*transpose(Kstar)/Fstar;
else else
%disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)]) %disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)])
end end
end end
% if all(abs(Pinf(:))<crit), % if all(abs(Pinf(:))<crit),
% oldRank = 0; % oldRank = 0;
% else % else
% oldRank = rank(Pinf,crit); % oldRank = rank(Pinf,crit);
% end % end
if newRank, if newRank,
oldRank = rank(Pinf,crit1); oldRank = rank(Pinf,crit1);
else else
oldRank = 0; oldRank = 0;
end end
a = T*a; a = T*a;
Pstar = T*Pstar*transpose(T)+QQ; Pstar = T*Pstar*transpose(T)+QQ;
Pinf = T*Pinf*transpose(T); Pinf = T*Pinf*transpose(T);
% if all(abs(Pinf(:))<crit), % if all(abs(Pinf(:))<crit),
% newRank = 0; % newRank = 0;
% else % else
% newRank = rank(Pinf,crit); % newRank = rank(Pinf,crit);
% end % end
if newRank, if newRank,
newRank = rank(Pinf,crit1); % new crit1 is used newRank = rank(Pinf,crit1); % new crit1 is used
end end
if oldRank ~= newRank if oldRank ~= newRank
disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!') disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!')
end end
end end
if t == smpl if t == smpl
error(['There isn''t enough information to estimate the initial' ... error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']); ' conditions of the nonstationary variables']);
end end
while notsteady & t < smpl while notsteady & t < smpl
t = t+1; t = t+1;
oldP = Pstar; oldP = Pstar;
for i=1:pp for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t); v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i)); Fi = Pstar(mf(i),mf(i));
if Fi > crit if Fi > crit
Ki = Pstar(:,mf(i)); Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi; a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi; Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end end
end end
a = T*a; a = T*a;
Pstar = T*Pstar*transpose(T) + QQ; Pstar = T*Pstar*transpose(T) + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit); notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end end
while t < smpl while t < smpl
t = t+1; t = t+1;
Pstar = oldP; Pstar = oldP;
for i=1:pp for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t); v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i)); Fi = Pstar(mf(i),mf(i));
if Fi > crit if Fi > crit
Ki = Pstar(:,mf(i)); Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi; a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi; Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end end
end end
a = T*a; a = T*a;
end end
% adding log-likelihhod constants % adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2; lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood. 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)
% 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 % Computes the diffuse likelihood without measurement error, in the case of
% a singular var-cov matrix. % a singular var-cov matrix.
% Univariate treatment of multivariate time series. % Univariate treatment of multivariate time series.
% %
% INPUTS % INPUTS
% T: mm*mm matrix % T: mm*mm matrix
% Z: pp*mm matrix % Z: pp*mm matrix
% R: mm*rr matrix % R: mm*rr matrix
% Q: rr*rr matrix % Q: rr*rr matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros % Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables % Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector % Y: pp*1 vector
% start: likelihood evaluation at 'start' % start: likelihood evaluation at 'start'
% %
% OUTPUTS % OUTPUTS
% LIK: likelihood % LIK: likelihood
% lik: density vector in each period % lik: density vector in each period
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space % See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 Dynare Team % Copyright (C) 2004-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% M. Ratto added lik in output [October 2005] % M. Ratto added lik in output [October 2005]
% changes by M. Ratto [April 2005] % changes by M. Ratto [April 2005]
% introduced new options options_.diffuse_d for termination of DKF % introduced new options options_.diffuse_d for termination of DKF
% new icc counter for Finf steps in DKF % new icc counter for Finf steps in DKF
% new termination for DKF % new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non % likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero. % zero.
% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf % [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf
% introduced a specific crit1 for the DKF termination % introduced a specific crit1 for the DKF termination
global bayestopt_ options_ global bayestopt_ options_
pp = size(Y,1); pp = size(Y,1);
mm = size(T,1); mm = size(T,1);
smpl = size(Y,2); smpl = size(Y,2);
a = zeros(mm,1); a = zeros(mm,1);
QQ = R*Q*R'; QQ = R*Q*R';
t = 0; t = 0;
lik = zeros(smpl,1); lik = zeros(smpl,1);
notsteady = 1; notsteady = 1;
crit = options_.kalman_tol; crit = options_.kalman_tol;
crit1 = 1.e-6; crit1 = 1.e-6;
newRank = rank(Pinf,crit1); newRank = rank(Pinf,crit1);
icc=0; icc=0;
while newRank & t < smpl while newRank & t < smpl
t = t+1; t = t+1;
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i) = Y(i,t)-Zi*a; v(i) = Y(i,t)-Zi*a;
Fstar = Zi*Pstar*Zi'; Fstar = Zi*Pstar*Zi';
Finf = Zi*Pinf*Zi'; Finf = Zi*Pinf*Zi';
Kstar = Pstar*Zi'; Kstar = Pstar*Zi';
if Finf > crit & newRank if Finf > crit & newRank
icc=icc+1; icc=icc+1;
Kinf = Pinf*Zi'; Kinf = Pinf*Zi';
a = a + Kinf*v(i)/Finf; a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ... Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ...
(Kstar*Kinf'+Kinf*Kstar')/Finf; (Kstar*Kinf'+Kinf*Kstar')/Finf;
Pinf = Pinf - Kinf*Kinf'/Finf; Pinf = Pinf - Kinf*Kinf'/Finf;
lik(t) = lik(t) + log(Finf); lik(t) = lik(t) + log(Finf);
if ~isempty(options_.diffuse_d), if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d); newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0); if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc; options_.diffuse_d = icc;
newRank=0; newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation') disp('You may have to reset the optimisation')
end end
else else
newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1)); newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1));
if newRank==0, if newRank==0,
P0= T*Pinf*T'; P0= T*Pinf*T';
newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005 newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005
if newRank==0, if newRank==0,
options_.diffuse_d = icc; options_.diffuse_d = icc;
end end
end end
end, end,
elseif Fstar > crit 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 %% 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 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]. %% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf,crit) == 0 %if rank(Pinf,crit) == 0
% the likelihood terms should alwasy be cumulated, not only % the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering % when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables % of observed variables
% presample options can be used to ignore initial time points % presample options can be used to ignore initial time points
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
a = a + Kstar*v(i)/Fstar; a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*(Kstar'/Fstar); Pstar = Pstar - Kstar*(Kstar'/Fstar);
else else
%disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)]) %disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)])
end end
end end
if newRank, if newRank,
oldRank = rank(Pinf,crit1); oldRank = rank(Pinf,crit1);
else else
oldRank = 0; oldRank = 0;
end end
a = T*a; a = T*a;
Pstar = T*Pstar*T'+QQ; Pstar = T*Pstar*T'+QQ;
Pinf = T*Pinf*T'; Pinf = T*Pinf*T';
if newRank, if newRank,
newRank = rank(Pinf,crit1); newRank = rank(Pinf,crit1);
end end
if oldRank ~= newRank if oldRank ~= newRank
disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!') disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!')
end end
end end
if t == smpl if t == smpl
error(['There isn''t enough information to estimate the initial' ... error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']); ' conditions of the nonstationary variables']);
end end
while notsteady & t < smpl while notsteady & t < smpl
t = t+1; t = t+1;
oldP = Pstar; oldP = Pstar;
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a; v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi'; Fi = Zi*Pstar*Zi';
if Fi > crit if Fi > crit
Ki = Pstar*Zi'; Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi; a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*(Ki'/Fi); Pstar = Pstar - Ki*(Ki'/Fi);
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end end
end end
a = T*a; a = T*a;
Pstar = T*Pstar*T' + QQ; Pstar = T*Pstar*T' + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit); notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end end
while t < smpl while t < smpl
t = t+1; t = t+1;
Pstar = oldP; Pstar = oldP;
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a; v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi'; Fi = Zi*Pstar*Zi';
if Fi > crit if Fi > crit
Ki = Pstar*Zi'; Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi; a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*Ki'/Fi; Pstar = Pstar - Ki*Ki'/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end end
end end
a = T*a; a = T*a;
end end
% adding log-likelihhod constants % adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2; lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood. 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)
% 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 % Computes the diffuse likelihood (H=measurement error) in the case of a non-singular var-cov matrix
% %
% INPUTS % INPUTS
% T: mm*mm matrix % T: mm*mm matrix
% R: mm*rr matrix % R: mm*rr matrix
% Q: rr*rr matrix % Q: rr*rr matrix
% H: pp*pp matrix % H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros % Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables % Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector % Y: pp*1 vector
% trend % trend
% start: likelihood evaluation at 'start' % start: likelihood evaluation at 'start'
% %
% OUTPUTS % OUTPUTS
% LIK: likelihood % LIK: likelihood
% lik: density vector in each period % lik: density vector in each period
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space % See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2005-2008 Dynare Team % Copyright (C) 2005-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% M. Ratto added lik in output % M. Ratto added lik in output
global bayestopt_ options_ global bayestopt_ options_
mf = bayestopt_.mf; mf = bayestopt_.mf;
smpl = size(Y,2); smpl = size(Y,2);
mm = size(T,2); mm = size(T,2);
pp = size(Y,1); pp = size(Y,1);
a = zeros(mm,1); a = zeros(mm,1);
dF = 1; dF = 1;
QQ = R*Q*transpose(R); QQ = R*Q*transpose(R);
t = 0; t = 0;
lik = zeros(smpl,1); lik = zeros(smpl,1);
LIK = Inf; LIK = Inf;
notsteady = 1; notsteady = 1;
crit = options_.kalman_tol; crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl while rank(Pinf,crit) & t < smpl
t = t+1; t = t+1;
v = Y(:,t)-a(mf)-trend(:,t); v = Y(:,t)-a(mf)-trend(:,t);
Finf = Pinf(mf,mf); Finf = Pinf(mf,mf);
if rcond(Finf) < crit if rcond(Finf) < crit
if ~all(abs(Finf(:))<crit) if ~all(abs(Finf(:))<crit)
return return
else else
iFstar = inv(Pstar(mf,mf)+H); iFstar = inv(Pstar(mf,mf)+H);
dFstar = det(Pstar(mf,mf)+H); dFstar = det(Pstar(mf,mf)+H);
Kstar = Pstar(:,mf)*iFstar; Kstar = Pstar(:,mf)*iFstar;
lik(t) = log(dFstar) + transpose(v)*iFstar*v; lik(t) = log(dFstar) + transpose(v)*iFstar*v;
Pinf = T*Pinf*transpose(T); Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ; Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ;
a = T*(a+Kstar*v); a = T*(a+Kstar*v);
end end
else else
lik(t) = log(det(Finf)); lik(t) = log(det(Finf));
iFinf = inv(Finf); iFinf = inv(Finf);
Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane)
Fstar = Pstar(mf,mf)+H; Fstar = Pstar(mf,mf)+H;
Kstar = (Pstar(:,mf)-Kinf*Fstar)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) 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; Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ;
Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T); Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T);
a = T*(a+Kinf*v); a = T*(a+Kinf*v);
end end
end end
if t == smpl if t == smpl
error(['There isn''t enough information to estimate the initial' ... error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']); ' conditions of the nonstationary variables']);
end end
F_singular = 1; F_singular = 1;
while notsteady & t < smpl while notsteady & t < smpl
t = t+1; t = t+1;
v = Y(:,t)-a(mf)-trend(:,t); v = Y(:,t)-a(mf)-trend(:,t);
F = Pstar(mf,mf)+H; F = Pstar(mf,mf)+H;
oldPstar = Pstar; oldPstar = Pstar;
dF = det(F); dF = det(F);
if rcond(F) < crit if rcond(F) < crit
if ~all(abs(F(:))<crit) if ~all(abs(F(:))<crit)
return return
else else
a = T*a; a = T*a;
Pstar = T*Pstar*transpose(T)+QQ; Pstar = T*Pstar*transpose(T)+QQ;
end end
else else
F_singular = 0; F_singular = 0;
iF = inv(F); iF = inv(F);
lik(t) = log(dF)+transpose(v)*iF*v; lik(t) = log(dF)+transpose(v)*iF*v;
K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane) K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane)
a = T*(a+K*v); %% --> factorization of the transition matrix... a = T*(a+K*v); %% --> factorization of the transition matrix...
Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane) Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane)
end end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end end
if F_singular == 1 if F_singular == 1
error(['The variance of the forecast error remains singular until the' ... error(['The variance of the forecast error remains singular until the' ...
'end of the sample']) 'end of the sample'])
end end
if t < smpl if t < smpl
t0 = t+1; t0 = t+1;
while t < smpl while t < smpl
t = t+1; t = t+1;
v = Y(:,t)-a(mf)-trend(:,t); v = Y(:,t)-a(mf)-trend(:,t);
a = T*(a+K*v); a = T*(a+K*v);
lik(t) = transpose(v)*iF*v; lik(t) = transpose(v)*iF*v;
end end
lik(t0:smpl) = lik(t0:smpl) + log(dF); lik(t0:smpl) = lik(t0:smpl) + log(dF);
end end
% adding log-likelihhod constants % adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2; lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood. 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)
% 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 % Computes the diffuse likelihood (H=measurement error) in the case of a non-singular var-cov matrix
% %
% INPUTS % INPUTS
% T: mm*mm matrix % T: mm*mm matrix
% Z: pp,mm matrix % Z: pp,mm matrix
% R: mm*rr matrix % R: mm*rr matrix
% Q: rr*rr matrix % Q: rr*rr matrix
% H: pp*pp matrix % H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros % Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables % Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector % Y: pp*1 vector
% start: likelihood evaluation at 'start' % start: likelihood evaluation at 'start'
% %
% OUTPUTS % OUTPUTS
% LIK: likelihood % LIK: likelihood
% lik: density vector in each period % lik: density vector in each period
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space % See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 Dynare Team % Copyright (C) 2004-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% M. Ratto added lik in output % M. Ratto added lik in output
global bayestopt_ options_ global bayestopt_ options_
smpl = size(Y,2); smpl = size(Y,2);
mm = size(T,2); mm = size(T,2);
pp = size(Y,1); pp = size(Y,1);
a = zeros(mm,1); a = zeros(mm,1);
dF = 1; dF = 1;
QQ = R*Q*transpose(R); QQ = R*Q*transpose(R);
t = 0; t = 0;
lik = zeros(smpl,1); lik = zeros(smpl,1);
LIK = Inf; LIK = Inf;
notsteady = 1; notsteady = 1;
crit = options_.kalman_tol; crit = options_.kalman_tol;
while rank(Pinf,crit) & t < smpl while rank(Pinf,crit) & t < smpl
t = t+1; t = t+1;
v = Y(:,t)-Z*a; v = Y(:,t)-Z*a;
Finf = Z*Pinf*Z'; Finf = Z*Pinf*Z';
if rcond(Finf) < crit if rcond(Finf) < crit
if ~all(abs(Finf(:)) < crit) if ~all(abs(Finf(:)) < crit)
return return
else else
Fstar = Z*Pstar*Z'+H; Fstar = Z*Pstar*Z'+H;
iFstar = inv(Fstar); iFstar = inv(Fstar);
dFstar = det(Fstar); dFstar = det(Fstar);
Kstar = Pstar*Z'*iFstar; Kstar = Pstar*Z'*iFstar;
lik(t) = log(dFstar) + v'*iFstar*v; lik(t) = log(dFstar) + v'*iFstar*v;
Pinf = T*Pinf*transpose(T); Pinf = T*Pinf*transpose(T);
Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ; Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ;
a = T*(a+Kstar*v); a = T*(a+Kstar*v);
end end
else else
lik(t) = log(det(Finf)); lik(t) = log(det(Finf));
iFinf = inv(Finf); iFinf = inv(Finf);
Kinf = Pinf*Z'*iFinf; Kinf = Pinf*Z'*iFinf;
Fstar = Z*Pstar*Z'+H; Fstar = Z*Pstar*Z'+H;
Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf; Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf;
Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ; Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ;
Pinf = T*(Pinf-Pinf*Z'*Kinf')*T'; Pinf = T*(Pinf-Pinf*Z'*Kinf')*T';
a = T*(a+Kinf*v); a = T*(a+Kinf*v);
end end
end end
if t == smpl if t == smpl
error(['There isn''t enough information to estimate the initial' ... error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']); ' conditions of the nonstationary variables']);
end end
F_singular = 1; F_singular = 1;
while notsteady & t < smpl while notsteady & t < smpl
t = t+1; t = t+1;
v = Y(:,t)-Z*a; v = Y(:,t)-Z*a;
F = Z*Pstar*Z'+H; F = Z*Pstar*Z'+H;
oldPstar = Pstar; oldPstar = Pstar;
dF = det(F); dF = det(F);
if rcond(F) < crit if rcond(F) < crit
if ~all(abs(F(:))<crit) if ~all(abs(F(:))<crit)
return return
else else
a = T*a; a = T*a;
Pstar = T*Pstar*T'+QQ; Pstar = T*Pstar*T'+QQ;
end end
else else
F_singular = 0; F_singular = 0;
iF = inv(F); iF = inv(F);
lik(t) = log(dF)+v'*iF*v; lik(t) = log(dF)+v'*iF*v;
K = Pstar*Z'*iF; K = Pstar*Z'*iF;
a = T*(a+K*v); a = T*(a+K*v);
Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ; Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ;
end end
notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
end end
if F_singular == 1 if F_singular == 1
error(['The variance of the forecast error remains singular until the' ... error(['The variance of the forecast error remains singular until the' ...
'end of the sample']) 'end of the sample'])
end end
if t < smpl if t < smpl
t0 = t+1; t0 = t+1;
while t < smpl while t < smpl
t = t+1; t = t+1;
v = Y(:,t)-Z*a; v = Y(:,t)-Z*a;
a = T*(a+K*v); a = T*(a+K*v);
lik(t) = v'*iF*v; lik(t) = v'*iF*v;
end end
lik(t0:smpl) = lik(t0:smpl) + log(dF); lik(t0:smpl) = lik(t0:smpl) + log(dF);
end end
% adding log-likelihhod constants % adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2; lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood. 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)
% 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 % Computes the diffuse likelihood with measurement error, in the case of
% a singular var-cov matrix. % a singular var-cov matrix.
% Univariate treatment of multivariate time series. % Univariate treatment of multivariate time series.
% %
% INPUTS % INPUTS
% T: mm*mm matrix % T: mm*mm matrix
% R: mm*rr matrix % R: mm*rr matrix
% Q: rr*rr matrix % Q: rr*rr matrix
% H: pp*pp matrix % H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros % Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables % Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector % Y: pp*1 vector
% trend % trend
% start: likelihood evaluation at 'start' % start: likelihood evaluation at 'start'
% %
% OUTPUTS % OUTPUTS
% LIK: likelihood % LIK: likelihood
% lik: density vector in each period % lik: density vector in each period
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space % See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2005-2008 Dynare Team % Copyright (C) 2005-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% M. Ratto added lik in output [October 2005] % M. Ratto added lik in output [October 2005]
% changes by M. Ratto % changes by M. Ratto
% introduced new global variable id_ for termination of DKF % introduced new global variable id_ for termination of DKF
% introduced a persistent fmax, in order to keep track the max order of % introduced a persistent fmax, in order to keep track the max order of
% magnitude of the 'zero' values in Pinf at DKF termination % magnitude of the 'zero' values in Pinf at DKF termination
% new icc counter for Finf steps in DKF % new icc counter for Finf steps in DKF
% new termination for DKF % new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non % likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero. this bug is fixed. % zero. this bug is fixed.
global bayestopt_ options_ global bayestopt_ options_
mf = bayestopt_.mf; mf = bayestopt_.mf;
pp = size(Y,1); pp = size(Y,1);
mm = size(T,1); mm = size(T,1);
smpl = size(Y,2); smpl = size(Y,2);
a = zeros(mm,1); a = zeros(mm,1);
QQ = R*Q*transpose(R); QQ = R*Q*transpose(R);
t = 0; t = 0;
lik = zeros(smpl,1); lik = zeros(smpl,1);
notsteady = 1; notsteady = 1;
crit = options_.kalman_tol; crit = options_.kalman_tol;
crit1 = 1.e-6; crit1 = 1.e-6;
newRank = rank(Pinf,crit1); newRank = rank(Pinf,crit1);
icc = 0; icc = 0;
while newRank & t < smpl %% Matrix Finf is assumed to be zero while newRank & t < smpl %% Matrix Finf is assumed to be zero
t = t+1; t = t+1;
for i=1:pp for i=1:pp
v(i) = Y(i,t)-a(mf(i))-trend(i,t); v(i) = Y(i,t)-a(mf(i))-trend(i,t);
Fstar = Pstar(mf(i),mf(i))+H(i,i); Fstar = Pstar(mf(i),mf(i))+H(i,i);
Finf = Pinf(mf(i),mf(i)); Finf = Pinf(mf(i),mf(i));
Kstar = Pstar(:,mf(i)); Kstar = Pstar(:,mf(i));
if Finf > crit & newRank if Finf > crit & newRank
icc = icc + 1; icc = icc + 1;
Kinf = Pinf(:,mf(i)); Kinf = Pinf(:,mf(i));
a = a + Kinf*v(i)/Finf; a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ... Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ...
(Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf; (Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf;
Pinf = Pinf - Kinf*transpose(Kinf)/Finf; Pinf = Pinf - Kinf*transpose(Kinf)/Finf;
lik(t) = lik(t) + log(Finf); lik(t) = lik(t) + log(Finf);
% start new termination criterion for DKF % start new termination criterion for DKF
if ~isempty(options_.diffuse_d), if ~isempty(options_.diffuse_d),
newRank = (icc<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; % M. Ratto this line is BUGGY
if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0); if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc; options_.diffuse_d = icc;
newRank=0; newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation') disp('You may have to reset the optimisation')
end end
else else
%newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY %newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY
newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1)); newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1));
if newRank==0, if newRank==0,
P0= T*Pinf*transpose(T); 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); % M. Ratto this line is BUGGY
newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 10 Oct 2005 newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 10 Oct 2005
if newRank==0, if newRank==0,
options_.diffuse_d = icc; options_.diffuse_d = icc;
end end
end end
end, end,
% end new termination and checks for DKF and fmax % end new termination and checks for DKF and fmax
elseif Finf > crit 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 %% 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 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]. %% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf) == 0 %if rank(Pinf) == 0
% the likelihood terms should alwasy be cumulated, not only % the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering % when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables % of observed variables
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
%end %end
a = a + Kstar*v(i)/Fstar; a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*transpose(Kstar)/Fstar; Pstar = Pstar - Kstar*transpose(Kstar)/Fstar;
else else
% disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fi)]) % disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fi)])
end end
end end
if newRank if newRank
oldRank = rank(Pinf,crit1); oldRank = rank(Pinf,crit1);
else else
oldRank = 0; oldRank = 0;
end end
a = T*a; a = T*a;
Pstar = T*Pstar*transpose(T)+QQ; Pstar = T*Pstar*transpose(T)+QQ;
Pinf = T*Pinf*transpose(T); Pinf = T*Pinf*transpose(T);
if newRank if newRank
newRank = rank(Pinf,crit1); newRank = rank(Pinf,crit1);
end end
if oldRank ~= newRank if oldRank ~= newRank
disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!') disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!')
end end
end end
if t == smpl if t == smpl
error(['There isn''t enough information to estimate the initial' ... error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']); ' conditions of the nonstationary variables']);
end end
while notsteady & t < smpl while notsteady & t < smpl
t = t+1; t = t+1;
for i=1:pp for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t); v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i))+H(i,i); Fi = Pstar(mf(i),mf(i))+H(i,i);
if Fi > crit if Fi > crit
Ki = Pstar(:,mf(i)); Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi; a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi; Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
end end
end end
oldP = Pstar; oldP = Pstar;
a = T*a; a = T*a;
Pstar = T*Pstar*transpose(T) + QQ; Pstar = T*Pstar*transpose(T) + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit); notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end end
while t < smpl while t < smpl
t = t+1; t = t+1;
for i=1:pp for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t); v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
Fi = Pstar(mf(i),mf(i))+H(i,i); Fi = Pstar(mf(i),mf(i))+H(i,i);
if Fi > crit if Fi > crit
Ki = Pstar(:,mf(i)); Ki = Pstar(:,mf(i));
a = a + Ki*v(i)/Fi; a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi; Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
end end
end end
a = T*a; a = T*a;
end end
% adding log-likelihhod constants % adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2; lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood. 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_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start)
% function [LIK, lik] = DiffuseLikelihoodH3_A(T,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 % Computes the diffuse likelihood without measurement error, in the case of
% a singular var-cov matrix. % a singular var-cov matrix.
% Univariate treatment of multivariate time series. % Univariate treatment of multivariate time series.
% %
% INPUTS % INPUTS
% T: mm*mm matrix % T: mm*mm matrix
% Z: pp*mm matrix % Z: pp*mm matrix
% R: mm*rr matrix % R: mm*rr matrix
% Q: rr*rr matrix % Q: rr*rr matrix
% H: pp*pp matrix % H: pp*pp matrix
% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros % Pinf: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar: mm*mm variance-covariance matrix with stationary variables % Pstar: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector % Y: pp*1 vector
% start: likelihood evaluation at 'start' % start: likelihood evaluation at 'start'
% %
% OUTPUTS % OUTPUTS
% LIK: likelihood % LIK: likelihood
% lik: density vector in each period % lik: density vector in each period
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space % See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 Dynare Team % Copyright (C) 2004-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% M. Ratto added lik in output [October 2005] % M. Ratto added lik in output [October 2005]
% changes by M. Ratto [April 2005] % changes by M. Ratto [April 2005]
% introduced new options options_.diffuse_d for termination of DKF % introduced new options options_.diffuse_d for termination of DKF
% new icc counter for Finf steps in DKF % new icc counter for Finf steps in DKF
% new termination for DKF % new termination for DKF
% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non % likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
% zero. % zero.
% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf % [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf
% introduced a specific crit1 for the DKF termination % introduced a specific crit1 for the DKF termination
global bayestopt_ options_ global bayestopt_ options_
pp = size(Y,1); pp = size(Y,1);
mm = size(T,1); mm = size(T,1);
smpl = size(Y,2); smpl = size(Y,2);
a = zeros(mm,1); a = zeros(mm,1);
QQ = R*Q*R'; QQ = R*Q*R';
t = 0; t = 0;
lik = zeros(smpl,1); lik = zeros(smpl,1);
notsteady = 1; notsteady = 1;
crit = options_.kalman_tol; crit = options_.kalman_tol;
crit1 = 1.e-6; crit1 = 1.e-6;
newRank = rank(Pinf,crit1); newRank = rank(Pinf,crit1);
icc=0; icc=0;
while newRank & t < smpl while newRank & t < smpl
t = t+1; t = t+1;
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i) = Y(i,t)-Zi*a; v(i) = Y(i,t)-Zi*a;
Fstar = Zi*Pstar*Zi'+H(i,i); Fstar = Zi*Pstar*Zi'+H(i,i);
Finf = Zi*Pinf*Zi'; Finf = Zi*Pinf*Zi';
Kstar = Pstar*Zi'; Kstar = Pstar*Zi';
if Finf > crit & newRank if Finf > crit & newRank
icc=icc+1; icc=icc+1;
Kinf = Pinf*Zi'; Kinf = Pinf*Zi';
a = a + Kinf*v(i)/Finf; a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ... Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ...
(Kstar*Kinf'+Kinf*Kstar')/Finf; (Kstar*Kinf'+Kinf*Kstar')/Finf;
Pinf = Pinf - Kinf*Kinf'/Finf; Pinf = Pinf - Kinf*Kinf'/Finf;
lik(t) = lik(t) + log(Finf); lik(t) = lik(t) + log(Finf);
if ~isempty(options_.diffuse_d), if ~isempty(options_.diffuse_d),
newRank = (icc<options_.diffuse_d); newRank = (icc<options_.diffuse_d);
if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0); if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0);
options_.diffuse_d = icc; options_.diffuse_d = icc;
newRank=0; newRank=0;
disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
disp('You may have to reset the optimisation') disp('You may have to reset the optimisation')
end end
else else
newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1)); newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1));
if newRank==0, if newRank==0,
P0= T*Pinf*T'; P0= T*Pinf*T';
newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005 newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005
if newRank==0, if newRank==0,
options_.diffuse_d = icc; options_.diffuse_d = icc;
end end
end end
end, end,
elseif Fstar > crit 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 %% 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 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]. %% rank(Pinf)=0. [stéphane,11-03-2004].
%if rank(Pinf,crit) == 0 %if rank(Pinf,crit) == 0
% the likelihood terms should alwasy be cumulated, not only % the likelihood terms should alwasy be cumulated, not only
% when Pinf=0, otherwise the lik would depend on the ordering % when Pinf=0, otherwise the lik would depend on the ordering
% of observed variables % of observed variables
% presample options can be used to ignore initial time points % presample options can be used to ignore initial time points
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
a = a + Kstar*v(i)/Fstar; a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*Kstar'/Fstar; Pstar = Pstar - Kstar*Kstar'/Fstar;
else else
%disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)]) %disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)])
end end
end end
if newRank, if newRank,
oldRank = rank(Pinf,crit1); oldRank = rank(Pinf,crit1);
else else
oldRank = 0; oldRank = 0;
end end
a = T*a; a = T*a;
Pstar = T*Pstar*T'+QQ; Pstar = T*Pstar*T'+QQ;
Pinf = T*Pinf*T'; Pinf = T*Pinf*T';
if newRank, if newRank,
newRank = rank(Pinf,crit1); newRank = rank(Pinf,crit1);
end end
if oldRank ~= newRank if oldRank ~= newRank
disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!') disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!')
end end
end end
if t == smpl if t == smpl
error(['There isn''t enough information to estimate the initial' ... error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']); ' conditions of the nonstationary variables']);
end end
while notsteady & t < smpl while notsteady & t < smpl
t = t+1; t = t+1;
oldP = Pstar; oldP = Pstar;
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a; v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi'+H(i,i); Fi = Zi*Pstar*Zi'+H(i,i);
if Fi > crit if Fi > crit
Ki = Pstar*Zi'; Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi; a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*Ki'/Fi; Pstar = Pstar - Ki*Ki'/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end end
end end
a = T*a; a = T*a;
Pstar = T*Pstar*T' + QQ; Pstar = T*Pstar*T' + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit); notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end end
while t < smpl while t < smpl
t = t+1; t = t+1;
Pstar = oldP; Pstar = oldP;
for i=1:pp for i=1:pp
Zi = Z(i,:); Zi = Z(i,:);
v(i) = Y(i,t) - Zi*a; v(i) = Y(i,t) - Zi*a;
Fi = Zi*Pstar*Zi'+H(i,i); Fi = Zi*Pstar*Zi'+H(i,i);
if Fi > crit if Fi > crit
Ki = Pstar*Zi'; Ki = Pstar*Zi';
a = a + Ki*v(i)/Fi; a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*Ki'/Fi; Pstar = Pstar - Ki*Ki'/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
else else
%disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
end end
end end
a = T*a; a = T*a;
end end
% adding log-likelihhod constants % adding log-likelihhod constants
lik = (lik + pp*log(2*pi))/2; lik = (lik + pp*log(2*pi))/2;
LIK = sum(lik(start:end)); % Minus the log-likelihood. 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/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ options_ global bayestopt_ options_
mf = bayestopt_.mf; mf = bayestopt_.mf;
pp = size(Y,1); pp = size(Y,1);
mm = size(T,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))); 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)); 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) 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 end
Pstar = cat(1,cat(2,Pstar,zeros(mm,pp)),cat(2,zeros(pp,mm),H)); Pstar = cat(1,cat(2,Pstar,zeros(mm,pp)),cat(2,zeros(pp,mm),H));
a = zeros(mm+pp,1); a = zeros(mm+pp,1);
@ -42,71 +42,71 @@ crit = options_.kalman_tol;
newRank = rank(Pinf,crit); newRank = rank(Pinf,crit);
while rank(Pinf,crit) & t < smpl %% Matrix Finf is assumed to be zero while rank(Pinf,crit) & t < smpl %% Matrix Finf is assumed to be zero
t = t+1; t = t+1;
for i=1:pp for i=1:pp
v(i) = Y(i,t)-a(mf(i))-a(mm+i)-trend(i,t); 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); Fstar = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i);
Finf = Pinf(mf(i),mf(i)); Finf = Pinf(mf(i),mf(i));
Kstar = Pstar(:,mf(i))+Pstar(:,mm+i); Kstar = Pstar(:,mf(i))+Pstar(:,mm+i);
if Finf > crit if Finf > crit
Kinf = Pinf(:,mf(i)); Kinf = Pinf(:,mf(i));
a = a + Kinf*v(i)/Finf; a = a + Kinf*v(i)/Finf;
Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ... Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ...
(Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf; (Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf;
Pinf = Pinf - Kinf*transpose(Kinf)/Finf; Pinf = Pinf - Kinf*transpose(Kinf)/Finf;
lik(t) = lik(t) + log(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 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 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]. %% rank(Pinf)=0. [stéphane,11-03-2004].
if rank(Pinf) == 0 if rank(Pinf) == 0
lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
end end
a = a + Kstar*v(i)/Fstar; a = a + Kstar*v(i)/Fstar;
Pstar = Pstar - Kstar*transpose(Kstar)/Fstar; Pstar = Pstar - Kstar*transpose(Kstar)/Fstar;
end end
oldRank = rank(Pinf,crit); oldRank = rank(Pinf,crit);
a = T*a; a = T*a;
Pstar = T*Pstar*transpose(T)+QQ; Pstar = T*Pstar*transpose(T)+QQ;
Pinf = T*Pinf*transpose(T); Pinf = T*Pinf*transpose(T);
newRank = rank(Pinf,crit); newRank = rank(Pinf,crit);
if oldRank ~= newRank if oldRank ~= newRank
disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!') disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!')
end end
end end
end end
if t == smpl if t == smpl
error(['There isn''t enough information to estimate the initial' ... error(['There isn''t enough information to estimate the initial' ...
' conditions of the nonstationary variables']); ' conditions of the nonstationary variables']);
end end
while notsteady & t < smpl while notsteady & t < smpl
t = t+1; t = t+1;
for i=1:pp for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t) -a(mm+i); 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); Fi = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i);
if Fi > crit if Fi > crit
Ki = Pstar(:,mf(i))+Pstar(:,mm+i); Ki = Pstar(:,mf(i))+Pstar(:,mm+i);
a = a + Ki*v(i)/Fi; a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi; Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
end end
end end
oldP = Pstar; oldP = Pstar;
a = T*a; a = T*a;
Pstar = T*Pstar*transpose(T) + QQ; Pstar = T*Pstar*transpose(T) + QQ;
notsteady = ~(max(max(abs(Pstar-oldP)))<crit); notsteady = ~(max(max(abs(Pstar-oldP)))<crit);
end end
while t < smpl while t < smpl
t = t+1; t = t+1;
for i=1:pp for i=1:pp
v(i) = Y(i,t) - a(mf(i)) - trend(i,t) - a(mm+i); 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); Fi = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i);
if Fi > crit if Fi > crit
Ki = Pstar(:,mf(i))+Pstar(:,mm+i); Ki = Pstar(:,mf(i))+Pstar(:,mm+i);
a = a + Ki*v(i)/Fi; a = a + Ki*v(i)/Fi;
Pstar = Pstar - Ki*transpose(Ki)/Fi; Pstar = Pstar - Ki*transpose(Ki)/Fi;
lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi;
end end
end end
a = T*a; a = T*a;
end end
% adding log-likelihhod constants % 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_ global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_
fval = []; fval = [];
ys = []; ys = [];
trend_coeff = []; trend_coeff = [];
cost_flag = 1; cost_flag = 1;
nobs = size(options_.varobs,1); nobs = size(options_.varobs,1);
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 1. Get the structural parameters & define penalties % 1. Get the structural parameters & define penalties
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb) if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
k = find(xparam1 < bayestopt_.lb); k = find(xparam1 < bayestopt_.lb);
fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2); fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
cost_flag = 0; cost_flag = 0;
info = 41; info = 41;
return; return;
end end
if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub) if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
k = find(xparam1 > bayestopt_.ub); k = find(xparam1 > bayestopt_.ub);
fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2); fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
cost_flag = 0; cost_flag = 0;
info = 42; info = 42;
return; return;
end end
Q = M_.Sigma_e; Q = M_.Sigma_e;
H = M_.H; H = M_.H;
for i=1:estim_params_.nvx for i=1:estim_params_.nvx
k =estim_params_.var_exo(i,1); k =estim_params_.var_exo(i,1);
Q(k,k) = xparam1(i)*xparam1(i); Q(k,k) = xparam1(i)*xparam1(i);
end end
offset = estim_params_.nvx; offset = estim_params_.nvx;
if estim_params_.nvn if estim_params_.nvn
for i=1:estim_params_.nvn for i=1:estim_params_.nvn
k = estim_params_.var_endo(i,1); k = estim_params_.var_endo(i,1);
H(k,k) = xparam1(i+offset)*xparam1(i+offset); H(k,k) = xparam1(i+offset)*xparam1(i+offset);
end end
offset = offset+estim_params_.nvn; offset = offset+estim_params_.nvn;
end end
if estim_params_.ncx if estim_params_.ncx
for i=1:estim_params_.ncx for i=1:estim_params_.ncx
k1 =estim_params_.corrx(i,1); k1 =estim_params_.corrx(i,1);
k2 =estim_params_.corrx(i,2); k2 =estim_params_.corrx(i,2);
Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2)); Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
Q(k2,k1) = Q(k1,k2); Q(k2,k1) = Q(k1,k2);
end end
[CholQ,testQ] = chol(Q); [CholQ,testQ] = chol(Q);
if testQ %% The variance-covariance matrix of the structural innovations is not definite positive. 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. %% We have to compute the eigenvalues of this matrix in order to build the penalty.
a = diag(eig(Q)); a = diag(eig(Q));
k = find(a < 0); k = find(a < 0);
if k > 0 if k > 0
fval = bayestopt_.penalty+sum(-a(k)); fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0; cost_flag = 0;
info = 43; info = 43;
return return
end end
end end
offset = offset+estim_params_.ncx; offset = offset+estim_params_.ncx;
end end
if estim_params_.ncn if estim_params_.ncn
for i=1:estim_params_.ncn for i=1:estim_params_.ncn
k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1)); k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2)); k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
H(k2,k1) = H(k1,k2); H(k2,k1) = H(k1,k2);
end end
[CholH,testH] = chol(H); [CholH,testH] = chol(H);
if testH if testH
a = diag(eig(H)); a = diag(eig(H));
k = find(a < 0); k = find(a < 0);
if k > 0 if k > 0
fval = bayestopt_.penalty+sum(-a(k)); fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0; cost_flag = 0;
info = 44; info = 44;
return return
end end
end end
offset = offset+estim_params_.ncn; offset = offset+estim_params_.ncn;
end end
if estim_params_.np > 0 if estim_params_.np > 0
M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
end end
M_.Sigma_e = Q; M_.Sigma_e = Q;
M_.H = H; M_.H = H;
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 2. call model setup & reduction program % 2. call model setup & reduction program
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,... [T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
bayestopt_.restrict_columns,... bayestopt_.restrict_columns,...
bayestopt_.restrict_aux); bayestopt_.restrict_aux);
if info(1) == 1 || info(1) == 2 || info(1) == 5 if info(1) == 1 || info(1) == 2 || info(1) == 5
fval = bayestopt_.penalty+1; fval = bayestopt_.penalty+1;
cost_flag = 0; cost_flag = 0;
return return
elseif info(1) == 3 || info(1) == 4 || info(1)==6 ||info(1) == 19 || info(1) == 20 || info(1) == 21 elseif info(1) == 3 || info(1) == 4 || info(1)==6 ||info(1) == 19 || info(1) == 20 || info(1) == 21
fval = bayestopt_.penalty+info(2); fval = bayestopt_.penalty+info(2);
cost_flag = 0; cost_flag = 0;
return return
end end
bayestopt_.mf = bayestopt_.mf1; bayestopt_.mf = bayestopt_.mf1;
if options_.noconstant if options_.noconstant
constant = zeros(nobs,1); constant = zeros(nobs,1);
else else
if options_.loglinear if options_.loglinear
constant = log(SteadyState(bayestopt_.mfys)); constant = log(SteadyState(bayestopt_.mfys));
else else
constant = SteadyState(bayestopt_.mfys); constant = SteadyState(bayestopt_.mfys);
end end
end end
if bayestopt_.with_trend if bayestopt_.with_trend
trend_coeff = zeros(nobs,1); trend_coeff = zeros(nobs,1);
t = options_.trend_coeffs; t = options_.trend_coeffs;
for i=1:length(t) for i=1:length(t)
if ~isempty(t{i}) if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i}); trend_coeff(i) = evalin('base',t{i});
end end
end end
trend = repmat(constant,1,gend)+trend_coeff*[1:gend]; trend = repmat(constant,1,gend)+trend_coeff*[1:gend];
else else
trend = repmat(constant,1,gend); trend = repmat(constant,1,gend);
end end
start = options_.presample+1; start = options_.presample+1;
np = size(T,1); np = size(T,1);
mf = bayestopt_.mf; mf = bayestopt_.mf;
no_missing_data_flag = (number_of_observations==gend*nobs); no_missing_data_flag = (number_of_observations==gend*nobs);
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter % 3. Initial condition of the Kalman filter
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
kalman_algo = options_.kalman_algo; kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2 if kalman_algo ~= 2
kalman_algo = 1; kalman_algo = 1;
end end
Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold); Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = []; Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2 if kalman_algo ~= 2
kalman_algo = 1; kalman_algo = 1;
end end
Pstar = options_.Harvey_scale_factor*eye(np); Pstar = options_.Harvey_scale_factor*eye(np);
Pinf = []; Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4 if kalman_algo ~= 4
kalman_algo = 3; kalman_algo = 3;
end end
[QT,ST] = schur(T); [QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1); [QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k); nk = length(k);
nk1 = nk+1; nk1 = nk+1;
Pinf = zeros(np,np); Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk); Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np); Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT; B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2 for i=np:-1:nk+2
if ST(i,i-1) == 0 if ST(i,i-1) == 0
if i == np if i == np
c = zeros(np-nk,1); c = zeros(np-nk,1);
else else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... 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)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else else
if i == np if i == np
c = zeros(np-nk,1); c = zeros(np-nk,1);
c1 = zeros(np-nk,1); c1 = zeros(np-nk,1);
else else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... 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)*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); 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)')+... 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-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); ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... 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)]; -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]; 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) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end); Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1; i = i - 1;
end end
end end
if i == nk+2 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); 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)); Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end end
Z = QT(mf,:); Z = QT(mf,:);
R1 = QT'*R; R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0); [QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8); k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
if length(k) > 0 if length(k) > 0
k1 = EE(:,k); k1 = EE(:,k);
dd =ones(nk,1); dd =ones(nk,1);
dd(k1) = zeros(length(k1),1); dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd); Pinf(1:nk,1:nk) = diag(dd);
end end
end end
if kalman_algo == 2 if kalman_algo == 2
end end
kalman_tol = options_.kalman_tol; kalman_tol = options_.kalman_tol;
riccati_tol = options_.riccati_tol; riccati_tol = options_.riccati_tol;
mf = bayestopt_.mf1; mf = bayestopt_.mf1;
Y = data-trend; Y = data-trend;
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 4. Likelihood evaluation % 4. Likelihood evaluation
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
if (kalman_algo==1)% Multivariate Kalman Filter if (kalman_algo==1)% Multivariate Kalman Filter
if no_missing_data_flag if no_missing_data_flag
LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol);
else else
LIK = ... LIK = ...
missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ... 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); data_index,number_of_observations,no_more_missing_observations);
end end
if isinf(LIK) if isinf(LIK)
kalman_algo = 2; kalman_algo = 2;
end end
end end
if (kalman_algo==2)% Univariate Kalman Filter if (kalman_algo==2)% Univariate Kalman Filter
no_correlation_flag = 1; no_correlation_flag = 1;
if length(H)==1 & H == 0 if length(H)==1 & H == 0
H = zeros(nobs,1); H = zeros(nobs,1);
else else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H); H = diag(H);
else else
no_correlation_flag = 0; no_correlation_flag = 0;
end end
end end
if no_correlation_flag 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); 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 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); 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
end end
if (kalman_algo==3)% Multivariate Diffuse Kalman Filter if (kalman_algo==3)% Multivariate Diffuse Kalman Filter
if no_missing_data_flag if no_missing_data_flag
LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol, ... LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol, ...
riccati_tol); riccati_tol);
else else
LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf, ... LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf, ...
Pstar,Y,start,Z,kalman_tol,riccati_tol,... Pstar,Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,... data_index,number_of_observations,...
no_more_missing_observations); no_more_missing_observations);
end end
if isinf(LIK) if isinf(LIK)
kalman_algo = 4; kalman_algo = 4;
end end
end end
if (kalman_algo==4)% Univariate Diffuse Kalman Filter if (kalman_algo==4)% Univariate Diffuse Kalman Filter
no_correlation_flag = 1; no_correlation_flag = 1;
if length(H)==1 & H == 0 if length(H)==1 & H == 0
H = zeros(nobs,1); H = zeros(nobs,1);
else else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H); H = diag(H);
else else
no_correlation_flag = 0; no_correlation_flag = 0;
end end
end end
if no_correlation_flag if no_correlation_flag
LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y, ... LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y, ...
start,Z,kalman_tol,riccati_tol,data_index,... start,Z,kalman_tol,riccati_tol,data_index,...
number_of_observations,no_more_missing_observations); number_of_observations,no_more_missing_observations);
else else
LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar, ... LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar, ...
Y,start,Z,kalman_tol,riccati_tol,... Y,start,Z,kalman_tol,riccati_tol,...
data_index,number_of_observations,... data_index,number_of_observations,...
no_more_missing_observations); no_more_missing_observations);
end end
end end
if imag(LIK) ~= 0 if imag(LIK) ~= 0
likelihood = bayestopt_.penalty; likelihood = bayestopt_.penalty;
else else
likelihood = LIK; likelihood = LIK;
end end
% ------------------------------------------------------------------------------ % ------------------------------------------------------------------------------
% Adds prior if necessary % Adds prior if necessary
% ------------------------------------------------------------------------------ % ------------------------------------------------------------------------------
lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
fval = (likelihood-lnprior); fval = (likelihood-lnprior);
options_.kalman_algo = kalman_algo; 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_ global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_
fval = []; fval = [];
ys = []; ys = [];
trend_coeff = []; trend_coeff = [];
llik = NaN; llik = NaN;
cost_flag = 1; cost_flag = 1;
nobs = size(options_.varobs,1); nobs = size(options_.varobs,1);
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 1. Get the structural parameters & define penalties % 1. Get the structural parameters & define penalties
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb) if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
k = find(xparam1 < bayestopt_.lb); k = find(xparam1 < bayestopt_.lb);
fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2); fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
cost_flag = 0; cost_flag = 0;
info = 41; info = 41;
return; return;
end end
if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub) if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
k = find(xparam1 > bayestopt_.ub); k = find(xparam1 > bayestopt_.ub);
fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2); fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
cost_flag = 0; cost_flag = 0;
info = 42; info = 42;
return; return;
end end
Q = M_.Sigma_e; Q = M_.Sigma_e;
H = M_.H; H = M_.H;
for i=1:estim_params_.nvx for i=1:estim_params_.nvx
k =estim_params_.var_exo(i,1); k =estim_params_.var_exo(i,1);
Q(k,k) = xparam1(i)*xparam1(i); Q(k,k) = xparam1(i)*xparam1(i);
end end
offset = estim_params_.nvx; offset = estim_params_.nvx;
if estim_params_.nvn if estim_params_.nvn
for i=1:estim_params_.nvn for i=1:estim_params_.nvn
k = estim_params_.var_endo(i,1); k = estim_params_.var_endo(i,1);
H(k,k) = xparam1(i+offset)*xparam1(i+offset); H(k,k) = xparam1(i+offset)*xparam1(i+offset);
end end
offset = offset+estim_params_.nvn; offset = offset+estim_params_.nvn;
end end
if estim_params_.ncx if estim_params_.ncx
for i=1:estim_params_.ncx for i=1:estim_params_.ncx
k1 =estim_params_.corrx(i,1); k1 =estim_params_.corrx(i,1);
k2 =estim_params_.corrx(i,2); k2 =estim_params_.corrx(i,2);
Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2)); Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
Q(k2,k1) = Q(k1,k2); Q(k2,k1) = Q(k1,k2);
end end
[CholQ,testQ] = chol(Q); [CholQ,testQ] = chol(Q);
if testQ %% The variance-covariance matrix of the structural innovations is not definite positive. 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. %% We have to compute the eigenvalues of this matrix in order to build the penalty.
a = diag(eig(Q)); a = diag(eig(Q));
k = find(a < 0); k = find(a < 0);
if k > 0 if k > 0
fval = bayestopt_.penalty+sum(-a(k)); fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0; cost_flag = 0;
info = 43; info = 43;
return return
end end
end end
offset = offset+estim_params_.ncx; offset = offset+estim_params_.ncx;
end end
if estim_params_.ncn if estim_params_.ncn
for i=1:estim_params_.ncn for i=1:estim_params_.ncn
k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1)); k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2)); k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
H(k2,k1) = H(k1,k2); H(k2,k1) = H(k1,k2);
end end
[CholH,testH] = chol(H); [CholH,testH] = chol(H);
if testH if testH
a = diag(eig(H)); a = diag(eig(H));
k = find(a < 0); k = find(a < 0);
if k > 0 if k > 0
fval = bayestopt_.penalty+sum(-a(k)); fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0; cost_flag = 0;
info = 44; info = 44;
return return
end end
end end
offset = offset+estim_params_.ncn; offset = offset+estim_params_.ncn;
end end
if estim_params_.np > 0 if estim_params_.np > 0
M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
end end
M_.Sigma_e = Q; M_.Sigma_e = Q;
M_.H = H; M_.H = H;
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 2. call model setup & reduction program % 2. call model setup & reduction program
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,... [T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
bayestopt_.restrict_columns,... bayestopt_.restrict_columns,...
bayestopt_.restrict_aux); bayestopt_.restrict_aux);
if info(1) == 1 | info(1) == 2 | info(1) == 5 if info(1) == 1 | info(1) == 2 | info(1) == 5
fval = bayestopt_.penalty+1; fval = bayestopt_.penalty+1;
cost_flag = 0; cost_flag = 0;
return 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 fval = bayestopt_.penalty+info(2);%^2; % penalty power raised in DR1.m and resol already. GP July'08
cost_flag = 0; cost_flag = 0;
return return
end end
bayestopt_.mf = bayestopt_.mf1; bayestopt_.mf = bayestopt_.mf1;
if ~options_.noconstant if ~options_.noconstant
if options_.loglinear == 1 if options_.loglinear == 1
constant = log(SteadyState(bayestopt_.mfys)); constant = log(SteadyState(bayestopt_.mfys));
else else
constant = SteadyState(bayestopt_.mfys); constant = SteadyState(bayestopt_.mfys);
end end
else else
constant = zeros(nobs,1); constant = zeros(nobs,1);
end end
if bayestopt_.with_trend == 1 if bayestopt_.with_trend == 1
trend_coeff = zeros(nobs,1); trend_coeff = zeros(nobs,1);
t = options_.trend_coeffs; t = options_.trend_coeffs;
for i=1:length(t) for i=1:length(t)
if ~isempty(t{i}) if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i}); trend_coeff(i) = evalin('base',t{i});
end end
end end
trend = repmat(constant,1,gend)+trend_coeff*[1:gend]; trend = repmat(constant,1,gend)+trend_coeff*[1:gend];
else else
trend = repmat(constant,1,gend); trend = repmat(constant,1,gend);
end end
start = options_.presample+1; start = options_.presample+1;
np = size(T,1); np = size(T,1);
mf = bayestopt_.mf; mf = bayestopt_.mf;
no_missing_data_flag = (number_of_observations==gend*nobs); no_missing_data_flag = (number_of_observations==gend*nobs);
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter % 3. Initial condition of the Kalman filter
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
kalman_algo = options_.kalman_algo; kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2 if kalman_algo ~= 2
kalman_algo = 1; kalman_algo = 1;
end end
Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold); Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = []; Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2 if kalman_algo ~= 2
kalman_algo = 1; kalman_algo = 1;
end end
Pstar = options_.Harvey_scale_factor*eye(np); Pstar = options_.Harvey_scale_factor*eye(np);
Pinf = []; Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4 if kalman_algo ~= 4
kalman_algo = 3; kalman_algo = 3;
end end
[QT,ST] = schur(T); [QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1); [QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k); nk = length(k);
nk1 = nk+1; nk1 = nk+1;
Pinf = zeros(np,np); Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk); Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np); Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT; B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2 for i=np:-1:nk+2
if ST(i,i-1) == 0 if ST(i,i-1) == 0
if i == np if i == np
c = zeros(np-nk,1); c = zeros(np-nk,1);
else else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... 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)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else else
if i == np if i == np
c = zeros(np-nk,1); c = zeros(np-nk,1);
c1 = zeros(np-nk,1); c1 = zeros(np-nk,1);
else else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... 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)*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); 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)')+... 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-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); ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... 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)]; -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]; 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) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end); Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1; i = i - 1;
end end
end end
if i == nk+2 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); 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)); Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end end
Z = QT(mf,:); Z = QT(mf,:);
R1 = QT'*R; R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0); [QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8); k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
if length(k) > 0 if length(k) > 0
k1 = EE(:,k); k1 = EE(:,k);
dd =ones(nk,1); dd =ones(nk,1);
dd(k1) = zeros(length(k1),1); dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd); Pinf(1:nk,1:nk) = diag(dd);
end end
end end
if kalman_algo == 2 if kalman_algo == 2
no_correlation_flag = 1; no_correlation_flag = 1;
if length(H)==1 if length(H)==1
H = zeros(nobs,1); H = zeros(nobs,1);
else else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H); H = diag(H);
else else
no_correlation_flag = 1; no_correlation_flag = 1;
end end
end end
end end
kalman_tol = options_.kalman_tol; kalman_tol = options_.kalman_tol;
riccati_tol = options_.riccati_tol; riccati_tol = options_.riccati_tol;
mf = bayestopt_.mf1; mf = bayestopt_.mf1;
Y = data-trend; Y = data-trend;
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 4. Likelihood evaluation % 4. Likelihood evaluation
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
if (kalman_algo==1)% Multivariate Kalman Filter if (kalman_algo==1)% Multivariate Kalman Filter
if no_missing_data_flag if no_missing_data_flag
[LIK, lik] = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); [LIK, lik] = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol);
else else
[LIK, lik] = ... [LIK, lik] = ...
missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ... 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); data_index,number_of_observations,no_more_missing_observations);
end end
if isinf(LIK) if isinf(LIK)
kalman_algo = 2; kalman_algo = 2;
end end
end end
if (kalman_algo==2)% Univariate Kalman Filter if (kalman_algo==2)% Univariate Kalman Filter
if no_correlation_flag 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); [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 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); [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
end end
if (kalman_algo==3)% Multivariate Diffuse Kalman Filter if (kalman_algo==3)% Multivariate Diffuse Kalman Filter
if no_missing_data_flag if no_missing_data_flag
data1 = data - trend; data1 = data - trend;
if any(any(H ~= 0)) if any(any(H ~= 0))
[LIK, lik] = DiffuseLikelihoodH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,start); [LIK, lik] = DiffuseLikelihoodH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,start);
else else
[LIK, lik] = DiffuseLikelihood1_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start); [LIK, lik] = DiffuseLikelihood1_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start);
end end
if isinf(LIK) if isinf(LIK)
kalman_algo = 4; kalman_algo = 4;
end end
else else
error(['The diffuse filter is not yet implemented for models with missing observations']) error(['The diffuse filter is not yet implemented for models with missing observations'])
end end
end end
if (kalman_algo==4)% Univariate Diffuse Kalman Filter if (kalman_algo==4)% Univariate Diffuse Kalman Filter
data1 = data - trend; data1 = data - trend;
if any(any(H ~= 0)) if any(any(H ~= 0))
if ~estim_params_.ncn if ~estim_params_.ncn
[LIK, lik] = DiffuseLikelihoodH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start); [LIK, lik] = DiffuseLikelihoodH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start);
else else
[LIK, lik] = DiffuseLikelihoodH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start); [LIK, lik] = DiffuseLikelihoodH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start);
end end
else else
[LIK, lik] = DiffuseLikelihood3_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start); [LIK, lik] = DiffuseLikelihood3_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start);
end end
end end
if imag(LIK) ~= 0 if imag(LIK) ~= 0
likelihood = bayestopt_.penalty; likelihood = bayestopt_.penalty;
else else
likelihood = LIK; likelihood = LIK;
end end
% ------------------------------------------------------------------------------ % ------------------------------------------------------------------------------
% Adds prior if necessary % Adds prior if necessary
% ------------------------------------------------------------------------------ % ------------------------------------------------------------------------------
lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
fval = (likelihood-lnprior); fval = (likelihood-lnprior);
options_.kalman_algo = kalman_algo; options_.kalman_algo = kalman_algo;
llik=[-lnprior; lik(start:end)]; 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ M_ oo_ estim_params_ options_ global bayestopt_ M_ oo_ estim_params_ options_
alphahat = []; alphahat = [];
etahat = []; etahat = [];
epsilonhat = []; epsilonhat = [];
ahat = []; ahat = [];
SteadyState = []; SteadyState = [];
trend_coeff = []; trend_coeff = [];
aK = []; aK = [];
T = []; T = [];
R = []; R = [];
P = []; P = [];
PK = []; PK = [];
d = []; d = [];
decomp = []; decomp = [];
nobs = size(options_.varobs,1); nobs = size(options_.varobs,1);
smpl = size(Y,2); smpl = size(Y,2);
set_all_parameters(xparam1); set_all_parameters(xparam1);
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 2. call model setup & reduction program % 2. call model setup & reduction program
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
[T,R,SteadyState] = dynare_resolve; [T,R,SteadyState] = dynare_resolve;
bayestopt_.mf = bayestopt_.mf2; bayestopt_.mf = bayestopt_.mf2;
if options_.noconstant if options_.noconstant
constant = zeros(nobs,1); constant = zeros(nobs,1);
else else
if options_.loglinear == 1 if options_.loglinear == 1
constant = log(SteadyState(bayestopt_.mfys)); constant = log(SteadyState(bayestopt_.mfys));
else else
constant = SteadyState(bayestopt_.mfys); constant = SteadyState(bayestopt_.mfys);
end end
end end
trend_coeff = zeros(nobs,1); trend_coeff = zeros(nobs,1);
if bayestopt_.with_trend == 1 if bayestopt_.with_trend == 1
trend_coeff = zeros(nobs,1); trend_coeff = zeros(nobs,1);
t = options_.trend_coeffs; t = options_.trend_coeffs;
for i=1:length(t) for i=1:length(t)
if ~isempty(t{i}) if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i}); trend_coeff(i) = evalin('base',t{i});
end end
end end
trend = constant*ones(1,gend)+trend_coeff*(1:gend); trend = constant*ones(1,gend)+trend_coeff*(1:gend);
else else
trend = constant*ones(1,gend); trend = constant*ones(1,gend);
end end
start = options_.presample+1; start = options_.presample+1;
np = size(T,1); np = size(T,1);
mf = bayestopt_.mf; mf = bayestopt_.mf;
% ------------------------------------------------------------------------------ % ------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter % 3. Initial condition of the Kalman filter
% ------------------------------------------------------------------------------ % ------------------------------------------------------------------------------
% %
% C'est ici qu'il faut déterminer Pinf et Pstar. Si le modèle est stationnaire, % 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 % alors il suffit de poser Pstar comme la solution de l'éuation de Lyapounov et
% Pinf=[]. % Pinf=[].
% %
Q = M_.Sigma_e; Q = M_.Sigma_e;
H = M_.H; H = M_.H;
kalman_algo = options_.kalman_algo; kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2 if kalman_algo ~= 2
kalman_algo = 1; kalman_algo = 1;
end end
Pstar = lyapunov_symm(T,R*Q*transpose(R),options_.qz_criterium,options_.lyapunov_complex_threshold); Pstar = lyapunov_symm(T,R*Q*transpose(R),options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = []; Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2 if kalman_algo ~= 2
kalman_algo = 1; kalman_algo = 1;
end end
Pstar = options_.Harvey_scale_factor*eye(np); Pstar = options_.Harvey_scale_factor*eye(np);
Pinf = []; Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4 if kalman_algo ~= 4
kalman_algo = 3; kalman_algo = 3;
end end
[QT,ST] = schur(T); [QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1); [QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k); nk = length(k);
nk1 = nk+1; nk1 = nk+1;
Pinf = zeros(np,np); Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk); Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np); Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT; B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2 for i=np:-1:nk+2
if ST(i,i-1) == 0 if ST(i,i-1) == 0
if i == np if i == np
c = zeros(np-nk,1); c = zeros(np-nk,1);
else else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... 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)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else else
if i == np if i == np
c = zeros(np-nk,1); c = zeros(np-nk,1);
c1 = zeros(np-nk,1); c1 = zeros(np-nk,1);
else else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... 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)*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); 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)')+... 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-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); ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... 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)]; -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]; 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) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end); Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1; i = i - 1;
end end
end end
if i == nk+2 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); 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)); Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end end
Z = QT(mf,:); Z = QT(mf,:);
R1 = QT'*R; R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0); [QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8); k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
if length(k) > 0 if length(k) > 0
k1 = EE(:,k); k1 = EE(:,k);
dd =ones(nk,1); dd =ones(nk,1);
dd(k1) = zeros(length(k1),1); dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd); Pinf(1:nk,1:nk) = diag(dd);
end end
end end
% ----------------------------------------------------------------------------- % -----------------------------------------------------------------------------
% 4. Kalman smoother % 4. Kalman smoother
% ----------------------------------------------------------------------------- % -----------------------------------------------------------------------------
if any(any(H ~= 0)) % should be replaced by a flag if any(any(H ~= 0)) % should be replaced by a flag
if kalman_algo == 1 if kalman_algo == 1
[alphahat,epsilonhat,etahat,ahat,aK] = ... [alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH1(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf); DiffuseKalmanSmootherH1(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
if all(alphahat(:)==0) if all(alphahat(:)==0)
kalman_algo = 2; kalman_algo = 2;
if ~estim_params_.ncn if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,aK] = ... [alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf); DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
else else
[alphahat,epsilonhat,etahat,ahat,aK] = ... [alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ... DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ...
nobs,np,smpl,mf); nobs,np,smpl,mf);
end end
end end
elseif options_.kalman_algo == 2 elseif options_.kalman_algo == 2
if ~estim_params_.ncn if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,aK] = ... [alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf); DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
else else
[alphahat,epsilonhat,etahat,ahat,aK] = ... [alphahat,epsilonhat,etahat,ahat,aK] = ...
DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ... DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ...
nobs,np,smpl,mf); nobs,np,smpl,mf);
end end
elseif kalman_algo == 3 | kalman_algo == 4 elseif kalman_algo == 3 | kalman_algo == 4
data1 = Y - trend; data1 = Y - trend;
if kalman_algo == 3 if kalman_algo == 3
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl); DiffuseKalmanSmootherH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl);
if all(alphahat(:)==0) if all(alphahat(:)==0)
kalman_algo = 4; kalman_algo = 4;
if ~estim_params_.ncn if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl); DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl);
else else
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ... DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ...
nobs,np,smpl); nobs,np,smpl);
end end
end end
else else
if ~estim_params_.ncn if ~estim_params_.ncn
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ... DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ...
nobs,np,smpl); nobs,np,smpl);
else else
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ...
DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ... DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ...
nobs,np,smpl); nobs,np,smpl);
end end
end end
alphahat = QT*alphahat; alphahat = QT*alphahat;
ahat = QT*ahat; ahat = QT*ahat;
nk = options_.nk; nk = options_.nk;
for jnk=1:nk for jnk=1:nk
aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:)); aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:));
for i=1:size(PK,4) for i=1:size(PK,4)
PK(jnk,:,:,i) = QT*squeeze(PK(jnk,:,:,i))*QT'; PK(jnk,:,:,i) = QT*squeeze(PK(jnk,:,:,i))*QT';
end end
for i=1:size(decomp,4) for i=1:size(decomp,4)
decomp(jnk,:,:,i) = QT*squeeze(decomp(jnk,:,:,i)); decomp(jnk,:,:,i) = QT*squeeze(decomp(jnk,:,:,i));
end end
end end
for i=1:size(P,4) for i=1:size(P,4)
P(:,:,i) = QT*squeeze(P(:,:,i))*QT'; P(:,:,i) = QT*squeeze(P(:,:,i))*QT';
end end
end end
else else
if kalman_algo == 1 if kalman_algo == 1
if missing_value if missing_value
[alphahat,etahat,ahat,aK] = missing_DiffuseKalmanSmoother1(T,R,Q, ... [alphahat,etahat,ahat,aK] = missing_DiffuseKalmanSmoother1(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index); Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index);
else else
[alphahat,etahat,ahat,aK] = DiffuseKalmanSmoother1(T,R,Q, ... [alphahat,etahat,ahat,aK] = DiffuseKalmanSmoother1(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf); Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
end end
if all(alphahat(:)==0) if all(alphahat(:)==0)
kalman_algo = 2; kalman_algo = 2;
end end
end end
if kalman_algo == 2 if kalman_algo == 2
if missing_value if missing_value
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3(T,R,Q, ... [alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index); Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index);
else else
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3(T,R,Q, ... [alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3(T,R,Q, ...
Pinf,Pstar,Y,trend,nobs,np,smpl,mf); Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
end end
end end
if kalman_algo == 3 if kalman_algo == 3
data1 = Y - trend; data1 = Y - trend;
if missing_value if missing_value
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother1_Z(ST, ... [alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother1_Z(ST, ...
Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index); Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index);
else else
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother1_Z(ST, ... [alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother1_Z(ST, ...
Z,R1,Q,Pinf,Pstar, ... Z,R1,Q,Pinf,Pstar, ...
data1,nobs,np,smpl); data1,nobs,np,smpl);
end end
if all(alphahat(:)==0) if all(alphahat(:)==0)
options_.kalman_algo = 4; options_.kalman_algo = 4;
end end
end end
if kalman_algo == 4 if kalman_algo == 4
data1 = Y - trend; data1 = Y - trend;
if missing_value if missing_value
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3_Z(ST, ... [alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3_Z(ST, ...
Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index); Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index);
else else
[alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3_Z(ST, ... [alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3_Z(ST, ...
Z,R1,Q,Pinf,Pstar, ... Z,R1,Q,Pinf,Pstar, ...
data1,nobs,np,smpl); data1,nobs,np,smpl);
end end
end end
if kalman_algo == 3 | kalman_algo == 4 if kalman_algo == 3 | kalman_algo == 4
alphahat = QT*alphahat; alphahat = QT*alphahat;
ahat = QT*ahat; ahat = QT*ahat;
nk = options_.nk; nk = options_.nk;
% $$$ if M_.exo_nbr<2 % Fix the crash of Dynare when the estimated model has only one structural shock (problem with % $$$ 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). % $$$ % the squeeze function, that does not affect 2D arrays).
% $$$ size_decomp = 0; % $$$ size_decomp = 0;
% $$$ else % $$$ else
% $$$ size_decomp = size(decomp,4); % $$$ size_decomp = size(decomp,4);
% $$$ end % $$$ end
for jnk=1:nk for jnk=1:nk
aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:)); aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:));
for i=1:size(PK,4) for i=1:size(PK,4)
PK(jnk,:,:,i) = QT*dynare_squeeze(PK(jnk,:,:,i))*QT'; PK(jnk,:,:,i) = QT*dynare_squeeze(PK(jnk,:,:,i))*QT';
end end
for i=1:size(decomp,4) for i=1:size(decomp,4)
decomp(jnk,:,:,i) = QT*dynare_squeeze(decomp(jnk,:,:,i)); decomp(jnk,:,:,i) = QT*dynare_squeeze(decomp(jnk,:,:,i));
end end
end end
for i=1:size(P,4) for i=1:size(P,4)
P(:,:,i) = QT*dynare_squeeze(P(:,:,i))*QT'; P(:,:,i) = QT*dynare_squeeze(P(:,:,i))*QT';
end end
end end
end end

View File

@ -146,15 +146,15 @@ TheoreticalAutoCovarianceOfTheObservedVariables = ...
zeros(NumberOfObservedVariables,NumberOfObservedVariables,NumberOfLags+1); zeros(NumberOfObservedVariables,NumberOfObservedVariables,NumberOfLags+1);
TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) = tmp0(mf,mf)+constant'*constant; TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) = tmp0(mf,mf)+constant'*constant;
for lag = 1:NumberOfLags for lag = 1:NumberOfLags
tmp0 = T*tmp0; tmp0 = T*tmp0;
TheoreticalAutoCovarianceOfTheObservedVariables(:,:,lag+1) = tmp0(mf,mf) ... TheoreticalAutoCovarianceOfTheObservedVariables(:,:,lag+1) = tmp0(mf,mf) ...
+ constant'*constant; + constant'*constant;
end end
% Build the theoretical "covariance" between Y and X % Build the theoretical "covariance" between Y and X
GYX = zeros(NumberOfObservedVariables,NumberOfParameters); GYX = zeros(NumberOfObservedVariables,NumberOfParameters);
for i=1:NumberOfLags for i=1:NumberOfLags
GYX(:,(i-1)*NumberOfObservedVariables+1:i*NumberOfObservedVariables) = ... GYX(:,(i-1)*NumberOfObservedVariables+1:i*NumberOfObservedVariables) = ...
TheoreticalAutoCovarianceOfTheObservedVariables(:,:,i+1); TheoreticalAutoCovarianceOfTheObservedVariables(:,:,i+1);
end end
if ~options_.noconstant if ~options_.noconstant
GYX(:,end) = constant'; GYX(:,end) = constant';
@ -181,41 +181,41 @@ assignin('base','GXX',GXX);
assignin('base','GYX',GYX); assignin('base','GYX',GYX);
if ~isinf(dsge_prior_weight) if ~isinf(dsge_prior_weight)
tmp0 = dsge_prior_weight*gend*TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) + mYY ; tmp0 = dsge_prior_weight*gend*TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) + mYY ;
tmp1 = dsge_prior_weight*gend*GYX + mYX; tmp1 = dsge_prior_weight*gend*GYX + mYX;
tmp2 = inv(dsge_prior_weight*gend*GXX+mXX); tmp2 = inv(dsge_prior_weight*gend*GXX+mXX);
SIGMAu = tmp0 - tmp1*tmp2*tmp1'; clear('tmp0'); SIGMAu = tmp0 - tmp1*tmp2*tmp1'; clear('tmp0');
if ~ispd(SIGMAu) if ~ispd(SIGMAu)
v = diag(SIGMAu); v = diag(SIGMAu);
k = find(v<0); k = find(v<0);
fval = bayestopt_.penalty + sum(v(k).^2); fval = bayestopt_.penalty + sum(v(k).^2);
info = 52; info = 52;
cost_flag = 0; cost_flag = 0;
return; return;
end end
SIGMAu = SIGMAu / (gend*(1+dsge_prior_weight)); SIGMAu = SIGMAu / (gend*(1+dsge_prior_weight));
PHI = tmp2*tmp1'; clear('tmp1'); PHI = tmp2*tmp1'; clear('tmp1');
prodlng1 = sum(gammaln(.5*((1+dsge_prior_weight)*gend- ... prodlng1 = sum(gammaln(.5*((1+dsge_prior_weight)*gend- ...
NumberOfObservedVariables*NumberOfLags ... NumberOfObservedVariables*NumberOfLags ...
+1-(1:NumberOfObservedVariables)'))); +1-(1:NumberOfObservedVariables)')));
prodlng2 = sum(gammaln(.5*(dsge_prior_weight*gend- ... prodlng2 = sum(gammaln(.5*(dsge_prior_weight*gend- ...
NumberOfObservedVariables*NumberOfLags ... NumberOfObservedVariables*NumberOfLags ...
+1-(1:NumberOfObservedVariables)'))); +1-(1:NumberOfObservedVariables)')));
lik = .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX+mXX)) ... 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*((dsge_prior_weight+1)*gend-NumberOfParameters)*log(det((dsge_prior_weight+1)*gend*SIGMAu)) ...
- .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX)) ... - .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*(dsge_prior_weight*gend-NumberOfParameters)*log(det(dsge_prior_weight*gend*(GYY-GYX*inv(GXX)*GYX'))) ...
+ .5*NumberOfObservedVariables*gend*log(2*pi) ... + .5*NumberOfObservedVariables*gend*log(2*pi) ...
- .5*log(2)*NumberOfObservedVariables*((dsge_prior_weight+1)*gend-NumberOfParameters) ... - .5*log(2)*NumberOfObservedVariables*((dsge_prior_weight+1)*gend-NumberOfParameters) ...
+ .5*log(2)*NumberOfObservedVariables*(dsge_prior_weight*gend-NumberOfParameters) ... + .5*log(2)*NumberOfObservedVariables*(dsge_prior_weight*gend-NumberOfParameters) ...
- prodlng1 + prodlng2; - prodlng1 + prodlng2;
else else
iGXX = inv(GXX); iGXX = inv(GXX);
SIGMAu = GYY - GYX*iGXX*transpose(GYX); SIGMAu = GYY - GYX*iGXX*transpose(GYX);
PHI = iGXX*transpose(GYX); PHI = iGXX*transpose(GYX);
lik = gend * ( log(det(SIGMAu)) + NumberOfObservedVariables*log(2*pi) + ... lik = gend * ( log(det(SIGMAu)) + NumberOfObservedVariables*log(2*pi) + ...
trace(inv(SIGMAu)*(mYY - transpose(mYX*PHI) - mYX*PHI + transpose(PHI)*mXX*PHI)/gend)); trace(inv(SIGMAu)*(mYY - transpose(mYX*PHI) - mYX*PHI + transpose(PHI)*mXX*PHI)/gend));
lik = .5*lik;% Minus likelihood lik = .5*lik;% Minus likelihood
end end
lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); 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, blck)
% function Draws = GetAllPosteriorDraws(column,FirstMhFile,FirstLine,TotalNumberOfMhFile,NumberOfDraws) % function Draws = GetAllPosteriorDraws(column,FirstMhFile,FirstLine,TotalNumberOfMhFile,NumberOfDraws)
% Gets all posterior draws % Gets all posterior draws
% %
% INPUTS % INPUTS
% column: column % column: column
% FirstMhFile: first mh file % FirstMhFile: first mh file
% FirstLine: first line % FirstLine: first line
% TotalNumberOfMhFile: total number of mh file % TotalNumberOfMhFile: total number of mh file
% NumberOfDraws: number of draws % NumberOfDraws: number of draws
% OUTPUTS % OUTPUTS
% Draws: draws from posterior distribution % Draws: draws from posterior distribution
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2005-2008 Dynare Team % Copyright (C) 2005-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ global M_ options_
nblck = options_.mh_nblck; nblck = options_.mh_nblck;
iline = FirstLine; iline = FirstLine;
linee = 1; linee = 1;
DirectoryName = CheckPath('metropolis'); DirectoryName = CheckPath('metropolis');
if nblck>1 && nargin<6 if nblck>1 && nargin<6
Draws = zeros(NumberOfDraws*nblck,1); Draws = zeros(NumberOfDraws*nblck,1);
iline0=iline; iline0=iline;
if column>0 if column>0
for blck = 1:nblck for blck = 1:nblck
iline=iline0; iline=iline0;
for file = FirstMhFile:TotalNumberOfMhFile for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2') load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2')
NumberOfLines = size(x2(iline:end,:),1); NumberOfLines = size(x2(iline:end,:),1);
Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column); Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column);
linee = linee+NumberOfLines; linee = linee+NumberOfLines;
iline = 1; iline = 1;
end end
end end
else else
for blck = 1:nblck for blck = 1:nblck
iline=iline0; iline=iline0;
for file = FirstMhFile:TotalNumberOfMhFile for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2') load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2')
NumberOfLines = size(logpo2(iline:end),1); NumberOfLines = size(logpo2(iline:end),1);
Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end); Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end);
linee = linee+NumberOfLines; linee = linee+NumberOfLines;
iline = 1; iline = 1;
end end
end end
end end
else else
if nblck==1 if nblck==1
blck=1; blck=1;
end end
if column>0 if column>0
for file = FirstMhFile:TotalNumberOfMhFile for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2') load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2')
NumberOfLines = size(x2(iline:end,:),1); NumberOfLines = size(x2(iline:end,:),1);
Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column); Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column);
linee = linee+NumberOfLines; linee = linee+NumberOfLines;
iline = 1; iline = 1;
end end
else else
for file = FirstMhFile:TotalNumberOfMhFile for file = FirstMhFile:TotalNumberOfMhFile
load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2') load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2')
NumberOfLines = size(logpo2(iline:end,:),1); NumberOfLines = size(logpo2(iline:end,:),1);
Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end); Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end);
linee = linee+NumberOfLines; linee = linee+NumberOfLines;
iline = 1; iline = 1;
end end
end end
end end

View File

@ -1,39 +1,39 @@
function [xparams, logpost] = GetOneDraw(type) function [xparams, logpost] = GetOneDraw(type)
% function [xparams, logpost] = GetOneDraw(type) % function [xparams, logpost] = GetOneDraw(type)
% draws one row from metropolis % draws one row from metropolis
% %
% INPUTS % INPUTS
% type: posterior % type: posterior
% prior % prior
% %
% OUTPUTS % OUTPUTS
% xparams: vector of estimated parameters (drawn from posterior distribution) % xparams: vector of estimated parameters (drawn from posterior distribution)
% logpost: log of the posterior density relative to this row % logpost: log of the posterior density relative to this row
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2005-2008 Dynare Team % Copyright (C) 2005-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
switch type switch type
case 'posterior' case 'posterior'
[xparams, logpost] = metropolis_draw(0); [xparams, logpost] = metropolis_draw(0);
case 'prior' case 'prior'
xparams = prior_draw(0); xparams = prior_draw(0);
end end

View File

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

View File

@ -1,169 +1,169 @@
function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info) function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info)
% Copyright (C) 2005 Dynare Team % Copyright (C) 2005 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ global M_ options_
FigHandle = figure('Name',FigureProperties.Name); FigHandle = figure('Name',FigureProperties.Name);
NAMES = cell(NumberOfPlots,1); NAMES = cell(NumberOfPlots,1);
if options_.TeX if options_.TeX
TeXNAMES = cell(NumberOfPlots,1); TeXNAMES = cell(NumberOfPlots,1);
end end
if NumberOfPlots == 9 if NumberOfPlots == 9
nr = 3; nr = 3;
nc = 3; nc = 3;
elseif NumberOfPlots == 8 elseif NumberOfPlots == 8
nr = 3; nr = 3;
nc = 3; nc = 3;
elseif NumberOfPlots == 7 elseif NumberOfPlots == 7
nr = 3; nr = 3;
nc = 3; nc = 3;
elseif NumberOfPlots == 6 elseif NumberOfPlots == 6
nr = 2; nr = 2;
nc = 3; nc = 3;
elseif NumberOfPlots == 5 elseif NumberOfPlots == 5
nr = 3; nr = 3;
nc = 2; nc = 2;
elseif NumberOfPlots == 4 elseif NumberOfPlots == 4
nr = 2; nr = 2;
nc = 2; nc = 2;
elseif NumberOfPlots == 3 elseif NumberOfPlots == 3
nr = 2; nr = 2;
nc = 2; nc = 2;
elseif NumberOfPlots == 2 elseif NumberOfPlots == 2
nr = 1; nr = 1;
nc = 2; nc = 2;
elseif NumberOfPlots == 1 elseif NumberOfPlots == 1
nr = 1; nr = 1;
nc = 1; nc = 1;
end end
for plt = 1:NumberOfPlots for plt = 1:NumberOfPlots
eval(['NumberOfCurves = Info.Box' int2str(plt) '.Number;']) eval(['NumberOfCurves = Info.Box' int2str(plt) '.Number;'])
NumberOfObservations = zeros(2,1); NumberOfObservations = zeros(2,1);
x = cell(NumberOfCurves,1); x = cell(NumberOfCurves,1);
y = cell(NumberOfCurves,1); y = cell(NumberOfCurves,1);
PltType = cell(NumberofCurves,1); PltType = cell(NumberofCurves,1);
top = NaN(NumberOfCurves,1); top = NaN(NumberOfCurves,1);
bottom = NaN(NumberOfCurves,1); bottom = NaN(NumberOfCurves,1);
binf = NaN(NumberOfCurves,1); binf = NaN(NumberOfCurves,1);
bsup = NaN(NumberOfCurves,1); bsup = NaN(NumberOfCurves,1);
for curve = 1:NumberOfCurves for curve = 1:NumberOfCurves
eval(['x{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.xdata;']) eval(['x{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.xdata;'])
eval(['y{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.ydata;']) eval(['y{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.ydata;'])
eval(['name = Info.Box' int2str(plt) '.Curve' int2str(curve) '.variablename;']) eval(['name = Info.Box' int2str(plt) '.Curve' int2str(curve) '.variablename;'])
eval(['PltType{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.type']); eval(['PltType{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.type']);
if length(x{curve})-length(y{curve}) if length(x{curve})-length(y{curve})
disp('MakeFigure :: The number of observations in x doesn''t match with ') disp('MakeFigure :: The number of observations in x doesn''t match with ')
disp(['the number of observation in y for ' name ]) disp(['the number of observation in y for ' name ])
return return
end end
if Info.PlotProperties.CutTop if Info.PlotProperties.CutTop
top(curve) = max(y{curve}); top(curve) = max(y{curve});
else Info.PlotProperties.CutBottom else Info.PlotProperties.CutBottom
bottom(curve) = min(y{curve}); bottom(curve) = min(y{curve});
end end
binf(curve) = min(x{curve}); binf(curve) = min(x{curve});
bsup(curve) = max(x{curve}); bsup(curve) = max(x{curve});
end end
ymax = max(top); ymax = max(top);
ymin = min(bottom); ymin = min(bottom);
xmin = min(binf); xmin = min(binf);
xmax = max(bsup); xmax = max(bsup);
if isnan(ymin(plt)) if isnan(ymin(plt))
ymin = 0; ymin = 0;
end end
eval(['NAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.name;']) eval(['NAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.name;'])
if options_.TeX if options_.TeX
eval(['TeXNAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.texname;']) eval(['TeXNAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.texname;'])
end end
subplot(nr,nc,plt) subplot(nr,nc,plt)
hold on hold on
for curve = 1:NumberOfCurves for curve = 1:NumberOfCurves
hh = plot(x{curve},y{curve}); hh = plot(x{curve},y{curve});
if strcmpi(PltType{curve},'PriorDensity') if strcmpi(PltType{curve},'PriorDensity')
set(hh,'Color',[0.7 0.7 0.7],'LineStyle','-','LineWidth',2) set(hh,'Color',[0.7 0.7 0.7],'LineStyle','-','LineWidth',2)
% %
% %
elseif strcmpi(PltType{curve},'DensityEstimate') elseif strcmpi(PltType{curve},'DensityEstimate')
set(hh,'Color','k','LineStyle','-','LineWidth',2) set(hh,'Color','k','LineStyle','-','LineWidth',2)
% %
% %
elseif strcmpi(PltType{curve},'ModeEstimate') elseif strcmpi(PltType{curve},'ModeEstimate')
set(hh,'Color','g','LineStyle','--','LineWidth',2) set(hh,'Color','g','LineStyle','--','LineWidth',2)
% %
% %
elseif strcmpi(PltType{curve},'SmoothVariable') elseif strcmpi(PltType{curve},'SmoothVariable')
set(hh,'Color','k','LineStyle','-','LineWidth',2) set(hh,'Color','k','LineStyle','-','LineWidth',2)
% %
% %
elseif strcmpi(PltType{curve},'Deciles') elseif strcmpi(PltType{curve},'Deciles')
set(hh,'Color','g','LineStyle','-','LineWidth',1) set(hh,'Color','g','LineStyle','-','LineWidth',1)
% %
% %
elseif strcmpi(PltType{curve},'Forecasts') elseif strcmpi(PltType{curve},'Forecasts')
set(hh,'Color','','LineStyle','-','LineWidth',2) set(hh,'Color','','LineStyle','-','LineWidth',2)
% %
% %
elseif strcmpi(PltType{curve},'ForecastsHPD') elseif strcmpi(PltType{curve},'ForecastsHPD')
set(hh,'Color','k','LineStyle','-','LineWidth',1) set(hh,'Color','k','LineStyle','-','LineWidth',1)
% %
% %
elseif strcmpi(PltType{curve},'ForecastsDeciles') elseif strcmpi(PltType{curve},'ForecastsDeciles')
set(hh,'Color','g','LineStyle','-','LineWidth',1) set(hh,'Color','g','LineStyle','-','LineWidth',1)
% %
% %
elseif strcmpi(PltType{curve},'DiagnosticWithin') elseif strcmpi(PltType{curve},'DiagnosticWithin')
set(hh,'Color','b','LineStyle','-','LineWidth',2) set(hh,'Color','b','LineStyle','-','LineWidth',2)
% %
% %
elseif strcmpi(PltType{curve},'DiagnosticPooled') elseif strcmpi(PltType{curve},'DiagnosticPooled')
set(hh,'Color','r','LineStyle','-','LineWidth',2) set(hh,'Color','r','LineStyle','-','LineWidth',2)
% %
% %
end end
end end
axis([xmin xmax ymin ymax]) axis([xmin xmax ymin ymax])
title(NAMES{plt}) title(NAMES{plt})
drawnow drawnow
hold off hold off
end end
if Info.SaveFormat.Eps if Info.SaveFormat.Eps
if isempty(Info.SaveFormat.Name) if isempty(Info.SaveFormat.Name)
eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.eps']); eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.eps']);
else else
eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.eps']); eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.eps']);
end end
end end
if Info.SaveFormat.Pdf && ~exist('OCTAVE_VERSION') if Info.SaveFormat.Pdf && ~exist('OCTAVE_VERSION')
if isempty(Info.SaveFormat.Name) if isempty(Info.SaveFormat.Name)
eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number)]); eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number)]);
else else
eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name]); eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name]);
end end
end end
if Info.SaveFormat.Fig && ~exist('OCTAVE_VERSION') if Info.SaveFormat.Fig && ~exist('OCTAVE_VERSION')
if isempty(Info.SaveFormat.Name) if isempty(Info.SaveFormat.Name)
saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.fig']); saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.fig']);
else else
saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.fig']); saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.fig']);
end end
end end

View File

@ -1,94 +1,94 @@
function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab) function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab)
% Core functionality for MCMC Diagnostics, which can be parallelized % Core functionality for MCMC Diagnostics, which can be parallelized
% Copyright (C) 2005-2009 Dynare Team % Copyright (C) 2005-2009 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if nargin<4, if nargin<4,
whoiam=0; whoiam=0;
end end
struct2local(myinputs); struct2local(myinputs);
if ~exist('MhDirectoryName'), if ~exist('MhDirectoryName'),
MhDirectoryName = CheckPath('metropolis'); MhDirectoryName = CheckPath('metropolis');
end end
ALPHA = 0.2; % increase too much with the number of simulations. ALPHA = 0.2; % increase too much with the number of simulations.
tmp = zeros(NumberOfDraws*nblck,3); tmp = zeros(NumberOfDraws*nblck,3);
UDIAG = zeros(NumberOfLines,6,npar-fpar+1); UDIAG = zeros(NumberOfLines,6,npar-fpar+1);
if whoiam if whoiam
waitbarString = ['Please wait... McMCDiagnostics (' int2str(fpar) 'of' int2str(npar) ')...']; waitbarString = ['Please wait... McMCDiagnostics (' int2str(fpar) 'of' int2str(npar) ')...'];
if Parallel(ThisMatlab).Local, if Parallel(ThisMatlab).Local,
waitbarTitle=['Local ']; waitbarTitle=['Local '];
else else
waitbarTitle=[Parallel(ThisMatlab).PcName]; waitbarTitle=[Parallel(ThisMatlab).PcName];
end end
fMessageStatus(0,whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo); fMessageStatus(0,whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo);
end end
for j=fpar:npar, for j=fpar:npar,
fprintf(' Parameter %d... ',j); fprintf(' Parameter %d... ',j);
for b = 1:nblck for b = 1:nblck
startline = 0; startline = 0;
for n = 1:NumberOfMcFilesPerBlock for n = 1:NumberOfMcFilesPerBlock
%load([MhDirectoryName '/' mcfiles(n,1,b).name],'x2'); %load([MhDirectoryName '/' mcfiles(n,1,b).name],'x2');
load([MhDirectoryName '/' M_.fname '_mh',int2str(n),'_blck' int2str(b) ... load([MhDirectoryName '/' M_.fname '_mh',int2str(n),'_blck' int2str(b) ...
'.mat'],'x2'); '.mat'],'x2');
nx2 = size(x2,1); nx2 = size(x2,1);
tmp((b-1)*NumberOfDraws+startline+(1:nx2),1) = x2(:,j); tmp((b-1)*NumberOfDraws+startline+(1:nx2),1) = x2(:,j);
% clear x2; % clear x2;
startline = startline + nx2; startline = startline + nx2;
end end
% $$$ %load([MhDirectoryName '/' mcfiles(NumberOfMcFilesPerBlock,1,b).name],'x2'); % $$$ %load([MhDirectoryName '/' mcfiles(NumberOfMcFilesPerBlock,1,b).name],'x2');
% $$$ load([MhDirectoryName '/' M_.fname '_mh',int2str(NumberOfMcFilesPerBlock),'_blck' int2str(b) '.mat'],'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); % $$$ tmp((b-1)*NumberOfDraws+startline+1:(b-1)*NumberOfDraws+MAX_nruns*(LastFileNumber-1)+LastLineNumber,1) = x2(:,j);
% $$$ clear x2; % $$$ clear x2;
% $$$ startline = startline + LastLineNumber; % $$$ startline = startline + LastLineNumber;
end end
tmp(:,2) = kron(transpose(1:nblck),ones(NumberOfDraws,1)); tmp(:,2) = kron(transpose(1:nblck),ones(NumberOfDraws,1));
tmp(:,3) = kron(ones(nblck,1),time'); tmp(:,3) = kron(ones(nblck,1),time');
tmp = sortrows(tmp,1); tmp = sortrows(tmp,1);
ligne = 0; ligne = 0;
for iter = Origin:StepSize:NumberOfDraws for iter = Origin:StepSize:NumberOfDraws
ligne = ligne+1; ligne = ligne+1;
linea = ceil(0.5*iter); linea = ceil(0.5*iter);
n = iter-linea+1; n = iter-linea+1;
cinf = round(n*ALPHA/2); cinf = round(n*ALPHA/2);
csup = round(n*(1-ALPHA/2)); csup = round(n*(1-ALPHA/2));
CINF = round(nblck*n*ALPHA/2); CINF = round(nblck*n*ALPHA/2);
CSUP = round(nblck*n*(1-ALPHA/2)); CSUP = round(nblck*n*(1-ALPHA/2));
temp = tmp(find((tmp(:,3)>=linea) & (tmp(:,3)<=iter)),1:2); temp = tmp(find((tmp(:,3)>=linea) & (tmp(:,3)<=iter)),1:2);
UDIAG(ligne,1,j-fpar+1) = temp(CSUP,1)-temp(CINF,1); UDIAG(ligne,1,j-fpar+1) = temp(CSUP,1)-temp(CINF,1);
moyenne = mean(temp(:,1));%% Pooled mean. moyenne = mean(temp(:,1));%% Pooled mean.
UDIAG(ligne,3,j-fpar+1) = sum((temp(:,1)-moyenne).^2)/(nblck*n-1); 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); UDIAG(ligne,5,j-fpar+1) = sum(abs(temp(:,1)-moyenne).^3)/(nblck*n-1);
for i=1:nblck for i=1:nblck
pmet = temp(find(temp(:,2)==i)); pmet = temp(find(temp(:,2)==i));
UDIAG(ligne,2,j-fpar+1) = UDIAG(ligne,2,j-fpar+1) + pmet(csup,1)-pmet(cinf,1); UDIAG(ligne,2,j-fpar+1) = UDIAG(ligne,2,j-fpar+1) + pmet(csup,1)-pmet(cinf,1);
moyenne = mean(pmet,1); %% Within mean. 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,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); UDIAG(ligne,6,j-fpar+1) = UDIAG(ligne,6,j-fpar+1) + sum(abs(pmet(:,1)-moyenne).^3)/(n-1);
end end
end end
fprintf('Done! \n'); fprintf('Done! \n');
if whoiam, if whoiam,
waitbarString = [ 'Parameter ' int2str(j) '/' int2str(npar) ' done.']; waitbarString = [ 'Parameter ' int2str(j) '/' int2str(npar) ' done.'];
fMessageStatus((j-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo) fMessageStatus((j-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo)
end end
end end
myoutput.UDIAG = UDIAG; myoutput.UDIAG = UDIAG;

View File

@ -1,189 +1,189 @@
function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt_, oo_) function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt_, oo_)
% function PlotPosteriorDistributions() % function PlotPosteriorDistributions()
% plots posterior distributions % plots posterior distributions
% %
% INPUTS % INPUTS
% estim_params_ [structure] % estim_params_ [structure]
% M_ [structure] % M_ [structure]
% options_ [structure] % options_ [structure]
% bayestopt_ [structure] % bayestopt_ [structure]
% oo_ [structure] % oo_ [structure]
% %
% OUTPUTS % OUTPUTS
% oo_ [structure] % oo_ [structure]
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2005-2008 Dynare Team % Copyright (C) 2005-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
OutputDirectoryName = CheckPath('Output'); OutputDirectoryName = CheckPath('Output');
TeX = options_.TeX; TeX = options_.TeX;
nblck = options_.mh_nblck; nblck = options_.mh_nblck;
nvx = estim_params_.nvx; nvx = estim_params_.nvx;
nvn = estim_params_.nvn; nvn = estim_params_.nvn;
ncx = estim_params_.ncx; ncx = estim_params_.ncx;
ncn = estim_params_.ncn; ncn = estim_params_.ncn;
np = estim_params_.np ; np = estim_params_.np ;
npar = nvx+nvn+ncx+ncn+np; npar = nvx+nvn+ncx+ncn+np;
MaxNumberOfPlotPerFigure = 9;% The square root must be an integer! MaxNumberOfPlotPerFigure = 9;% The square root must be an integer!
nn = sqrt(MaxNumberOfPlotPerFigure); nn = sqrt(MaxNumberOfPlotPerFigure);
figurename = 'Priors and posteriors'; figurename = 'Priors and posteriors';
if TeX if TeX
fidTeX = fopen([OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors.TeX'],'w'); fidTeX = fopen([OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by PlotPosteriorDistributions.m (Dynare).\n'); fprintf(fidTeX,'%% TeX eps-loader file generated by PlotPosteriorDistributions.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']); fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n'); fprintf(fidTeX,' \n');
end end
figunumber = 0; figunumber = 0;
subplotnum = 0; subplotnum = 0;
for i=1:npar for i=1:npar
subplotnum = subplotnum+1; subplotnum = subplotnum+1;
if subplotnum == 1 if subplotnum == 1
figunumber = figunumber+1; figunumber = figunumber+1;
if options_.nograph if options_.nograph
hfig = figure('Name',figurename,'Visible','off'); hfig = figure('Name',figurename,'Visible','off');
else else
hfig = figure('Name',figurename); hfig = figure('Name',figurename);
end end
end end
if subplotnum == 1 if subplotnum == 1
if TeX if TeX
TeXNAMES = []; TeXNAMES = [];
end end
NAMES = []; NAMES = [];
end end
[nam,texnam] = get_the_name(i,TeX); [nam,texnam] = get_the_name(i,TeX);
NAMES = strvcat(NAMES,nam); NAMES = strvcat(NAMES,nam);
if TeX if TeX
TeXNAMES = strvcat(TeXNAMES,texnam); TeXNAMES = strvcat(TeXNAMES,texnam);
end end
[x2,f2,abscissa,dens,binf2,bsup2] = draw_prior_density(i,bayestopt_); [x2,f2,abscissa,dens,binf2,bsup2] = draw_prior_density(i,bayestopt_);
top2 = max(f2); top2 = max(f2);
if i <= nvx if i <= nvx
name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:)); name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:));
eval(['x1 = oo_.posterior_density.shocks_std.' name '(:,1);']) eval(['x1 = oo_.posterior_density.shocks_std.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.shocks_std.' name '(:,2);']) 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 '(:,1) = x2;'])
eval(['oo_.prior_density.shocks_std.' name '(:,2) = f2;']) eval(['oo_.prior_density.shocks_std.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.shocks_std.' name ';']) eval(['pmod = oo_.posterior_mode.shocks_std.' name ';'])
end end
elseif i <= nvx+nvn elseif i <= nvx+nvn
name = deblank(options_.varobs(estim_params_.var_endo(i-nvx,1),:)); name = deblank(options_.varobs(estim_params_.var_endo(i-nvx,1),:));
eval(['x1 = oo_.posterior_density.measurement_errors_std.' name '(:,1);']) eval(['x1 = oo_.posterior_density.measurement_errors_std.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.measurement_errors_std.' name '(:,2);']) eval(['f1 = oo_.posterior_density.measurement_errors_std.' name '(:,2);'])
eval(['oo_.prior_density.mearsurement_errors_std.' name '(:,1) = x2;']) eval(['oo_.prior_density.mearsurement_errors_std.' name '(:,1) = x2;'])
eval(['oo_.prior_density.measurement_errors_std.' name '(:,2) = f2;']) eval(['oo_.prior_density.measurement_errors_std.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.measurement_errors_std.' name ';']) eval(['pmod = oo_.posterior_mode.measurement_errors_std.' name ';'])
end end
elseif i <= nvx+nvn+ncx elseif i <= nvx+nvn+ncx
j = i - (nvx+nvn); j = i - (nvx+nvn);
k1 = estim_params_.corrx(j,1); k1 = estim_params_.corrx(j,1);
k2 = estim_params_.corrx(j,2); k2 = estim_params_.corrx(j,2);
name = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))]; name = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))];
eval(['x1 = oo_.posterior_density.shocks_corr.' name '(:,1);']) eval(['x1 = oo_.posterior_density.shocks_corr.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.shocks_corr.' name '(:,2);']) 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 '(:,1) = x2;'])
eval(['oo_.prior_density.shocks_corr.' name '(:,2) = f2;']) eval(['oo_.prior_density.shocks_corr.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.shocks_corr.' name ';']) eval(['pmod = oo_.posterior_mode.shocks_corr.' name ';'])
end end
elseif i <= nvx+nvn+ncx+ncn elseif i <= nvx+nvn+ncx+ncn
j = i - (nvx+nvn+ncx); j = i - (nvx+nvn+ncx);
k1 = estim_params_.corrn(j,1); k1 = estim_params_.corrn(j,1);
k2 = estim_params_.corrn(j,2); k2 = estim_params_.corrn(j,2);
name = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))]; name = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))];
eval(['x1 = oo_.posterior_density.measurement_errors_corr.' name '(:,1);']) eval(['x1 = oo_.posterior_density.measurement_errors_corr.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.measurement_errors_corr.' name '(:,2);']) eval(['f1 = oo_.posterior_density.measurement_errors_corr.' name '(:,2);'])
eval(['oo_.prior_density.mearsurement_errors_corr.' name '(:,1) = x2;']) eval(['oo_.prior_density.mearsurement_errors_corr.' name '(:,1) = x2;'])
eval(['oo_.prior_density.measurement_errors_corr.' name '(:,2) = f2;']) eval(['oo_.prior_density.measurement_errors_corr.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.measurement_errors_corr.' name ';']) eval(['pmod = oo_.posterior_mode.measurement_errors_corr.' name ';'])
end end
else else
j = i - (nvx+nvn+ncx+ncn); j = i - (nvx+nvn+ncx+ncn);
name = deblank(M_.param_names(estim_params_.param_vals(j,1),:)); name = deblank(M_.param_names(estim_params_.param_vals(j,1),:));
eval(['x1 = oo_.posterior_density.parameters.' name '(:,1);']) eval(['x1 = oo_.posterior_density.parameters.' name '(:,1);'])
eval(['f1 = oo_.posterior_density.parameters.' name '(:,2);']) eval(['f1 = oo_.posterior_density.parameters.' name '(:,2);'])
eval(['oo_.prior_density.parameters.' name '(:,1) = x2;']) eval(['oo_.prior_density.parameters.' name '(:,1) = x2;'])
eval(['oo_.prior_density.parameters.' name '(:,2) = f2;']) eval(['oo_.prior_density.parameters.' name '(:,2) = f2;'])
if options_.posterior_mode_estimation if options_.posterior_mode_estimation
eval(['pmod = oo_.posterior_mode.parameters.' name ';']) eval(['pmod = oo_.posterior_mode.parameters.' name ';'])
end end
end end
top1 = max(f1); top1 = max(f1);
top0 = max([top1;top2]); top0 = max([top1;top2]);
binf1 = x1(1); binf1 = x1(1);
bsup1 = x1(end); bsup1 = x1(end);
borneinf = min(binf1,binf2); borneinf = min(binf1,binf2);
bornesup = max(bsup1,bsup2); bornesup = max(bsup1,bsup2);
subplot(nn,nn,subplotnum) subplot(nn,nn,subplotnum)
hh = plot(x2,f2,'-k','linewidth',2); hh = plot(x2,f2,'-k','linewidth',2);
set(hh,'color',[0.7 0.7 0.7]); set(hh,'color',[0.7 0.7 0.7]);
hold on; hold on;
plot(x1,f1,'-k','linewidth',2); plot(x1,f1,'-k','linewidth',2);
if options_.posterior_mode_estimation if options_.posterior_mode_estimation
plot( [pmod pmod], [0.0 1.1*top0], '--g', 'linewidth', 2); plot( [pmod pmod], [0.0 1.1*top0], '--g', 'linewidth', 2);
end end
box on; box on;
axis([borneinf bornesup 0 1.1*top0]); axis([borneinf bornesup 0 1.1*top0]);
title(nam,'Interpreter','none'); title(nam,'Interpreter','none');
hold off; hold off;
drawnow drawnow
if subplotnum == MaxNumberOfPlotPerFigure | i == npar; if subplotnum == MaxNumberOfPlotPerFigure | i == npar;
eval(['print -depsc2 ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.eps']); eval(['print -depsc2 ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.eps']);
if ~exist('OCTAVE_VERSION') if ~exist('OCTAVE_VERSION')
eval(['print -dpdf ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber)]); eval(['print -dpdf ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber)]);
end end
if options_.nograph, if options_.nograph,
set(hfig,'Visible','on'); set(hfig,'Visible','on');
end end
if ~exist('OCTAVE_VERSION') if ~exist('OCTAVE_VERSION')
saveas(hfig,[OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.fig']); saveas(hfig,[OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.fig']);
end end
if TeX if TeX
fprintf(fidTeX,'\\begin{figure}[H]\n'); fprintf(fidTeX,'\\begin{figure}[H]\n');
for j = 1:size(NAMES,1) for j = 1:size(NAMES,1)
fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(j,:)),deblank(TeXNAMES(j,:))); fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(j,:)),deblank(TeXNAMES(j,:)));
end end
fprintf(fidTeX,'\\centering\n'); fprintf(fidTeX,'\\centering\n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_PriorsAndPosteriors%s}\n',M_.fname,int2str(figunumber)); fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_PriorsAndPosteriors%s}\n',M_.fname,int2str(figunumber));
fprintf(fidTeX,'\\caption{Priors and posteriors.}'); fprintf(fidTeX,'\\caption{Priors and posteriors.}');
fprintf(fidTeX,'\\label{Fig:PriorsAndPosteriors:%s}\n',int2str(figunumber)); fprintf(fidTeX,'\\label{Fig:PriorsAndPosteriors:%s}\n',int2str(figunumber));
fprintf(fidTeX,'\\end{figure}\n'); fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n'); fprintf(fidTeX,' \n');
if i == npar if i == npar
fprintf(fidTeX,'%% End of TeX file.\n'); fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX); fclose(fidTeX);
end end
end end
if options_.nograph, if options_.nograph,
close(hfig), close(hfig),
end end
subplotnum = 0; subplotnum = 0;
end end
end end

View File

@ -1,273 +1,273 @@
function PosteriorFilterSmootherAndForecast(Y,gend, type,data_index) function PosteriorFilterSmootherAndForecast(Y,gend, type,data_index)
% function PosteriorFilterSmootherAndForecast(Y,gend, type) % function PosteriorFilterSmootherAndForecast(Y,gend, type)
% Computes posterior filter smoother and forecasts % Computes posterior filter smoother and forecasts
% %
% INPUTS % INPUTS
% Y: data % Y: data
% gend: number of observations % gend: number of observations
% type: posterior % type: posterior
% prior % prior
% gsa % gsa
% %
% OUTPUTS % OUTPUTS
% none % none
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2005-2008 Dynare Team % Copyright (C) 2005-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_ estim_params_ oo_ M_ bayestopt_ global options_ estim_params_ oo_ M_ bayestopt_
nvx = estim_params_.nvx; nvx = estim_params_.nvx;
nvn = estim_params_.nvn; nvn = estim_params_.nvn;
ncx = estim_params_.ncx; ncx = estim_params_.ncx;
ncn = estim_params_.ncn; ncn = estim_params_.ncn;
np = estim_params_.np ; np = estim_params_.np ;
npar = nvx+nvn+ncx+ncn+np; npar = nvx+nvn+ncx+ncn+np;
offset = npar-np; offset = npar-np;
naK = length(options_.filter_step_ahead); naK = length(options_.filter_step_ahead);
%% %%
MaxNumberOfPlotPerFigure = 4;% The square root must be an integer! MaxNumberOfPlotPerFigure = 4;% The square root must be an integer!
MaxNumberOfBytes=options_.MaxNumberOfBytes; MaxNumberOfBytes=options_.MaxNumberOfBytes;
endo_nbr=M_.endo_nbr; endo_nbr=M_.endo_nbr;
exo_nbr=M_.exo_nbr; exo_nbr=M_.exo_nbr;
nvobs = size(options_.varobs,1); nvobs = size(options_.varobs,1);
nn = sqrt(MaxNumberOfPlotPerFigure); nn = sqrt(MaxNumberOfPlotPerFigure);
iendo = 1:endo_nbr; iendo = 1:endo_nbr;
i_last_obs = gend+(1-M_.maximum_endo_lag:0); i_last_obs = gend+(1-M_.maximum_endo_lag:0);
horizon = options_.forecast; horizon = options_.forecast;
maxlag = M_.maximum_endo_lag; maxlag = M_.maximum_endo_lag;
%% %%
CheckPath('Plots/'); CheckPath('Plots/');
DirectoryName = CheckPath('metropolis'); DirectoryName = CheckPath('metropolis');
load([ DirectoryName '/' M_.fname '_mh_history.mat']) load([ DirectoryName '/' M_.fname '_mh_history.mat'])
FirstMhFile = record.KeepedDraws.FirstMhFile; FirstMhFile = record.KeepedDraws.FirstMhFile;
FirstLine = record.KeepedDraws.FirstLine; FirstLine = record.KeepedDraws.FirstLine;
TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); LastMhFile = TotalNumberOfMhFiles; TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); LastMhFile = TotalNumberOfMhFiles;
TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); TotalNumberOfMhDraws = sum(record.MhDraws(:,1));
NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws);
clear record; clear record;
B = min(1200, round(0.25*NumberOfDraws)); B = min(1200, round(0.25*NumberOfDraws));
B = 200; B = 200;
%% %%
MAX_nruns = min(B,ceil(options_.MaxNumberOfBytes/(npar+2)/8)); MAX_nruns = min(B,ceil(options_.MaxNumberOfBytes/(npar+2)/8));
MAX_nsmoo = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*gend)/8)); MAX_nsmoo = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*gend)/8));
MAX_ninno = min(B,ceil(MaxNumberOfBytes/(exo_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)); MAX_nerro = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)*gend)/8));
if naK if naK
MAX_naK = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)* ... MAX_naK = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)* ...
length(options_.filter_step_ahead)*gend)/8)); length(options_.filter_step_ahead)*gend)/8));
end end
if horizon if horizon
MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8)); MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8));
MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ... MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ...
8)); 8));
IdObs = bayestopt_.mfys; IdObs = bayestopt_.mfys;
end end
%% %%
varlist = options_.varlist; varlist = options_.varlist;
if isempty(varlist) if isempty(varlist)
varlist = M_.endo_names; varlist = M_.endo_names;
SelecVariables = transpose(1:M_.endo_nbr); SelecVariables = transpose(1:M_.endo_nbr);
nvar = M_.endo_nbr; nvar = M_.endo_nbr;
else else
nvar = size(varlist,1); nvar = size(varlist,1);
SelecVariables = []; SelecVariables = [];
for i=1:nvar for i=1:nvar
if ~isempty(strmatch(varlist(i,:),M_.endo_names,'exact')) if ~isempty(strmatch(varlist(i,:),M_.endo_names,'exact'))
SelecVariables = [SelecVariables;strmatch(varlist(i,:),M_.endo_names,'exact')]; SelecVariables = [SelecVariables;strmatch(varlist(i,:),M_.endo_names,'exact')];
end end
end end
end end
irun1 = 1; irun1 = 1;
irun2 = 1; irun2 = 1;
irun3 = 1; irun3 = 1;
irun4 = 1; irun4 = 1;
irun5 = 1; irun5 = 1;
irun6 = 1; irun6 = 1;
irun7 = 1; irun7 = 1;
ifil1 = 0; ifil1 = 0;
ifil2 = 0; ifil2 = 0;
ifil3 = 0; ifil3 = 0;
ifil4 = 0; ifil4 = 0;
ifil5 = 0; ifil5 = 0;
ifil6 = 0; ifil6 = 0;
ifil7 = 0; ifil7 = 0;
h = waitbar(0,'Bayesian smoother...'); h = waitbar(0,'Bayesian smoother...');
stock_param = zeros(MAX_nruns, npar); stock_param = zeros(MAX_nruns, npar);
stock_logpo = zeros(MAX_nruns,1); stock_logpo = zeros(MAX_nruns,1);
stock_ys = zeros(MAX_nruns,endo_nbr); stock_ys = zeros(MAX_nruns,endo_nbr);
if options_.smoother if options_.smoother
stock_smooth = zeros(endo_nbr,gend,MAX_nsmoo); stock_smooth = zeros(endo_nbr,gend,MAX_nsmoo);
stock_innov = zeros(exo_nbr,gend,B); stock_innov = zeros(exo_nbr,gend,B);
stock_error = zeros(nvobs,gend,MAX_nerro); stock_error = zeros(nvobs,gend,MAX_nerro);
end end
if options_.filter_step_ahead if options_.filter_step_ahead
stock_filter = zeros(naK,endo_nbr,gend+options_.filter_step_ahead(end),MAX_naK); stock_filter = zeros(naK,endo_nbr,gend+options_.filter_step_ahead(end),MAX_naK);
end end
if options_.forecast if options_.forecast
stock_forcst_mean = zeros(endo_nbr,horizon+maxlag,MAX_nforc1); stock_forcst_mean = zeros(endo_nbr,horizon+maxlag,MAX_nforc1);
stock_forcst_total = zeros(endo_nbr,horizon+maxlag,MAX_nforc2); stock_forcst_total = zeros(endo_nbr,horizon+maxlag,MAX_nforc2);
end end
for b=1:B for b=1:B
%deep = GetOneDraw(NumberOfDraws,FirstMhFile,LastMhFile,FirstLine,MAX_nruns,DirectoryName); %deep = GetOneDraw(NumberOfDraws,FirstMhFile,LastMhFile,FirstLine,MAX_nruns,DirectoryName);
[deep, logpo] = GetOneDraw(type); [deep, logpo] = GetOneDraw(type);
set_all_parameters(deep); set_all_parameters(deep);
dr = resol(oo_.steady_state,0); dr = resol(oo_.steady_state,0);
[alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK] = ... [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK] = ...
DsgeSmoother(deep,gend,Y,data_index); DsgeSmoother(deep,gend,Y,data_index);
if options_.loglinear if options_.loglinear
stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ... stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ...
repmat(log(dr.ys(dr.order_var)),1,gend); repmat(log(dr.ys(dr.order_var)),1,gend);
else else
stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ... stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ...
repmat(dr.ys(dr.order_var),1,gend); repmat(dr.ys(dr.order_var),1,gend);
end end
if nvx if nvx
stock_innov(:,:,irun2) = etahat; stock_innov(:,:,irun2) = etahat;
end end
if nvn if nvn
stock_error(:,:,irun3) = epsilonhat; stock_error(:,:,irun3) = epsilonhat;
end end
if naK if naK
stock_filter(:,dr.order_var,:,irun4) = aK(options_.filter_step_ahead,1:endo_nbr,:); stock_filter(:,dr.order_var,:,irun4) = aK(options_.filter_step_ahead,1:endo_nbr,:);
end end
stock_param(irun5,:) = deep; stock_param(irun5,:) = deep;
stock_logpo(irun5,1) = logpo; stock_logpo(irun5,1) = logpo;
stock_ys(irun5,:) = SteadyState'; stock_ys(irun5,:) = SteadyState';
if horizon if horizon
yyyy = alphahat(iendo,i_last_obs); yyyy = alphahat(iendo,i_last_obs);
yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr)); yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr));
if options_.prefilter == 1 if options_.prefilter == 1
yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ... yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ...
horizon+maxlag,1); horizon+maxlag,1);
end end
yf(:,IdObs) = yf(:,IdObs)+(gend+[1-maxlag:horizon]')*trend_coeff'; yf(:,IdObs) = yf(:,IdObs)+(gend+[1-maxlag:horizon]')*trend_coeff';
if options_.loglinear == 1 if options_.loglinear == 1
yf = yf+repmat(log(SteadyState'),horizon+maxlag,1); yf = yf+repmat(log(SteadyState'),horizon+maxlag,1);
% yf = exp(yf); % yf = exp(yf);
else else
yf = yf+repmat(SteadyState',horizon+maxlag,1); yf = yf+repmat(SteadyState',horizon+maxlag,1);
end end
yf1 = forcst2(yyyy,horizon,dr,1); yf1 = forcst2(yyyy,horizon,dr,1);
if options_.prefilter == 1 if options_.prefilter == 1
yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ... yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ...
repmat(bayestopt_.mean_varobs',[horizon+maxlag,1,1]); repmat(bayestopt_.mean_varobs',[horizon+maxlag,1,1]);
end end
yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-maxlag:horizon]')* ... yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-maxlag:horizon]')* ...
trend_coeff',[1,1,1]); trend_coeff',[1,1,1]);
if options_.loglinear == 1 if options_.loglinear == 1
yf1 = yf1 + repmat(log(SteadyState'),[horizon+maxlag,1,1]); yf1 = yf1 + repmat(log(SteadyState'),[horizon+maxlag,1,1]);
% yf1 = exp(yf1); % yf1 = exp(yf1);
else else
yf1 = yf1 + repmat(SteadyState',[horizon+maxlag,1,1]); yf1 = yf1 + repmat(SteadyState',[horizon+maxlag,1,1]);
end end
stock_forcst_mean(:,:,irun6) = yf'; stock_forcst_mean(:,:,irun6) = yf';
stock_forcst_total(:,:,irun7) = yf1'; stock_forcst_total(:,:,irun7) = yf1';
end end
irun1 = irun1 + 1; irun1 = irun1 + 1;
irun2 = irun2 + 1; irun2 = irun2 + 1;
irun3 = irun3 + 1; irun3 = irun3 + 1;
irun4 = irun4 + 1; irun4 = irun4 + 1;
irun5 = irun5 + 1; irun5 = irun5 + 1;
irun6 = irun6 + 1; irun6 = irun6 + 1;
irun7 = irun7 + 1; irun7 = irun7 + 1;
if irun1 > MAX_nsmoo | b == B if irun1 > MAX_nsmoo | b == B
stock = stock_smooth(:,:,1:irun1-1); stock = stock_smooth(:,:,1:irun1-1);
ifil1 = ifil1 + 1; ifil1 = ifil1 + 1;
save([DirectoryName '/' M_.fname '_smooth' int2str(ifil1) '.mat'],'stock'); save([DirectoryName '/' M_.fname '_smooth' int2str(ifil1) '.mat'],'stock');
irun1 = 1; irun1 = 1;
end end
if nvx & (irun2 > MAX_ninno | b == B) if nvx & (irun2 > MAX_ninno | b == B)
stock = stock_innov(:,:,1:irun2-1); stock = stock_innov(:,:,1:irun2-1);
ifil2 = ifil2 + 1; ifil2 = ifil2 + 1;
save([DirectoryName '/' M_.fname '_inno' int2str(ifil2) '.mat'],'stock'); save([DirectoryName '/' M_.fname '_inno' int2str(ifil2) '.mat'],'stock');
irun2 = 1; irun2 = 1;
end end
if nvn & (irun3 > MAX_error | b == B) if nvn & (irun3 > MAX_error | b == B)
stock = stock_error(:,:,1:irun3-1); stock = stock_error(:,:,1:irun3-1);
ifil3 = ifil3 + 1; ifil3 = ifil3 + 1;
save([DirectoryName '/' M_.fname '_error' int2str(ifil3) '.mat'],'stock'); save([DirectoryName '/' M_.fname '_error' int2str(ifil3) '.mat'],'stock');
irun3 = 1; irun3 = 1;
end end
if naK & (irun4 > MAX_naK | b == B) if naK & (irun4 > MAX_naK | b == B)
stock = stock_filter(:,:,:,1:irun4-1); stock = stock_filter(:,:,:,1:irun4-1);
ifil4 = ifil4 + 1; ifil4 = ifil4 + 1;
save([DirectoryName '/' M_.fname '_filter' int2str(ifil4) '.mat'],'stock'); save([DirectoryName '/' M_.fname '_filter' int2str(ifil4) '.mat'],'stock');
irun4 = 1; irun4 = 1;
end end
if irun5 > MAX_nruns | b == B if irun5 > MAX_nruns | b == B
stock = stock_param(1:irun5-1,:); stock = stock_param(1:irun5-1,:);
ifil5 = ifil5 + 1; ifil5 = ifil5 + 1;
save([DirectoryName '/' M_.fname '_param' int2str(ifil5) '.mat'],'stock','stock_logpo','stock_ys'); save([DirectoryName '/' M_.fname '_param' int2str(ifil5) '.mat'],'stock','stock_logpo','stock_ys');
irun5 = 1; irun5 = 1;
end end
if horizon & (irun6 > MAX_nforc1 | b == B) if horizon & (irun6 > MAX_nforc1 | b == B)
stock = stock_forcst_mean(:,:,1:irun6-1); stock = stock_forcst_mean(:,:,1:irun6-1);
ifil6 = ifil6 + 1; ifil6 = ifil6 + 1;
save([DirectoryName '/' M_.fname '_forc_mean' int2str(ifil6) '.mat'],'stock'); save([DirectoryName '/' M_.fname '_forc_mean' int2str(ifil6) '.mat'],'stock');
irun6 = 1; irun6 = 1;
end end
if horizon & (irun7 > MAX_nforc2 | b == B) if horizon & (irun7 > MAX_nforc2 | b == B)
stock = stock_forcst_total(:,:,1:irun7-1); stock = stock_forcst_total(:,:,1:irun7-1);
ifil7 = ifil7 + 1; ifil7 = ifil7 + 1;
save([DirectoryName '/' M_.fname '_forc_total' int2str(ifil7) '.mat'],'stock'); save([DirectoryName '/' M_.fname '_forc_total' int2str(ifil7) '.mat'],'stock');
irun7 = 1; irun7 = 1;
end end
waitbar(b/B,h); waitbar(b/B,h);
end end
close(h) close(h)
stock_gend=gend; stock_gend=gend;
stock_data=Y; stock_data=Y;
save([DirectoryName '/' M_.fname '_data.mat'],'stock_gend','stock_data'); save([DirectoryName '/' M_.fname '_data.mat'],'stock_gend','stock_data');
if options_.smoother if options_.smoother
pm3(endo_nbr,gend,ifil1,B,'Smoothed variables',... pm3(endo_nbr,gend,ifil1,B,'Smoothed variables',...
M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,... M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
'names2','smooth',[M_.fname '/metropolis'],'_smooth') 'names2','smooth',[M_.fname '/metropolis'],'_smooth')
end end
if options_.forecast if options_.forecast
pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (mean)',... pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (mean)',...
M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,... M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
'names2','smooth',[M_.fname '/metropolis'],'_forc_mean') 'names2','smooth',[M_.fname '/metropolis'],'_forc_mean')
pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (total)',... pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (total)',...
M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,... M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
'names2','smooth',[M_.fname '/metropolis'],'_forc_total') 'names2','smooth',[M_.fname '/metropolis'],'_forc_total')
end end

View File

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

View File

@ -1,183 +1,183 @@
function ReshapeMatFiles(type, type2) function ReshapeMatFiles(type, type2)
% function ReshapeMatFiles(type, type2) % function ReshapeMatFiles(type, type2)
% Reshapes and sorts (along the mcmc simulations) the mat files generated by DYNARE. % Reshapes and sorts (along the mcmc simulations) the mat files generated by DYNARE.
% 4D-arrays are splitted along the first dimension. % 4D-arrays are splitted along the first dimension.
% 3D-arrays are splitted along the second dimension. % 3D-arrays are splitted along the second dimension.
% %
% INPUTS: % INPUTS:
% type: statistics type in the repertory: % type: statistics type in the repertory:
% dgse % dgse
% irf_bvardsge % irf_bvardsge
% smooth % smooth
% filter % filter
% error % error
% innov % innov
% forcst % forcst
% forcst1 % forcst1
% type2: analysis type: % type2: analysis type:
% posterior % posterior
% gsa % gsa
% prior % prior
% %
% OUTPUTS: % OUTPUTS:
% none % none
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2003-2007 Dynare Team % Copyright (C) 2003-2007 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ global M_ options_
if nargin==1, if nargin==1,
MhDirectoryName = [ CheckPath('metropolis') '/' ]; MhDirectoryName = [ CheckPath('metropolis') '/' ];
else else
if strcmpi(type2,'posterior') if strcmpi(type2,'posterior')
MhDirectoryName = [CheckPath('metropolis') '/' ]; MhDirectoryName = [CheckPath('metropolis') '/' ];
elseif strcmpi(type2,'gsa') elseif strcmpi(type2,'gsa')
if options_.opt_gsa.morris==1, if options_.opt_gsa.morris==1,
MhDirectoryName = [CheckPath('GSA\SCREEN') '/' ]; MhDirectoryName = [CheckPath('GSA\SCREEN') '/' ];
elseif options_.opt_gsa.morris==2, elseif options_.opt_gsa.morris==2,
MhDirectoryName = [CheckPath('GSA\IDENTIF') '/' ]; MhDirectoryName = [CheckPath('GSA\IDENTIF') '/' ];
else else
MhDirectoryName = [CheckPath('GSA') '/' ]; MhDirectoryName = [CheckPath('GSA') '/' ];
end end
else else
MhDirectoryName = [CheckPath('prior') '/' ]; MhDirectoryName = [CheckPath('prior') '/' ];
end end
end end
switch type switch type
case 'irf_dsge' case 'irf_dsge'
CAPtype = 'IRF_DSGE'; CAPtype = 'IRF_DSGE';
TYPEsize = [ options_.irf , size(options_.varlist,1) , M_.exo_nbr ]; TYPEsize = [ options_.irf , size(options_.varlist,1) , M_.exo_nbr ];
TYPEarray = 4; TYPEarray = 4;
case 'irf_bvardsge' case 'irf_bvardsge'
CAPtype = 'IRF_BVARDSGE'; CAPtype = 'IRF_BVARDSGE';
TYPEsize = [ options_.irf , size(options_.varobs,1) , M_.exo_nbr ]; TYPEsize = [ options_.irf , size(options_.varobs,1) , M_.exo_nbr ];
TYPEarray = 4; TYPEarray = 4;
case 'smooth' case 'smooth'
CAPtype = 'SMOOTH'; CAPtype = 'SMOOTH';
TYPEsize = [ M_.endo_nbr , options_.nobs ]; TYPEsize = [ M_.endo_nbr , options_.nobs ];
TYPEarray = 3; TYPEarray = 3;
case 'filter' case 'filter'
CAPtype = 'FILTER'; CAPtype = 'FILTER';
TYPEsize = [ M_.endo_nbr , options_.nobs + 1 ];% TO BE CHECKED! TYPEsize = [ M_.endo_nbr , options_.nobs + 1 ];% TO BE CHECKED!
TYPEarray = 3; TYPEarray = 3;
case 'error' case 'error'
CAPtype = 'ERROR'; CAPtype = 'ERROR';
TYPEsize = [ size(options_.varobs,1) , options_.nobs ]; TYPEsize = [ size(options_.varobs,1) , options_.nobs ];
TYPEarray = 3; TYPEarray = 3;
case 'innov' case 'innov'
CAPtype = 'INNOV'; CAPtype = 'INNOV';
TYPEsize = [ M_.exo_nbr , options_.nobs ]; TYPEsize = [ M_.exo_nbr , options_.nobs ];
TYPEarray = 3; TYPEarray = 3;
case 'forcst' case 'forcst'
CAPtype = 'FORCST'; CAPtype = 'FORCST';
TYPEsize = [ M_.endo_nbr , options_.forecast ]; TYPEsize = [ M_.endo_nbr , options_.forecast ];
TYPEarray = 3; TYPEarray = 3;
case 'forcst1' case 'forcst1'
CAPtype = 'FORCST1'; CAPtype = 'FORCST1';
TYPEsize = [ M_.endo_nbr , options_.forecast ]; TYPEsize = [ M_.endo_nbr , options_.forecast ];
TYPEarray = 3; TYPEarray = 3;
otherwise otherwise
disp('ReshapeMatFiles :: Unknown argument!') disp('ReshapeMatFiles :: Unknown argument!')
return return
end end
TYPEfiles = dir([MhDirectoryName M_.fname '_' type '*.mat']); TYPEfiles = dir([MhDirectoryName M_.fname '_' type '*.mat']);
NumberOfTYPEfiles = length(TYPEfiles); NumberOfTYPEfiles = length(TYPEfiles);
B = options_.B; B = options_.B;
switch TYPEarray switch TYPEarray
case 4 case 4
if NumberOfTYPEfiles > 1 if NumberOfTYPEfiles > 1
NumberOfPeriodsPerTYPEfiles = ceil(TYPEsize(1)/NumberOfTYPEfiles); NumberOfPeriodsPerTYPEfiles = ceil(TYPEsize(1)/NumberOfTYPEfiles);
foffset = NumberOfTYPEfiles-floor(TYPEsize(1)/NumberOfPeriodsPerTYPEfiles); foffset = NumberOfTYPEfiles-floor(TYPEsize(1)/NumberOfPeriodsPerTYPEfiles);
reste = TYPEsize(1)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-foffset); reste = TYPEsize(1)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-foffset);
idx = 0; idx = 0;
jdx = 0; jdx = 0;
for f1=1:NumberOfTYPEfiles-foffset for f1=1:NumberOfTYPEfiles-foffset
eval(['STOCK_' CAPtype ' = zeros(NumberOfPeriodsPerTYPEfiles,TYPEsize(2),TYPEsize(3),B);']) eval(['STOCK_' CAPtype ' = zeros(NumberOfPeriodsPerTYPEfiles,TYPEsize(2),TYPEsize(3),B);'])
for f2 = 1:NumberOfTYPEfiles for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']);
eval(['STOCK_' CAPtype '(:,:,:,idx+1:idx+size(stock_' type ',4))=stock_' ... eval(['STOCK_' CAPtype '(:,:,:,idx+1:idx+size(stock_' type ',4))=stock_' ...
type '(jdx+1:jdx+NumberOfPeriodsPerTYPEfiles,:,:,:);']) type '(jdx+1:jdx+NumberOfPeriodsPerTYPEfiles,:,:,:);'])
eval(['idx = idx + size(stock_' type ',4);']) eval(['idx = idx + size(stock_' type ',4);'])
end end
%eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);']) %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]); save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]);
jdx = jdx + NumberOfPeriodsPerTYPEfiles; jdx = jdx + NumberOfPeriodsPerTYPEfiles;
idx = 0; idx = 0;
end end
if reste if reste
eval(['STOCK_' CAPtype ' = zeros(reste,TYPEsize(2),TYPEsize(3),B);']) eval(['STOCK_' CAPtype ' = zeros(reste,TYPEsize(2),TYPEsize(3),B);'])
for f2 = 1:NumberOfTYPEfiles for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); 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(['STOCK_' CAPtype '(:,:,:,idx+1:idx+size(stock_' type ',4))=stock_' type '(jdx+1:jdx+reste,:,:,:);'])
eval(['idx = idx + size(stock_' type ',4);']) eval(['idx = idx + size(stock_' type ',4);'])
end end
%eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);']) %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles-foffset+1) '.mat'],['STOCK_' CAPtype]); save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles-foffset+1) '.mat'],['STOCK_' CAPtype]);
end end
else else
load([MhDirectoryName M_.fname '_' type '1.mat']); load([MhDirectoryName M_.fname '_' type '1.mat']);
%eval(['STOCK_' CAPtype ' = sort(stock_' type ',4);']) %eval(['STOCK_' CAPtype ' = sort(stock_' type ',4);'])
eval(['STOCK_' CAPtype ' = stock_' type ';']) eval(['STOCK_' CAPtype ' = stock_' type ';'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]); save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]);
end end
% Original file format may be useful in some cases... % Original file format may be useful in some cases...
% for file = 1:NumberOfTYPEfiles % for file = 1:NumberOfTYPEfiles
% delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat']) % delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat'])
% end % end
case 3 case 3
if NumberOfTYPEfiles>1 if NumberOfTYPEfiles>1
NumberOfPeriodsPerTYPEfiles = ceil( TYPEsize(2)/NumberOfTYPEfiles ); NumberOfPeriodsPerTYPEfiles = ceil( TYPEsize(2)/NumberOfTYPEfiles );
reste = TYPEsize(2)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-1); reste = TYPEsize(2)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-1);
idx = 0; idx = 0;
jdx = 0; jdx = 0;
for f1=1:NumberOfTYPEfiles-1 for f1=1:NumberOfTYPEfiles-1
eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),NumberOfPeriodsPerTYPEfiles,B);']) eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),NumberOfPeriodsPerTYPEfiles,B);'])
for f2 = 1:NumberOfTYPEfiles for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); 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(['STOCK_' CAPtype '(:,:,idx+1:idx+size(stock_ ' type ',3))=stock_' type '(:,jdx+1:jdx+NumberOfPeriodsPerTYPEfiles,:);'])
eval(['idx = idx + size(stock_' type ',3);']) eval(['idx = idx + size(stock_' type ',3);'])
end end
%eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);']) %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]); save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]);
jdx = jdx + NumberOfPeriodsPerTYPEfiles; jdx = jdx + NumberOfPeriodsPerTYPEfiles;
idx = 0; idx = 0;
end end
eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),reste,B);']) eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),reste,B);'])
for f2 = 1:NumberOfTYPEfiles for f2 = 1:NumberOfTYPEfiles
load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); 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(['STOCK_' CAPtype '(:,:,idx+1:idx+size(stock_' type ',3))=stock_' type '(:,jdx+1:jdx+reste,:);'])
eval(['idx = idx + size(stock_' type ',3);']) eval(['idx = idx + size(stock_' type ',3);'])
end end
%eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);']) %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles) '.mat'],['STOCK_' CAPtype]); save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles) '.mat'],['STOCK_' CAPtype]);
else else
load([MhDirectoryName M_.fname '_' type '1.mat']); load([MhDirectoryName M_.fname '_' type '1.mat']);
%eval(['STOCK_' CAPtype ' = sort(stock_' type ',3);']) %eval(['STOCK_' CAPtype ' = sort(stock_' type ',3);'])
eval(['STOCK_' CAPtype ' = stock_' type ';']) eval(['STOCK_' CAPtype ' = stock_' type ';'])
save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]); save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]);
end end
% Original file format may be useful in some cases... % Original file format may be useful in some cases...
% for file = 1:NumberOfTYPEfiles % for file = 1:NumberOfTYPEfiles
% delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat']) % delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat'])
% end % end
end end

View File

@ -1,179 +1,179 @@
function [omega,f] = UnivariateSpectralDensity(dr,var_list) function [omega,f] = UnivariateSpectralDensity(dr,var_list)
% This function computes the theoretical spectral density of each % This function computes the theoretical spectral density of each
% endogenous variable declared in var_list. Results are stored in % endogenous variable declared in var_list. Results are stored in
% oo_ and may be plotted. % oo_ and may be plotted.
% %
% Adapted from th_autocovariances.m. % Adapted from th_autocovariances.m.
% Copyright (C) 2006-2009 Dynare Team % Copyright (C) 2006-2009 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_ oo_ M_ global options_ oo_ M_
omega = []; f = []; omega = []; f = [];
if options_.order > 1 if options_.order > 1
disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density') disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density')
disp('with a second order approximation of the DSGE model!') disp('with a second order approximation of the DSGE model!')
disp('Set order = 1.') disp('Set order = 1.')
return return
end end
pltinfo = 1;%options_.SpectralDensity.Th.plot; pltinfo = 1;%options_.SpectralDensity.Th.plot;
cutoff = 150;%options_.SpectralDensity.Th.cutoff; cutoff = 150;%options_.SpectralDensity.Th.cutoff;
sdl = 0.01;%options_.SepctralDensity.Th.sdl; sdl = 0.01;%options_.SepctralDensity.Th.sdl;
omega = (0:sdl:pi)'; omega = (0:sdl:pi)';
GridSize = length(omega); GridSize = length(omega);
exo_names_orig_ord = M_.exo_names_orig_ord; exo_names_orig_ord = M_.exo_names_orig_ord;
if exist('OCTAVE_VERSION') if exist('OCTAVE_VERSION')
warning('off', 'Octave:divide-by-zero') warning('off', 'Octave:divide-by-zero')
else else
warning off MATLAB:dividebyzero warning off MATLAB:dividebyzero
end end
if nargin<2 if nargin<2
var_list = []; var_list = [];
end end
if size(var_list,1) == 0 if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :); var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end end
nvar = size(var_list,1); nvar = size(var_list,1);
ivar=zeros(nvar,1); ivar=zeros(nvar,1);
for i=1:nvar for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact');
if isempty(i_tmp) if isempty(i_tmp)
error (['One of the variable specified does not exist']) ; error (['One of the variable specified does not exist']) ;
else else
ivar(i) = i_tmp; ivar(i) = i_tmp;
end end
end end
f = zeros(nvar,GridSize); f = zeros(nvar,GridSize);
ghx = dr.ghx; ghx = dr.ghx;
ghu = dr.ghu; ghu = dr.ghu;
npred = dr.npred; npred = dr.npred;
nstatic = dr.nstatic; nstatic = dr.nstatic;
kstate = dr.kstate; kstate = dr.kstate;
order = dr.order_var; order = dr.order_var;
iv(order) = [1:length(order)]; iv(order) = [1:length(order)];
nx = size(ghx,2); nx = size(ghx,2);
ikx = [nstatic+1:nstatic+npred]; ikx = [nstatic+1:nstatic+npred];
A = zeros(nx,nx); A = zeros(nx,nx);
k0 = kstate(find(kstate(:,2) <= M_.maximum_lag+1),:); k0 = kstate(find(kstate(:,2) <= M_.maximum_lag+1),:);
i0 = find(k0(:,2) == M_.maximum_lag+1); i0 = find(k0(:,2) == M_.maximum_lag+1);
i00 = i0; i00 = i0;
n0 = length(i0); n0 = length(i0);
A(i0,:) = ghx(ikx,:); A(i0,:) = ghx(ikx,:);
AS = ghx(:,i0); AS = ghx(:,i0);
ghu1 = zeros(nx,M_.exo_nbr); ghu1 = zeros(nx,M_.exo_nbr);
ghu1(i0,:) = ghu(ikx,:); ghu1(i0,:) = ghu(ikx,:);
for i=M_.maximum_lag:-1:2 for i=M_.maximum_lag:-1:2
i1 = find(k0(:,2) == i); i1 = find(k0(:,2) == i);
n1 = size(i1,1); n1 = size(i1,1);
j1 = zeros(n1,1); j1 = zeros(n1,1);
j2 = j1; j2 = j1;
for k1 = 1:n1 for k1 = 1:n1
j1(k1) = find(k0(i00,1)==k0(i1(k1),1)); j1(k1) = find(k0(i00,1)==k0(i1(k1),1));
j2(k1) = find(k0(i0,1)==k0(i1(k1),1)); j2(k1) = find(k0(i0,1)==k0(i1(k1),1));
end end
AS(:,j1) = AS(:,j1)+ghx(:,i1); AS(:,j1) = AS(:,j1)+ghx(:,i1);
i0 = i1; i0 = i1;
end end
Gamma = zeros(nvar,cutoff+1); Gamma = zeros(nvar,cutoff+1);
[A,B] = kalman_transition_matrix(dr,ikx',1:nx,dr.transition_auxiliary_variables,M_.exo_nbr); [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); [vx, u] = lyapunov_symm(A,B*M_.Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold);
iky = iv(ivar); iky = iv(ivar);
if ~isempty(u) if ~isempty(u)
iky = iky(find(any(abs(ghx(iky,:)*u) < options_.Schur_vec_tol,2))); iky = iky(find(any(abs(ghx(iky,:)*u) < options_.Schur_vec_tol,2)));
ivar = dr.order_var(iky); ivar = dr.order_var(iky);
end end
aa = ghx(iky,:); aa = ghx(iky,:);
bb = ghu(iky,:); bb = ghu(iky,:);
if options_.hp_filter == 0 if options_.hp_filter == 0
tmp = aa*vx*aa'+ bb*M_.Sigma_e*bb'; tmp = aa*vx*aa'+ bb*M_.Sigma_e*bb';
k = find(abs(tmp) < 1e-12); k = find(abs(tmp) < 1e-12);
tmp(k) = 0; tmp(k) = 0;
Gamma(:,1) = diag(tmp); Gamma(:,1) = diag(tmp);
vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb'); vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb');
tmp = aa*vxy; tmp = aa*vxy;
k = find(abs(tmp) < 1e-12); k = find(abs(tmp) < 1e-12);
tmp(k) = 0; tmp(k) = 0;
Gamma(:,2) = diag(tmp); Gamma(:,2) = diag(tmp);
for i=2:cutoff for i=2:cutoff
vxy = A*vxy; vxy = A*vxy;
tmp = aa*vxy; tmp = aa*vxy;
k = find(abs(tmp) < 1e-12); k = find(abs(tmp) < 1e-12);
tmp(k) = 0; tmp(k) = 0;
Gamma(:,i+1) = diag(tmp); Gamma(:,i+1) = diag(tmp);
end end
else else
iky = iv(ivar); iky = iv(ivar);
aa = ghx(iky,:); aa = ghx(iky,:);
bb = ghu(iky,:); bb = ghu(iky,:);
lambda = options_.hp_filter; lambda = options_.hp_filter;
ngrid = options_.hp_ngrid; ngrid = options_.hp_ngrid;
freqs = 0 : ((2*pi)/ngrid) : (2*pi*(1 - .5/ngrid)); freqs = 0 : ((2*pi)/ngrid) : (2*pi*(1 - .5/ngrid));
tpos = exp( sqrt(-1)*freqs); tpos = exp( sqrt(-1)*freqs);
tneg = exp(-sqrt(-1)*freqs); tneg = exp(-sqrt(-1)*freqs);
hp1 = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2); hp1 = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2);
mathp_col = []; mathp_col = [];
IA = eye(size(A,1)); IA = eye(size(A,1));
IE = eye(M_.exo_nbr); IE = eye(M_.exo_nbr);
for ig = 1:ngrid for ig = 1:ngrid
f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*ghu1;IE]... f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*ghu1;IE]...
*M_.Sigma_e*[ghu1'*inv(IA-A'*tpos(ig)) IE]); % state variables *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 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 f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series
mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row
% for ifft % for ifft
end; end;
imathp_col = real(ifft(mathp_col))*(2*pi); imathp_col = real(ifft(mathp_col))*(2*pi);
tmp = reshape(imathp_col(1,:),nvar,nvar); tmp = reshape(imathp_col(1,:),nvar,nvar);
k = find(abs(tmp)<1e-12); k = find(abs(tmp)<1e-12);
tmp(k) = 0; tmp(k) = 0;
Gamma(:,1) = diag(tmp); Gamma(:,1) = diag(tmp);
sy = sqrt(Gamma(:,1)); sy = sqrt(Gamma(:,1));
sy = sy *sy'; sy = sy *sy';
for i=1:cutoff-1 for i=1:cutoff-1
tmp = reshape(imathp_col(i+1,:),nvar,nvar)./sy; tmp = reshape(imathp_col(i+1,:),nvar,nvar)./sy;
k = find(abs(tmp) < 1e-12); k = find(abs(tmp) < 1e-12);
tmp(k) = 0; tmp(k) = 0;
Gamma(:,i+1) = diag(tmp); Gamma(:,i+1) = diag(tmp);
end end
end end
H = 1:cutoff; H = 1:cutoff;
for i=1:nvar for i=1:nvar
f(i,:) = Gamma(i,1)/(2*pi) + Gamma(i,H+1)*cos(H'*omega')/pi; f(i,:) = Gamma(i,1)/(2*pi) + Gamma(i,H+1)*cos(H'*omega')/pi;
end end
if exist('OCTAVE_VERSION') if exist('OCTAVE_VERSION')
warning('on', 'Octave:divide-by-zero') warning('on', 'Octave:divide-by-zero')
else else
warning on MATLAB:dividebyzero warning on MATLAB:dividebyzero
end end
if pltinfo if pltinfo
for i= 1:nvar for i= 1:nvar
figure('Name',['Spectral Density of ' deblank(M_.endo_names(ivar(i),:)) '.']) figure('Name',['Spectral Density of ' deblank(M_.endo_names(ivar(i),:)) '.'])
plot(omega,f(i,:),'-k','linewidth',2) plot(omega,f(i,:),'-k','linewidth',2)
xlabel('0 \leq \omega \leq \pi') xlabel('0 \leq \omega \leq \pi')
ylabel('f(\omega)') ylabel('f(\omega)')
box on box on
axis tight axis tight
end end
end end

View File

@ -1,7 +1,7 @@
function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ... 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 % Add auxiliary variables to the steady state vector
% Copyright (C) 2009 Dynare Team % Copyright (C) 2009 Dynare Team
% %
% This file is part of Dynare. % 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
n = length(aux_vars); n = length(aux_vars);
ys1 = [ys;zeros(n,1)]; ys1 = [ys;zeros(n,1)];
k = size(ys,1)+1; k = size(ys,1)+1;
aux_lead_nbr = 0; aux_lead_nbr = 0;
for i=1:n for i=1:n
if aux_vars(i).type == 1 if aux_vars(i).type == 1
ys1(k) = ys(aux_vars(i).orig_index); ys1(k) = ys(aux_vars(i).orig_index);
elseif aux_vars(i).type == 0 elseif aux_vars(i).type == 0
aux_lead_nbr = aux_lead_nbr + 1; aux_lead_nbr = aux_lead_nbr + 1;
end
k = k+1;
end end
k = k+1;
for i=1:aux_lead_nbr+1; end
res = feval([fname '_static'],ys1,...
[exo_steady_state; ... for i=1:aux_lead_nbr+1;
exo_det_steady_state],params); res = feval([fname '_static'],ys1,...
for j=1:n [exo_steady_state; ...
if aux_vars(j).type == 0 exo_det_steady_state],params);
el = aux_vars(j).endo_index; for j=1:n
ys1(el) = ys1(el)-res(el); if aux_vars(j).type == 0
end el = aux_vars(j).endo_index;
ys1(el) = ys1(el)-res(el);
end end
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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
AutoregressiveParameters = NaN(p,1); AutoregressiveParameters = NaN(p,1);
InnovationVariance = NaN; InnovationVariance = NaN;
switch p switch p
case 1 case 1
AutoregressiveParameters = Rho(1); AutoregressiveParameters = Rho(1);
case 2 case 2
tmp = (Rho(2)-1)/(Rho(1)*Rho(1)-1); tmp = (Rho(2)-1)/(Rho(1)*Rho(1)-1);
AutoregressiveParameters(1) = Rho(1)*tmp; AutoregressiveParameters(1) = Rho(1)*tmp;
AutoregressiveParameters(2) = 1-tmp; AutoregressiveParameters(2) = 1-tmp;
case 3 case 3
t1 = 1/(Rho(2)-2*Rho(1)*Rho(1)+1); 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; 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); t3 = .5*(Rho(1)- Rho(3))/(Rho(2)-1);
AutoregressiveParameters(1) = t2-t3-Rho(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(2) = (Rho(2)*Rho(2)-Rho(3)*Rho(1)-Rho(1)*Rho(1)+Rho(2))*t1 ;
AutoregressiveParameters(3) = t3-Rho(1)+t2; AutoregressiveParameters(3) = t3-Rho(1)+t2;
otherwise otherwise
AutocorrelationMatrix = eye(p); AutocorrelationMatrix = eye(p);
for i=1:p-1 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);
AutocorrelationMatrix = AutocorrelationMatrix + diag(Rho(i)*ones(p-i,1),-i); AutocorrelationMatrix = AutocorrelationMatrix + diag(Rho(i)*ones(p-i,1),-i);
end
AutoregressiveParameters = AutocorrelationMatrix\Rho;
end 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/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if size(dg,2)>1 if size(dg,2)>1
dg=dg'; dg=dg';
end end
if size(dx,2)>1 if size(dx,2)>1
dx=dx'; dx=dx';
end end
Hdg = H0*dg; Hdg = H0*dg;
dgdx = dg'*dx; dgdx = dg'*dx;
if (abs(dgdx) >1e-12) 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 else
disp('bfgs update failed.') disp('bfgs update failed.')
disp(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))]); disp(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))]);
disp(['dg''*dx = ' num2str(dgdx)]) disp(['dg''*dx = ' num2str(dgdx)])
disp(['|H*dg| = ' num2str(Hdg'*Hdg)]) disp(['|H*dg| = ' num2str(Hdg'*Hdg)])
H=H0; H=H0;
end end
save H.dat H 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
status = 0; status = 0;
r=b-feval(func,x,varargin{:}); r=b-feval(func,x,varargin{:});
rh_0 = r; rh_0 = r;
rh = r; rh = r;
rho_0 = 1; rho_0 = 1;
alpha = 1; alpha = 1;
w = 1; w = 1;
v = 0; v = 0;
p = 0; p = 0;
k = 0; k = 0;
rho_1 = rh_0'*r; rho_1 = rh_0'*r;
tolr = tole*norm(b); tolr = tole*norm(b);
while norm(r) > tolr & k < kmax while norm(r) > tolr & k < kmax
k = k+1; k = k+1;
beta = (rho_1/rho_0)*(alpha/w); beta = (rho_1/rho_0)*(alpha/w);
p = r+beta*(p-w*v); 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); rho_1 = -w*(rh_0'*t);
x = x+alpha*p+w*r; x = x+alpha*p+w*r;
r = r-w*t; r = r-w*t;
end end
if k == kmax if k == kmax
status = 1; status = 1;
warning(sprintf('BICSTABN didn''t converge after %d iterations: norm(r) = %g',kmax,norm(r))); warning(sprintf('BICSTABN didn''t converge after %d iterations: norm(r) = %g',kmax,norm(r)));
end end

View File

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

View File

@ -49,28 +49,28 @@ ir = ir-ny ;
i = 2 ; i = 2 ;
while i <= M_.maximum_lead | i <= options_.periods 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 ; ofs = (((options_.periods-i)*ny+1)-1)*jcf*8 ;
junk = fseek(fid,ofs,-1) ; junk = fseek(fid,ofs,-1) ;
c = fread(fid,[jcf,ny],'float64')' ; c = fread(fid,[jcf,ny],'float64')' ;
d1(ir) = c(:,jcf) - c(:,1:size(irf1,1))*d1(irf1) ; d1(ir) = c(:,jcf) - c(:,1:size(irf1,1))*d1(irf1) ;
ir = ir - ny ; ir = ir - ny ;
irf = irf - ny ; irf = irf - ny ;
i = i + 1 ; i = i + 1 ;
end end
while i <= options_.periods while i <= options_.periods
ofs = (((options_.periods-i)*ny+1)-1)*jcf*8 ; ofs = (((options_.periods-i)*ny+1)-1)*jcf*8 ;
junk = fseek(fid,ofs,-1) ; junk = fseek(fid,ofs,-1) ;
c = fread(fid,[jcf,ny],'float64')' ; c = fread(fid,[jcf,ny],'float64')' ;
d1(ir) = c(:,jcf)-c(:,icf)*d1(irf) ; d1(ir) = c(:,jcf)-c(:,icf)*d1(irf) ;
ir = ir-ny ; ir = ir-ny ;
irf = irf-ny ; irf = irf-ny ;
i = i+1; i = i+1;
end end
return ; 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ global M_ oo_
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);']); 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)); s2=upper(deblank(s2));
for im = 1:m for im = 1:m
key = s1(im,:) ; key = s1(im,:) ;
h = size(s2,1) ; h = size(s2,1) ;
l = 1 ; l = 1 ;
while l <= h while l <= h
mid = round((h+l)/2) ; mid = round((h+l)/2) ;
temp = s2(mid,:) ; temp = s2(mid,:) ;
if ~ strcmp(key,temp) if ~ strcmp(key,temp)
for i = 1:min(length(key),length(temp)) for i = 1:min(length(key),length(temp))
if temp(i) > key(i) if temp(i) > key(i)
h = mid - 1 ; h = mid - 1 ;
break break
else else
l = mid + 1 ; l = mid + 1 ;
break break
end end
end end
else else
x(im) = mid ; x(im) = mid ;
break break
end end
end 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
for nlags = 1:maxnlags for nlags = 1:maxnlags
[ny, nx, posterior, prior] = bvar_toolbox(nlags); [ny, nx, posterior, prior] = bvar_toolbox(nlags);
posterior_int = matrictint(posterior.S, posterior.df, posterior.XXi); posterior_int = matrictint(posterior.S, posterior.df, posterior.XXi);
prior_int = matrictint(prior.S, prior.df, prior.XXi); prior_int = matrictint(prior.S, prior.df, prior.XXi);
lik_nobs = posterior.df - prior.df; lik_nobs = posterior.df - prior.df;
log_dnsty = posterior_int - prior_int - 0.5*ny*lik_nobs*log(2*pi); log_dnsty = posterior_int - prior_int - 0.5*ny*lik_nobs*log(2*pi);
disp(' ') disp(' ')
fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ... fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ...
nlags, log_dnsty); nlags, log_dnsty);
disp(' ') disp(' ')
end end
function w = matrictint(S, df, XXi) function w = matrictint(S, df, XXi)
@ -64,31 +64,31 @@ function w = matrictint(S, df, XXi)
% Original file downloaded from: % Original file downloaded from:
% http://sims.princeton.edu/yftp/VARtools/matlab/matrictint.m % 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) k=size(XXi,1);
error('singular XXi') ny=size(S,1);
end [cx,p]=chol(XXi);
if any(diag(cs<100*eps)) [cs,q]=chol(S);
error('singular S')
end
% Matrix-normal component if any(diag(cx)<100*eps)
w1 = 0.5*k*ny*log(2*pi)+ny*sum(log(diag(cx))); error('singular XXi')
end
% Inverse-Wishart component if any(diag(cs<100*eps))
w2 = -df*sum(log(diag(cs))) + 0.5*df*ny*log(2) + ny*(ny-1)*0.25*log(pi) + ggammaln(ny, df); error('singular S')
end
w = w1 + w2;
% 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) function lgg = ggammaln(m, df)
if df <= (m-1) if df <= (m-1)
error('too few df in ggammaln') error('too few df in ggammaln')
else else
garg = 0.5*(df+(0:-1:1-m)); garg = 0.5*(df+(0:-1:1-m));
lgg = sum(gammaln(garg)); lgg = sum(gammaln(garg));
end end

View File

@ -28,158 +28,158 @@ function bvar_forecast(nlags)
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_ oo_ M_ 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);
sims_no_shock = NaN(options_.forecast, ny, options_.bvar_replic); options_ = set_default_option(options_, 'bvar_replic', 2000);
sims_with_shocks = NaN(options_.forecast, ny, options_.bvar_replic); 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 % Option 'lower' of chol() not available in old versions of
% Matlab, so using transpose % Matlab, so using transpose
XXi_lower_chol = chol(posterior.XXi)'; Sigma_lower_chol = chol(Sigma)';
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);
% Option 'lower' of chol() not available in old versions of Phi = rand_matrix_normal(k, ny, posterior.PhiHat, Sigma_lower_chol, XXi_lower_chol);
% 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
% With shocks % All the eigenvalues of the companion matrix have to be on or inside the unit circle
lags_data = forecast_data.initval; Companion_matrix(1:ny,:) = Phi(1:ny*nlags,:)';
for t = 1:options_.forecast test = (abs(eig(Companion_matrix)));
X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.xdata(t, :) ]; if any(test>1.0000000000001)
shock = (Sigma_lower_chol * randn(ny, 1))'; p = p+1;
y = X * Phi + shock; end
lags_data(1:end-1,:) = lags_data(2:end, :); d = d+1;
lags_data(end,:) = y;
sims_with_shocks(t, :, d) = y; % Without shocks
end 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 end
if p > 0 % With shocks
disp(' ') lags_data = forecast_data.initval;
disp(['Some of the VAR models sampled from the posterior distribution']) for t = 1:options_.forecast
disp(['were found to be explosive (' num2str(p/options_.bvar_replic) ' percent).']) X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.xdata(t, :) ];
disp(' ') 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 end
% Plot graphs rmse = sqrt(sq_err_cumul / size(sq_err_cumul, 1));
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); 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) 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,:)); % Store results
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,:)); DirectoryName = [ M_.fname '/bvar_forecast' ];
eval(['oo_.bvar.forecast.no_shock.Mean.' name ' = sims_no_shock_mean(:,i);']); if ~isdir(DirectoryName)
eval(['oo_.bvar.forecast.no_shock.Median.' name ' = sims_no_shock_median(:,i);']); if ~isdir(M_.fname)
eval(['oo_.bvar.forecast.no_shock.Var.' name ' = var(sims, 0, 2);']); mkdir(M_.fname);
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 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_ oo_ M_ global options_ oo_ M_
if nargin==1
identification = 'Cholesky';
end
options_ = set_default_option(options_, 'bvar_replic', 2000);
[ny, nx, posterior, prior] = bvar_toolbox(nlags); if nargin==1
identification = 'Cholesky';
S_inv_upper_chol = chol(inv(posterior.S)); end
% Option 'lower' of chol() not available in old versions of options_ = set_default_option(options_, 'bvar_replic', 2000);
% 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. [ny, nx, posterior, prior] = bvar_toolbox(nlags);
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);
% Get the Autoregressive matrices from a matrix variate distribution. S_inv_upper_chol = chol(inv(posterior.S));
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
if strcmpi(identification,'Cholesky') % Option 'lower' of chol() not available in old versions of
StructuralMat = Sigma_lower_chol; % Matlab, so using transpose
elseif strcmpi(identification,'SquareRoot') XXi_lower_chol = chol(posterior.XXi)';
StructuralMat = sqrtm(Sigma);
end k = ny*nlags+nx;
% Build the IRFs... % Declaration of the companion matrix
lags_data = zeros(ny,ny*nlags) ; Companion_matrix = diag(ones(ny*(nlags-1),1),-ny);
sampled_irfs(:,:,1,draw) = Sigma_lower_chol ;
lags_data(:,1:ny) = Sigma_lower_chol ; % Number of explosive VAR models sampled
for t=2:options_.irf p = 0;
sampled_irfs(:,:,t,draw) = lags_data(:,:)*Phi(1:ny*nlags,:) ;
lags_data(:,ny+1:end) = lags_data(:,1:end-ny) ; % Initialize a four dimensional array.
lags_data(:,1:ny) = sampled_irfs(:,:,t,draw) ; sampled_irfs = NaN(ny, ny, options_.irf, options_.bvar_replic);
end
for draw=1:options_.bvar_replic
end
if p > 0 % Get a covariance matrix from an inverted Wishart distribution.
disp(' ') Sigma = rand_inverse_wishart(ny, posterior.df, S_inv_upper_chol);
disp(['Some of the VAR models sampled from the posterior distribution']) Sigma_upper_chol = chol(Sigma);
disp(['were found to be explosive (' int2str(p) ' samples).']) Sigma_lower_chol = transpose(Sigma_upper_chol);
disp(' ')
% 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 end
posterior_mean_irfs = mean(sampled_irfs,4); if strcmpi(identification,'Cholesky')
posterior_variance_irfs = var(sampled_irfs, 1, 4); StructuralMat = Sigma_lower_chol;
elseif strcmpi(identification,'SquareRoot')
sorted_irfs = sort(sampled_irfs,4); StructuralMat = sqrtm(Sigma);
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 end
% Save intermediate results % Build the IRFs...
DirectoryName = [ M_.fname '/bvar_irf' ]; lags_data = zeros(ny,ny*nlags) ;
if ~isdir(DirectoryName) sampled_irfs(:,:,1,draw) = Sigma_lower_chol ;
mkdir('.',DirectoryName); 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
save([ DirectoryName '/simulations.mat'], 'sampled_irfs');
end
% Save results in oo_ if p > 0
for i=1:ny disp(' ')
shock_name = options_.varobs(i, :); disp(['Some of the VAR models sampled from the posterior distribution'])
for j=1:ny disp(['were found to be explosive (' int2str(p) ' samples).'])
variable_name = options_.varobs(j, :); disp(' ')
eval(['oo_.bvar.irf.Mean.' variable_name '.' shock_name ' = posterior_mean_irfs(' int2str(j) ',' int2str(i) ',:);']) end
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) ',:);']) posterior_mean_irfs = mean(sampled_irfs,4);
eval(['oo_.bvar.irf.Upper_bound.' variable_name '.' shock_name ' = posterior_up_conf_irfs(' int2str(j) ',' int2str(i) ',:);']) posterior_variance_irfs = var(sampled_irfs, 1, 4);
eval(['oo_.bvar.irf.Lower_bound.' variable_name '.' shock_name ' = posterior_down_conf_irfs(' int2str(j) ',' int2str(i) ',:);'])
end sorted_irfs = sort(sampled_irfs,4);
end 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: % This function uses the following Dynare options:
% - datafile, first_obs, varobs, xls_sheet, xls_range, nobs, presample % - datafile, first_obs, varobs, xls_sheet, xls_range, nobs, presample
% - bvar_prior_{tau,decay,lambda,mu,omega,flat,train} % - bvar_prior_{tau,decay,lambda,mu,omega,flat,train}
% Copyright (C) 2003-2007 Christopher Sims % Copyright (C) 2003-2007 Christopher Sims
% Copyright (C) 2007-2008 Dynare Team % 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_ 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
train = options_.bvar_prior_train; % Load dataset
dataset = read_variables(options_.datafile, options_.varobs, [], options_.xls_sheet, options_.xls_range);
if options_.first_obs + options_.presample - train <= nlags options_ = set_default_option(options_, 'nobs', size(dataset,1)-options_.first_obs+1);
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; % Parameters for prior
options_ = set_default_option(options_, 'bvar_prior_tau', 3);
% Prepare dataset options_ = set_default_option(options_, 'bvar_prior_decay', 0.5);
if options_.loglinear & ~options_.logdata options_ = set_default_option(options_, 'bvar_prior_lambda', 5);
dataset = log(dataset); options_ = set_default_option(options_, 'bvar_prior_mu', 2);
end options_ = set_default_option(options_, 'bvar_prior_omega', 1);
if options_.prefilter options_ = set_default_option(options_, 'bvar_prior_flat', 0);
dataset(idx,:) = dataset(idx,:) - ones(length(idx),1)*mean(dataset(idx,:)); options_ = set_default_option(options_, 'bvar_prior_train', 0);
end
mnprior.tight = options_.bvar_prior_tau;
mnprior.decay = options_.bvar_prior_decay;
% Use only initializations lags for the variance prior if options_.first_obs + options_.presample <= nlags
vprior.sig = std(dataset(options_.first_obs+options_.presample-nlags:options_.first_obs+options_.presample-1,:))'; error('first_obs+presample should be > nlags (for initializing the VAR)')
vprior.w = options_.bvar_prior_omega; end
lambda = options_.bvar_prior_lambda; train = options_.bvar_prior_train;
mu = options_.bvar_prior_mu;
flat = options_.bvar_prior_flat; if options_.first_obs + options_.presample - train <= nlags
error('first_obs+presample-train should be > nlags (for initializating the VAR)')
ny = size(dataset, 2); end
if options_.prefilter | options_.noconstant
nx = 0; 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 else
nx = 1; forecast_data.realized_val = [];
end end
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
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)
%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: % Original file downloaded from:
% http://sims.princeton.edu/yftp/VARtools/matlab/varprior.m % http://sims.princeton.edu/yftp/VARtools/matlab/varprior.m
if ~isempty(mnprior) if ~isempty(mnprior)
xdum = zeros(lags+1,nx,lags,nv); xdum = zeros(lags+1,nx,lags,nv);
ydum = zeros(lags+1,nv,lags,nv); ydum = zeros(lags+1,nv,lags,nv);
for il = 1:lags for il = 1:lags
ydum(il+1,:,il,:) = il^mnprior.decay*diag(vprior.sig); ydum(il+1,:,il,:) = il^mnprior.decay*diag(vprior.sig);
end end
ydum(1,:,1,:) = diag(vprior.sig); ydum(1,:,1,:) = diag(vprior.sig);
ydum = mnprior.tight*reshape(ydum,[lags+1,nv,lags*nv]); ydum = mnprior.tight*reshape(ydum,[lags+1,nv,lags*nv]);
ydum = flipdim(ydum,1); ydum = flipdim(ydum,1);
xdum = mnprior.tight*reshape(xdum,[lags+1,nx,lags*nv]); xdum = mnprior.tight*reshape(xdum,[lags+1,nx,lags*nv]);
xdum = flipdim(xdum,1); xdum = flipdim(xdum,1);
breaks = (lags+1)*[1:(nv*lags)]'; 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); lbreak = breaks(end);
else
ydum = [];
xdum = [];
breaks = [];
lbreak = 0;
end end
if ~isempty(vprior) & vprior.w>0 end
ydum2 = zeros(lags+1,nv,nv); dimy = size(ydum);
xdum2 = zeros(lags+1,nx,nv); ydum = reshape(permute(ydum,[1 3 2]),dimy(1)*dimy(3),nv);
ydum2(end,:,:) = diag(vprior.sig); xdum = reshape(permute(xdum,[1 3 2]),dimy(1)*dimy(3),nx);
for i = 1:vprior.w breaks = breaks(1:(end-1));
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));
function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu) function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)
%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: % Original file downloaded from:
% http://sims.princeton.edu/yftp/VARtools/matlab/rfvar3.m % http://sims.princeton.edu/yftp/VARtools/matlab/rfvar3.m
[T,nvar] = size(ydata); [T,nvar] = size(ydata);
nox = isempty(xdata); 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 if ~nox
[T2,nx] = size(xdata); xbar = mean(xdata(1:lags,:),1);
else else
T2 = T; xbar = [];
nx = 0;
xdata = zeros(T2,0);
end end
% note that x must be same length as y, even though first part of x will not be used. if lambda ~= 0
% This is so that the lags parameter can be changed without reshaping the xdata matrix. if lambda>0
if T2 ~= T, error('Mismatch of x and y data lengths'),end xdum = lambda*[repmat(ybar,1,lags) xbar];
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);
else else
xbar = []; lambda = -lambda;
end xdum = lambda*[repmat(ybar,1,lags) zeros(size(xbar))];
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];
end end
ydum = zeros(1,nvar);
ydum(1,:) = lambda*ybar;
y = [y;ydum];
X = [X;xdum];
end end
if mu>0
% Compute OLS regression and residuals xdum = [repmat(diag(ybar),1,lags) zeros(nvar,nx)]*mu;
[vl,d,vr] = svd(X,0); ydum = mu*diag(ybar);
di = 1./diag(d); X = [X;xdum];
B = (vr.*repmat(di',nvar*lags+nx,1))*vl'*y; y = [y;ydum];
u = y-X*B; end
xxi = vr.*repmat(di',nvar*lags+nx,1); end
xxi = xxi*xxi';
% Compute OLS regression and residuals
var.B = B; [vl,d,vr] = svd(X,0);
var.u = u; di = 1./diag(d);
var.xxi = xxi; 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global oo_ M_ vx 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);
ikx = [nstatic+1:nstatic+npred]; ncstr = 0;
ni = size(var_indices,1);
A = zeros(nx,nx); for i=1:nar+3
A(1:npred,:)=ghx(ikx,:); ncstr = ncstr + size(var_indices{i},1);
offset_r = npred; end
offset_c = 0; if cova
i0 = find(kstate(:,2) == M_.maximum_lag+1); if ncstr < M_.exo_nbr*(M_.exo_nbr+1)/2
n0 = size(i0,1); error(['number of preset variances is smaller than number of shock' ...
for i=M_.maximum_lag:-1:2 ' 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); i1 = find(kstate(:,2) == i);
n1 = size(i1,1); n1 = size(i1,1);
j = zeros(n1,1); j = zeros(n1,1);
for j1 = 1:n1 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 end
A(offset_r+1:offset_r+n1,offset_c+j)=eye(n1); A(offset_r+1:offset_r+n1,offset_c+j)=eye(n1);
offset_r = offset_r + n1; offset_r = offset_r + n1;
offset_c = offset_c + n0; offset_c = offset_c + n0;
i0 = i1; i0 = i1;
n0 = n1; n0 = n1;
end end
ghu1 = [ghu(ikx,:);zeros(nx-npred,M_.exo_nbr)]; ghu1 = [ghu(ikx,:);zeros(nx-npred,M_.exo_nbr)];
% IA = speye(nx*nx)-kron(A,A); % IA = speye(nx*nx)-kron(A,A);
% kron_ghu = kron(ghu1,ghu1); % 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}) 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 end
if i ~= 2 & i ~= 3 & ~isempty(var_indices{i}) 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
end end
if ~isempty(var_indices{2}) if ~isempty(var_indices{2})
var_indices{2}(:,2) = indnv(iv(var_indices{2}(:,2)),iiy); 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)); var_indices{2} = sub2ind([ny ny],var_indices{2}(:,1),var_indices{2}(:,2));
end end
if ~isempty(var_indices{3}) if ~isempty(var_indices{3})
var_indices{3} = sub2ind([M_.exo_nbr M_.exo_nbr],var_indices{3}(:,1),var_indices{3}(:,2)); var_indices{3} = sub2ind([M_.exo_nbr M_.exo_nbr],var_indices{3}(:,1),var_indices{3}(:,2));
end end
if isempty(M_.Sigma_e) if isempty(M_.Sigma_e)
M_.Sigma_e = 0.01*eye(M_.exo_nbr); M_.Sigma_e = 0.01*eye(M_.exo_nbr);
b = 0.1*ghu1*ghu1'; b = 0.1*ghu1*ghu1';
else else
b = ghu1*M_.Sigma_e*ghu1'; b = ghu1*M_.Sigma_e*ghu1';
M_.Sigma_e = chol(M_.Sigma_e+1e-14*eye(M_.exo_nbr)); M_.Sigma_e = chol(M_.Sigma_e+1e-14*eye(M_.exo_nbr));
end end
options=optimset('LargeScale','on','MaxFunEvals',20000*ny,'TolX',1e-4, ... options=optimset('LargeScale','on','MaxFunEvals',20000*ny,'TolX',1e-4, ...
'TolFun',1e-4,'Display','Iter','MaxIter',10000); '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]=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,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); 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); objective = calib_obj2(diag(M_.Sigma_e),A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar);
disp('CALIBRATION') disp('CALIBRATION')
disp('') disp('')
if ~isempty(var_indices{1}) if ~isempty(var_indices{1})
disp(sprintf('%16s %14s %14s %14s %14s','Std. Dev','Target','Obtained','Diff')); disp(sprintf('%16s %14s %14s %14s %14s','Std. Dev','Target','Obtained','Diff'));
str = ' '; str = ' ';
for i=1:size(var_indices{1},1) for i=1:size(var_indices{1},1)
[i1,i2] = ind2sub([ny ny],var_indices{1}(i)); [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)); 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); disp(str);
end end
end end
if ~isempty(var_indices{2}) if ~isempty(var_indices{2})
disp(sprintf('%32s %14s %14s','Correlations','Target','Obtained','Diff')); disp(sprintf('%32s %14s %14s','Correlations','Target','Obtained','Diff'));
str = ' '; str = ' ';
for i=1:size(var_indices{2},1) for i=1:size(var_indices{2},1)
[i1,i2]=ind2sub([ny ny],var_indices{2}(i)); [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)),:), ... 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)); M_.endo_names(order(iiy(i2)),:),targets{2}(i),objective{2}(i),objective{2}(i)-targets{2}(i));
disp(str); disp(str);
end end
end end
if ~isempty(var_indices{3}) if ~isempty(var_indices{3})
disp(sprintf('%32s %16s %16s','Constrained shocks (co)variances','Target','Obtained')); disp(sprintf('%32s %16s %16s','Constrained shocks (co)variances','Target','Obtained'));
str = ' '; str = ' ';
for i=1:size(var_indices{3},1) for i=1:size(var_indices{3},1)
[i1,i2]=ind2sub([M_.exo_nbr M_.exo_nbr],var_indices{3}(i)); [i1,i2]=ind2sub([M_.exo_nbr M_.exo_nbr],var_indices{3}(i));
if i1 == i2 if i1 == i2
str = sprintf('%32s: %16.4f %16.4f',M_.exo_name(order(i1),:), ... str = sprintf('%32s: %16.4f %16.4f',M_.exo_name(order(i1),:), ...
targets{3}(i),objective{3}(i)); targets{3}(i),objective{3}(i));
else else
str = sprintf('%16s,%16s: %16.4f %16.4f',M_.exo_name(order(i1),:), ... str = sprintf('%16s,%16s: %16.4f %16.4f',M_.exo_name(order(i1),:), ...
M_.exo_name(order(i2), :),targets{3}(i),objective{3}(i)); M_.exo_name(order(i2), :),targets{3}(i),objective{3}(i));
end end
disp(str); disp(str);
end end
end end
flag = 1; flag = 1;
for j=4:nar+3 for j=4:nar+3
if ~isempty(var_indices{j}) if ~isempty(var_indices{j})
if flag if flag
disp(sprintf('%16s %16s %16s','Autocorrelations','Target','Obtained')); disp(sprintf('%16s %16s %16s','Autocorrelations','Target','Obtained'));
str = ' '; str = ' ';
flag = 0; flag = 0;
end end
for i=1:size(var_indices{j},1) for i=1:size(var_indices{j},1)
[i1,i2] = ind2sub([ny ny],var_indices{j}(i)); [i1,i2] = ind2sub([ny ny],var_indices{j}(i));
str = sprintf('%16s(%d): %16.4f %16.4f',M_.endo_names(order(iiy(i1)),:), ... str = sprintf('%16s(%d): %16.4f %16.4f',M_.endo_names(order(iiy(i1)),:), ...
j-3,targets{j}(i),objective{j}(i)); j-3,targets{j}(i),objective{j}(i));
disp(str); disp(str);
end end
end 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);
disp('');
% 10/9/02 MJ 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global vx fold options_ global vx fold options_
oo_.gamma_y = cell(nar+1,1); oo_.gamma_y = cell(nar+1,1);
% M_.Sigma_e = M_.Sigma_e'*M_.Sigma_e; % M_.Sigma_e = M_.Sigma_e'*M_.Sigma_e;
M_.Sigma_e=diag(M_.Sigma_e); M_.Sigma_e=diag(M_.Sigma_e);
nx = size(ghx,2); nx = size(ghx,2);
b=ghu1*M_.Sigma_e*ghu1'; b=ghu1*M_.Sigma_e*ghu1';
vx = []; vx = [];
if isempty(vx) if isempty(vx)
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 else
[vx,status] = bicgstab_(@f_var,b(:),vx(:),1e-8,50,A,nx); [vx,status] = bicgstab_(@f_var,b(:),vx(:),1e-8,50,A,nx);
if status 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 else
vx=reshape(vx,nx,nx); vx=reshape(vx,nx,nx);
end end
end end
oo_.gamma_y{1} = ghx*vx*ghx'+ ghu*M_.Sigma_e*ghu'; oo_.gamma_y{1} = ghx*vx*ghx'+ ghu*M_.Sigma_e*ghu';
f = 0; f = 0;
if ~isempty(targets{1}) if ~isempty(targets{1})
e = targets{1}-sqrt(oo_.gamma_y{1}(iy{1})); e = targets{1}-sqrt(oo_.gamma_y{1}(iy{1}));
f = e'*(var_weights{1}.*e); f = e'*(var_weights{1}.*e);
end end
sy = sqrt(diag(oo_.gamma_y{1})); sy = sqrt(diag(oo_.gamma_y{1}));
sy = sy *sy'; sy = sy *sy';
if ~isempty(targets{2}) if ~isempty(targets{2})
e = targets{2}-oo_.gamma_y{1}(iy{2})./(sy(iy{2})+1e-10); e = targets{2}-oo_.gamma_y{1}(iy{2})./(sy(iy{2})+1e-10);
f = f+e'*(var_weights{2}.*e); f = f+e'*(var_weights{2}.*e);
end end
if ~isempty(targets{3}) if ~isempty(targets{3})
e = targets{3}-sqrt(M_.Sigma_e(iy{3})); e = targets{3}-sqrt(M_.Sigma_e(iy{3}));
f = f+e'*(var_weights{3}.*e); f = f+e'*(var_weights{3}.*e);
end end
% autocorrelations % autocorrelations
if nar > 0 if nar > 0
vxy = (A*vx*ghx'+ghu1*M_.Sigma_e*ghu'); vxy = (A*vx*ghx'+ghu1*M_.Sigma_e*ghu');
oo_.gamma_y{2} = ghx*vxy./(sy+1e-10); oo_.gamma_y{2} = ghx*vxy./(sy+1e-10);
if ~isempty(targets{4}) if ~isempty(targets{4})
e = targets{4}-oo_.gamma_y{2}(iy{4}); e = targets{4}-oo_.gamma_y{2}(iy{4});
f = f+e'*(var_weights{4}.*e); f = f+e'*(var_weights{4}.*e);
end end
for i=2:nar for i=2:nar
vxy = A*vxy; vxy = A*vxy;
oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10); oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10);
if ~isempty(targets{i+3}) if ~isempty(targets{i+3})
e = targets{i+3}-oo_.gamma_y{i+1}(iy{i+3}); e = targets{i+3}-oo_.gamma_y{i+1}(iy{i+3});
f = f+e'*(var_weights{i+3}.*e); f = f+e'*(var_weights{i+3}.*e);
end end
end end
end end
if isempty(fold) | f < 2*fold if isempty(fold) | f < 2*fold
fold = f; fold = f;
vxold = vx; vxold = vx;
end end
% 11/04/02 MJ generalized for correlations, autocorrelations and % 11/04/02 MJ generalized for correlations, autocorrelations and
% constraints on M_.Sigma_e % constraints on M_.Sigma_e
% 01/25/03 MJ targets std. dev. instead of variances % 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global vx fold options_ 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
sy = sqrt(diag(oo_.gamma_y{1})); objective = cell (nar+3);
sy = sy *sy'; oo_.gamma_y = cell(nar+1,1);
if ~isempty(targets{2}) 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); objective{2} = oo_.gamma_y{1}(iy{2})./(sy(iy{2})+1e-10);
end end
if ~isempty(targets{3}) if ~isempty(targets{3})
objective{3} = M_.Sigma_e(iy{3}); objective{3} = M_.Sigma_e(iy{3});
end end
% autocorrelations % autocorrelations
if nar > 0 if nar > 0
vxy = (A*vx*ghx'+ghu1*M_.Sigma_e*ghu'); vxy = (A*vx*ghx'+ghu1*M_.Sigma_e*ghu');
oo_.gamma_y{2} = ghx*vxy./(sy+1e-10); oo_.gamma_y{2} = ghx*vxy./(sy+1e-10);
if ~isempty(targets{4}) if ~isempty(targets{4})
objective{4} = oo_.gamma_y{2}(iy{4}); objective{4} = oo_.gamma_y{2}(iy{4});
end end
for i=2:nar for i=2:nar
vxy = A*vxy; vxy = A*vxy;
oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10); oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10);
if ~isempty(targets{i+3}) if ~isempty(targets{i+3})
objecitve{i+3} = oo_.gamma_y{i+1}(iy{i+3}); objecitve{i+3} = oo_.gamma_y{i+1}(iy{i+3});
end end
end end
end end
% 11/04/02 MJ generalized for correlations, autocorrelations and % 11/04/02 MJ generalized for correlations, autocorrelations and
% constraints on M_.Sigma_e % constraints on M_.Sigma_e

View File

@ -30,63 +30,63 @@ function result = check
global M_ options_ oo_ global M_ options_ oo_
if options_.block || options_.bytecode if options_.block || options_.bytecode
error('CHECK: incompatibility with "block" or "bytecode" option') 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 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
msg = 0; msg = 0;
if options_.bvar_dsge && options_.bayesian_irf if options_.bvar_dsge && options_.bayesian_irf
if ~isempty(varlist) if ~isempty(varlist)
for i=1:size(varlist,1) for i=1:size(varlist,1)
idx = strmatch(deblank(varlist(i,:)),options_.varobs,'exact'); idx = strmatch(deblank(varlist(i,:)),options_.varobs,'exact');
if isempty(idx) if isempty(idx)
disp([varlist(i,:) ' is not an observed variable!']); disp([varlist(i,:) ' is not an observed variable!']);
msg = 1; msg = 1;
end end
end end
if size(varlist,1)~=size(options_.varobs) if size(varlist,1)~=size(options_.varobs)
msg = 1; msg = 1;
end end
if msg if msg
disp(' ') disp(' ')
disp('Posterior IRFs will be computed for all observed variables.') disp('Posterior IRFs will be computed for all observed variables.')
disp(' ') disp(' ')
end end
end
varlist = options_.varobs;
return
end end
varlist = options_.varobs;
if isempty(varlist) return
disp(' ') end
disp(['You did not declare endogenous variables after the estimation command.'])
cas = []; if isempty(varlist)
if options_.bayesian_irf disp(' ')
cas = 'Posterior IRFs'; disp(['You did not declare endogenous variables after the estimation command.'])
end cas = [];
if options_.moments_varendo if options_.bayesian_irf
if isempty(cas) cas = 'Posterior IRFs';
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('')
end end
if options_.moments_varendo
if isempty(cas)
cas = 'Posterior moments';
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 else
line_of_text = [line_of_text , ' ' , token]; cas = [ cas , ', posterior moments'];
end
if index==max_number_of_words_per_line
disp(line_of_text)
index = 0;
line_of_text = [];
end end
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) 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() function check_model()
% Copyright (C) 2005-2006 Dynare Team % Copyright (C) 2005-2006 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ global M_
xlen = M_.maximum_exo_lag+M_.maximum_exo_lead + 1; xlen = M_.maximum_exo_lag+M_.maximum_exo_lead + 1;
if ~ M_.lead_lag_incidence(M_.maximum_lag+1,:) > 0 if ~ M_.lead_lag_incidence(M_.maximum_lag+1,:) > 0
error ('RESOL: Error in model specification: some variables don"t appear as current') ; error ('RESOL: Error in model specification: some variables don"t appear as current') ;
end end
if xlen > 1 if xlen > 1
error (['RESOL: stochastic exogenous variables must appear only at the' ... error (['RESOL: stochastic exogenous variables must appear only at the' ...
' current period. Use additional endogenous variables']) ; ' current period. Use additional endogenous variables']) ;
end end
if (M_.exo_det_nbr > 0) & (M_.maximum_lag > 1 | M_.maximum_lead > 1) if (M_.exo_det_nbr > 0) & (M_.maximum_lag > 1 | M_.maximum_lead > 1)
error(['Exogenous deterministic variables are currently only allowed in' ... error(['Exogenous deterministic variables are currently only allowed in' ...
' models with leads and lags on only one period']) ' models with leads and lags on only one period'])
end 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
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 if nargout>1
description = ''; description = 'select_posterior_draws has to be called.';
end end
return
%% Get informations about mcmc files. else
if ~exist([ M_.dname '/metropolis'],'dir') number_of_last_posterior_draws_file = length(drawsinfo);
disp('check_posterior_analysis_data:: Can''t find any mcmc file!') pddate = get_date_of_a_file([ M_.dname '/metropolis/' M_.fname '_posterior_draws'...
return int2str(number_of_last_posterior_draws_file) '.mat']);
end if pddate<mhdate
mhname = get_name_of_the_last_mh_file(M_); info = 2; % _posterior_draws files have to be updated.
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 if nargout>1
description = 'select_posterior_draws has to be called.'; description = 'posterior draws files have to be updated.';
end end
return return
else else
number_of_last_posterior_draws_file = length(drawsinfo); info = 3; % Ok!
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.
if nargout>1 if nargout>1
description = 'posterior draws files have to be processed.'; description = 'posterior draws files are up to date.';
end 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 else
number_of_the_last_post_data_file = length(pdfinfo); info = 6; % Ok (nothing to do ;-)
name_of_the_last_post_data_file = ... if nargout>1
[ './' M_.dname ... description = 'There is nothing to do';
'/metropolis/' ... end
M_.fname '_' ... end
generic_post_data_file_name ... end
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

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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
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']); info = 0;
name_of_the_last_prior_draw_file = prior_draws_info(end).name; if nargout>1
date_of_the_last_prior_draw_file = prior_draws_info(end).datenum; description = '';
end
%% Get informations about _posterior_draws files.
if isempty(prior_draws_info) %% Get informations about prior draws files.
info = 1; 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 if nargout>1
description = 'prior_sampler has to be called.'; description = 'prior draws files have to be updated.';
end end
return return
else else
number_of_last_prior_draws_file = length(prior_draws_info); info = 3; % Nothing to do!
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;
if nargout>1 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 end
return
else else
number_of_the_last_prior_data_file = length(pdfinfo); info = 6; % Ok (nothing to do ;-)
name_of_the_last_prior_data_file = pdinfo(end).name; if nargout>1
pdfdate = pdinfo(end).datenum; description = 'prior data files are up to date.';
% /!\ 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
end end
end end
end

View File

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

View File

@ -1,31 +1,31 @@
function moments=compute_model_moments(dr,M_,options_) function moments=compute_model_moments(dr,M_,options_)
% %
% INPUTS % INPUTS
% dr: structure describing model solution % dr: structure describing model solution
% M_: structure of Dynare options % M_: structure of Dynare options
% options_ % options_
% %
% OUTPUTS % OUTPUTS
% moments: a cell array containing requested moments % moments: a cell array containing requested moments
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2008 Dynare Team % Copyright (C) 2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
moments = th_autocovariances(dr,options_.varlist,M_,options_); 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
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_); if strcmpi(type,'posterior')
NumberOfExogenousVariables = M_.exo_nbr; posterior = 1;
list_of_exogenous_variables = M_.exo_names; if nargin==4
NumberOfLags = options_.ar; var_list_ = options_.varobs;
Steps = options_.conditional_variance_decomposition; 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. NumberOfEndogenousVariables = rows(var_list_);
if posterior NumberOfExogenousVariables = M_.exo_nbr;
for i=1:NumberOfEndogenousVariables list_of_exogenous_variables = M_.exo_names;
for j=i:NumberOfEndogenousVariables NumberOfLags = options_.ar;
oo_ = posterior_analysis('variance',var_list_(i,:),var_list_(j,:),[],options_,M_,oo_); Steps = options_.conditional_variance_decomposition;
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 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 i=1:NumberOfEndogenousVariables
for j=i:NumberOfEndogenousVariables for j=1:NumberOfEndogenousVariables
oo_ = prior_analysis('variance',var_list_(i,:),var_list_(j,:),[],options_,M_,oo_); oo_ = posterior_analysis('correlation',var_list_(i,:),var_list_(j,:),h,options_,M_,oo_);
end end
end end
end end
% CORRELATION FUNCTION. else
if posterior for h=NumberOfLags:-1:1
for h=NumberOfLags:-1:1 for i=1:NumberOfEndogenousVariables
for i=1:NumberOfEndogenousVariables for j=1:NumberOfEndogenousVariables
for j=1:NumberOfEndogenousVariables oo_ = prior_analysis('correlation',var_list_(i,:),var_list_(j,:),h,options_,M_,oo_);
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
end end
end end
end end
% VARIANCE DECOMPOSITION. end
if posterior % VARIANCE DECOMPOSITION.
for i=1:NumberOfEndogenousVariables if posterior
for j=1:NumberOfExogenousVariables for i=1:NumberOfEndogenousVariables
oo_ = posterior_analysis('decomposition',var_list_(i,:),M_.exo_names(j,:),[],options_,M_,oo_); for j=1:NumberOfExogenousVariables
end oo_ = posterior_analysis('decomposition',var_list_(i,:),M_.exo_names(j,:),[],options_,M_,oo_);
end 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 end
% CONDITIONAL VARIANCE DECOMPOSITION. else
if posterior for i=1:NumberOfEndogenousVariables
for i=1:NumberOfEndogenousVariables for j=1:NumberOfExogenousVariables
for j=1:NumberOfExogenousVariables oo_ = prior_analysis('decomposition',var_list_(i,:),M_.exo_names(j,:),[],options_,M_,oo_);
oo_ = posterior_analysis('conditional decomposition',var_list_(i,:),M_.exo_names(j,:),Steps,options_,M_,oo_);
end
end end
else end
for i=1:NumberOfEndogenousVariables end
for j=1:NumberOfExogenousVariables % CONDITIONAL VARIANCE DECOMPOSITION.
oo_ = prior_analysis('conditional decomposition',var_list_(i,:),M_.exo_names(j,:),Steps,options_,M_,oo_); if posterior
end 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 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
number_of_state_innovations = ... number_of_state_innovations = ...
StateSpaceModel.number_of_state_innovations; StateSpaceModel.number_of_state_innovations;
transition_matrix = StateSpaceModel.transition_matrix; transition_matrix = StateSpaceModel.transition_matrix;
number_of_state_equations = ... number_of_state_equations = ...
StateSpaceModel.number_of_state_equations; StateSpaceModel.number_of_state_equations;
nSteps = length(Steps); nSteps = length(Steps);
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 ConditionalVariance = zeros(number_of_state_equations,number_of_state_equations);
B = StateSpaceModel.impulse_matrix.* ... ConditionalVariance = repmat(ConditionalVariance,[1 1 nSteps ...
repmat(sqrt(diag(StateSpaceModel.state_innovations_covariance_matrix)'),... number_of_state_innovations]);
number_of_state_equations,1);
else if StateSpaceModel.sigma_e_is_diagonal
B = StateSpaceModel.impulse_matrix*chol(StateSpaceModel.state_innovations_covariance_matrix)'; B = StateSpaceModel.impulse_matrix.* ...
end repmat(sqrt(diag(StateSpaceModel.state_innovations_covariance_matrix)'),...
number_of_state_equations,1);
for i=1:number_of_state_innovations else
BB = B(:,i)*B(:,i)'; B = StateSpaceModel.impulse_matrix*chol(StateSpaceModel.state_innovations_covariance_matrix)';
V = zeros(number_of_state_equations,number_of_state_equations); end
m = 1;
for h = 1:max(Steps) for i=1:number_of_state_innovations
V = transition_matrix*V*transition_matrix'+BB; BB = B(:,i)*B(:,i)';
if h == Steps(m) V = zeros(number_of_state_equations,number_of_state_equations);
ConditionalVariance(:,:,m,i) = V; m = 1;
m = m+1; for h = 1:max(Steps)
end V = transition_matrix*V*transition_matrix'+BB;
if h == Steps(m)
ConditionalVariance(:,:,m,i) = V;
m = m+1;
end end
end end
end
ConditionalVariance = ConditionalVariance(SubsetOfVariables,SubsetOfVariables,:,:);
NumberOfVariables = length(SubsetOfVariables); ConditionalVariance = ConditionalVariance(SubsetOfVariables,SubsetOfVariables,:,:);
PackedConditionalVarianceDecomposition = zeros(NumberOfVariables*(NumberOfVariables+1)/2,length(Steps),StateSpaceModel.number_of_state_innovations); NumberOfVariables = length(SubsetOfVariables);
for i=1:number_of_state_innovations PackedConditionalVarianceDecomposition = zeros(NumberOfVariables*(NumberOfVariables+1)/2,length(Steps),StateSpaceModel.number_of_state_innovations);
for h = 1:length(Steps) for i=1:number_of_state_innovations
PackedConditionalVarianceDecomposition(:,h,i) = vech(ConditionalVariance(:,:,h,i)); for h = 1:length(Steps)
end PackedConditionalVarianceDecomposition(:,h,i) = vech(ConditionalVariance(:,:,h,i));
end 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if strcmpi(type,'posterior') if strcmpi(type,'posterior')
TYPE = 'Posterior'; TYPE = 'Posterior';
PATH = [dname '/metropolis/']; PATH = [dname '/metropolis/'];
else else
TYPE = 'Prior'; TYPE = 'Prior';
PATH = [dname '/prior/moments/']; PATH = [dname '/prior/moments/'];
end end
indx = check_name(vartan,var); indx = check_name(vartan,var);
if isempty(indx) if isempty(indx)
disp([ type '_analysis:: ' var ' is not a stationary endogenous variable!']) disp([ type '_analysis:: ' var ' is not a stationary endogenous variable!'])
return return
end end
endogenous_variable_index = sum(1:indx); endogenous_variable_index = sum(1:indx);
exogenous_variable_index = check_name(exonames,exo); exogenous_variable_index = check_name(exonames,exo);
if isempty(exogenous_variable_index) if isempty(exogenous_variable_index)
disp([ type '_analysis:: ' exo ' is not a declared exogenous variable!']) disp([ type '_analysis:: ' exo ' is not a declared exogenous variable!'])
return return
end end
name = [ var '.' exo ]; name = [ var '.' exo ];
if isfield(oo_, [ TYPE 'TheoreticalMoments' ]) if isfield(oo_, [ TYPE 'TheoreticalMoments' ])
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge') if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'ConditionalVarianceDecomposition') if isfield(temporary_structure,'ConditionalVarianceDecomposition')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean;']) eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean;'])
if isfield(temporary_structure,name) if isfield(temporary_structure,name)
if sum(Steps-temporary_structure.(name)(1,:)) == 0 if sum(Steps-temporary_structure.(name)(1,:)) == 0
% Nothing (new) to do here... % Nothing (new) to do here...
return return
end
end end
end end
end 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
p_mean = NaN(2,length(Steps)); ListOfFiles = dir([ PATH fname '_' TYPE 'ConditionalVarianceDecomposition*.mat']);
p_mean(1,:) = Steps; i1 = 1; tmp = zeros(NumberOfSimulations,length(Steps));
p_median = NaN(1,length(Steps)); for file = 1:length(ListOfFiles)
p_variance = NaN(1,length(Steps)); load([ PATH ListOfFiles(file).name ]);
p_deciles = NaN(9,length(Steps)); % 4D-array (endovar,time,exovar,simul)
p_density = NaN(2^9,2,length(Steps)); i2 = i1 + size(Conditional_decomposition_array,4) - 1;
p_hpdinf = NaN(1,length(Steps)); tmp(i1:i2,:) = transpose(dynare_squeeze(Conditional_decomposition_array(endogenous_variable_index,:,exogenous_variable_index,:)));
p_hpdsup = NaN(1,length(Steps)); i1 = i2+1;
for i=1:length(Steps) end
if ~isconst(tmp(:,i))
[pp_mean, pp_median, pp_var, hpd_interval, pp_deciles, pp_density] = ... p_mean = NaN(2,length(Steps));
posterior_moments(tmp(:,i),1,mh_conf_sig); p_mean(1,:) = Steps;
p_mean(2,i) = pp_mean; p_median = NaN(1,length(Steps));
p_median(i) = pp_median; p_variance = NaN(1,length(Steps));
p_variance(i) = pp_var; p_deciles = NaN(9,length(Steps));
p_deciles(:,i) = pp_deciles; p_density = NaN(2^9,2,length(Steps));
p_hpdinf(i) = hpd_interval(1); p_hpdinf = NaN(1,length(Steps));
p_hpdinf(i) = hpd_interval(2); p_hpdsup = NaN(1,length(Steps));
p_density(:,:,i) = pp_density; for i=1:length(Steps)
end 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 end
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean.' name ' = p_mean;']); end
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.median.' name ' = p_median;']); eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean.' name ' = p_mean;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.variance.' name ' = p_variance;']); eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.median.' name ' = p_median;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdinf.' name ' = p_hpdinf;']); eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.variance.' name ' = p_variance;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdsup.' name ' = p_hpdsup;']); eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdinf.' name ' = p_hpdinf;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.deciles.' name ' = p_deciles;']); eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdsup.' name ' = p_hpdsup;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.density.' name ' = p_density;']); 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if strcmpi(type,'posterior') if strcmpi(type,'posterior')
TYPE = 'Posterior'; TYPE = 'Posterior';
PATH = [dname '/metropolis/']; PATH = [dname '/metropolis/'];
else else
TYPE = 'Prior'; TYPE = 'Prior';
PATH = [dname '/prior/moments/']; PATH = [dname '/prior/moments/'];
end end
indx1 = check_name(vartan,var1); indx1 = check_name(vartan,var1);
if isempty(indx1) if isempty(indx1)
disp([ type '_analysis:: ' var1 ' is not a stationary endogenous variable!']) 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 return
end end
if ~isempty(var2) else
indx2 = check_name(vartan,var2); indx2 = indx1;
if isempty(indx2) var2 = var1;
disp([ type '_analysis:: ' var2 ' is not a stationary endogenous variable!']) end
return
end
else
indx2 = indx1;
var2 = var1;
end
if isfield(oo_,[TYPE 'TheoreticalMoments']) if isfield(oo_,[TYPE 'TheoreticalMoments'])
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge') if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'correlation') if isfield(temporary_structure,'correlation')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean;']) eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean;'])
if isfield(temporary_structure,var1) if isfield(temporary_structure,var1)
eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean.' var1 ';']) eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean.' var1 ';'])
if isfield(temporary_structure_1,var2) if isfield(temporary_structure_1,var2)
eval(['temporary_structure_2 = temporary_structure_1.' var2 ';']) eval(['temporary_structure_2 = temporary_structure_1.' var2 ';'])
l1 = length(temporary_structure_2); l1 = length(temporary_structure_2);
if l1<nar if l1<nar
% INITIALIZATION: % INITIALIZATION:
oo_ = initialize_output_structure(var1,var2,nar,type,oo_); oo_ = initialize_output_structure(var1,var2,nar,type,oo_);
delete([PATH fname '_' TYPE 'Correlations*']) delete([PATH fname '_' TYPE 'Correlations*'])
[nvar,vartan,NumberOfFiles] = ... [nvar,vartan,NumberOfFiles] = ...
dsge_simulated_theoretical_correlation(SampleSize,nar,M_,options_,oo_,type); dsge_simulated_theoretical_correlation(SampleSize,nar,M_,options_,oo_,type);
else
if ~isnan(temporary_structure_2(nar))
%Nothing to do.
return
end
end
else else
oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_); if ~isnan(temporary_structure_2(nar))
%Nothing to do.
return
end
end end
else else
oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_); 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 else
oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_); oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_);
end end
ListOfFiles = dir([ PATH fname '_' TYPE 'Correlations*.mat']); else
i1 = 1; tmp = zeros(SampleSize,1); oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_);
for file = 1:length(ListOfFiles) end
load([ PATH ListOfFiles(file).name ]); ListOfFiles = dir([ PATH fname '_' TYPE 'Correlations*.mat']);
i2 = i1 + rows(Correlation_array) - 1; i1 = 1; tmp = zeros(SampleSize,1);
tmp(i1:i2) = Correlation_array(:,indx1,indx2,nar); for file = 1:length(ListOfFiles)
i1 = i2+1; load([ PATH ListOfFiles(file).name ]);
end i2 = i1 + rows(Correlation_array) - 1;
name = [ var1 '.' var2 ]; tmp(i1:i2) = Correlation_array(:,indx1,indx2,nar);
if ~isconst(tmp) i1 = i2+1;
[p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ... end
posterior_moments(tmp,1,mh_conf_sig); name = [ var1 '.' var2 ];
if isfield(oo_,[ TYPE 'TheoreticalMoments']) if ~isconst(tmp)
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) [p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ...
if isfield(temporary_structure,'dsge') posterior_moments(tmp,1,mh_conf_sig);
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) if isfield(oo_,[ TYPE 'TheoreticalMoments'])
if isfield(temporary_structure,'correlation') eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'mean',nar,p_mean); if isfield(temporary_structure,'dsge')
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'median',nar,p_median); eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'variance',nar,p_var); if isfield(temporary_structure,'correlation')
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdinf',nar,hpd_interval(1)); oo_ = fill_output_structure(var1,var2,TYPE,oo_,'mean',nar,p_mean);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdsup',nar,hpd_interval(2)); oo_ = fill_output_structure(var1,var2,TYPE,oo_,'median',nar,p_median);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'deciles',nar,p_deciles); oo_ = fill_output_structure(var1,var2,TYPE,oo_,'variance',nar,p_var);
oo_ = fill_output_structure(var1,var2,TYPE,oo_,'density',nar,density); oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdinf',nar,hpd_interval(1));
end oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdsup',nar,hpd_interval(2));
end oo_ = fill_output_structure(var1,var2,TYPE,oo_,'deciles',nar,p_deciles);
end oo_ = fill_output_structure(var1,var2,TYPE,oo_,'density',nar,density);
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 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_) function oo_ = initialize_output_structure(var1,var2,nar,type,oo_)
name = [ var1 '.' var2 ]; name = [ var1 '.' var2 ];
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.mean.' name ' = NaN(' int2str(nar) ',1);']); 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.median.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.variance.' 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.hpdinf.' name ' = NaN(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.hpdsup.' 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.deciles.' name ' = cell(' int2str(nar) ',1);']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name ' = cell(' int2str(nar) ',1);']); eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name ' = cell(' int2str(nar) ',1);']);
for i=1:nar for i=1:nar
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name '(' int2str(i) ',1) = {NaN};']); eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name '(' int2str(i) ',1) = {NaN};']);
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.deciles.' name '(' int2str(i) ',1) = {NaN};']); eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.deciles.' name '(' int2str(i) ',1) = {NaN};']);
end end
function oo_ = fill_output_structure(var1,var2,type,oo_,moment,lag,result) function oo_ = fill_output_structure(var1,var2,type,oo_,moment,lag,result)
name = [ var1 '.' var2 ]; name = [ var1 '.' var2 ];
switch moment switch moment
case {'mean','median','variance','hpdinf','hpdsup'} case {'mean','median','variance','hpdinf','hpdsup'}
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = result;']); eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = result;']);
case {'deciles','density'} case {'deciles','density'}
eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = {result};']); eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = {result};']);
otherwise otherwise
disp('fill_output_structure:: Unknown field!') disp('fill_output_structure:: Unknown field!')
end end

View File

@ -1,41 +1,41 @@
function co = cosn(H); function co = cosn(H);
% function co = cosn(H); % function co = cosn(H);
% computes the cosine of the angle between the H(:,1) and its % computes the cosine of the angle between the H(:,1) and its
% projection onto the span of H(:,2:end) % projection onto the span of H(:,2:end)
% %
% Not the same as multiple correlation coefficient since the means are not % Not the same as multiple correlation coefficient since the means are not
% zero % zero
% %
% Copyright (C) 2008 Dynare Team % Copyright (C) 2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
y = H(:,1); y = H(:,1);
X = H(:,2:end); X = H(:,2:end);
% y = H(:,1); % y = H(:,1);
% X = H(:,2:end); % X = H(:,2:end);
yhat = X*(X\y); yhat = X*(X\y);
if rank(yhat), if rank(yhat),
co = y'*yhat/sqrt((y'*y)*(yhat'*yhat)); co = y'*yhat/sqrt((y'*y)*(yhat'*yhat));
else else
co=0; co=0;
end 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if strcmpi(type,'posterior') if strcmpi(type,'posterior')
TYPE = 'Posterior'; TYPE = 'Posterior';
PATH = [dname '/metropolis/']; PATH = [dname '/metropolis/'];
else else
TYPE = 'Prior'; TYPE = 'Prior';
PATH = [dname '/prior/moments/']; PATH = [dname '/prior/moments/'];
end end
indx1 = check_name(vartan,var1); indx1 = check_name(vartan,var1);
if isempty(indx1) if isempty(indx1)
disp([ type '_analysis:: ' var1 ' is not a stationary endogenous variable!']) 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 return
end end
if ~isempty(var2) else
indx2 = check_name(vartan,var2); indx2 = indx1;
if isempty(indx2) var2 = var1;
disp([ type '_analysis:: ' var2 ' is not a stationary endogenous variable!']) end
return
end
else
indx2 = indx1;
var2 = var1;
end
if isfield(oo_,[ TYPE 'TheoreticalMoments']) if isfield(oo_,[ TYPE 'TheoreticalMoments'])
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;'])
if isfield(temporary_structure,'dsge') if isfield(temporary_structure,'dsge')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;'])
if isfield(temporary_structure,'covariance') if isfield(temporary_structure,'covariance')
eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean;']) eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean;'])
if isfield(temporary_structure,var1) if isfield(temporary_structure,var1)
eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' var1 ';']) eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' var1 ';'])
if isfield(temporary_structure_1,var2) 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!). % Nothing to do (the covariance matrix is symmetric!).
return return
end 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 end
end end
end
ListOfFiles = dir([ PATH fname '_' TYPE '2ndOrderMoments*.mat']); ListOfFiles = dir([ PATH fname '_' TYPE '2ndOrderMoments*.mat']);
i1 = 1; tmp = zeros(NumberOfSimulations,1); i1 = 1; tmp = zeros(NumberOfSimulations,1);
for file = 1:length(ListOfFiles) for file = 1:length(ListOfFiles)
load([ PATH ListOfFiles(file).name ]); load([ PATH ListOfFiles(file).name ]);
i2 = i1 + rows(Covariance_matrix) - 1; i2 = i1 + rows(Covariance_matrix) - 1;
tmp(i1:i2) = Covariance_matrix(:,symmetric_matrix_index(indx1,indx2,nvar)); tmp(i1:i2) = Covariance_matrix(:,symmetric_matrix_index(indx1,indx2,nvar));
i1 = i2+1; i1 = i2+1;
end end
name = [var1 '.' var2]; name = [var1 '.' var2];
if ~isconst(tmp) if ~isconst(tmp)
[p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ... [p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ...
posterior_moments(tmp,1,mh_conf_sig); posterior_moments(tmp,1,mh_conf_sig);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' name ' = p_mean;']); 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.median.' name ' = p_median;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.variance.' name ' = p_var;']); 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.hpdinf.' name ' = hpd_interval(1);']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdsup.' name ' = hpd_interval(2);']); 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.deciles.' name ' = p_deciles;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = density;']); eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = density;']);
else else
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' name ' = NaN;']); eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.median.' 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.variance.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdinf.' 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.hpdsup.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.deciles.' name ' = NaN;']); eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.deciles.' name ' = NaN;']);
eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = NaN;']); eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = NaN;']);
end end

View File

@ -60,152 +60,152 @@ g = g0;
gnorm = norm(g); gnorm = norm(g);
% %
if (gnorm < 1.e-12) & ~badg % put ~badg 8/4/94 if (gnorm < 1.e-12) & ~badg % put ~badg 8/4/94
retcode =1; retcode =1;
dxnorm=0; dxnorm=0;
% gradient convergence % gradient convergence
else else
% with badg true, we don't try to match rate of improvement to directional % 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. % derivative. We're satisfied just to get some improvement in f.
% %
%if(badg) %if(badg)
% dx = -g*FCHANGE/(gnorm*gnorm); % dx = -g*FCHANGE/(gnorm*gnorm);
% dxnorm = norm(dx); % dxnorm = norm(dx);
% if dxnorm > 1e12 % if dxnorm > 1e12
% disp('Bad, small gradient problem.') % disp('Bad, small gradient problem.')
% dx = dx*FCHANGE/dxnorm; % dx = dx*FCHANGE/dxnorm;
% end % end
%else %else
% Gauss-Newton step; % Gauss-Newton step;
%---------- Start of 7/19/93 mod --------------- %---------- Start of 7/19/93 mod ---------------
%[v d] = eig(H0); %[v d] = eig(H0);
%toc %toc
%d=max(1e-10,abs(diag(d))); %d=max(1e-10,abs(diag(d)));
%d=abs(diag(d)); %d=abs(diag(d));
%dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g); %dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g);
% toc % toc
dx = -H0*g; dx = -H0*g;
% toc % toc
dxnorm = norm(dx); dxnorm = norm(dx);
if dxnorm > 1e12 if dxnorm > 1e12
disp('Near-singular H problem.') disp('Near-singular H problem.')
dx = dx*FCHANGE/dxnorm; dx = dx*FCHANGE/dxnorm;
end end
dfhat = dx'*g0; dfhat = dx'*g0;
%end %end
% %
% %
if ~badg if ~badg
% test for alignment of dx with gradient and fix if necessary % test for alignment of dx with gradient and fix if necessary
a = -dfhat/(gnorm*dxnorm); a = -dfhat/(gnorm*dxnorm);
if a<ANGLE if a<ANGLE
dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g; dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g;
dfhat = dx'*g; dfhat = dx'*g;
dxnorm = norm(dx); dxnorm = norm(dx);
disp(sprintf('Correct for low angle: %g',a)) disp(sprintf('Correct for low angle: %g',a))
end end
end end
disp(sprintf('Predicted improvement: %18.9f',-dfhat/2)) disp(sprintf('Predicted improvement: %18.9f',-dfhat/2))
% %
% Have OK dx, now adjust length of step (lambda) until min and % Have OK dx, now adjust length of step (lambda) until min and
% max improvement rate criteria are met. % max improvement rate criteria are met.
done=0; done=0;
factor=3; factor=3;
shrink=1; shrink=1;
lambdaMin=0; lambdaMin=0;
lambdaMax=inf; lambdaMax=inf;
lambdaPeak=0; lambdaPeak=0;
fPeak=f0; fPeak=f0;
lambdahat=0; lambdahat=0;
while ~done while ~done
if size(x0,2)>1 if size(x0,2)>1
dxtest=x0+dx'*lambda; dxtest=x0+dx'*lambda;
else else
dxtest=x0+dx*lambda; dxtest=x0+dx*lambda;
end end
% home % home
f = feval(fcn,dxtest,varargin{:}); f = feval(fcn,dxtest,varargin{:});
%ARGLIST %ARGLIST
%f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); %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); % f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8);
disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f )) disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f ))
%debug %debug
%disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda)) %disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda))
if f<fhat if f<fhat
fhat=f; fhat=f;
xhat=dxtest; xhat=dxtest;
lambdahat = lambda; lambdahat = lambda;
end end
fcount=fcount+1; fcount=fcount+1;
shrinkSignal = (~badg & (f0-f < max([-THETA*dfhat*lambda 0]))) | (badg & (f0-f) < 0) ; shrinkSignal = (~badg & (f0-f < max([-THETA*dfhat*lambda 0]))) | (badg & (f0-f) < 0) ;
growSignal = ~badg & ( (lambda > 0) & (f0-f > -(1-THETA)*dfhat*lambda) ); growSignal = ~badg & ( (lambda > 0) & (f0-f > -(1-THETA)*dfhat*lambda) );
if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) ) if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) )
if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak)) if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak))
shrink=1; shrink=1;
factor=factor^.6; factor=factor^.6;
while lambda/factor <= lambdaPeak while lambda/factor <= lambdaPeak
factor=factor^.6; 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 end
%if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB) if (lambda<lambdaMax) & (lambda>lambdaPeak)
if abs(factor-1)<MINDFAC lambdaMax=lambda;
if abs(lambda)<4
retcode=2;
else
retcode=7;
end
done=1;
end end
end lambda=lambda/factor;
if (lambda<lambdaMax) & (lambda>lambdaPeak) if abs(lambda) < MINLAMB
lambdaMax=lambda; if (lambda > 0) & (f0 <= fhat)
end % try going against gradient, which may be inaccurate
lambda=lambda/factor; lambda = -lambda*factor^6
if abs(lambda) < MINLAMB else
if (lambda > 0) & (f0 <= fhat) if lambda < 0
% try going against gradient, which may be inaccurate retcode = 6;
lambda = -lambda*factor^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 else
if lambda < 0 retcode=0;
retcode = 6;
else
retcode = 3;
end
done = 1;
end end
end end
elseif (growSignal & lambda>0) | (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0))) end
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
disp(sprintf('Norm of dx %10.5g', dxnorm)) 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) 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) %[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 % fcn: string naming the objective function to be minimized
% x0: initial value of the parameter vector % x0: initial value of the parameter vector
% H0: initial value for the inverse Hessian. Must be positive definite. % 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. % 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 % 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. % 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 % crit: Convergence criterion. Iteration will cease when it proves impossible to improve the
% function value by more than crit. % function value by more than crit.
% nit: Maximum number of iterations. % nit: Maximum number of iterations.
% method: integer scalar, 2, 3 or 5 points formula. % method: integer scalar, 2, 3 or 5 points formula.
% penalty: scalar double, size of the penality. % penalty: scalar double, size of the penality.
% varargin: A list of optional length of additional parameters that get handed off to fcn each % varargin: A list of optional length of additional parameters that get handed off to fcn each
% time it is called. % time it is called.
% Note that if the program ends abnormally, it is possible to retrieve the current x, % 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 % 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 % 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 % 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.) % may be a decent starting point. One can also start from the one with best function value.)
% Original file downloaded from: % Original file downloaded from:
% http://sims.princeton.edu/yftp/optimize/mfiles/csminwel.m % http://sims.princeton.edu/yftp/optimize/mfiles/csminwel.m
% Copyright (C) 1993-2007 Christopher Sims % Copyright (C) 1993-2007 Christopher Sims
% Copyright (C) 2006-2008 Dynare Team % Copyright (C) 2006-2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ global bayestopt_
fh = []; fh = [];
xh = []; xh = [];
[nx,no]=size(x0); [nx,no]=size(x0);
nx=max(nx,no); nx=max(nx,no);
Verbose=1; Verbose=1;
NumGrad= isempty(grad); NumGrad= isempty(grad);
done=0; done=0;
itct=0; itct=0;
fcount=0; fcount=0;
snit=100; snit=100;
%tailstr = ')'; %tailstr = ')';
%stailstr = []; %stailstr = [];
% Lines below make the number of Pi's optional. This is inefficient, though, and precludes % 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 % 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 % changed with the editor for each application. Places where this is required are marked
% with ARGLIST comments % with ARGLIST comments
%for i=nargin-6:-1:1 %for i=nargin-6:-1:1
% tailstr=[ ',P' num2str(i) tailstr]; % tailstr=[ ',P' num2str(i) tailstr];
% stailstr=[' P' num2str(i) stailstr]; % stailstr=[' P' num2str(i) stailstr];
%end %end
[f0,cost_flag] = feval(fcn,x0,varargin{:}); [f0,cost_flag] = feval(fcn,x0,varargin{:});
if ~cost_flag if ~cost_flag
disp('Bad initial parameter.') disp('Bad initial parameter.')
return return
end end
if NumGrad if NumGrad
switch method switch method
case 2 case 2
[g,badg] = numgrad(fcn,x0, varargin{:}); [g,badg] = numgrad(fcn,x0, varargin{:});
case 3 case 3
[g,badg] = numgrad3(fcn,x0, varargin{:}); [g,badg] = numgrad3(fcn,x0, varargin{:});
case 5 case 5
[g,badg] = numgrad5(fcn,x0, varargin{:}); [g,badg] = numgrad5(fcn,x0, varargin{:});
end end
else else
[g,badg] = feval(grad,x0,varargin{:}); [g,badg] = feval(grad,x0,varargin{:});
end end
retcode3=101; retcode3=101;
x=x0; x=x0;
f=f0; f=f0;
H=H0; H=H0;
cliff=0; cliff=0;
while ~done while ~done
bayestopt_.penalty = f; bayestopt_.penalty = f;
g1=[]; g2=[]; g3=[]; g1=[]; g2=[]; g3=[];
%addition fj. 7/6/94 for control %addition fj. 7/6/94 for control
disp('-----------------') disp('-----------------')
disp('-----------------') disp('-----------------')
%disp('f and x at the beginning of new iteration') %disp('f and x at the beginning of new iteration')
disp(sprintf('f at the beginning of new iteration, %20.10f',f)) disp(sprintf('f at the beginning of new iteration, %20.10f',f))
%-----------Comment out this line if the x vector is long---------------- %-----------Comment out this line if the x vector is long----------------
% disp([sprintf('x = ') sprintf('%15.8g %15.8g %15.8g %15.8g\n',x)]); % disp([sprintf('x = ') sprintf('%15.8g %15.8g %15.8g %15.8g\n',x)]);
%------------------------- %-------------------------
itct=itct+1; itct=itct+1;
[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,varargin{:}); [f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,varargin{:});
%ARGLIST %ARGLIST
%[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,P1,P2,P3,P4,P5,P6,P7,... %[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,P1,P2,P3,P4,P5,P6,P7,...
% P8,P9,P10,P11,P12,P13); % P8,P9,P10,P11,P12,P13);
% itct=itct+1; % itct=itct+1;
fcount = fcount+fc; fcount = fcount+fc;
% erased on 8/4/94 % erased on 8/4/94
% if (retcode == 1) | (abs(f1-f) < crit) % if (retcode == 1) | (abs(f1-f) < crit)
% done=1; % done=1;
% end % end
% if itct > nit % if itct > nit
% done = 1; % done = 1;
% retcode = -retcode; % retcode = -retcode;
% end % end
if retcode1 ~= 1 if retcode1 ~= 1
if retcode1==2 | retcode1==4 if retcode1==2 | retcode1==4
wall1=1; badg1=1; wall1=1; badg1=1;
else else
if NumGrad if NumGrad
switch method switch method
case 2 case 2
[g1 badg1] = numgrad(fcn, x1,varargin{:}); [g1 badg1] = numgrad(fcn, x1,varargin{:});
case 3 case 3
[g1 badg1] = numgrad3(fcn, x1,varargin{:}); [g1 badg1] = numgrad3(fcn, x1,varargin{:});
case 5 case 5
[g1,badg1] = numgrad5(fcn,x0, varargin{:}); [g1,badg1] = numgrad5(fcn,x0, varargin{:});
end end
else else
[g1 badg1] = feval(grad,x1,varargin{:}); [g1 badg1] = feval(grad,x1,varargin{:});
end end
wall1=badg1; wall1=badg1;
% g1 % g1
save g1.mat g1 x1 f1 varargin; save g1.mat g1 x1 f1 varargin;
%ARGLIST %ARGLIST
%save g1 g1 x1 f1 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; %save g1 g1 x1 f1 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end end
if wall1 % & (~done) by Jinill if wall1 % & (~done) by Jinill
% Bad gradient or back and forth on step length. Possibly at % Bad gradient or back and forth on step length. Possibly at
% cliff edge. Try perturbing search direction. % cliff edge. Try perturbing search direction.
% %
%fcliff=fh;xcliff=xh; %fcliff=fh;xcliff=xh;
Hcliff=H+diag(diag(H).*rand(nx,1)); Hcliff=H+diag(diag(H).*rand(nx,1));
disp('Cliff. Perturbing search direction.') disp('Cliff. Perturbing search direction.')
[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,varargin{:}); [f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,varargin{:});
%ARGLIST %ARGLIST
%[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,P1,P2,P3,P4,... %[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,P1,P2,P3,P4,...
% P5,P6,P7,P8,P9,P10,P11,P12,P13); % P5,P6,P7,P8,P9,P10,P11,P12,P13);
fcount = fcount+fc; % put by Jinill fcount = fcount+fc; % put by Jinill
if f2 < f if f2 < f
if retcode2==2 | retcode2==4 if retcode2==2 | retcode2==4
wall2=1; badg2=1; wall2=1; badg2=1;
else else
if NumGrad if NumGrad
switch method switch method
case 2 case 2
[g2 badg2] = numgrad(fcn, x2,varargin{:}); [g2 badg2] = numgrad(fcn, x2,varargin{:});
case 3 case 3
[g2 badg2] = numgrad3(fcn, x2,varargin{:}); [g2 badg2] = numgrad3(fcn, x2,varargin{:});
case 5 case 5
[g2,badg2] = numgrad5(fcn,x0, varargin{:}); [g2,badg2] = numgrad5(fcn,x0, varargin{:});
end end
else else
[g2 badg2] = feval(grad,x2,varargin{:}); [g2 badg2] = feval(grad,x2,varargin{:});
end end
wall2=badg2; wall2=badg2;
% g2 % g2
badg2 badg2
save g2.mat g2 x2 f2 varargin save g2.mat g2 x2 f2 varargin
%ARGLIST %ARGLIST
%save g2 g2 x2 f2 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; %save g2 g2 x2 f2 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end end
if wall2 if wall2
disp('Cliff again. Try traversing') disp('Cliff again. Try traversing')
if norm(x2-x1) < 1e-13 if norm(x2-x1) < 1e-13
f3=f; x3=x; badg3=1;retcode3=101; f3=f; x3=x; badg3=1;retcode3=101;
else else
gcliff=((f2-f1)/((norm(x2-x1))^2))*(x2-x1); gcliff=((f2-f1)/((norm(x2-x1))^2))*(x2-x1);
if(size(x0,2)>1), gcliff=gcliff', end if(size(x0,2)>1), gcliff=gcliff', end
[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),varargin{:}); [f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),varargin{:});
%ARGLIST %ARGLIST
%[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),P1,P2,P3,... %[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),P1,P2,P3,...
% P4,P5,P6,P7,P8,... % P4,P5,P6,P7,P8,...
% P9,P10,P11,P12,P13); % P9,P10,P11,P12,P13);
fcount = fcount+fc; % put by Jinill fcount = fcount+fc; % put by Jinill
if retcode3==2 | retcode3==4 if retcode3==2 | retcode3==4
wall3=1; badg3=1; wall3=1; badg3=1;
else else
if NumGrad if NumGrad
switch method switch method
case 2 case 2
[g3 badg3] = numgrad(fcn, x3,varargin{:}); [g3 badg3] = numgrad(fcn, x3,varargin{:});
case 3 case 3
[g3 badg3] = numgrad3(fcn, x3,varargin{:}); [g3 badg3] = numgrad3(fcn, x3,varargin{:});
case 5 case 5
[g3,badg3] = numgrad5(fcn,x0, varargin{:}); [g3,badg3] = numgrad5(fcn,x0, varargin{:});
end end
else else
[g3 badg3] = feval(grad,x3,varargin{:}); [g3 badg3] = feval(grad,x3,varargin{:});
end end
wall3=badg3; wall3=badg3;
% g3 % g3
save g3.mat g3 x3 f3 varargin; save g3.mat g3 x3 f3 varargin;
%ARGLIST %ARGLIST
%save g3 g3 x3 f3 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; %save g3 g3 x3 f3 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end end
end end
else else
f3=f; x3=x; badg3=1; retcode3=101; f3=f; x3=x; badg3=1; retcode3=101;
end end
else else
f3=f; x3=x; badg3=1;retcode3=101; f3=f; x3=x; badg3=1;retcode3=101;
end end
else else
% normal iteration, no walls, or else we're finished here. % normal iteration, no walls, or else we're finished here.
f2=f; f3=f; badg2=1; badg3=1; retcode2=101; retcode3=101; f2=f; f3=f; badg2=1; badg3=1; retcode2=101; retcode3=101;
end end
else else
f2=f;f3=f;f1=f;retcode2=retcode1;retcode3=retcode1; f2=f;f3=f;f1=f;retcode2=retcode1;retcode3=retcode1;
end end
%how to pick gh and xh %how to pick gh and xh
if f3 < f - crit & badg3==0 & f3 < f2 & f3 < f1 if f3 < f - crit & badg3==0 & f3 < f2 & f3 < f1
ih=3; ih=3;
fh=f3;xh=x3;gh=g3;badgh=badg3;retcodeh=retcode3; fh=f3;xh=x3;gh=g3;badgh=badg3;retcodeh=retcode3;
elseif f2 < f - crit & badg2==0 & f2 < f1 elseif f2 < f - crit & badg2==0 & f2 < f1
ih=2; ih=2;
fh=f2;xh=x2;gh=g2;badgh=badg2;retcodeh=retcode2; fh=f2;xh=x2;gh=g2;badgh=badg2;retcodeh=retcode2;
elseif f1 < f - crit & badg1==0 elseif f1 < f - crit & badg1==0
ih=1; ih=1;
fh=f1;xh=x1;gh=g1;badgh=badg1;retcodeh=retcode1; fh=f1;xh=x1;gh=g1;badgh=badg1;retcodeh=retcode1;
else else
[fh,ih] = min([f1,f2,f3]); [fh,ih] = min([f1,f2,f3]);
%disp(sprintf('ih = %d',ih)) %disp(sprintf('ih = %d',ih))
%eval(['xh=x' num2str(ih) ';']) %eval(['xh=x' num2str(ih) ';'])
switch ih switch ih
case 1 case 1
xh=x1; xh=x1;
case 2 case 2
xh=x2; xh=x2;
case 3 case 3
xh=x3; xh=x3;
end %case end %case
%eval(['gh=g' num2str(ih) ';']) %eval(['gh=g' num2str(ih) ';'])
%eval(['retcodeh=retcode' num2str(ih) ';']) %eval(['retcodeh=retcode' num2str(ih) ';'])
retcodei=[retcode1,retcode2,retcode3]; retcodei=[retcode1,retcode2,retcode3];
retcodeh=retcodei(ih); retcodeh=retcodei(ih);
if exist('gh') if exist('gh')
nogh=isempty(gh); nogh=isempty(gh);
else else
nogh=1; nogh=1;
end end
if nogh if nogh
if NumGrad if NumGrad
switch method switch method
case 2 case 2
[gh,badgh] = numgrad(fcn,xh,varargin{:}); [gh,badgh] = numgrad(fcn,xh,varargin{:});
case 3 case 3
[gh,badgh] = numgrad3(fcn,xh,varargin{:}); [gh,badgh] = numgrad3(fcn,xh,varargin{:});
case 5 case 5
[gh,badgh] = numgrad5(fcn,xh,varargin{:}); [gh,badgh] = numgrad5(fcn,xh,varargin{:});
end end
else else
[gh badgh] = feval(grad, xh,varargin{:}); [gh badgh] = feval(grad, xh,varargin{:});
end end
end end
badgh=1; badgh=1;
end end
%end of picking %end of picking
%ih %ih
%fh %fh
%xh %xh
%gh %gh
%badgh %badgh
stuck = (abs(fh-f) < crit); stuck = (abs(fh-f) < crit);
if (~badg)&(~badgh)&(~stuck) if (~badg)&(~badgh)&(~stuck)
H = bfgsi(H,gh-g,xh-x); H = bfgsi(H,gh-g,xh-x);
end end
if Verbose if Verbose
disp('----') disp('----')
disp(sprintf('Improvement on iteration %d = %18.9f',itct,f-fh)) disp(sprintf('Improvement on iteration %d = %18.9f',itct,f-fh))
end end
% if Verbose % if Verbose
if itct > nit if itct > nit
disp('iteration count termination') disp('iteration count termination')
done = 1; done = 1;
elseif stuck elseif stuck
disp('improvement < crit termination') disp('improvement < crit termination')
done = 1; done = 1;
end end
rc=retcodeh; rc=retcodeh;
if rc == 1 if rc == 1
disp('zero gradient') disp('zero gradient')
elseif rc == 6 elseif rc == 6
disp('smallest step still improving too slow, reversed gradient') disp('smallest step still improving too slow, reversed gradient')
elseif rc == 5 elseif rc == 5
disp('largest step still improving too fast') disp('largest step still improving too fast')
elseif (rc == 4) | (rc==2) elseif (rc == 4) | (rc==2)
disp('back and forth on step length never finished') disp('back and forth on step length never finished')
elseif rc == 3 elseif rc == 3
disp('smallest step still improving too slow') disp('smallest step still improving too slow')
elseif rc == 7 elseif rc == 7
disp('warning: possible inaccuracy in H matrix') disp('warning: possible inaccuracy in H matrix')
end end
% end % end
f=fh; f=fh;
x=xh; x=xh;
g=gh; g=gh;
badg=badgh; badg=badgh;
end end
% what about making an m-file of 10 lines including numgrad.m % what about making an m-file of 10 lines including numgrad.m
% since it appears three times in csminwel.m % since it appears three times in csminwel.m

View File

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

View File

@ -1,63 +1,63 @@
function datatomfile (s,var_list) function datatomfile (s,var_list)
% 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 % 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. % variable preceeds the corresponding results. This command must follow SIMUL.
% %
% INPUTS % INPUTS
% s: data file name % s: data file name
% var_list: vector of selected endogenous variables % var_list: vector of selected endogenous variables
% %
% OUTPUTS % OUTPUTS
% none % none
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2001-2009 Dynare Team % Copyright (C) 2001-2009 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ global M_ oo_
sm=[s,'.m']; sm=[s,'.m'];
fid=fopen(sm,'w') ; fid=fopen(sm,'w') ;
if size(var_list,1) == 0 if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr,:); var_list = M_.endo_names(1:M_.orig_endo_nbr,:);
end end
n = size(var_list,1); n = size(var_list,1);
ivar=zeros(n,1); ivar=zeros(n,1);
for i=1:n for i=1:n
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact');
if isempty(i_tmp) if isempty(i_tmp)
error (['One of the specified variables does not exist']) ; error (['One of the specified variables does not exist']) ;
else else
ivar(i) = i_tmp; ivar(i) = i_tmp;
end end
end end
for i = 1:n for i = 1:n
fprintf(fid,[M_.endo_names(ivar(i),:), '=['],'\n') ; fprintf(fid,[M_.endo_names(ivar(i),:), '=['],'\n') ;
fprintf(fid,'\n') ; fprintf(fid,'\n') ;
fprintf(fid,'%15.8g\n',oo_.endo_simul(ivar(i),:)') ; fprintf(fid,'%15.8g\n',oo_.endo_simul(ivar(i),:)') ;
fprintf(fid,'\n') ; fprintf(fid,'\n') ;
fprintf(fid,'];\n') ; fprintf(fid,'];\n') ;
fprintf(fid,'\n') ; fprintf(fid,'\n') ;
end end
fclose(fid) ; fclose(fid) ;

View File

@ -24,27 +24,27 @@ ftest(s1,0) ;
i = [lag1(1):size(x,2)-lag1(2)+1]' ; i = [lag1(1):size(x,2)-lag1(2)+1]' ;
if size(options_.smpl,1) == 1 if size(options_.smpl,1) == 1
error(['DSAMPLE not specified.']) ; error(['DSAMPLE not specified.']) ;
end end
if options_.smpl(3) > 0 if options_.smpl(3) > 0
if options_.smpl(3) == 2 if options_.smpl(3) == 2
if options_.smpl(1)<0 | options_.smpl(2)>size(x,2)-lag1(2) if options_.smpl(1)<0 | options_.smpl(2)>size(x,2)-lag1(2)
error ('Wrong sample.') ; error ('Wrong sample.') ;
end end
i = [options_.smpl(1)+lag1(1):options_.smpl(2)+lag1(1)]' ; i = [options_.smpl(1)+lag1(1):options_.smpl(2)+lag1(1)]' ;
elseif options_.smpl(3) == 1 elseif options_.smpl(3) == 1
if options_.smpl(1)>size(x,2)-lag1(2) if options_.smpl(1)>size(x,2)-lag1(2)
error ('Wrong sample.') ; error ('Wrong sample.') ;
end end
i = [lag1(1):options_.smpl(1)+lag1(1)]' ; i = [lag1(1):options_.smpl(1)+lag1(1)]' ;
end end
end end
j = bseastr(nvx,nvy) ; j = bseastr(nvx,nvy) ;
if stop if stop
return ; return ;
end end
z = mean(mean(abs(x(j,i)-y(j,i)))) ; 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
m = length(Vector); m = length(Vector);
n = (sqrt(1+8*m)-1)/2; n = (sqrt(1+8*m)-1)/2;
k = cumsum(1:n); k = cumsum(1:n);
d = Vector(k); d = Vector(k);

View File

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

View File

@ -1,107 +1,107 @@
function disp_identification(pdraws, idemodel, idemoments, disp_pcorr) function disp_identification(pdraws, idemodel, idemoments, disp_pcorr)
% Copyright (C) 2008 Dynare Team % Copyright (C) 2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ global bayestopt_
if nargin<4 | isempty(disp_pcorr), if nargin<4 | isempty(disp_pcorr),
disp_pcorr=0; disp_pcorr=0;
end end
[SampleSize, npar] = size(pdraws); [SampleSize, npar] = size(pdraws);
jok = 0; jok = 0;
jokP = 0; jokP = 0;
jokJ = 0; jokJ = 0;
jokPJ = 0; jokPJ = 0;
if ~any(any(idemodel.ind==0)) if ~any(any(idemodel.ind==0))
disp(['All parameters are identified in the model in the MC sample (rank of H).' ]), disp(['All parameters are identified in the model in the MC sample (rank of H).' ]),
disp(' ') disp(' ')
end end
if ~any(any(idemoments.ind==0)) if ~any(any(idemoments.ind==0))
disp(['All parameters are identified by J moments in the MC sample (rank of J)' ]), disp(['All parameters are identified by J moments in the MC sample (rank of J)' ]),
end end
for j=1:npar, for j=1:npar,
if any(idemodel.ind(j,:)==0), if any(idemodel.ind(j,:)==0),
pno = 100*length(find(idemodel.ind(j,:)==0))/SampleSize; 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(['Parameter ',bayestopt_.name{j},' is not identified in the model for ',num2str(pno),'% of MC runs!' ])
disp(' ') disp(' ')
end end
if any(idemoments.ind(j,:)==0), if any(idemoments.ind(j,:)==0),
pno = 100*length(find(idemoments.ind(j,:)==0))/SampleSize; 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(['Parameter ',bayestopt_.name{j},' is not identified by J moments for ',num2str(pno),'% of MC runs!' ])
disp(' ') disp(' ')
end end
if any(idemodel.ind(j,:)==1), if any(idemodel.ind(j,:)==1),
iok = find(idemodel.ind(j,:)==1); iok = find(idemodel.ind(j,:)==1);
jok = jok+1; jok = jok+1;
kok(jok) = j; kok(jok) = j;
mmin(jok,1) = min(idemodel.Mco(j,iok)); mmin(jok,1) = min(idemodel.Mco(j,iok));
mmean(jok,1) = mean(idemodel.Mco(j,iok)); mmean(jok,1) = mean(idemodel.Mco(j,iok));
mmax(jok,1) = max(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); [ipmax, jpmax] = find(abs(squeeze(idemodel.Pco(j,[1:j-1,j+1:end],iok)))>0.95);
if ~isempty(ipmax) if ~isempty(ipmax)
jokP = jokP+1; jokP = jokP+1;
kokP(jokP) = j; kokP(jokP) = j;
ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1; ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1;
[N,X]=hist(ipmax,[1:npar]); [N,X]=hist(ipmax,[1:npar]);
jpM(jokP)={find(N)}; jpM(jokP)={find(N)};
NPM(jokP)={N(find(N))./SampleSize.*100}; NPM(jokP)={N(find(N))./SampleSize.*100};
pmeanM(jokP)={mean(squeeze(idemodel.Pco(j,find(N),iok))')}; pmeanM(jokP)={mean(squeeze(idemodel.Pco(j,find(N),iok))')};
pminM(jokP)={min(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))')}; pmaxM(jokP)={max(squeeze(idemodel.Pco(j,find(N),iok))')};
end end
end end
if any(idemoments.ind(j,:)==1), if any(idemoments.ind(j,:)==1),
iok = find(idemoments.ind(j,:)==1); iok = find(idemoments.ind(j,:)==1);
jokJ = jokJ+1; jokJ = jokJ+1;
kokJ(jokJ) = j; kokJ(jokJ) = j;
mminJ(jokJ,1) = min(idemoments.Mco(j,iok)); mminJ(jokJ,1) = min(idemoments.Mco(j,iok));
mmeanJ(jokJ,1) = mean(idemoments.Mco(j,iok)); mmeanJ(jokJ,1) = mean(idemoments.Mco(j,iok));
mmaxJ(jokJ,1) = max(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); [ipmax, jpmax] = find(abs(squeeze(idemoments.Pco(j,[1:j-1,j+1:end],iok)))>0.95);
if ~isempty(ipmax) if ~isempty(ipmax)
jokPJ = jokPJ+1; jokPJ = jokPJ+1;
kokPJ(jokPJ) = j; kokPJ(jokPJ) = j;
ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1; ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1;
[N,X]=hist(ipmax,[1:npar]); [N,X]=hist(ipmax,[1:npar]);
jpJ(jokPJ)={find(N)}; jpJ(jokPJ)={find(N)};
NPJ(jokPJ)={N(find(N))./SampleSize.*100}; NPJ(jokPJ)={N(find(N))./SampleSize.*100};
pmeanJ(jokPJ)={mean(squeeze(idemoments.Pco(j,find(N),iok))')}; pmeanJ(jokPJ)={mean(squeeze(idemoments.Pco(j,find(N),iok))')};
pminJ(jokPJ)={min(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))')}; pmaxJ(jokPJ)={max(squeeze(idemoments.Pco(j,find(N),iok))')};
end end
end end
end end
dyntable('Multi collinearity in the model:',strvcat('param','min','mean','max'), ... dyntable('Multi collinearity in the model:',strvcat('param','min','mean','max'), ...
strvcat(bayestopt_.name(kok)),[mmin, mmean, mmax],10,10,6); strvcat(bayestopt_.name(kok)),[mmin, mmean, mmax],10,10,6);
dyntable('Multi collinearity for moments in J:',strvcat('param','min','mean','max'), ... dyntable('Multi collinearity for moments in J:',strvcat('param','min','mean','max'), ...
strvcat(bayestopt_.name(kokJ)),[mminJ, mmeanJ, mmaxJ],10,10,6); strvcat(bayestopt_.name(kokJ)),[mminJ, mmeanJ, mmaxJ],10,10,6);
if disp_pcorr, if disp_pcorr,
for j=1:length(kokP), for j=1:length(kokP),
dyntable([bayestopt_.name{kokP(j)},' pairwise correlations in the model'],strvcat(' ','min','mean','max'), ... 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); strvcat(bayestopt_.name{jpM{j}}),[pminM{j}' pmeanM{j}' pmaxM{j}'],10,10,3);
end end
for j=1:length(kokPJ), for j=1:length(kokPJ),
dyntable([bayestopt_.name{kokPJ(j)},' pairwise correlations in J moments'],strvcat(' ','min','mean','max'), ... 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); strvcat(bayestopt_.name{jpJ{j}}),[pminJ{j}' pmeanJ{j}' pmaxJ{j}'],10,10,3);
end end
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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
disp(' ') disp(' ')
disp('MODEL SUMMARY') disp('MODEL SUMMARY')
disp(' ') disp(' ')
disp([' Number of variables: ' int2str(M.endo_nbr)]) disp([' Number of variables: ' int2str(M.endo_nbr)])
disp([' Number of stochastic shocks: ' int2str(M.exo_nbr)]) disp([' Number of stochastic shocks: ' int2str(M.exo_nbr)])
disp([' Number of state variables: ' ... disp([' Number of state variables: ' ...
int2str(length(find(dr.kstate(:,2) <= M.maximum_lag+1)))]) int2str(length(find(dr.kstate(:,2) <= M.maximum_lag+1)))])
disp([' Number of jumpers: ' ... disp([' Number of jumpers: ' ...
int2str(length(find(dr.kstate(:,2) == M.maximum_lag+2)))]) int2str(length(find(dr.kstate(:,2) == M.maximum_lag+2)))])
disp([' Number of static variables: ' int2str(dr.nstatic)]) disp([' Number of static variables: ' int2str(dr.nstatic)])
my_title='MATRIX OF COVARIANCE OF EXOGENOUS SHOCKS'; my_title='MATRIX OF COVARIANCE OF EXOGENOUS SHOCKS';
labels = deblank(M.exo_names); labels = deblank(M.exo_names);
headers = strvcat('Variables',labels); headers = strvcat('Variables',labels);
lh = size(labels,2)+2; lh = size(labels,2)+2;
dyntable(my_title,headers,labels,M.Sigma_e,lh,10,6); 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ oo_ global M_ options_ oo_
warning_old_state = warning;
warning off
if options_.hp_filter warning_old_state = warning;
error('STOCH_SIMUL: HP filter is not yet implemented for empirical moments') warning off
end
if options_.hp_filter
if size(var_list,1) == 0 error('STOCH_SIMUL: HP filter is not yet implemented for empirical moments')
var_list = M_.endo_names(1:M_.orig_endo_nbr, :); end
end
if size(var_list,1) == 0
nvar = size(var_list,1); var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
ivar=zeros(nvar,1); end
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); nvar = size(var_list,1);
if isempty(i_tmp) 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']) ; error (['One of the variable specified does not exist']) ;
else else
ivar(i) = i_tmp; ivar(i) = i_tmp;
end
end end
end
y = y(ivar,options_.drop+M_.maximum_lag+1: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);
labels = deblank(M_.endo_names(ivar,:)); m = mean(y);
y = y - repmat(m,size(y,1),1);
if options_.nomoments == 0 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)' ]; z = [ m' s' s2' (mean(y.^3)./s2.^1.5)' (mean(y.^4)./(s2.*s2)-3)' ];
title='MOMENTS OF SIMULATED VARIABLES'; title='MOMENTS OF SIMULATED VARIABLES';
if options_.hp_filter if options_.hp_filter
title = [title ' (HP filter, lambda = ' ... title = [title ' (HP filter, lambda = ' ...
int2str(options_.hp_filter) ')']; int2str(options_.hp_filter) ')'];
end end
headers=strvcat('VARIABLE','MEAN','STD. DEV.','VARIANCE','SKEWNESS', ... headers=strvcat('VARIABLE','MEAN','STD. DEV.','VARIANCE','SKEWNESS', ...
'KURTOSIS'); 'KURTOSIS');
dyntable(title,headers,labels,z,size(labels,2)+2,16,6); dyntable(title,headers,labels,z,size(labels,2)+2,16,6);
end end
if options_.nocorr == 0 if options_.nocorr == 0
corr = (y'*y/size(y,1))./(s'*s); corr = (y'*y/size(y,1))./(s'*s);
title = 'CORRELATION OF SIMULATED VARIABLES'; title = 'CORRELATION OF SIMULATED VARIABLES';
if options_.hp_filter if options_.hp_filter
title = [title ' (HP filter, lambda = ' ... title = [title ' (HP filter, lambda = ' ...
int2str(options_.hp_filter) ')']; int2str(options_.hp_filter) ')'];
end end
headers = strvcat('VARIABLE',M_.endo_names(ivar,:)); headers = strvcat('VARIABLE',M_.endo_names(ivar,:));
dyntable(title,headers,labels,corr,size(labels,2)+2,8,4); dyntable(title,headers,labels,corr,size(labels,2)+2,8,4);
end end
ar = options_.ar; ar = options_.ar;
options_ = set_default_option(options_,'ar',5); options_ = set_default_option(options_,'ar',5);
ar = options_.ar; ar = options_.ar;
if ar > 0 if ar > 0
autocorr = []; autocorr = [];
for i=1:ar for i=1:ar
oo_.autocorr{i} = y(ar+1:end,:)'*y(ar+1-i:end-i,:)./((size(y,1)-ar)*s'*s); 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}) ]; autocorr = [ autocorr diag(oo_.autocorr{i}) ];
end end
title = 'AUTOCORRELATION OF SIMULATED VARIABLES'; title = 'AUTOCORRELATION OF SIMULATED VARIABLES';
if options_.hp_filter if options_.hp_filter
title = [title ' (HP filter, lambda = ' ... title = [title ' (HP filter, lambda = ' ...
int2str(options_.hp_filter) ')']; int2str(options_.hp_filter) ')'];
end end
headers = strvcat('VARIABLE',int2str([1:ar]')); headers = strvcat('VARIABLE',int2str([1:ar]'));
dyntable(title,headers,labels,autocorr,size(labels,2)+2,8,4); dyntable(title,headers,labels,autocorr,size(labels,2)+2,8,4);
end end
warning(warning_old_state); warning(warning_old_state);

View File

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

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

View File

@ -38,37 +38,37 @@ sigma2 = sigma^2;
mu2 = mu^2; mu2 = mu^2;
if type == 2; % Inverse Gamma 2 if type == 2; % Inverse Gamma 2
nu = 2*(2+mu2/sigma2); nu = 2*(2+mu2/sigma2);
s = 2*mu*(1+mu2/sigma2); s = 2*mu*(1+mu2/sigma2);
elseif type == 1; % Inverse Gamma 1 elseif type == 1; % Inverse Gamma 1
if sigma2 < Inf; if sigma2 < Inf;
nu = sqrt(2*(2+mu2/sigma2)); nu = sqrt(2*(2+mu2/sigma2));
nu2 = 2*nu; nu2 = 2*nu;
nu1 = 2; nu1 = 2;
err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2; err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2;
while abs(nu2-nu1) > 1e-12 while abs(nu2-nu1) > 1e-12
if err > 0 if err > 0
nu1 = nu; nu1 = nu;
if nu < nu2 if nu < nu2
nu = nu2; nu = nu2;
else else
nu = 2*nu; nu = 2*nu;
nu2 = nu; nu2 = nu;
end end
else else
nu2 = nu; nu2 = nu;
end end
nu = (nu1+nu2)/2; nu = (nu1+nu2)/2;
err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2; err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2;
end end
s = (sigma2+mu2)*(nu-2); s = (sigma2+mu2)*(nu-2);
else; else;
nu = 2; nu = 2;
s = 2*mu2/pi; s = 2*mu2/pi;
end; end;
else; else;
s = -1; s = -1;
nu = -1; nu = -1;
end; end;
% 01/18/2004 MJ replaced fsolve with secant % 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% Check input aruments. % Check input aruments.
if ~(nargin==3 || nargin==5 || nargin==4 ) if ~(nargin==3 || nargin==5 || nargin==4 )
error('mode_and_variance_to mean:: 3 or 5 input arguments are needed!') 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 end
end
% Set defaults bounds. if nargin==4
if nargin==3 switch distribution
switch distribution case 1
case 1 upper_bound = Inf;
lower_bound = 0; case 3
upper_bound = Inf; upper_bound = Inf;
case 3 case 2
lower_bound = 0; upper_bound = Inf;
upper_bound = Inf; case 4
case 2 upper_bound = 1;
lower_bound = 0; otherwise
upper_bound = Inf; error('Unknown distribution!')
case 4
lower_bound = 0;
upper_bound = 1;
otherwise
error('Unknown distribution!')
end
end end
if nargin==4 end
switch distribution
case 1
upper_bound = Inf; if (distribution==1)% Gamma distribution
case 3 if m<lower_bound
upper_bound = Inf; error('The mode has to be greater than the lower bound!')
case 2
upper_bound = Inf;
case 4
upper_bound = 1;
otherwise
error('Unknown distribution!')
end
end end
if (m-lower_bound)<1e-12
error('The gamma distribution should be specified with the mean and variance.')
if (distribution==1)% Gamma distribution end
if m<lower_bound m = m - lower_bound ;
error('The mode has to be greater than the lower bound!') beta = -.5*m*(1-sqrt(1+4*s2/(m*m))) ;
end alpha = (m+beta)/beta ;
if (m-lower_bound)<1e-12 parameters(1) = alpha;
error('The gamma distribution should be specified with the mean and variance.') parameters(2) = beta;
end mu = alpha*beta + lower_bound ;
m = m - lower_bound ; return
beta = -.5*m*(1-sqrt(1+4*s2/(m*m))) ; end
alpha = (m+beta)/beta ;
parameters(1) = alpha; if (distribution==2)% Inverse Gamma - 2 distribution
parameters(2) = beta; if m<lower_bound+2*eps
mu = alpha*beta + lower_bound ; error('The mode has to be greater than the lower bound!')
return
end end
m = m - lower_bound ;
if (distribution==2)% Inverse Gamma - 2 distribution if isinf(s2)
if m<lower_bound+2*eps nu = 4;
error('The mode has to be greater than the lower bound!') s = 2*m;
end else
m = m - lower_bound ; delta = 2*(m*m/s2);
if isinf(s2) poly = [ 1 , -(8+delta) , 20-4*delta , -(16+4*delta) ];
nu = 4; all_roots = roots(poly);
s = 2*m; real_roots = all_roots(find(abs(imag(all_roots))<2*eps));
else nu = real_roots(find(real_roots>2));
delta = 2*(m*m/s2); s = m*(nu+2);
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
end end
parameters(1) = nu;
if (distribution==3)% Inverted Gamma 1 distribution parameters(2) = s;
if m<lower_bound+2*eps mu = s/(nu-2) + lower_bound;
error('The mode has to be greater than the lower bound!') return
end end
m = m - lower_bound ;
if isinf(s2) if (distribution==3)% Inverted Gamma 1 distribution
nu = 2; if m<lower_bound+2*eps
s = 3*(m*m); error('The mode has to be greater than the lower bound!')
else end
[mu, parameters] = mode_and_variance_to_mean(m,s2,2); m = m - lower_bound ;
nu = sqrt(parameters(1)); if isinf(s2)
nu2 = 2*nu; nu = 2;
nu1 = 2; s = 3*(m*m);
err = s2/(m*m) - (nu+1)/(nu-2) + .5*(nu+1)*(gamma((nu-1)/2)/gamma(nu/2))^2; else
while abs(nu2-nu1) > 1e-12 [mu, parameters] = mode_and_variance_to_mean(m,s2,2);
if err < 0 nu = sqrt(parameters(1));
nu1 = nu; nu2 = 2*nu;
if nu < nu2 nu1 = 2;
nu = nu2; err = s2/(m*m) - (nu+1)/(nu-2) + .5*(nu+1)*(gamma((nu-1)/2)/gamma(nu/2))^2;
else while abs(nu2-nu1) > 1e-12
nu = 2*nu; if err < 0
nu2 = nu; nu1 = nu;
end if nu < nu2
nu = nu2;
else else
nu = 2*nu;
nu2 = nu; nu2 = nu;
end end
nu = (nu1+nu2)/2; else
err = s2/(m*m) - (nu+1)/(nu-2) + .5*(nu+1)*(gamma((nu-1)/2)/gamma(nu/2))^2; nu2 = nu;
end 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 end
parameters(1) = nu; s = (nu+1)*(m*m) ;
parameters(2) = s;
mu = sqrt(.5*s)*gamma(.5*(nu-1))/gamma(.5*nu) + lower_bound ;
return
end end
parameters(1) = nu;
if (distribution==4)% Beta distribution parameters(2) = s;
if m<lower_bound mu = sqrt(.5*s)*gamma(.5*(nu-1))/gamma(.5*nu) + lower_bound ;
error('The mode has to be greater than the lower bound!') return
end end
if m>upper_bound
error('The mode has to be less than the upper bound!') if (distribution==4)% Beta distribution
end if m<lower_bound
if (m-lower_bound)<1e-12 error('The mode has to be greater than the lower bound!')
error('The beta distribution should be specified with the mean and variance.') end
end if m>upper_bound
if (upper_bound-m)<1e-12 error('The mode has to be less than the upper bound!')
error('The beta distribution should be specified with the mean and variance.') end
end if (m-lower_bound)<1e-12
ll = upper_bound-lower_bound; error('The beta distribution should be specified with the mean and variance.')
m = (m-lower_bound)/ll; end
s2 = s2/(ll*ll); if (upper_bound-m)<1e-12
delta = m^2/s2; error('The beta distribution should be specified with the mean and variance.')
poly = NaN(1,4); end
poly(1) = 1; ll = upper_bound-lower_bound;
poly(2) = 7*m-(1-m)*delta-3; m = (m-lower_bound)/ll;
poly(3) = 16*m^2-14*m+3-2*m*delta+delta; s2 = s2/(ll*ll);
poly(4) = 12*m^3-16*m^2+7*m-1; delta = m^2/s2;
all_roots = roots(poly); poly = NaN(1,4);
real_roots = all_roots(find(abs(imag(all_roots))<2*eps)); poly(1) = 1;
idx = find(real_roots>1); poly(2) = 7*m-(1-m)*delta-3;
if length(idx)>1 poly(3) = 16*m^2-14*m+3-2*m*delta+delta;
error('Multiplicity of solutions for the beta distribution specification.') poly(4) = 12*m^3-16*m^2+7*m-1;
elseif isempty(idx) all_roots = roots(poly);
disp('No solution for the beta distribution specification. You should reduce the variance.') real_roots = all_roots(find(abs(imag(all_roots))<2*eps));
error(); idx = find(real_roots>1);
end if length(idx)>1
alpha = real_roots(idx); error('Multiplicity of solutions for the beta distribution specification.')
beta = ((1-m)*alpha+2*m-1)/m; elseif isempty(idx)
parameters(1) = alpha; disp('No solution for the beta distribution specification. You should reduce the variance.')
parameters(2) = beta; error();
mu = alpha/(alpha+beta)*(upper_bound-lower_bound)+lower_bound; end
return alpha = real_roots(idx);
end 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
density = (2*pi)^(-.5*n) * ... density = (2*pi)^(-.5*n) * ...
prod(diag(Sigma_upper_chol))^(-1) * ... prod(diag(Sigma_upper_chol))^(-1) * ...
exp(-.5*(X-Mean)*(Sigma_upper_chol\(transpose(Sigma_upper_chol)\transpose(X-Mean)))); 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
nn = length(X); nn = length(X);
t1 = gamma( .5*(nn+df) ) / ( gamma( .5*nn ) * (df*pi)^(.5*nn) ) ; t1 = gamma( .5*(nn+df) ) / ( gamma( .5*nn ) * (df*pi)^(.5*nn) ) ;
t2 = t1 / prod(diag(Sigma_upper_chol)) ; 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)); 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
X = randn(v, m) * H_inv_upper_chol; X = randn(v, m) * H_inv_upper_chol;
% 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); % At this point, X'*X is Wishart distributed
SSi = 1 ./ (diag(S) .^ 2); % G = inv(X'*X);
G = (V .* repmat(SSi', m, 1)) * V';
% 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
B1 = randn(n * p, 1); B1 = randn(n * p, 1);
B2 = kron(Omega_lower_chol, Sigma_lower_chol) * B1; B2 = kron(Omega_lower_chol, Sigma_lower_chol) * B1;
B3 = reshape(B2, n, p); B3 = reshape(B2, n, p);
B = B3 + M; 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
n = length(Mean); n = length(Mean);
draw = Mean + randn(1,n) * Sigma_upper_chol * sqrt(df/sum(randn(df,1).^2)); 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)
%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 % Copyright (C) 2008 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
%task %task
info = 0; info = 0;
klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1;
kstate = dr.kstate; kstate = dr.kstate;
kad = dr.kad; kad = dr.kad;
kae = dr.kae; kae = dr.kae;
nstatic = dr.nstatic; nstatic = dr.nstatic;
nfwrd = dr.nfwrd; nfwrd = dr.nfwrd;
npred = dr.npred; npred = dr.npred;
nboth = dr.nboth; nboth = dr.nboth;
order_var = dr.order_var; order_var = dr.order_var;
nd = size(kstate,1); nd = size(kstate,1);
nz = nnz(M_.lead_lag_incidence); nz = nnz(M_.lead_lag_incidence);
sdyn = M_.endo_nbr - nstatic; sdyn = M_.endo_nbr - nstatic;
k0 = M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var); 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),:); k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:);
b = jacobia_(:,k0); b = jacobia_(:,k0);
if M_.maximum_endo_lead == 0; % backward models if M_.maximum_endo_lead == 0; % backward models
a = jacobia_(:,nonzeros(k1')); a = jacobia_(:,nonzeros(k1'));
dr.ghx = zeros(size(a)); dr.ghx = zeros(size(a));
m = 0; m = 0;
for i=M_.maximum_endo_lag:-1:1 for i=M_.maximum_endo_lag:-1:1
k = nonzeros(M_.lead_lag_incidence(i,order_var)); k = nonzeros(M_.lead_lag_incidence(i,order_var));
dr.ghx(:,m+[1:length(k)]) = -b\a(:,k); dr.ghx(:,m+[1:length(k)]) = -b\a(:,k);
m = m+length(k); m = m+length(k);
end end
if M_.exo_nbr & task~=1 if M_.exo_nbr & task~=1
jacobia_ jacobia_
jacobia_(:,nz+1:end) jacobia_(:,nz+1:end)
b b
dr.ghu = -b\jacobia_(:,nz+1:end); dr.ghu = -b\jacobia_(:,nz+1:end);
disp(['nz=' int2str(nz) ]); disp(['nz=' int2str(nz) ]);
dr.ghu dr.ghu
end end
dr.eigval = eig(transition_matrix(dr,M_)); dr.eigval = eig(transition_matrix(dr,M_));
dr.rank = 0; dr.rank = 0;
if any(abs(dr.eigval) > options_.qz_criterium) if any(abs(dr.eigval) > options_.qz_criterium)
temp = sort(abs(dr.eigval)); temp = sort(abs(dr.eigval));
nba = nnz(abs(dr.eigval) > options_.qz_criterium); nba = nnz(abs(dr.eigval) > options_.qz_criterium);
temp = temp(nd-nba+1:nd)-1-options_.qz_criterium; temp = temp(nd-nba+1:nd)-1-options_.qz_criterium;
info(1) = 3; info(1) = 3;
info(2) = temp'*temp; info(2) = temp'*temp;
end end
return; return;
end end
%forward--looking models %forward--looking models
if nstatic > 0 if nstatic > 0
[Q,R] = qr(b(:,1:nstatic)); [Q,R] = qr(b(:,1:nstatic));
aa = Q'*jacobia_; aa = Q'*jacobia_;
else else
aa = jacobia_; aa = jacobia_;
end end
a = aa(:,nonzeros(k1')); a = aa(:,nonzeros(k1'));
b = aa(:,k0); b = aa(:,k0);
b10 = b(1:nstatic,1:nstatic); b10 = b(1:nstatic,1:nstatic);
b11 = b(1:nstatic,nstatic+1:end); b11 = b(1:nstatic,nstatic+1:end);
b2 = b(nstatic+1:end,nstatic+1:end); b2 = b(nstatic+1:end,nstatic+1:end);
if any(isinf(a(:))) if any(isinf(a(:)))
info = 1; info = 1;
return return
end end
% buildind D and E % buildind D and E
%nd %nd
d = zeros(nd,nd) ; d = zeros(nd,nd) ;
e = d ; e = d ;
k = find(kstate(:,2) >= M_.maximum_endo_lag+2 & kstate(:,3)); k = find(kstate(:,2) >= M_.maximum_endo_lag+2 & kstate(:,3));
d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ; d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ;
k1 = find(kstate(:,2) == M_.maximum_endo_lag+2); k1 = find(kstate(:,2) == M_.maximum_endo_lag+2);
e(1:sdyn,k1) = -b2(:,kstate(k1,1)-nstatic); e(1:sdyn,k1) = -b2(:,kstate(k1,1)-nstatic);
k = find(kstate(:,2) <= M_.maximum_endo_lag+1 & kstate(:,4)); k = find(kstate(:,2) <= M_.maximum_endo_lag+1 & kstate(:,4));
e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ; e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ;
k2 = find(kstate(:,2) == M_.maximum_endo_lag+1); k2 = find(kstate(:,2) == M_.maximum_endo_lag+1);
k2 = k2(~ismember(kstate(k2,1),kstate(k1,1))); k2 = k2(~ismember(kstate(k2,1),kstate(k1,1)));
d(1:sdyn,k2) = b2(:,kstate(k2,1)-nstatic); d(1:sdyn,k2) = b2(:,kstate(k2,1)-nstatic);
if ~isempty(kad) if ~isempty(kad)
for j = 1:size(kad,1) for j = 1:size(kad,1)
d(sdyn+j,kad(j)) = 1 ; d(sdyn+j,kad(j)) = 1 ;
e(sdyn+j,kae(j)) = 1 ; e(sdyn+j,kae(j)) = 1 ;
end end
end end
%e %e
%d %d
[ss,tt,w,sdim,dr.eigval,info1] = mjdgges(e,d,options_.qz_criterium); [ss,tt,w,sdim,dr.eigval,info1] = mjdgges(e,d,options_.qz_criterium);
if info1 if info1
info(1) = 2; info(1) = 2;
info(2) = info1; info(2) = info1;
return return
end end
nba = nd-sdim; nba = nd-sdim;
nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1); nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1);
if task == 1 if task == 1
dr.rank = rank(w(1:nyf,nd-nyf+1:end)); dr.rank = rank(w(1:nyf,nd-nyf+1:end));
% Under Octave, eig(A,B) doesn't exist, and % Under Octave, eig(A,B) doesn't exist, and
% lambda = qz(A,B) won't return infinite eigenvalues % lambda = qz(A,B) won't return infinite eigenvalues
if ~exist('OCTAVE_VERSION') if ~exist('OCTAVE_VERSION')
dr.eigval = eig(e,d); dr.eigval = eig(e,d);
end end
return return
end end
if nba ~= nyf if nba ~= nyf
temp = sort(abs(dr.eigval)); temp = sort(abs(dr.eigval));
if nba > nyf if nba > nyf
temp = temp(nd-nba+1:nd-nyf)-1-options_.qz_criterium; temp = temp(nd-nba+1:nd-nyf)-1-options_.qz_criterium;
info(1) = 3; info(1) = 3;
elseif nba < nyf; elseif nba < nyf;
temp = temp(nd-nyf+1:nd-nba)-1-options_.qz_criterium; temp = temp(nd-nyf+1:nd-nba)-1-options_.qz_criterium;
info(1) = 4; info(1) = 4;
end end
info(2) = temp'*temp; info(2) = temp'*temp;
return return
end end
np = nd - nyf; np = nd - nyf;
n2 = np + 1; n2 = np + 1;
n3 = nyf; n3 = nyf;
n4 = n3 + 1; n4 = n3 + 1;
% derivatives with respect to dynamic state variables % derivatives with respect to dynamic state variables
% forward variables % forward variables
w1 =w(1:n3,n2:nd); w1 =w(1:n3,n2:nd);
if condest(w1) > 1e9; if condest(w1) > 1e9;
info(1) = 5; info(1) = 5;
info(2) = condest(w1); info(2) = condest(w1);
return; return;
else else
gx = -w1'\w(n4:nd,n2:nd)'; gx = -w1'\w(n4:nd,n2:nd)';
end end
% predetermined variables % predetermined variables
hx = w(1:n3,1:np)'*gx+w(n4:nd,1:np)'; 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); hx = (tt(1:np,1:np)*hx)\(ss(1:np,1:np)*hx);
k1 = find(kstate(n4:nd,2) == M_.maximum_endo_lag+1); k1 = find(kstate(n4:nd,2) == M_.maximum_endo_lag+1);
k2 = find(kstate(1:n3,2) == M_.maximum_endo_lag+2); k2 = find(kstate(1:n3,2) == M_.maximum_endo_lag+2);
hx(k1,:) hx(k1,:)
gx(k2(nboth+1:end),:) gx(k2(nboth+1:end),:)
dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)]; dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)];
dr.ghx dr.ghx
%lead variables actually present in the model %lead variables actually present in the model
j3 = nonzeros(kstate(:,3)); j3 = nonzeros(kstate(:,3));
j4 = find(kstate(:,3)); j4 = find(kstate(:,3));
% derivatives with respect to exogenous variables % derivatives with respect to exogenous variables
disp(['M_.exo_nbr=' int2str(M_.exo_nbr)]); disp(['M_.exo_nbr=' int2str(M_.exo_nbr)]);
if M_.exo_nbr if M_.exo_nbr
fu = aa(:,nz+(1:M_.exo_nbr)); fu = aa(:,nz+(1:M_.exo_nbr));
a1 = b; a1 = b;
aa1 = []; aa1 = [];
if nstatic > 0 if nstatic > 0
aa1 = a1(:,1:nstatic); aa1 = a1(:,1:nstatic);
end end
dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ... dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ...
npred) a1(:,nstatic+npred+1:end)]\fu; npred) a1(:,nstatic+npred+1:end)]\fu;
else else
dr.ghu = []; dr.ghu = [];
end end
% static variables % static variables
if nstatic > 0 if nstatic > 0
temp = -a(1:nstatic,j3)*gx(j4,:)*hx; temp = -a(1:nstatic,j3)*gx(j4,:)*hx;
j5 = find(kstate(n4:nd,4)); j5 = find(kstate(n4:nd,4));
temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4))); temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4)));
temp = b10\(temp-b11*dr.ghx); temp = b10\(temp-b11*dr.ghx);
dr.ghx = [temp; dr.ghx]; dr.ghx = [temp; dr.ghx];
temp = []; temp = [];
end end
if options_.loglinear == 1 if options_.loglinear == 1
k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1); k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1);
klag = dr.kstate(k,[1 2]); klag = dr.kstate(k,[1 2]);
k1 = dr.order_var; k1 = dr.order_var;
dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ... 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); 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; dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu;
end end
%% Necessary when using Sims' routines for QZ %% Necessary when using Sims' routines for QZ
if options_.use_qzdiv if options_.use_qzdiv
gx = real(gx); gx = real(gx);
hx = real(hx); hx = real(hx);
dr.ghx = real(dr.ghx); dr.ghx = real(dr.ghx);
dr.ghu = real(dr.ghu); dr.ghu = real(dr.ghu);
end end
%exogenous deterministic variables %exogenous deterministic variables
if M_.exo_det_nbr > 0 if M_.exo_det_nbr > 0
f1 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var)))); 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)))); f0 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var))));
fudet = sparse(jacobia_(:,nz+M_.exo_nbr+1:end)); 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)]); M1 = inv(f0+[zeros(M_.endo_nbr,nstatic) f1*gx zeros(M_.endo_nbr,nyf-nboth)]);
M2 = M1*f1; M2 = M1*f1;
dr.ghud = cell(M_.exo_det_length,1); dr.ghud = cell(M_.exo_det_length,1);
dr.ghud{1} = -M1*fudet; dr.ghud{1} = -M1*fudet;
for i = 2:M_.exo_det_length for i = 2:M_.exo_det_length
dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:); dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:);
end end
end end
if options_.order == 1 if options_.order == 1
return return
end end
% Second order % Second order
%tempex = oo_.exo_simul ; %tempex = oo_.exo_simul ;
%hessian = real(hessext('ff1_',[z; oo_.exo_steady_state]))' ; %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)); kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1));
if M_.maximum_endo_lag > 0 if M_.maximum_endo_lag > 0
kk = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); kk]; kk = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); kk];
end end
kk = kk'; kk = kk';
kk = find(kk(:)); kk = find(kk(:));
nk = size(kk,1) + M_.exo_nbr + M_.exo_det_nbr; nk = size(kk,1) + M_.exo_nbr + M_.exo_det_nbr;
k1 = M_.lead_lag_incidence(:,order_var); k1 = M_.lead_lag_incidence(:,order_var);
k1 = k1'; k1 = k1';
k1 = k1(:); k1 = k1(:);
k1 = k1(kk); k1 = k1(kk);
k2 = find(k1); k2 = find(k1);
kk1(k1(k2)) = k2; kk1(k1(k2)) = k2;
kk1 = [kk1 length(k1)+1:length(k1)+M_.exo_nbr+M_.exo_det_nbr]; kk1 = [kk1 length(k1)+1:length(k1)+M_.exo_nbr+M_.exo_det_nbr];
kk = reshape([1:nk^2],nk,nk); kk = reshape([1:nk^2],nk,nk);
kk1 = kk(kk1,kk1); kk1 = kk(kk1,kk1);
%[junk,junk,hessian] = feval([M_.fname '_dynamic'],z, oo_.exo_steady_state); %[junk,junk,hessian] = feval([M_.fname '_dynamic'],z, oo_.exo_steady_state);
hessian(:,kk1(:)) = hessian; hessian(:,kk1(:)) = hessian;
%oo_.exo_simul = tempex ; %oo_.exo_simul = tempex ;
%clear tempex %clear tempex
n1 = 0; n1 = 0;
n2 = np; n2 = np;
zx = zeros(np,np); zx = zeros(np,np);
zu=zeros(np,M_.exo_nbr); zu=zeros(np,M_.exo_nbr);
for i=2:M_.maximum_endo_lag+1 for i=2:M_.maximum_endo_lag+1
k1 = sum(kstate(:,2) == i); k1 = sum(kstate(:,2) == i);
zx(n1+1:n1+k1,n2-k1+1:n2)=eye(k1); zx(n1+1:n1+k1,n2-k1+1:n2)=eye(k1);
n1 = n1+k1; n1 = n1+k1;
n2 = n2-k1; n2 = n2-k1;
end end
kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1));
k0 = [1:M_.endo_nbr]; k0 = [1:M_.endo_nbr];
gx1 = dr.ghx; gx1 = dr.ghx;
hu = dr.ghu(nstatic+[1:npred],:); hu = dr.ghu(nstatic+[1:npred],:);
zx = [zx; gx1]; zx = [zx; gx1];
zu = [zu; dr.ghu]; zu = [zu; dr.ghu];
for i=1:M_.maximum_endo_lead for i=1:M_.maximum_endo_lead
k1 = find(kk(i+1,k0) > 0); k1 = find(kk(i+1,k0) > 0);
zu = [zu; gx1(k1,1:npred)*hu]; zu = [zu; gx1(k1,1:npred)*hu];
gx1 = gx1(k1,:)*hx; gx1 = gx1(k1,:)*hx;
zx = [zx; gx1]; zx = [zx; gx1];
kk = kk(:,k0); kk = kk(:,k0);
k0 = k1; k0 = k1;
end end
zx=[zx; zeros(M_.exo_nbr,np);zeros(M_.exo_det_nbr,np)]; 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)]; zu=[zu; eye(M_.exo_nbr);zeros(M_.exo_det_nbr,M_.exo_nbr)];
[nrzx,nczx] = size(zx); [nrzx,nczx] = size(zx);
rhs = -sparse_hessian_times_B_kronecker_C(hessian,zx); rhs = -sparse_hessian_times_B_kronecker_C(hessian,zx);
%lhs %lhs
n = M_.endo_nbr+sum(kstate(:,2) > M_.maximum_endo_lag+1 & kstate(:,2) < M_.maximum_endo_lag+M_.maximum_endo_lead+1); 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); A = zeros(n,n);
B = 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)); 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 % variables with the highest lead
k1 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead+1); k1 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead+1);
if M_.maximum_endo_lead > 1 if M_.maximum_endo_lead > 1
k2 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead); k2 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead);
[junk,junk,k3] = intersect(kstate(k1,1),kstate(k2,1)); [junk,junk,k3] = intersect(kstate(k1,1),kstate(k2,1));
else else
k2 = [1:M_.endo_nbr]; k2 = [1:M_.endo_nbr];
k3 = kstate(k1,1); k3 = kstate(k1,1);
end end
% Jacobian with respect to the variables with the highest lead % 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); B(1:M_.endo_nbr,end-length(k2)+k3) = jacobia_(:,kstate(k1,3)+M_.endo_nbr);
offset = M_.endo_nbr; offset = M_.endo_nbr;
k0 = [1:M_.endo_nbr]; k0 = [1:M_.endo_nbr];
gx1 = dr.ghx; gx1 = dr.ghx;
for i=1:M_.maximum_endo_lead-1 for i=1:M_.maximum_endo_lead-1
k1 = find(kstate(:,2) == M_.maximum_endo_lag+i+1); k1 = find(kstate(:,2) == M_.maximum_endo_lag+i+1);
[k2,junk,k3] = find(kstate(k1,3)); [k2,junk,k3] = find(kstate(k1,3));
A(1:M_.endo_nbr,offset+k2) = jacobia_(:,k3+M_.endo_nbr); A(1:M_.endo_nbr,offset+k2) = jacobia_(:,k3+M_.endo_nbr);
n1 = length(k1); n1 = length(k1);
A(offset+[1:n1],nstatic+[1:npred]) = -gx1(kstate(k1,1),1:npred); A(offset+[1:n1],nstatic+[1:npred]) = -gx1(kstate(k1,1),1:npred);
gx1 = gx1*hx; gx1 = gx1*hx;
A(offset+[1:n1],offset+[1:n1]) = eye(n1); A(offset+[1:n1],offset+[1:n1]) = eye(n1);
n0 = length(k0); n0 = length(k0);
E = eye(n0); E = eye(n0);
if i == 1 if i == 1
[junk,junk,k4]=intersect(kstate(k1,1),[1:M_.endo_nbr]); [junk,junk,k4]=intersect(kstate(k1,1),[1:M_.endo_nbr]);
else else
[junk,junk,k4]=intersect(kstate(k1,1),kstate(k0,1)); [junk,junk,k4]=intersect(kstate(k1,1),kstate(k0,1));
end end
i1 = offset-n0+n1; i1 = offset-n0+n1;
B(offset+[1:n1],offset-n0+[1:n0]) = -E(k4,:); B(offset+[1:n1],offset-n0+[1:n0]) = -E(k4,:);
k0 = k1; k0 = k1;
offset = offset + n1; offset = offset + n1;
end end
[junk,k1,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+M_.maximum_endo_lead+1,order_var)); [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:nstatic+npred)=...
A(1:M_.endo_nbr,nstatic+[1:npred])+jacobia_(:,k2)*gx1(k1,1:npred); A(1:M_.endo_nbr,nstatic+[1:npred])+jacobia_(:,k2)*gx1(k1,1:npred);
C = hx; C = hx;
D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))]; D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))];
dr.ghxx = gensylv(2,A,B,C,D); dr.ghxx = gensylv(2,A,B,C,D);
%ghxu %ghxu
%rhs %rhs
hu = dr.ghu(nstatic+1:nstatic+npred,:); hu = dr.ghu(nstatic+1:nstatic+npred,:);
%kk = reshape([1:np*np],np,np); %kk = reshape([1:np*np],np,np);
%kk = kk(1:npred,1:npred); %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 = -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); rhs = sparse_hessian_times_B_kronecker_C(hessian,zx,zu);
nyf1 = sum(kstate(:,2) == M_.maximum_endo_lag+2); nyf1 = sum(kstate(:,2) == M_.maximum_endo_lag+2);
hu1 = [hu;zeros(np-npred,M_.exo_nbr)]; hu1 = [hu;zeros(np-npred,M_.exo_nbr)];
%B1 = [B(1:M_.endo_nbr,:);zeros(size(A,1)-M_.endo_nbr,size(B,2))]; %B1 = [B(1:M_.endo_nbr,:);zeros(size(A,1)-M_.endo_nbr,size(B,2))];
[nrhx,nchx] = size(hx); [nrhx,nchx] = size(hx);
[nrhu1,nchu1] = size(hu1); [nrhu1,nchu1] = size(hu1);
B1 = B*A_times_B_kronecker_C(dr.ghxx,hx,hu1); B1 = B*A_times_B_kronecker_C(dr.ghxx,hx,hu1);
rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;
%lhs %lhs
dr.ghxu = A\rhs; dr.ghxu = A\rhs;
%ghuu %ghuu
%rhs %rhs
kk = reshape([1:np*np],np,np); kk = reshape([1:np*np],np,np);
kk = kk(1:npred,1:npred); kk = kk(1:npred,1:npred);
rhs = sparse_hessian_times_B_kronecker_C(hessian,zu); rhs = sparse_hessian_times_B_kronecker_C(hessian,zu);
B1 = A_times_B_kronecker_C(B*dr.ghxx,hu1); B1 = A_times_B_kronecker_C(B*dr.ghxx,hu1);
rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;
%lhs %lhs
dr.ghuu = A\rhs; dr.ghuu = A\rhs;
dr.ghxx = dr.ghxx(1:M_.endo_nbr,:); dr.ghxx = dr.ghxx(1:M_.endo_nbr,:);
dr.ghxu = dr.ghxu(1:M_.endo_nbr,:); dr.ghxu = dr.ghxu(1:M_.endo_nbr,:);
dr.ghuu = dr.ghuu(1:M_.endo_nbr,:); dr.ghuu = dr.ghuu(1:M_.endo_nbr,:);
% dr.ghs2 % dr.ghs2
% derivatives of F with respect to forward variables % derivatives of F with respect to forward variables
% reordering predetermined variables in diminishing lag order % reordering predetermined variables in diminishing lag order
O1 = zeros(M_.endo_nbr,nstatic); O1 = zeros(M_.endo_nbr,nstatic);
O2 = zeros(M_.endo_nbr,M_.endo_nbr-nstatic-npred); O2 = zeros(M_.endo_nbr,M_.endo_nbr-nstatic-npred);
LHS = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)); LHS = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var));
RHS = zeros(M_.endo_nbr,M_.exo_nbr^2); RHS = zeros(M_.endo_nbr,M_.exo_nbr^2);
kk = find(kstate(:,2) == M_.maximum_endo_lag+2); kk = find(kstate(:,2) == M_.maximum_endo_lag+2);
gu = dr.ghu; gu = dr.ghu;
guu = dr.ghuu; guu = dr.ghuu;
Gu = [dr.ghu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr)]; 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)]; Guu = [dr.ghuu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr*M_.exo_nbr)];
E = eye(M_.endo_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)); 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 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]; M_.lead_lag_incidenceordered = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); M_.lead_lag_incidenceordered];
end end
M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered'; M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered';
M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered(:); M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered(:);
k1 = find(M_.lead_lag_incidenceordered); k1 = find(M_.lead_lag_incidenceordered);
M_.lead_lag_incidenceordered(k1) = [1:length(k1)]'; 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)'; 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); kh = reshape([1:nk^2],nk,nk);
kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1); kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1);
E1 = [eye(npred); zeros(kp-npred,npred)]; E1 = [eye(npred); zeros(kp-npred,npred)];
H = E1; H = E1;
hxx = dr.ghxx(nstatic+[1:npred],:); hxx = dr.ghxx(nstatic+[1:npred],:);
for i=1:M_.maximum_endo_lead for i=1:M_.maximum_endo_lead
for j=i: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,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+j+1,order_var));
[junk,k3a,k3] = ... [junk,k3a,k3] = ...
find(M_.lead_lag_incidenceordered(M_.maximum_endo_lag+j+1,:)); find(M_.lead_lag_incidenceordered(M_.maximum_endo_lag+j+1,:));
nk3a = length(k3a); nk3a = length(k3a);
B1 = sparse_hessian_times_B_kronecker_C(hessian(:,kh(k3,k3)),gu(k3a,:)); B1 = sparse_hessian_times_B_kronecker_C(hessian(:,kh(k3,k3)),gu(k3a,:));
RHS = RHS + jacobia_(:,k2)*guu(k2a,:)+B1; RHS = RHS + jacobia_(:,k2)*guu(k2a,:)+B1;
end end
% LHS % LHS
[junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+i+1,order_var)); [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,:)]); LHS = LHS + jacobia_(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]);
if i == M_.maximum_endo_lead if i == M_.maximum_endo_lead
break break
end end
kk = find(kstate(:,2) == M_.maximum_endo_lag+i+1); kk = find(kstate(:,2) == M_.maximum_endo_lag+i+1);
gu = dr.ghx*Gu; gu = dr.ghx*Gu;
[nrGu,ncGu] = size(Gu); [nrGu,ncGu] = size(Gu);
G1 = A_times_B_kronecker_C(dr.ghxx,Gu); G1 = A_times_B_kronecker_C(dr.ghxx,Gu);
G2 = A_times_B_kronecker_C(hxx,Gu); G2 = A_times_B_kronecker_C(hxx,Gu);
guu = dr.ghx*Guu+G1; guu = dr.ghx*Guu+G1;
Gu = hx*Gu; Gu = hx*Gu;
Guu = hx*Guu; Guu = hx*Guu;
Guu(end-npred+1:end,:) = Guu(end-npred+1:end,:) + G2; Guu(end-npred+1:end,:) = Guu(end-npred+1:end,:) + G2;
H = E1 + hx*H; H = E1 + hx*H;
end end
RHS = RHS*M_.Sigma_e(:); RHS = RHS*M_.Sigma_e(:);
dr.fuu = RHS; dr.fuu = RHS;
%RHS = -RHS-dr.fbias; %RHS = -RHS-dr.fbias;
RHS = -RHS; RHS = -RHS;
dr.ghs2 = LHS\RHS; dr.ghs2 = LHS\RHS;
% deterministic exogenous variables % deterministic exogenous variables
if M_.exo_det_nbr > 0 if M_.exo_det_nbr > 0
hud = dr.ghud{1}(nstatic+1:nstatic+npred,:); 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)]; 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); R1 = hessian*kron(zx,zud);
dr.ghxud = cell(M_.exo_det_length,1); dr.ghxud = cell(M_.exo_det_length,1);
kf = [M_.endo_nbr-nyf+1:M_.endo_nbr]; kf = [M_.endo_nbr-nyf+1:M_.endo_nbr];
kp = nstatic+[1:npred]; kp = nstatic+[1:npred];
dr.ghxud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{1}(kp,:))); dr.ghxud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{1}(kp,:)));
Eud = eye(M_.exo_det_nbr); Eud = eye(M_.exo_det_nbr);
for i = 2:M_.exo_det_length for i = 2:M_.exo_det_length
hudi = dr.ghud{i}(kp,:); 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)]; 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); 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; 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 end
R1 = hessian*kron(zu,zud); R1 = hessian*kron(zu,zud);
dr.ghudud = cell(M_.exo_det_length,1); dr.ghudud = cell(M_.exo_det_length,1);
kf = [M_.endo_nbr-nyf+1:M_.endo_nbr]; 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,:))); dr.ghuud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghu(kp,:),dr.ghud{1}(kp,:)));
Eud = eye(M_.exo_det_nbr); Eud = eye(M_.exo_det_nbr);
for i = 2:M_.exo_det_length for i = 2:M_.exo_det_length
hudi = dr.ghud{i}(kp,:); 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)]; 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); R2 = hessian*kron(zu,zudi);
dr.ghuud{i} = -M2*dr.ghxud{i-1}(kf,:)*kron(hu,Eud)-M1*R2; dr.ghuud{i} = -M2*dr.ghxud{i-1}(kf,:)*kron(hu,Eud)-M1*R2;
end end
R1 = hessian*kron(zud,zud); R1 = hessian*kron(zud,zud);
dr.ghudud = cell(M_.exo_det_length,M_.exo_det_length); dr.ghudud = cell(M_.exo_det_length,M_.exo_det_length);
dr.ghudud{1,1} = -M1*R1-M2*dr.ghxx(kf,:)*kron(hud,hud); dr.ghudud{1,1} = -M1*R1-M2*dr.ghxx(kf,:)*kron(hud,hud);
for i = 2:M_.exo_det_length for i = 2:M_.exo_det_length
hudi = dr.ghud{i}(nstatic+1:nstatic+npred,:); 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)]; 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); R2 = hessian*kron(zudi,zudi);
dr.ghudud{i,i} = -M2*(dr.ghudud{i-1,i-1}(kf,:)+... dr.ghudud{i,i} = -M2*(dr.ghudud{i-1,i-1}(kf,:)+...
2*dr.ghxud{i-1}(kf,:)*kron(hudi,Eud) ... 2*dr.ghxud{i-1}(kf,:)*kron(hudi,Eud) ...
+dr.ghxx(kf,:)*kron(hudi,hudi))-M1*R2; +dr.ghxx(kf,:)*kron(hudi,hudi))-M1*R2;
R2 = hessian*kron(zud,zudi); R2 = hessian*kron(zud,zudi);
dr.ghudud{1,i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hud,Eud)+... dr.ghudud{1,i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hud,Eud)+...
dr.ghxx(kf,:)*kron(hud,hudi))... dr.ghxx(kf,:)*kron(hud,hudi))...
-M1*R2; -M1*R2;
for j=2:i-1 for j=2:i-1
hudj = dr.ghud{j}(kp,:); 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)]; 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); R2 = hessian*kron(zudj,zudi);
dr.ghudud{j,i} = -M2*(dr.ghudud{j-1,i-1}(kf,:)+dr.ghxud{j-1}(kf,:)* ... 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(hudi,Eud)+dr.ghxud{i-1}(kf,:)* ...
kron(hudj,Eud)+dr.ghxx(kf,:)*kron(hudj,hudi))-M1*R2; kron(hudj,Eud)+dr.ghxx(kf,:)*kron(hudj,hudi))-M1*R2;
end end
end 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
info = 0; info = 0;
options_ = set_default_option(options_,'loglinear',0); options_ = set_default_option(options_,'loglinear',0);
options_ = set_default_option(options_,'noprint',0); options_ = set_default_option(options_,'noprint',0);
options_ = set_default_option(options_,'olr',0); options_ = set_default_option(options_,'olr',0);
options_ = set_default_option(options_,'olr_beta',1); options_ = set_default_option(options_,'olr_beta',1);
options_ = set_default_option(options_,'qz_criterium',1.000001); options_ = set_default_option(options_,'qz_criterium',1.000001);
xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1; xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1;
klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1;
iyv = M_.lead_lag_incidence'; iyv = M_.lead_lag_incidence';
iyv = iyv(:); iyv = iyv(:);
iyr0 = find(iyv) ; iyr0 = find(iyv) ;
it_ = M_.maximum_lag + 1 ; it_ = M_.maximum_lag + 1 ;
if M_.exo_nbr == 0 if M_.exo_nbr == 0
oo_.exo_steady_state = [] ; 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 end
old_solve_algo = options_.solve_algo;
% expanding system for Optimal Linear Regulator % options_.solve_algo = 1;
if options_.ramsey_policy oo_.steady_state = dynare_solve('dyn_ramsey_static_',oo_.steady_state,0,M_,options_,oo_,it_);
if isfield(M_,'orig_model') options_.solve_algo = old_solve_algo;
orig_model = M_.orig_model; [junk,junk,multbar] = dyn_ramsey_static_(oo_.steady_state,M_,options_,oo_,it_);
M_.endo_nbr = orig_model.endo_nbr; [jacobia_,M_] = dyn_ramsey_dynamic_(oo_.steady_state,multbar,M_,options_,oo_,it_);
M_.orig_endo_nbr = orig_model.orig_endo_nbr; klen = M_.maximum_lag + M_.maximum_lead + 1;
M_.aux_vars = orig_model.aux_vars; dr.ys = [oo_.steady_state;zeros(M_.exo_nbr,1);multbar];
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];
% $$$ if options_.ramsey_policy == 2 % $$$ if options_.ramsey_policy == 2
% $$$ mask = M_.orig_model.lead_lag_incidence ~= 0; % $$$ 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); % $$$ 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_names = strvcat(M_.orig_model.endo_names, M_.endo_names(endo_nbr1+k,:));
% $$$ M_.endo_nbr = endo_nbr1+length(k); % $$$ M_.endo_nbr = endo_nbr1+length(k);
% $$$ end % $$$ end
else else
klen = M_.maximum_lag + M_.maximum_lead + 1; klen = M_.maximum_lag + M_.maximum_lead + 1;
iyv = M_.lead_lag_incidence'; iyv = M_.lead_lag_incidence';
iyv = iyv(:); iyv = iyv(:);
iyr0 = find(iyv) ; iyr0 = find(iyv) ;
it_ = M_.maximum_lag + 1 ; it_ = M_.maximum_lag + 1 ;
if M_.exo_nbr == 0 if M_.exo_nbr == 0
oo_.exo_steady_state = [] ; 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 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) ; options_.smpl = zeros(2,1) ;
if nargin == 0 if nargin == 0
options_.smpl(1) = 1 ; options_.smpl(1) = 1 ;
options_.smpl(2) = options_.periods ; options_.smpl(2) = options_.periods ;
elseif nargin == 1 elseif nargin == 1
if s1 > options_.periods if s1 > options_.periods
error('DSAMPLE: argument greater than number of periods'); error('DSAMPLE: argument greater than number of periods');
end end
options_.smpl(1) = 1 ; options_.smpl(1) = 1 ;
options_.smpl(2) = s1 ; options_.smpl(2) = s1 ;
else else
if s1 > options_.periods || s2 > options_.periods if s1 > options_.periods || s2 > options_.periods
error('DSAMPLE: one of the arguments is greater than number of periods'); error('DSAMPLE: one of the arguments is greater than number of periods');
end end
options_.smpl(1) = s1 ; options_.smpl(1) = s1 ;
options_.smpl(2) = s2 ; options_.smpl(2) = s2 ;
end end
% 02/23/01 MJ added error checking % 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_ global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_
fval = []; fval = [];
ys = []; ys = [];
trend_coeff = []; trend_coeff = [];
cost_flag = 1; cost_flag = 1;
nobs = size(options_.varobs,1); nobs = size(options_.varobs,1);
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 1. Get the structural parameters & define penalties % 1. Get the structural parameters & define penalties
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb) if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
k = find(xparam1 < bayestopt_.lb); k = find(xparam1 < bayestopt_.lb);
fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2); fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
cost_flag = 0; cost_flag = 0;
info = 41; info = 41;
return; return;
end end
if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub) if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
k = find(xparam1 > bayestopt_.ub); k = find(xparam1 > bayestopt_.ub);
fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2); fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
cost_flag = 0; cost_flag = 0;
info = 42; info = 42;
return; return;
end end
Q = M_.Sigma_e; Q = M_.Sigma_e;
H = M_.H; H = M_.H;
for i=1:estim_params_.nvx for i=1:estim_params_.nvx
k =estim_params_.var_exo(i,1); k =estim_params_.var_exo(i,1);
Q(k,k) = xparam1(i)*xparam1(i); Q(k,k) = xparam1(i)*xparam1(i);
end end
offset = estim_params_.nvx; offset = estim_params_.nvx;
if estim_params_.nvn if estim_params_.nvn
for i=1:estim_params_.nvn for i=1:estim_params_.nvn
k = estim_params_.var_endo(i,1); k = estim_params_.var_endo(i,1);
H(k,k) = xparam1(i+offset)*xparam1(i+offset); H(k,k) = xparam1(i+offset)*xparam1(i+offset);
end end
offset = offset+estim_params_.nvn; offset = offset+estim_params_.nvn;
end end
if estim_params_.ncx if estim_params_.ncx
for i=1:estim_params_.ncx for i=1:estim_params_.ncx
k1 =estim_params_.corrx(i,1); k1 =estim_params_.corrx(i,1);
k2 =estim_params_.corrx(i,2); k2 =estim_params_.corrx(i,2);
Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2)); Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
Q(k2,k1) = Q(k1,k2); Q(k2,k1) = Q(k1,k2);
end end
[CholQ,testQ] = chol(Q); [CholQ,testQ] = chol(Q);
if testQ %% The variance-covariance matrix of the structural innovations is not definite positive. 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. %% We have to compute the eigenvalues of this matrix in order to build the penalty.
a = diag(eig(Q)); a = diag(eig(Q));
k = find(a < 0); k = find(a < 0);
if k > 0 if k > 0
fval = bayestopt_.penalty+sum(-a(k)); fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0; cost_flag = 0;
info = 43; info = 43;
return return
end end
end end
offset = offset+estim_params_.ncx; offset = offset+estim_params_.ncx;
end end
if estim_params_.ncn if estim_params_.ncn
for i=1:estim_params_.ncn for i=1:estim_params_.ncn
k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1)); k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2)); k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
H(k2,k1) = H(k1,k2); H(k2,k1) = H(k1,k2);
end end
[CholH,testH] = chol(H); [CholH,testH] = chol(H);
if testH if testH
a = diag(eig(H)); a = diag(eig(H));
k = find(a < 0); k = find(a < 0);
if k > 0 if k > 0
fval = bayestopt_.penalty+sum(-a(k)); fval = bayestopt_.penalty+sum(-a(k));
cost_flag = 0; cost_flag = 0;
info = 44; info = 44;
return return
end end
end end
offset = offset+estim_params_.ncn; offset = offset+estim_params_.ncn;
end end
if estim_params_.np > 0 if estim_params_.np > 0
M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
end end
M_.Sigma_e = Q; M_.Sigma_e = Q;
M_.H = H; M_.H = H;
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 2. call model setup & reduction program % 2. call model setup & reduction program
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,... [T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
bayestopt_.restrict_columns,... bayestopt_.restrict_columns,...
bayestopt_.restrict_aux); bayestopt_.restrict_aux);
if info(1) == 1 | info(1) == 2 | info(1) == 5 if info(1) == 1 | info(1) == 2 | info(1) == 5
fval = bayestopt_.penalty+1; fval = bayestopt_.penalty+1;
cost_flag = 0; cost_flag = 0;
return 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 fval = bayestopt_.penalty+info(2);%^2; % penalty power raised in DR1.m and resol already. GP July'08
cost_flag = 0; cost_flag = 0;
return return
end end
bayestopt_.mf = bayestopt_.mf1; bayestopt_.mf = bayestopt_.mf1;
if ~options_.noconstant if ~options_.noconstant
if options_.loglinear == 1 if options_.loglinear == 1
constant = log(SteadyState(bayestopt_.mfys)); constant = log(SteadyState(bayestopt_.mfys));
else else
constant = SteadyState(bayestopt_.mfys); constant = SteadyState(bayestopt_.mfys);
end end
else else
constant = zeros(nobs,1); constant = zeros(nobs,1);
end end
if bayestopt_.with_trend == 1 if bayestopt_.with_trend == 1
trend_coeff = zeros(nobs,1); trend_coeff = zeros(nobs,1);
t = options_.trend_coeffs; t = options_.trend_coeffs;
for i=1:length(t) for i=1:length(t)
if ~isempty(t{i}) if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i}); trend_coeff(i) = evalin('base',t{i});
end end
end end
trend = repmat(constant,1,gend)+trend_coeff*[1:gend]; trend = repmat(constant,1,gend)+trend_coeff*[1:gend];
else else
trend = repmat(constant,1,gend); trend = repmat(constant,1,gend);
end end
start = options_.presample+1; start = options_.presample+1;
np = size(T,1); np = size(T,1);
mf = bayestopt_.mf; mf = bayestopt_.mf;
no_missing_data_flag = (number_of_observations==gend*nobs); no_missing_data_flag = (number_of_observations==gend*nobs);
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter % 3. Initial condition of the Kalman filter
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
kalman_algo = options_.kalman_algo; kalman_algo = options_.kalman_algo;
if options_.lik_init == 1 % Kalman filter if options_.lik_init == 1 % Kalman filter
if kalman_algo ~= 2 if kalman_algo ~= 2
kalman_algo = 1; kalman_algo = 1;
end end
Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold); Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold);
Pinf = []; Pinf = [];
elseif options_.lik_init == 2 % Old Diffuse Kalman filter elseif options_.lik_init == 2 % Old Diffuse Kalman filter
if kalman_algo ~= 2 if kalman_algo ~= 2
kalman_algo = 1; kalman_algo = 1;
end end
Pstar = 10*eye(np); Pstar = 10*eye(np);
Pinf = []; Pinf = [];
elseif options_.lik_init == 3 % Diffuse Kalman filter elseif options_.lik_init == 3 % Diffuse Kalman filter
if kalman_algo ~= 4 if kalman_algo ~= 4
kalman_algo = 3; kalman_algo = 3;
end end
[QT,ST] = schur(T); [QT,ST] = schur(T);
e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
[QT,ST] = ordschur(QT,ST,e1); [QT,ST] = ordschur(QT,ST,e1);
k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
nk = length(k); nk = length(k);
nk1 = nk+1; nk1 = nk+1;
Pinf = zeros(np,np); Pinf = zeros(np,np);
Pinf(1:nk,1:nk) = eye(nk); Pinf(1:nk,1:nk) = eye(nk);
Pstar = zeros(np,np); Pstar = zeros(np,np);
B = QT'*R*Q*R'*QT; B = QT'*R*Q*R'*QT;
for i=np:-1:nk+2 for i=np:-1:nk+2
if ST(i,i-1) == 0 if ST(i,i-1) == 0
if i == np if i == np
c = zeros(np-nk,1); c = zeros(np-nk,1);
else else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... 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)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end end
q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
else else
if i == np if i == np
c = zeros(np-nk,1); c = zeros(np-nk,1);
c1 = zeros(np-nk,1); c1 = zeros(np-nk,1);
else else
c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... 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)*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); 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)')+... 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-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); ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
end end
q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... 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)]; -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]; 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) = z(1:(i-nk));
Pstar(nk1:i,i-1) = z(i-nk+1:end); Pstar(nk1:i,i-1) = z(i-nk+1:end);
Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
i = i - 1; i = i - 1;
end end
end end
if i == nk+2 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); 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)); Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
end end
Z = QT(mf,:); Z = QT(mf,:);
R1 = QT'*R; R1 = QT'*R;
[QQ,RR,EE] = qr(Z*ST(:,1:nk),0); [QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
k = find(abs(diag(RR)) < 1e-8); k = find(abs(diag(RR)) < 1e-8);
if length(k) > 0 if length(k) > 0
k1 = EE(:,k); k1 = EE(:,k);
dd =ones(nk,1); dd =ones(nk,1);
dd(k1) = zeros(length(k1),1); dd(k1) = zeros(length(k1),1);
Pinf(1:nk,1:nk) = diag(dd); Pinf(1:nk,1:nk) = diag(dd);
end end
end end
if kalman_algo == 2 if kalman_algo == 2
no_correlation_flag = 1; no_correlation_flag = 1;
if length(H)==1 if length(H)==1
H = zeros(nobs,1); H = zeros(nobs,1);
else else
if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
H = diag(H); H = diag(H);
else else
no_correlation_flag = 0; no_correlation_flag = 0;
end end
end end
end end
kalman_tol = options_.kalman_tol; kalman_tol = options_.kalman_tol;
riccati_tol = options_.riccati_tol; riccati_tol = options_.riccati_tol;
mf = bayestopt_.mf1; mf = bayestopt_.mf1;
Y = data-trend; Y = data-trend;
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
% 4. Likelihood evaluation % 4. Likelihood evaluation
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
if (kalman_algo==1)% Multivariate Kalman Filter if (kalman_algo==1)% Multivariate Kalman Filter
if no_missing_data_flag if no_missing_data_flag
LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol);
else else
LIK = ... LIK = ...
missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ... 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); data_index,number_of_observations,no_more_missing_observations);
end end
if isinf(LIK) if isinf(LIK)
kalman_algo = 2; kalman_algo = 2;
end end
end end
if (kalman_algo==2)% Univariate Kalman Filter if (kalman_algo==2)% Univariate Kalman Filter
if no_correlation_flag 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); 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 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); 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
end end
if (kalman_algo==3)% Multivariate Diffuse Kalman Filter if (kalman_algo==3)% Multivariate Diffuse Kalman Filter
if no_missing_data_flag if no_missing_data_flag
LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol); LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol);
else else
LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,... 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); data_index,number_of_observations,no_more_missing_observations);
end end
if isinf(LIK) if isinf(LIK)
kalman_algo = 4; kalman_algo = 4;
end end
end end
if (kalman_algo==4)% Univariate Diffuse Kalman Filter if (kalman_algo==4)% Univariate Diffuse Kalman Filter
if no_correlation_flag if no_correlation_flag
LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,... 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); data_index,number_of_observations,no_more_missing_observations);
else else
LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,... 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); data_index,number_of_observations,no_more_missing_observations);
end end
end end
if imag(LIK) ~= 0 if imag(LIK) ~= 0
likelihood = bayestopt_.penalty; likelihood = bayestopt_.penalty;
else else
likelihood = LIK; likelihood = LIK;
end end
% ------------------------------------------------------------------------------ % ------------------------------------------------------------------------------
% Adds prior if necessary % Adds prior if necessary
% ------------------------------------------------------------------------------ % ------------------------------------------------------------------------------
lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
fval = (likelihood-lnprior); fval = (likelihood-lnprior);
options_.kalman_algo = kalman_algo; options_.kalman_algo = kalman_algo;

View File

@ -1,5 +1,5 @@
function [nvar,vartan,NumberOfConditionalDecompFiles] = ... 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 % This function computes the posterior or prior distribution of the conditional variance
% decomposition of the endogenous variables (or a subset of the endogenous variables). % decomposition of the endogenous variables (or a subset of the endogenous variables).
% %

View File

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

View File

@ -1,5 +1,5 @@
function [nvar,vartan,NumberOfDecompFiles] = ... 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 % This function computes the posterior or prior distribution of the variance
% decomposition of the observed endogenous variables. % 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ global M_
y = M_.freq*(year-M_.start_date(1))+period-M_.start_date(2)+1; 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 % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ options_ global M_ oo_ options_
if options_.smpl == 0 if options_.smpl == 0
k = [1:size(oo_.endo_simul,2)]; k = [1:size(oo_.endo_simul,2)];
else else
k = [M_.maximum_lag+options_.smpl(1):M_.maximum_lag+options_.smpl(2)]; k = [M_.maximum_lag+options_.smpl(1):M_.maximum_lag+options_.smpl(2)];
end end
if nargin == 0 if nargin == 0
if nargout > 0 if nargout > 0
t = ['DYNARE dyn2vec error: the function doesn''t return values when' ... t = ['DYNARE dyn2vec error: the function doesn''t return values when' ...
' used without input argument']; ' used without input argument'];
error(t); error(t);
end end
for i=1:size(oo_.endo_simul,1) 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 end
return return
else else
j = strmatch(s1,M_.endo_names,'exact'); j = strmatch(s1,M_.endo_names,'exact');
if ~ isempty(j) if ~ isempty(j)
z = oo_.endo_simul(j,k)'; z = oo_.endo_simul(j,k)';
else else
j = strmatch(s1,M_.exo_names,'exact'); j = strmatch(s1,M_.exo_names,'exact');
if ~ isempty(j) if ~ isempty(j)
if options_.smpl == 0 if options_.smpl == 0
z = oo_.exo_simul(:,j); z = oo_.exo_simul(:,j);
else else
z = oo_.exo_simul(M_.maximum_lag+options_.smpl(1):M_.maximum_lag+options_.smpl(2)); z = oo_.exo_simul(M_.maximum_lag+options_.smpl(1):M_.maximum_lag+options_.smpl(2));
end end
else else
t = ['DYNARE dyn2vec error: variable ' deblank(s1(i,:)) ' doesn''t' ... t = ['DYNARE dyn2vec error: variable ' deblank(s1(i,:)) ' doesn''t' ...
' exist.'] ; ' exist.'] ;
error (t) ; error (t) ;
end end
end end
end end
if nargout == 0 if nargout == 0
if nargin == 1 if nargin == 1
assignin('base',s1,z); assignin('base',s1,z);
elseif nargin == 2 elseif nargin == 2
assignin('base',s2,z); assignin('base',s2,z);
end end
else else
zss=oo_.steady_state(j); zss=oo_.steady_state(j);
end end
% 02/23/01 MJ redone, incorporating FC's improvements % 02/23/01 MJ redone, incorporating FC's improvements
% 08/24/01 MJ replaced globlize by internal assignin % 08/24/01 MJ replaced globlize by internal assignin
% 08/24/01 MJ added 'exact' to strmatch (thanks to David Vavra) % 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,M_] = dyn_ramsey_dynamic_(ys,lbar,M_,options_,oo_,it_)
% function J = dyn_ramsey_dynamic_(ys,lbar) % function J = dyn_ramsey_dynamic_(ys,lbar)
% dyn_ramsey_dynamic_ sets up the Jacobian of the expanded model for optimal % dyn_ramsey_dynamic_ sets up the Jacobian of the expanded model for optimal
% policies. It modifies several fields of M_ % policies. It modifies several fields of M_
% %
% INPUTS: % INPUTS:
% ys: steady state of original endogenous variables % ys: steady state of original endogenous variables
% lbar: steady state of Lagrange multipliers % lbar: steady state of Lagrange multipliers
% %
% OUPTUTS: % OUPTUTS:
% J: jaocobian of expanded model % J: jaocobian of expanded model
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2003-2009 Dynare Team % Copyright (C) 2003-2009 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% retrieving model parameters % retrieving model parameters
endo_nbr = M_.endo_nbr; endo_nbr = M_.endo_nbr;
i_endo_nbr = 1:endo_nbr; i_endo_nbr = 1:endo_nbr;
endo_names = M_.endo_names; endo_names = M_.endo_names;
% exo_nbr = M_.exo_nbr+M_.exo_det_nbr; % exo_nbr = M_.exo_nbr+M_.exo_det_nbr;
% exo_names = vertcat(M_.exo_names,M_.exo_det_names); % exo_names = vertcat(M_.exo_names,M_.exo_det_names);
exo_nbr = M_.exo_nbr; exo_nbr = M_.exo_nbr;
exo_names = M_.exo_names; exo_names = M_.exo_names;
i_leadlag = M_.lead_lag_incidence; i_leadlag = M_.lead_lag_incidence;
max_lead = M_.maximum_lead; max_lead = M_.maximum_lead;
max_endo_lead = M_.maximum_endo_lead; max_endo_lead = M_.maximum_endo_lead;
max_lag = M_.maximum_lag; max_lag = M_.maximum_lag;
max_endo_lag = M_.maximum_endo_lag; max_endo_lag = M_.maximum_endo_lag;
leadlag_nbr = max_lead+max_lag+1; leadlag_nbr = max_lead+max_lag+1;
fname = M_.fname; fname = M_.fname;
% instr_names = options_.olr_inst; % instr_names = options_.olr_inst;
% instr_nbr = size(options_.olr_inst,1); % instr_nbr = size(options_.olr_inst,1);
% discount factor % discount factor
beta = options_.planner_discount; beta = options_.planner_discount;
% storing original values % storing original values
orig_model.endo_nbr = endo_nbr; orig_model.endo_nbr = endo_nbr;
orig_model.orig_endo_nbr = M_.orig_endo_nbr; orig_model.orig_endo_nbr = M_.orig_endo_nbr;
orig_model.aux_vars = M_.aux_vars; orig_model.aux_vars = M_.aux_vars;
orig_model.endo_names = endo_names; orig_model.endo_names = endo_names;
orig_model.lead_lag_incidence = i_leadlag; orig_model.lead_lag_incidence = i_leadlag;
orig_model.maximum_lead = max_lead; orig_model.maximum_lead = max_lead;
orig_model.maximum_endo_lead = max_endo_lead; orig_model.maximum_endo_lead = max_endo_lead;
orig_model.maximum_lag = max_lag; orig_model.maximum_lag = max_lag;
orig_model.maximum_endo_lag = max_endo_lag; orig_model.maximum_endo_lag = max_endo_lag;
y = repmat(ys,1,max_lag+max_lead+1); y = repmat(ys,1,max_lag+max_lead+1);
k = find(i_leadlag'); k = find(i_leadlag');
% retrieving derivatives of the objective function % retrieving derivatives of the objective function
[U,Uy,Uyy] = feval([fname '_objective_static'],ys,zeros(1,exo_nbr), M_.params); [U,Uy,Uyy] = feval([fname '_objective_static'],ys,zeros(1,exo_nbr), M_.params);
Uy = Uy'; Uy = Uy';
Uyy = reshape(Uyy,endo_nbr,endo_nbr); Uyy = reshape(Uyy,endo_nbr,endo_nbr);
% retrieving derivatives of original model % retrieving derivatives of original model
[f,fJ,fH] = feval([fname '_dynamic'],y(k),[oo_.exo_simul oo_.exo_det_simul], M_.params, it_); [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); instr_nbr = endo_nbr - size(f,1);
mult_nbr = endo_nbr-instr_nbr; mult_nbr = endo_nbr-instr_nbr;
% parameters for expanded model % parameters for expanded model
endo_nbr1 = 2*endo_nbr-instr_nbr+exo_nbr; endo_nbr1 = 2*endo_nbr-instr_nbr+exo_nbr;
max_lead1 = max_lead + max_lag; max_lead1 = max_lead + max_lag;
max_lag1 = max_lead1; max_lag1 = max_lead1;
max_leadlag1 = max_lead1; max_leadlag1 = max_lead1;
% adding new variables names % adding new variables names
endo_names1 = endo_names; endo_names1 = endo_names;
% adding shocks to endogenous variables % adding shocks to endogenous variables
endo_names1 = strvcat(endo_names1, exo_names); endo_names1 = strvcat(endo_names1, exo_names);
% adding multipliers names % adding multipliers names
for i=1:mult_nbr; for i=1:mult_nbr;
endo_names1 = strvcat(endo_names1,['mult_' int2str(i)]); endo_names1 = strvcat(endo_names1,['mult_' int2str(i)]);
end end
% expanding matrix of lead/lag incidence % expanding matrix of lead/lag incidence
% %
% multipliers lead/lag incidence % multipliers lead/lag incidence
i_mult = []; i_mult = [];
for i=1:leadlag_nbr for i=1:leadlag_nbr
i_mult = [any(fJ(:,nonzeros(i_leadlag(i,:))) ~= 0,2)' ; i_mult]; i_mult = [any(fJ(:,nonzeros(i_leadlag(i,:))) ~= 0,2)' ; i_mult];
end end
% putting it all together: % putting it all together:
% original variables, exogenous variables made endogenous, multipliers % original variables, exogenous variables made endogenous, multipliers
% %
% number of original dynamic variables % number of original dynamic variables
n_dyn = nnz(i_leadlag); n_dyn = nnz(i_leadlag);
% numbering columns of dynamic multipliers to be put in the last columns % numbering columns of dynamic multipliers to be put in the last columns
% of the new Jacobian % of the new Jacobian
i_leadlag1 = [cumsum(i_leadlag(1:max_lag,:),1); ... i_leadlag1 = [cumsum(i_leadlag(1:max_lag,:),1); ...
repmat(i_leadlag(max_lag+1,:),leadlag_nbr,1); ... repmat(i_leadlag(max_lag+1,:),leadlag_nbr,1); ...
flipud(cumsum(flipud(i_leadlag(max_lag+2:end,:)),1))]; flipud(cumsum(flipud(i_leadlag(max_lag+2:end,:)),1))];
i_leadlag1 = i_leadlag1'; i_leadlag1 = i_leadlag1';
k = find(i_leadlag1 > 0); k = find(i_leadlag1 > 0);
n = length(k); n = length(k);
i_leadlag1(k) = 1:n; i_leadlag1(k) = 1:n;
i_leadlag1 = i_leadlag1'; i_leadlag1 = i_leadlag1';
i_mult = i_mult'; i_mult = i_mult';
k = find(i_mult > 0); k = find(i_mult > 0);
i_mult(k) = n+leadlag_nbr*exo_nbr+(1:length(k)); i_mult(k) = n+leadlag_nbr*exo_nbr+(1:length(k));
i_mult = i_mult'; i_mult = i_mult';
i_leadlag1 = [ i_leadlag1 ... i_leadlag1 = [ i_leadlag1 ...
[zeros(max_lag,exo_nbr);... [zeros(max_lag,exo_nbr);...
reshape(n+(1:leadlag_nbr*exo_nbr),exo_nbr,leadlag_nbr)'; ... reshape(n+(1:leadlag_nbr*exo_nbr),exo_nbr,leadlag_nbr)'; ...
zeros(max_lead,exo_nbr)] ... zeros(max_lead,exo_nbr)] ...
[zeros(max_lag,mult_nbr);... [zeros(max_lag,mult_nbr);...
i_mult;... i_mult;...
zeros(max_lead,mult_nbr)]]; zeros(max_lead,mult_nbr)]];
i_leadlag1 = i_leadlag1'; i_leadlag1 = i_leadlag1';
k = find(i_leadlag1 > 0); k = find(i_leadlag1 > 0);
n = length(k); n = length(k);
i_leadlag1(k) = 1:n; i_leadlag1(k) = 1:n;
i_leadlag1 = i_leadlag1'; i_leadlag1 = i_leadlag1';
% building Jacobian of expanded model % building Jacobian of expanded model
jacobian = zeros(endo_nbr+mult_nbr,nnz(i_leadlag1)+exo_nbr); jacobian = zeros(endo_nbr+mult_nbr,nnz(i_leadlag1)+exo_nbr);
% derivatives of f.o.c. w.r. to endogenous variables % derivatives of f.o.c. w.r. to endogenous variables
% to be rearranged further down % to be rearranged further down
lbarfH = lbar'*fH; lbarfH = lbar'*fH;
% indices of Hessian columns % indices of Hessian columns
n1 = nnz(i_leadlag)+exo_nbr; n1 = nnz(i_leadlag)+exo_nbr;
iH = reshape(1:n1^2,n1,n1); iH = reshape(1:n1^2,n1,n1);
J = zeros(endo_nbr1,nnz(i_leadlag1)+exo_nbr); J = zeros(endo_nbr1,nnz(i_leadlag1)+exo_nbr);
% second order derivatives of objective function % second order derivatives of objective function
J(1:endo_nbr,i_leadlag1(max_leadlag1+1,1:endo_nbr)) = Uyy; J(1:endo_nbr,i_leadlag1(max_leadlag1+1,1:endo_nbr)) = Uyy;
% loop on lead/lags in expanded model % loop on lead/lags in expanded model
for i=1:2*max_leadlag1 + 1 for i=1:2*max_leadlag1 + 1
% index of variables at the current lag in expanded model % index of variables at the current lag in expanded model
kc = find(i_leadlag1(i,i_endo_nbr) > 0); kc = find(i_leadlag1(i,i_endo_nbr) > 0);
t1 = max(1,i-max_leadlag1); t1 = max(1,i-max_leadlag1);
t2 = min(i,max_leadlag1+1); t2 = min(i,max_leadlag1+1);
% loop on lead/lag blocks of relevant 1st order derivatives % loop on lead/lag blocks of relevant 1st order derivatives
for j = t1:t2 for j = t1:t2
% derivatives w.r. endogenous variables % derivatives w.r. endogenous variables
ic = find(i_leadlag(i-j+1,:) > 0 ); ic = find(i_leadlag(i-j+1,:) > 0 );
kc1 = i_leadlag(i-j+1,ic); kc1 = i_leadlag(i-j+1,ic);
[junk,ic1,ic2] = intersect(ic,kc); [junk,ic1,ic2] = intersect(ic,kc);
kc2 = i_leadlag1(i,kc(ic2)); kc2 = i_leadlag1(i,kc(ic2));
ir = find(i_leadlag(max_leadlag1+2-j,:) > 0 ); ir = find(i_leadlag(max_leadlag1+2-j,:) > 0 );
kr1 = i_leadlag(max_leadlag1+2-j,ir); kr1 = i_leadlag(max_leadlag1+2-j,ir);
J(ir,kc2) = J(ir,kc2) + beta^(j-max_lead-1)... J(ir,kc2) = J(ir,kc2) + beta^(j-max_lead-1)...
*reshape(lbarfH(iH(kr1,kc1)),length(kr1),length(kc1)); *reshape(lbarfH(iH(kr1,kc1)),length(kr1),length(kc1));
end end
end end
% derivatives w.r. aux. variables for lead/lag exogenous shocks % derivatives w.r. aux. variables for lead/lag exogenous shocks
for i=1:leadlag_nbr for i=1:leadlag_nbr
kc = i_leadlag1(max_lag+i,endo_nbr+(1:exo_nbr)); kc = i_leadlag1(max_lag+i,endo_nbr+(1:exo_nbr));
ir = find(i_leadlag(leadlag_nbr+1-i,:) > 0); ir = find(i_leadlag(leadlag_nbr+1-i,:) > 0);
kr1 = i_leadlag(leadlag_nbr+1-i,ir); kr1 = i_leadlag(leadlag_nbr+1-i,ir);
J(ir,kc) = beta^(i-max_lead-1)... J(ir,kc) = beta^(i-max_lead-1)...
*reshape(lbarfH(iH(kr1,n_dyn+(1:exo_nbr))),length(kr1), ... *reshape(lbarfH(iH(kr1,n_dyn+(1:exo_nbr))),length(kr1), ...
exo_nbr); exo_nbr);
end end
% derivatives w.r. Lagrange multipliers % derivatives w.r. Lagrange multipliers
for i=1:leadlag_nbr for i=1:leadlag_nbr
ic1 = find(i_leadlag(leadlag_nbr+1-i,:) > 0); ic1 = find(i_leadlag(leadlag_nbr+1-i,:) > 0);
kc1 = i_leadlag(leadlag_nbr+1-i,ic1); kc1 = i_leadlag(leadlag_nbr+1-i,ic1);
ic2 = find(i_leadlag1(max_lag+i,endo_nbr+exo_nbr+(1:mult_nbr)) > 0); 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); kc2 = i_leadlag1(max_lag+i,endo_nbr+exo_nbr+ic2);
J(ic1,kc2) = beta^(i-max_lead-1)*fJ(ic2,kc1)'; J(ic1,kc2) = beta^(i-max_lead-1)*fJ(ic2,kc1)';
end end
% Jacobian of original equations % Jacobian of original equations
% %
% w.r. endogenous variables % w.r. endogenous variables
ir = endo_nbr+(1:endo_nbr-instr_nbr); ir = endo_nbr+(1:endo_nbr-instr_nbr);
for i=1:leadlag_nbr for i=1:leadlag_nbr
ic1 = find(i_leadlag(i,:) > 0); ic1 = find(i_leadlag(i,:) > 0);
kc1 = i_leadlag(i,ic1); kc1 = i_leadlag(i,ic1);
ic2 = find(i_leadlag1(max_lead+i,:) > 0); ic2 = find(i_leadlag1(max_lead+i,:) > 0);
kc2 = i_leadlag1(max_lead+i,ic2); kc2 = i_leadlag1(max_lead+i,ic2);
[junk,junk,ic3] = intersect(ic1,ic2); [junk,junk,ic3] = intersect(ic1,ic2);
J(ir,kc2(ic3)) = fJ(:,kc1); J(ir,kc2(ic3)) = fJ(:,kc1);
end end
% w.r. exogenous variables % w.r. exogenous variables
J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = fJ(:,nnz(i_leadlag)+(1:exo_nbr)); J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = fJ(:,nnz(i_leadlag)+(1:exo_nbr));
% auxiliary variable for exogenous shocks % auxiliary variable for exogenous shocks
ir = 2*endo_nbr-instr_nbr+(1:exo_nbr); ir = 2*endo_nbr-instr_nbr+(1:exo_nbr);
kc = i_leadlag1(leadlag_nbr,endo_nbr+(1:exo_nbr)); kc = i_leadlag1(leadlag_nbr,endo_nbr+(1:exo_nbr));
J(ir,kc) = eye(exo_nbr); J(ir,kc) = eye(exo_nbr);
J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = -eye(exo_nbr); J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = -eye(exo_nbr);
% eliminating empty columns % eliminating empty columns
% getting indices of nonzero entries % getting indices of nonzero entries
m = find(i_leadlag1'); m = find(i_leadlag1');
n1 = max_lag1*endo_nbr1+1; n1 = max_lag1*endo_nbr1+1;
n2 = n1+endo_nbr-1; n2 = n1+endo_nbr-1;
n = length(m); n = length(m);
k = 1:size(J,2); k = 1:size(J,2);
for i=1:n for i=1:n
if sum(abs(J(:,i))) < 1e-8 if sum(abs(J(:,i))) < 1e-8
if m(i) < n1 | m(i) > n2 if m(i) < n1 | m(i) > n2
k(i) = 0; k(i) = 0;
m(i) = 0; m(i) = 0;
end end
end end
end end
J = J(:,nonzeros(k)); J = J(:,nonzeros(k));
i_leadlag1 = zeros(size(i_leadlag1))'; i_leadlag1 = zeros(size(i_leadlag1))';
i_leadlag1(nonzeros(m)) = 1:nnz(m); i_leadlag1(nonzeros(m)) = 1:nnz(m);
i_leadlag1 = i_leadlag1'; i_leadlag1 = i_leadlag1';
% setting expanded model parameters % setting expanded model parameters
% storing original values % storing original values
M_.endo_nbr = endo_nbr1; M_.endo_nbr = endo_nbr1;
% Consider that there is no auxiliary variable, because otherwise it % Consider that there is no auxiliary variable, because otherwise it
% interacts badly with the auxiliary variables from the preprocessor. % interacts badly with the auxiliary variables from the preprocessor.
M_.orig_endo_nbr = endo_nbr1; M_.orig_endo_nbr = endo_nbr1;
M_.aux_vars = []; M_.aux_vars = [];
M_.endo_names = endo_names1; M_.endo_names = endo_names1;
M_.lead_lag_incidence = i_leadlag1; M_.lead_lag_incidence = i_leadlag1;
M_.maximum_lead = max_lead1; M_.maximum_lead = max_lead1;
M_.maximum_endo_lead = max_lead1; M_.maximum_endo_lead = max_lead1;
M_.maximum_lag = max_lag1; M_.maximum_lag = max_lag1;
M_.maximum_endo_lag = max_lag1; M_.maximum_endo_lag = max_lag1;
M_.orig_model = orig_model; 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,M_,options_,oo_,it_)
% function [resids, rJ,mult] = dyn_ramsey_static_(x) % function [resids, rJ,mult] = dyn_ramsey_static_(x)
% Computes the static first order conditions for optimal policy % Computes the static first order conditions for optimal policy
% %
% INPUTS % INPUTS
% x: vector of endogenous variables % x: vector of endogenous variables
% %
% OUTPUTS % OUTPUTS
% resids: residuals of non linear equations % resids: residuals of non linear equations
% rJ: Jacobian % rJ: Jacobian
% mult: Lagrangian multipliers % mult: Lagrangian multipliers
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2003-2007 Dynare Team % Copyright (C) 2003-2007 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
% Dynare is free software: you can redistribute it and/or modify % Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by % it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or % the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version. % (at your option) any later version.
% %
% Dynare is distributed in the hope that it will be useful, % Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of % but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. % GNU General Public License for more details.
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% recovering usefull fields % recovering usefull fields
endo_nbr = M_.endo_nbr; endo_nbr = M_.endo_nbr;
exo_nbr = M_.exo_nbr; exo_nbr = M_.exo_nbr;
fname = M_.fname; fname = M_.fname;
% inst_nbr = M_.inst_nbr; % inst_nbr = M_.inst_nbr;
% i_endo_no_inst = M_.endogenous_variables_without_instruments; % i_endo_no_inst = M_.endogenous_variables_without_instruments;
max_lead = M_.maximum_lead; max_lead = M_.maximum_lead;
max_lag = M_.maximum_lag; max_lag = M_.maximum_lag;
beta = options_.planner_discount; beta = options_.planner_discount;
% indices of all endogenous variables % indices of all endogenous variables
i_endo = [1:endo_nbr]'; i_endo = [1:endo_nbr]';
% indices of endogenous variable except instruments % indices of endogenous variable except instruments
% i_inst = M_.instruments; % i_inst = M_.instruments;
% lead_lag incidence matrix for endogenous variables % lead_lag incidence matrix for endogenous variables
i_lag = M_.lead_lag_incidence; i_lag = M_.lead_lag_incidence;
if options_.steadystate_flag if options_.steadystate_flag
k_inst = []; k_inst = [];
instruments = options_.instruments; instruments = options_.instruments;
for i = 1:size(instruments,1) for i = 1:size(instruments,1)
k_inst = [k_inst; strmatch(options_.instruments(i,:), ... k_inst = [k_inst; strmatch(options_.instruments(i,:), ...
M_.endo_names,'exact')]; M_.endo_names,'exact')];
end end
oo_.steady_state(k_inst) = x; oo_.steady_state(k_inst) = x;
[x,check] = feval([M_.fname '_steadystate'],... [x,check] = feval([M_.fname '_steadystate'],...
oo_.steady_state,... oo_.steady_state,...
[oo_.exo_steady_state; ... [oo_.exo_steady_state; ...
oo_.exo_det_steady_state]); oo_.exo_det_steady_state]);
if size(x,1) < M_.endo_nbr if size(x,1) < M_.endo_nbr
if length(M_.aux_vars) > 0 if length(M_.aux_vars) > 0
x = add_auxiliary_variables_to_steadystate(x,M_.aux_vars,... x = add_auxiliary_variables_to_steadystate(x,M_.aux_vars,...
M_.fname,... M_.fname,...
oo_.exo_steady_state,... oo_.exo_steady_state,...
oo_.exo_det_steady_state,... oo_.exo_det_steady_state,...
M_.params); M_.params);
else else
error([M_.fname '_steadystate.m doesn''t match the model']); error([M_.fname '_steadystate.m doesn''t match the model']);
end end
end end
end end
% value and Jacobian of objective function % value and Jacobian of objective function
ex = zeros(1,M_.exo_nbr); ex = zeros(1,M_.exo_nbr);
[U,Uy,Uyy] = feval([fname '_objective_static'],x(i_endo),ex, M_.params); [U,Uy,Uyy] = feval([fname '_objective_static'],x(i_endo),ex, M_.params);
Uy = Uy'; Uy = Uy';
Uyy = reshape(Uyy,endo_nbr,endo_nbr); Uyy = reshape(Uyy,endo_nbr,endo_nbr);
y = repmat(x(i_endo),1,max_lag+max_lead+1); y = repmat(x(i_endo),1,max_lag+max_lead+1);
% value and Jacobian of dynamic function % value and Jacobian of dynamic function
k = find(i_lag'); k = find(i_lag');
it_ = 1; it_ = 1;
% [f,fJ,fH] = feval([fname '_dynamic'],y(k),ex); % [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_); [f,fJ] = feval([fname '_dynamic'],y(k),[oo_.exo_simul oo_.exo_det_simul], M_.params, it_);
% indices of Lagrange multipliers % indices of Lagrange multipliers
inst_nbr = endo_nbr - size(f,1); inst_nbr = endo_nbr - size(f,1);
i_mult = [endo_nbr+1:2*endo_nbr-inst_nbr]'; i_mult = [endo_nbr+1:2*endo_nbr-inst_nbr]';
% derivatives of Lagrangian with respect to endogenous variables % derivatives of Lagrangian with respect to endogenous variables
% res1 = Uy; % res1 = Uy;
A = zeros(endo_nbr,endo_nbr-inst_nbr); A = zeros(endo_nbr,endo_nbr-inst_nbr);
for i=1:max_lag+max_lead+1 for i=1:max_lag+max_lead+1
% select variables present in the model at a given lag % select variables present in the model at a given lag
[junk,k1,k2] = find(i_lag(i,:)); [junk,k1,k2] = find(i_lag(i,:));
% res1(k1) = res1(k1) + beta^(max_lag-i+1)*fJ(:,k2)'*x(i_mult); % 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)'; A(k1,:) = A(k1,:) + beta^(max_lag-i+1)*fJ(:,k2)';
end end
% i_inst = var_index(options_.olr_inst); % i_inst = var_index(options_.olr_inst);
% k = setdiff(1:size(A,1),i_inst); % k = setdiff(1:size(A,1),i_inst);
% mult = -A(k,:)\Uy(k); % mult = -A(k,:)\Uy(k);
mult = -A\Uy; mult = -A\Uy;
% resids = [f; Uy(i_inst)+A(i_inst,:)*mult]; % resids = [f; Uy(i_inst)+A(i_inst,:)*mult];
resids1 = Uy+A*mult; resids1 = Uy+A*mult;
% resids = [f; sqrt(resids1'*resids1/endo_nbr)]; % resids = [f; sqrt(resids1'*resids1/endo_nbr)];
[q,r,e] = qr([A Uy]'); [q,r,e] = qr([A Uy]');
if options_.steadystate_flag if options_.steadystate_flag
resids = [r(end,(endo_nbr-inst_nbr+1:end))']; resids = [r(end,(endo_nbr-inst_nbr+1:end))'];
else else
resids = [f; r(end,(endo_nbr-inst_nbr+1:end))']; resids = [f; r(end,(endo_nbr-inst_nbr+1:end))'];
end end
rJ = []; rJ = [];
return; return;
% Jacobian of first order conditions % Jacobian of first order conditions
n = nnz(i_lag)+exo_nbr; n = nnz(i_lag)+exo_nbr;
iH = reshape(1:n^2,n,n); iH = reshape(1:n^2,n,n);
rJ = zeros(2*endo_nbr-inst_nbr,2*endo_nbr-inst_nbr); rJ = zeros(2*endo_nbr-inst_nbr,2*endo_nbr-inst_nbr);
rJ(i_endo,i_endo) = Uyy; rJ(i_endo,i_endo) = Uyy;
for i=1:max_lag+max_lead+1 for i=1:max_lag+max_lead+1
% select variables present in the model at a given lag % select variables present in the model at a given lag
[junk,k1,k2] = find(i_lag(i,:)); [junk,k1,k2] = find(i_lag(i,:));
k3 = length(k2); 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,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(k1,i_mult) = rJ(k1,i_mult) + beta^(max_lag-1+1)*fJ(:,k2)';
rJ(i_mult,k1) = rJ(i_mult,k1) + fJ(:,k2); rJ(i_mult,k1) = rJ(i_mult,k1) + fJ(:,k2);
end end
% rJ = 1e-3*rJ; % rJ = 1e-3*rJ;
% rJ(209,210) = rJ(209,210)+1-1e-3; % rJ(209,210) = rJ(209,210)+1-1e-3;

View File

@ -59,13 +59,13 @@ end
warning_config() warning_config()
if exist('OCTAVE_VERSION') if exist('OCTAVE_VERSION')
if octave_ver_less_than('3.0.0') 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.'); 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 end
else else
if matlab_ver_less_than('6.5') 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).'); 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
end end
% disable output paging (it is on by default on Octave) % disable output paging (it is on by default on Octave)
@ -73,44 +73,44 @@ more off
% sets default format for save() command % sets default format for save() command
if exist('OCTAVE_VERSION') if exist('OCTAVE_VERSION')
default_save_options('-mat') default_save_options('-mat')
end end
% detect if MEX files are present; if not, use alternative M-files % detect if MEX files are present; if not, use alternative M-files
dynareroot = dynare_config; dynareroot = dynare_config;
if nargin < 1 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 end
if ~ischar(fname) if ~ischar(fname)
error('DYNARE: argument of dynare must be a text string') error('DYNARE: argument of dynare must be a text string')
end end
% Testing if file have extension % Testing if file have extension
% If no extension default .mod is added % If no extension default .mod is added
if isempty(strfind(fname,'.')) if isempty(strfind(fname,'.'))
fname1 = [fname '.dyn']; fname1 = [fname '.dyn'];
d = dir(fname1); d = dir(fname1);
if length(d) == 0 if length(d) == 0
fname1 = [fname '.mod']; fname1 = [fname '.mod'];
end end
fname = fname1; fname = fname1;
% Checking file extension % Checking file extension
else else
if ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.MOD') ... if ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.MOD') ...
&& ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.DYN') && ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.DYN')
error('DYNARE: argument must be a filename with .mod or .dyn extension') error('DYNARE: argument must be a filename with .mod or .dyn extension')
end; end;
end; end;
d = dir(fname); d = dir(fname);
if length(d) == 0 if length(d) == 0
error(['DYNARE: can''t open ' fname]) error(['DYNARE: can''t open ' fname])
end end
command = ['"' dynareroot 'dynare_m" ' fname] ; command = ['"' dynareroot 'dynare_m" ' fname] ;
for i=2:nargin for i=2:nargin
command = [command ' ' varargin{i-1}]; command = [command ' ' varargin{i-1}];
end end
% Workaround for bug in Octave >= 3.2 % Workaround for bug in Octave >= 3.2
@ -122,11 +122,11 @@ end
[status, result] = system(command); [status, result] = system(command);
disp(result) disp(result)
if status if status
% Should not use "error(result)" since message will be truncated if too long % Should not use "error(result)" since message will be truncated if too long
error('DYNARE: preprocessing failed') error('DYNARE: preprocessing failed')
end end
if ~ isempty(find(abs(fname) == 46)) if ~ isempty(find(abs(fname) == 46))
fname = fname(:,1:find(abs(fname) == 46)-1) ; fname = fname(:,1:find(abs(fname) == 46)-1) ;
end end
evalin('base',fname) ; evalin('base',fname) ;

View File

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