Move many functions towards consistent naming

Related to #1776
kalman-mex
Johannes Pfeifer 2023-10-24 22:21:15 +02:00
parent af20512476
commit 879d92fbf8
36 changed files with 590 additions and 552 deletions

View File

@ -227,7 +227,7 @@ elseif options_.lik_init == 5 % Old diffuse Kalman filter only for th
end
R_tmp = R(stable, :);
T_tmp = T(stable,stable);
Pstar_tmp=lyapunov_solver(T_tmp,R_tmp,Q,DynareOptions);
Pstar_tmp=lyapunov_solver(T_tmp,R_tmp,Q,options_);
Pstar(stable, stable) = Pstar_tmp;
Pinf = [];
end

View File

@ -1,5 +1,5 @@
function WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions,opts_decomp)
%function WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions)
function WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,M_,options_,opts_decomp)
% WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,M_,options_,opts_decomp)
% Saves the results from the shock_decomposition command to xls
%
% Inputs
@ -8,10 +8,11 @@ function WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,Dyna
% endo_names [exo_nbr*string length] variable names from M_.endo_names
% i_var [n_var*1] vector indices of requested variables in M_.endo_names and z
% initial_date [dseries object] first period of decomposition to plot
% DynareModel [structure] Dynare model structure
% DynareOptions [structure] Dynare options structure
% M_ [structure] Dynare model structure
% options_ [structure] Dynare options structure
% opts_decomp [structure] decomposition options structure
% Copyright © 2016-2022 Dynare Team
% Copyright © 2016-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -28,16 +29,16 @@ function WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,Dyna
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
OutputDirectoryName = CheckPath('Output',DynareModel.dname);
OutputDirectoryName = CheckPath('Output',M_.dname);
SteadyState=zeros(DynareModel.endo_nbr,1);
SteadyState=zeros(M_.endo_nbr,1);
fig_mode='';
fig_mode1='';
fig_name='';
screen_shocks=0;
use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups;
use_shock_groups = options_.plot_shock_decomp.use_shock_groups;
if use_shock_groups
shock_groups = DynareModel.shock_groups.(use_shock_groups);
shock_groups = M_.shock_groups.(use_shock_groups);
shock_ind = fieldnames(shock_groups);
end
@ -120,9 +121,9 @@ for j=1:nvar
fig_name1 = strrep(fig_name1,'.','');
if ~ismac
STATUS = xlswrite([OutputDirectoryName,filesep,DynareModel.fname,'_shock_decomposition',fig_mode,fig_name1],d0,endo_names{i_var(j)});
STATUS = xlswrite([OutputDirectoryName,filesep,M_.fname,'_shock_decomposition',fig_mode,fig_name1],d0,endo_names{i_var(j)});
else
writetable(cell2table(d0), [OutputDirectoryName,filesep,DynareModel.fname,'_shock_decomposition',fig_mode,fig_name1 '.xls'], 'Sheet', endo_names{i_var(j)},'WriteVariableNames',false);
writetable(cell2table(d0), [OutputDirectoryName,filesep,M_.fname,'_shock_decomposition',fig_mode,fig_name1 '.xls'], 'Sheet', endo_names{i_var(j)},'WriteVariableNames',false);
end
warning_config;

View File

@ -1,5 +1,5 @@
function forecasts = backward_model_forecast(initialcondition, listofvariables, periods, withuncertainty)
%function forecasts = backward_model_forecast(initialcondition, listofvariables, periods, withuncertainty)
% Returns unconditional forecasts.
%
% INPUTS

View File

@ -1,5 +1,5 @@
function [endogenousvariables, exogenousvariables] = backward_model_inversion(constraints, exogenousvariables, initialconditions, endo_names, exo_names, freeinnovations, DynareModel, DynareOptions, DynareOutput)
function [endogenousvariables, exogenousvariables] = backward_model_inversion(constraints, exogenousvariables, initialconditions, endo_names, exo_names, freeinnovations, M_, options_, oo_)
% [endogenousvariables, exogenousvariables] = backward_model_inversion(constraints, exogenousvariables, initialconditions, endo_names, exo_names, freeinnovations, M_, options_, oo_)
% INPUTS
% - constraints [dseries] with N constrained endogenous variables from t1 to t2.
% - exogenousvariables [dseries] with Q exogenous variables.
@ -7,6 +7,9 @@ function [endogenousvariables, exogenousvariables] = backward_model_inversion(co
% - endo_names [cell] list of endogenous variable names.
% - exo_names [cell] list of exogenous variable names.
% - freeinstruments [cell] list of exogenous variable names used to control the constrained endogenous variables.
% - M_ [structure] describing the model
% - options_ [structure] describing the options
% - oo_ [structure] storing the results
%
% OUTPUTS
% - endogenous [dseries]
@ -33,7 +36,7 @@ function [endogenousvariables, exogenousvariables] = backward_model_inversion(co
% Get indices for the free innovations.
freeinnovations_id = zeros(length(freeinnovations), 1);
if length(freeinnovations)<DynareModel.exo_nbr
if length(freeinnovations)<M_.exo_nbr
for i=1:length(freeinnovations)
freeinnovations_id(i) = find(strcmp(freeinnovations{i}, exo_names));
end
@ -45,7 +48,7 @@ nxfree = length(freeinnovations_id);
% Get indices for the the controlled and free endogenous variables.
controlledendogenousvariables_id = zeros(length(freeinnovations), 1);
if length(freeinnovations)<DynareModel.endo_nbr
if length(freeinnovations)<M_.endo_nbr
for i=1:length(freeinnovations)
controlledendogenousvariables_id(i) = find(strcmp(constraints.name{i}, endo_names));
end
@ -65,15 +68,15 @@ ModelInversion.nxfree = nxfree;
ModelInversion.y_constrained_id = controlledendogenousvariables_id;
ModelInversion.y_free_id = freeendogenousvariables_id;
ModelInversion.x_free_id = freeinnovations_id;
ModelInversion.J_id = [DynareModel.endo_nbr+ModelInversion.y_free_id ; 3*DynareModel.endo_nbr+ModelInversion.x_free_id];
ModelInversion.J_id = [M_.endo_nbr+ModelInversion.y_free_id ; 3*M_.endo_nbr+ModelInversion.x_free_id];
% Get function handles to the dynamic model routines.
dynamic_resid = str2func([DynareModel.fname '.sparse.dynamic_resid']);
dynamic_g1 = str2func([DynareModel.fname '.sparse.dynamic_g1']);
dynamic_resid = str2func([M_.fname '.sparse.dynamic_resid']);
dynamic_g1 = str2func([M_.fname '.sparse.dynamic_g1']);
% Initialization of the returned simulations (endogenous variables).
Y = NaN(DynareModel.endo_nbr, nobs(constraints));
Y = [transpose(initialconditions{DynareModel.endo_names{:}}(constraints.dates(1)-1).data), Y];
Y = NaN(M_.endo_nbr, nobs(constraints));
Y = [transpose(initialconditions{M_.endo_names{:}}(constraints.dates(1)-1).data), Y];
for i=1:nyctrl
Y(controlledendogenousvariables_id(i),2:end) = transpose(constraints.data(:,i));
end
@ -94,8 +97,8 @@ for t = 1:nobs(constraints)
z = [Y(freeendogenousvariables_id,ity-1); zeros(nxfree, 1)];
% Solves for z.
[z, failed, ~, ~, errorcode] = dynare_solve(@dynamic_backward_model_for_inversion, z, ...
DynareOptions.simul.maxit, DynareOptions.dynatol.f, DynareOptions.dynatol.x, ...
DynareOptions, dynamic_resid, dynamic_g1, ylag, ycur, X(itx,:), DynareModel.params, DynareOutput.steady_state, DynareModel.dynamic_g1_sparse_rowval, DynareModel.dynamic_g1_sparse_colval, DynareModel.dynamic_g1_sparse_colptr, ModelInversion);
options_.simul.maxit, options_.dynatol.f, options_.dynatol.x, ...
options_, dynamic_resid, dynamic_g1, ylag, ycur, X(itx,:), M_.params, oo_.steady_state, M_.dynamic_g1_sparse_rowval, M_.dynamic_g1_sparse_colval, M_.dynamic_g1_sparse_colptr, ModelInversion);
if failed
error('Nonlinear solver failed with errorcode=%i', errorcode)
end

View File

@ -1,5 +1,5 @@
function [deviations, baseline, irfs] = backward_model_irf(initialcondition, innovationbaseline, listofshocks, listofvariables, varargin)
% [deviations, baseline, irfs] = backward_model_irf(initialcondition, innovationbaseline, listofshocks, listofvariables, varargin)
% Returns impulse response functions.
%
% INPUTS

View File

@ -1,22 +1,22 @@
function [simulations, errorflag] = simul_backward_linear_model(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations)
function [simulations, errorflag] = simul_backward_linear_model(initialconditions, samplesize, options_, M_, oo_, innovations)
% [simulations, errorflag] = simul_backward_linear_model(initialconditions, samplesize, options_, M_, oo_, innovations)
% Simulates a stochastic linear backward looking model.
%
% INPUTS
% - initialconditions [dseries] initial conditions for the endogenous variables.
% - samplesize [integer] scalar, number of periods for the simulation.
% - DynareOptions [struct] Dynare's options_ global structure.
% - DynareModel [struct] Dynare's M_ global structure.
% - DynareOutput [struct] Dynare's oo_ global structure.
% - options_ [struct] Dynare's options_ global structure.
% - M_ [struct] Dynare's M_ global structure.
% - oo_ [struct] Dynare's oo_ global structure.
% - innovations [double] T*q matrix, innovations to be used for the simulation.
%
% OUTPUTS
% - DynareOutput [struct] Dynare's oo_ global structure.
% - oo_ [struct] Dynare's oo_ global structure.
% - errorflag [logical] scalar, equal to false iff the simulation did not fail.
%
% REMARKS
% [1] The innovations used for the simulation are saved in DynareOutput.exo_simul, and the resulting paths for the endogenous
% variables are saved in DynareOutput.endo_simul.
% [1] The innovations used for the simulation are saved in oo_.exo_simul, and the resulting paths for the endogenous
% variables are saved in oo_.endo_simul.
% [2] The last input argument is not mandatory. If absent we use random draws and rescale them with the informations provided
% through the shocks block.
% [3] If the first input argument is empty, the endogenous variables are initialized with 0, or if available with the informations
@ -39,21 +39,21 @@ function [simulations, errorflag] = simul_backward_linear_model(initialcondition
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if DynareModel.maximum_lead
error('Model defined in %s.mod is not backward.', DynareModel.fname)
if M_.maximum_lead
error('Model defined in %s.mod is not backward.', M_.fname)
end
if ~DynareModel.maximum_lag
error('Model defined in %s.mod is not backward.', DynareModel.fname)
if ~M_.maximum_lag
error('Model defined in %s.mod is not backward.', M_.fname)
end
if nargin<6
innovations = [];
end
[initialconditions, samplesize, innovations, DynareOptions, DynareModel, DynareOutput, endonames, exonames, dynamic_resid, dynamic_g1] = ...
simul_backward_model_init(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations);
[initialconditions, samplesize, innovations, options_, M_, oo_, endonames, exonames, dynamic_resid, dynamic_g1] = ...
simul_backward_model_init(initialconditions, samplesize, options_, M_, oo_, innovations);
[ysim, xsim, errorflag] = simul_backward_linear_model_(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations, dynamic_resid, dynamic_g1);
[ysim, xsim, errorflag] = simul_backward_linear_model_(initialconditions, samplesize, options_, M_, oo_, innovations, dynamic_resid, dynamic_g1);
simulations = [dseries(ysim', initialconditions.init, endonames(1:DynareModel.orig_endo_nbr)), dseries(xsim, initialconditions.init, exonames)];
simulations = [dseries(ysim', initialconditions.init, endonames(1:M_.orig_endo_nbr)), dseries(xsim, initialconditions.init, exonames)];

View File

@ -1,22 +1,22 @@
function [ysim, xsim, errorflag] = simul_backward_linear_model_(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations, dynamic_resid, dynamic_g1)
function [ysim, xsim, errorflag] = simul_backward_linear_model_(initialconditions, samplesize, options_, M_, oo_, innovations, dynamic_resid, dynamic_g1)
% [ysim, xsim, errorflag] = simul_backward_linear_model_(initialconditions, samplesize, options_, M_, oo_, innovations, dynamic_resid, dynamic_g1)
% Simulates a stochastic linear backward looking model.
%
% INPUTS
% - initialconditions [dseries] initial conditions for the endogenous variables.
% - samplesize [integer] scalar, number of periods for the simulation.
% - DynareOptions [struct] Dynare's options_ global structure.
% - DynareModel [struct] Dynare's M_ global structure.
% - DynareOutput [struct] Dynare's oo_ global structure.
% - options_ [struct] Dynare's options_ global structure.
% - M_ [struct] Dynare's M_ global structure.
% - oo_ [struct] Dynare's oo_ global structure.
% - innovations [double] T*q matrix, innovations to be used for the simulation.
%
% OUTPUTS
% - DynareOutput [struct] Dynare's oo_ global structure.
% - oo_ [struct] Dynare's oo_ global structure.
% - errorflag [logical] scalar, equal to false iff the simulation did not fail.
%
% REMARKS
% [1] The innovations used for the simulation are saved in DynareOutput.exo_simul, and the resulting paths for the endogenous
% variables are saved in DynareOutput.endo_simul.
% [1] The innovations used for the simulation are saved in oo_.exo_simul, and the resulting paths for the endogenous
% variables are saved in oo_.endo_simul.
% [2] The last input argument is not mandatory. If absent we use random draws and rescale them with the informations provided
% through the shocks block.
% [3] If the first input argument is empty, the endogenous variables are initialized with 0, or if available with the informations
@ -42,17 +42,17 @@ function [ysim, xsim, errorflag] = simul_backward_linear_model_(initialcondition
errorflag = false;
if ~isempty(innovations)
DynareOutput.exo_simul(initialconditions.nobs+(1:samplesize),:) = innovations;
oo_.exo_simul(initialconditions.nobs+(1:samplesize),:) = innovations;
end
% Get coefficients
y = [zeros(2*DynareModel.endo_nbr,1); NaN(DynareModel.endo_nbr,1)];
x = zeros(DynareModel.exo_nbr, 1);
[cst, T_order, T] = dynamic_resid(y, x, DynareModel.params, DynareOutput.steady_state);
jacob = dynamic_g1(y, x, DynareModel.params, DynareOutput.steady_state, DynareModel.dynamic_g1_sparse_rowval, DynareModel.dynamic_g1_sparse_colval, DynareModel.dynamic_g1_sparse_colptr, T_order, T);
y = [zeros(2*M_.endo_nbr,1); NaN(M_.endo_nbr,1)];
x = zeros(M_.exo_nbr, 1);
[cst, T_order, T] = dynamic_resid(y, x, M_.params, oo_.steady_state);
jacob = dynamic_g1(y, x, M_.params, oo_.steady_state, M_.dynamic_g1_sparse_rowval, M_.dynamic_g1_sparse_colval, M_.dynamic_g1_sparse_colptr, T_order, T);
try
A0inv = inv(jacob(:,DynareModel.endo_nbr+(1:DynareModel.endo_nbr)));
A0inv = inv(jacob(:,M_.endo_nbr+(1:M_.endo_nbr)));
catch
errorflag = true;
ysim = [];
@ -60,13 +60,13 @@ catch
return
end
A1 = jacob(:,1:DynareModel.endo_nbr);
B = jacob(:,3*DynareModel.endo_nbr+1:end);
A1 = jacob(:,1:M_.endo_nbr);
B = jacob(:,3*M_.endo_nbr+1:end);
% Simulations
for it = initialconditions.nobs+(1:samplesize)
DynareOutput.endo_simul(:,it) = -A0inv*(cst + A1*DynareOutput.endo_simul(:,it-1) + B*DynareOutput.exo_simul(it,:)');
oo_.endo_simul(:,it) = -A0inv*(cst + A1*oo_.endo_simul(:,it-1) + B*oo_.exo_simul(it,:)');
end
ysim = DynareOutput.endo_simul(1:DynareModel.orig_endo_nbr,:);
xsim = DynareOutput.exo_simul;
ysim = oo_.endo_simul(1:M_.orig_endo_nbr,:);
xsim = oo_.exo_simul;

View File

@ -1,5 +1,5 @@
function [initialconditions, samplesize, innovations, DynareOptions, DynareModel, DynareOutput, endonames, exonames, dynamic_resid, dynamic_g1, y] = ...
simul_backward_model_init(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations)
function [initialconditions, samplesize, innovations, options_, M_, oo_, endonames, exonames, dynamic_resid, dynamic_g1, y] = ...
simul_backward_model_init(initialconditions, samplesize, options_, M_, oo_, innovations)
% Initialization of the routines simulating backward models.
@ -21,7 +21,7 @@ function [initialconditions, samplesize, innovations, DynareOptions, DynareModel
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
% Test if the model is backward.
if DynareModel.maximum_lead
if M_.maximum_lead
error('simul_backward_nonlinear_model:: The specified model is not backward looking!')
end
@ -30,39 +30,39 @@ if ~(isdseries(initialconditions) || isempty(initialconditions))
error('First input argument must be a dseries object or an empty array!')
end
% If initialconditions is empty instantiates a dseries object with the informations available in DynareModel.endo_histval.
% If initialconditions is empty instantiates a dseries object with the informations available in M_.endo_histval.
if isempty(initialconditions)
yinitdata = zeros(DynareModel.orig_endo_nbr, DynareModel.orig_maximum_lag);
yinitdata(:,1) = DynareModel.endo_histval(1:DynareModel.orig_endo_nbr);
xinitdata = zeros(DynareModel.exo_nbr, DynareModel.orig_maximum_lag);
if DynareModel.orig_maximum_endo_lag>1
for i = 1:length(DynareModel.aux_vars)
if DynareModel.aux_vars(i).type==1
yinitdata(DynareModel.aux_vars(i).orig_index, abs(DynareModel.aux_vars(i).orig_lead_lag)+1) = ...
DynareModel.endo_histval(DynareModel.orig_endo_nbr+i);
yinitdata = zeros(M_.orig_endo_nbr, M_.orig_maximum_lag);
yinitdata(:,1) = M_.endo_histval(1:M_.orig_endo_nbr);
xinitdata = zeros(M_.exo_nbr, M_.orig_maximum_lag);
if M_.orig_maximum_endo_lag>1
for i = 1:length(M_.aux_vars)
if M_.aux_vars(i).type==1
yinitdata(M_.aux_vars(i).orig_index, abs(M_.aux_vars(i).orig_lead_lag)+1) = ...
M_.endo_histval(M_.orig_endo_nbr+i);
end
end
yinitdata = flip(yinitdata, 2);
end
if DynareModel.orig_maximum_exo_lag>0
for i = 1:length(DynareModel.aux_vars)
if DynareModel.aux_vars(i).type==3
xinitdata(DynareModel.aux_vars(i).orig_index, abs(DynareModel.aux_vars(i).orig_lead_lag)+1) = ...
DynareModel.endo_histval(DynareModel.orig_endo_nbr+i);
if M_.orig_maximum_exo_lag>0
for i = 1:length(M_.aux_vars)
if M_.aux_vars(i).type==3
xinitdata(M_.aux_vars(i).orig_index, abs(M_.aux_vars(i).orig_lead_lag)+1) = ...
M_.endo_histval(M_.orig_endo_nbr+i);
end
end
xinitdata = flip(xinitdata, 2);
end
initialconditions = dseries([transpose(yinitdata) transpose(xinitdata)], '1Y', ...
vertcat(DynareModel.endo_names(1:DynareModel.orig_endo_nbr), DynareModel.exo_names));
vertcat(M_.endo_names(1:M_.orig_endo_nbr), M_.exo_names));
end
[initialconditions, info] = checkdatabase(initialconditions, DynareModel, false, true);
[initialconditions, info] = checkdatabase(initialconditions, M_, false, true);
% Test if the first argument contains all the lagged endogenous variables
endonames = DynareModel.endo_names;
endonames = M_.endo_names;
missingendogenousvariables = setdiff(endonames, initialconditions.name);
endolags = get_lags_on_endogenous_variables(DynareModel);
endolags = get_lags_on_endogenous_variables(M_);
endolags_ = endolags(find(endolags));
endowithlagnames = endonames(find(endolags));
if ~isempty(missingendogenousvariables)
@ -103,9 +103,9 @@ if missinginitialcondition
end
% If the model has lags on the exogenous variables, test if we have corresponding initial conditions.
exonames = DynareModel.exo_names;
exonames = M_.exo_names;
missingexogenousvariables = setdiff(exonames, initialconditions.name);
exolags = get_lags_on_exogenous_variables(DynareModel);
exolags = get_lags_on_exogenous_variables(M_);
exolags_ = exolags(find(exolags));
exowithlagnames = exonames(find(exolags));
if ~isempty(missingexogenousvariables)
@ -147,52 +147,52 @@ end
if nargin<6 || isempty(innovations)
% Set the covariance matrix of the structural innovations.
variances = diag(DynareModel.Sigma_e);
number_of_shocks = length(DynareModel.Sigma_e);
variances = diag(M_.Sigma_e);
number_of_shocks = length(M_.Sigma_e);
positive_var_indx = find(variances>0);
effective_number_of_shocks = length(positive_var_indx);
covariance_matrix = DynareModel.Sigma_e(positive_var_indx,positive_var_indx);
covariance_matrix = M_.Sigma_e(positive_var_indx,positive_var_indx);
covariance_matrix_upper_cholesky = chol(covariance_matrix);
% Set seed to its default state.
if DynareOptions.bnlms.set_dynare_seed_to_default
DynareOptions=set_dynare_seed_local_options(DynareOptions,'default');
if options_.bnlms.set_dynare_seed_to_default
options_=set_dynare_seed_local_options(options_,'default');
end
% Simulate structural innovations.
switch DynareOptions.bnlms.innovation_distribution
switch options_.bnlms.innovation_distribution
case 'gaussian'
DynareOutput.bnlms.shocks = randn(samplesize,effective_number_of_shocks)*covariance_matrix_upper_cholesky;
oo_.bnlms.shocks = randn(samplesize,effective_number_of_shocks)*covariance_matrix_upper_cholesky;
otherwise
error(['simul_backward_nonlinear_model:: ' DynareOptions.bnlms.innovation_distribution ' distribution for the structural innovations is not (yet) implemented!'])
error(['simul_backward_nonlinear_model:: ' options_.bnlms.innovation_distribution ' distribution for the structural innovations is not (yet) implemented!'])
end
% Put the simulated innovations in DynareOutput.exo_simul.
DynareOutput.exo_simul = zeros(samplesize,number_of_shocks);
DynareOutput.exo_simul(:,positive_var_indx) = DynareOutput.bnlms.shocks;
innovations = DynareOutput.exo_simul;
% Put the simulated innovations in oo_.exo_simul.
oo_.exo_simul = zeros(samplesize,number_of_shocks);
oo_.exo_simul(:,positive_var_indx) = oo_.bnlms.shocks;
innovations = oo_.exo_simul;
else
DynareOutput.exo_simul = innovations; % innovations
oo_.exo_simul = innovations; % innovations
end
% Initialization of the returned simulations.
DynareOutput.endo_simul = NaN(DynareModel.endo_nbr, samplesize+initialconditions.nobs);
oo_.endo_simul = NaN(M_.endo_nbr, samplesize+initialconditions.nobs);
for i=1:length(endonames)
if ismember(endonames{i}, initialconditions.name)
DynareOutput.endo_simul(i,1:initialconditions.nobs) = transpose(initialconditions{endonames{i}}.data);
oo_.endo_simul(i,1:initialconditions.nobs) = transpose(initialconditions{endonames{i}}.data);
end
end
% Initialization of the array for the exogenous variables.
DynareOutput.exo_simul = [NaN(initialconditions.nobs, DynareModel.exo_nbr); DynareOutput.exo_simul ];
oo_.exo_simul = [NaN(initialconditions.nobs, M_.exo_nbr); oo_.exo_simul ];
for i=1:length(exonames)
if ismember(exonames{i}, initialconditions.name)
DynareOutput.exo_simul(1:initialconditions.nobs, i) = initialconditions{exonames{i}}.data;
oo_.exo_simul(1:initialconditions.nobs, i) = initialconditions{exonames{i}}.data;
end
end
if nargout>8
% Get function handles to the dynamic model routines.
dynamic_resid = str2func([DynareModel.fname,'.sparse.dynamic_resid']);
dynamic_g1 = str2func([DynareModel.fname,'.sparse.dynamic_g1']);
dynamic_resid = str2func([M_.fname,'.sparse.dynamic_resid']);
dynamic_g1 = str2func([M_.fname,'.sparse.dynamic_g1']);
% initialization of vector y.
y = NaN(3*DynareModel.endo_nbr,1);
y = NaN(3*M_.endo_nbr,1);
end

View File

@ -1,13 +1,13 @@
function [simulations, errorflag] = simul_backward_nonlinear_model(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations)
% function simulations = simul_backward_nonlinear_model(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations)
function [simulations, errorflag] = simul_backward_nonlinear_model(initialconditions, samplesize, options_, M_, oo_, innovations)
% function simulations = simul_backward_nonlinear_model(initialconditions, samplesize, options_, M_, oo_, innovations)
% Simulates a stochastic non linear backward looking model with arbitrary precision (a deterministic solver is used).
%
% INPUTS
% - initial_conditions [dseries] initial conditions for the endogenous variables.
% - sample_size [integer] scalar, number of periods for the simulation.
% - DynareOptions [struct] Dynare's options_ global structure.
% - DynareModel [struct] Dynare's M_ global structure.
% - DynareOutput [struct] Dynare's oo_ global structure.
% - options_ [struct] Dynare's options_ global structure.
% - M_ [struct] Dynare's M_ global structure.
% - oo_ [struct] Dynare's oo_ global structure.
% - innovations [double] T*q matrix, innovations to be used for the simulation.
%
% OUTPUTS
@ -15,8 +15,8 @@ function [simulations, errorflag] = simul_backward_nonlinear_model(initialcondit
% - errorflag [logical] scalar, equal to false iff the simulation did not fail.
%
% REMARKS
% [1] The innovations used for the simulation are saved in DynareOutput.exo_simul, and the resulting paths for the endogenous
% variables are saved in DynareOutput.endo_simul.
% [1] The innovations used for the simulation are saved in oo_.exo_simul, and the resulting paths for the endogenous
% variables are saved in oo_.endo_simul.
% [2] The last input argument is not mandatory. If absent we use random draws and rescale them with the informations provided
% through the shocks block.
% [3] If the first input argument is empty, the endogenous variables are initialized with 0, or if available with the informations
@ -39,21 +39,21 @@ function [simulations, errorflag] = simul_backward_nonlinear_model(initialcondit
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if DynareModel.maximum_lead
error('Model defined in %s.mod is not backward.', DynareModel.fname)
if M_.maximum_lead
error('Model defined in %s.mod is not backward.', M_.fname)
end
if ~DynareModel.maximum_lag
error('Model defined in %s.mod is not backward.', DynareModel.fname)
if ~M_.maximum_lag
error('Model defined in %s.mod is not backward.', M_.fname)
end
if nargin<6
innovations = [];
end
[initialconditions, samplesize, innovations, DynareOptions, DynareModel, DynareOutput, endonames, exonames, dynamic_resid, dynamic_g1] = ...
simul_backward_model_init(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations);
[initialconditions, samplesize, innovations, options_, M_, oo_, endonames, exonames, dynamic_resid, dynamic_g1] = ...
simul_backward_model_init(initialconditions, samplesize, options_, M_, oo_, innovations);
[ysim, xsim, errorflag] = simul_backward_nonlinear_model_(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations, dynamic_resid, dynamic_g1);
[ysim, xsim, errorflag] = simul_backward_nonlinear_model_(initialconditions, samplesize, options_, M_, oo_, innovations, dynamic_resid, dynamic_g1);
simulations = [dseries(ysim', initialconditions.init, endonames(1:DynareModel.orig_endo_nbr)), dseries(xsim, initialconditions.init, exonames)];
simulations = [dseries(ysim', initialconditions.init, endonames(1:M_.orig_endo_nbr)), dseries(xsim, initialconditions.init, exonames)];

View File

@ -1,22 +1,24 @@
function [ysim, xsim, errorflag] = simul_backward_nonlinear_model_(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations, dynamic_resid, dynamic_g1)
function [ysim, xsim, errorflag] = simul_backward_nonlinear_model_(initialconditions, samplesize, options_, M_, oo_, innovations, dynamic_resid, dynamic_g1)
% [ysim, xsim, errorflag] = simul_backward_nonlinear_model_(initialconditions, samplesize, options_, M_, oo_, innovations, dynamic_resid, dynamic_g1)
% Simulates a stochastic non linear backward looking model with arbitrary precision (a deterministic solver is used).
%
% INPUTS
% - initial_conditions [dseries] initial conditions for the endogenous variables.
% - sample_size [integer] scalar, number of periods for the simulation.
% - DynareOptions [struct] Dynare's options_ global structure.
% - DynareModel [struct] Dynare's M_ global structure.
% - DynareOutput [struct] Dynare's oo_ global structure.
% - options_ [struct] Dynare's options_ global structure.
% - M_ [struct] Dynare's M_ global structure.
% - oo_ [struct] Dynare's oo_ global structure.
% - innovations [double] T*q matrix, innovations to be used for the simulation.
% - dynamic_resid
% - dynamic_g1
%
% OUTPUTS
% - DynareOutput [struct] Dynare's oo_ global structure.
% - oo_ [struct] Dynare's oo_ global structure.
% - errorflag [logical] scalar, equal to false iff the simulation did not fail.
%
% REMARKS
% [1] The innovations used for the simulation are saved in DynareOutput.exo_simul, and the resulting paths for the endogenous
% variables are saved in DynareOutput.endo_simul.
% [1] The innovations used for the simulation are saved in oo_.exo_simul, and the resulting paths for the endogenous
% variables are saved in oo_.endo_simul.
% [2] The last input argument is not mandatory. If absent we use random draws and rescale them with the informations provided
% through the shocks block.
% [3] If the first input argument is empty, the endogenous variables are initialized with 0, or if available with the informations
@ -43,18 +45,18 @@ debug = false;
errorflag = false;
if ~isempty(innovations)
DynareOutput.exo_simul(initialconditions.nobs+(1:samplesize),:) = innovations;
oo_.exo_simul(initialconditions.nobs+(1:samplesize),:) = innovations;
end
if ismember(DynareOptions.solve_algo, [12,14])
[funcs, feedback_vars_idxs] = setup_time_recursive_block_simul(DynareModel);
if ismember(options_.solve_algo, [12,14])
[funcs, feedback_vars_idxs] = setup_time_recursive_block_simul(M_);
end
function [r, J] = block_wrapper(z, feedback_vars_idx, func, y_dynamic, x, sparse_rowval, sparse_colval, sparse_colptr, T)
% NB: do as few computations as possible inside this function, since it is
% called a very large number of times
y_dynamic(feedback_vars_idx) = z;
[~, ~, r, J] = feval(func, y_dynamic, x, DynareModel.params, DynareOutput.steady_state, ...
[~, ~, r, J] = feval(func, y_dynamic, x, M_.params, oo_.steady_state, ...
sparse_rowval, sparse_colval, sparse_colptr, T);
end
@ -63,21 +65,21 @@ for it = initialconditions.nobs+(1:samplesize)
if debug
dprintf('Period t = %s.', num2str(it-initialconditions.nobs));
end
y_ = DynareOutput.endo_simul(:,it-1);
y_ = oo_.endo_simul(:,it-1);
y = y_; % A good guess for the initial conditions is the previous values for the endogenous variables.
x = DynareOutput.exo_simul(it,:);
x = oo_.exo_simul(it,:);
try
if ismember(DynareOptions.solve_algo, [12,14])
T = NaN(DynareModel.block_structure.dyn_tmp_nbr);
y_dynamic = [y_; y; NaN(DynareModel.endo_nbr, 1)];
for blk = 1:length(DynareModel.block_structure.block)
sparse_rowval = DynareModel.block_structure.block(blk).g1_sparse_rowval;
sparse_colval = DynareModel.block_structure.block(blk).g1_sparse_colval;
sparse_colptr = DynareModel.block_structure.block(blk).g1_sparse_colptr;
if DynareModel.block_structure.block(blk).Simulation_Type ~= 1 % Not an evaluate forward block
if ismember(options_.solve_algo, [12,14])
T = NaN(M_.block_structure.dyn_tmp_nbr);
y_dynamic = [y_; y; NaN(M_.endo_nbr, 1)];
for blk = 1:length(M_.block_structure.block)
sparse_rowval = M_.block_structure.block(blk).g1_sparse_rowval;
sparse_colval = M_.block_structure.block(blk).g1_sparse_colval;
sparse_colptr = M_.block_structure.block(blk).g1_sparse_colptr;
if M_.block_structure.block(blk).Simulation_Type ~= 1 % Not an evaluate forward block
[z, errorflag, ~, ~, errorcode] = dynare_solve(@block_wrapper, y_dynamic(feedback_vars_idxs{blk}), ...
DynareOptions.simul.maxit, DynareOptions.dynatol.f, ...
DynareOptions.dynatol.x, DynareOptions, ...
options_.simul.maxit, options_.dynatol.f, ...
options_.dynatol.x, options_, ...
feedback_vars_idxs{blk}, funcs{blk}, y_dynamic, x, sparse_rowval, sparse_colval, sparse_colptr, T);
if errorflag
error('Nonlinear solver routine failed with errorcode=%i in block %i and period %i.', errorcode, blk, it)
@ -86,44 +88,44 @@ for it = initialconditions.nobs+(1:samplesize)
end
%% Compute endogenous if the block is of type evaluate or if there are recursive variables in a solve block.
%% Also update the temporary terms vector.
[y_dynamic, T] = feval(funcs{blk}, y_dynamic, x, DynareModel.params, ...
DynareOutput.steady_state, sparse_rowval, sparse_colval, ...
[y_dynamic, T] = feval(funcs{blk}, y_dynamic, x, M_.params, ...
oo_.steady_state, sparse_rowval, sparse_colval, ...
sparse_colptr, T);
end
DynareOutput.endo_simul(:,it) = y_dynamic(DynareModel.endo_nbr+(1:DynareModel.endo_nbr));
oo_.endo_simul(:,it) = y_dynamic(M_.endo_nbr+(1:M_.endo_nbr));
else
[DynareOutput.endo_simul(:,it), errorflag, ~, ~, errorcode] = ...
[oo_.endo_simul(:,it), errorflag, ~, ~, errorcode] = ...
dynare_solve(@dynamic_backward_model_for_simulation, y, ...
DynareOptions.simul.maxit, DynareOptions.dynatol.f, DynareOptions.dynatol.x, ...
DynareOptions, dynamic_resid, dynamic_g1, y_, x, DynareModel.params, DynareOutput.steady_state, DynareModel.dynamic_g1_sparse_rowval, DynareModel.dynamic_g1_sparse_colval, DynareModel.dynamic_g1_sparse_colptr);
options_.simul.maxit, options_.dynatol.f, options_.dynatol.x, ...
options_, dynamic_resid, dynamic_g1, y_, x, M_.params, oo_.steady_state, M_.dynamic_g1_sparse_rowval, M_.dynamic_g1_sparse_colval, M_.dynamic_g1_sparse_colptr);
if errorflag
error('Nonlinear solver routine failed with errorcode=%i in period %i.', errorcode, it)
end
end
catch Error
errorflag = true;
DynareOutput.endo_simul = DynareOutput.endo_simul(:, 1:it-1);
oo_.endo_simul = oo_.endo_simul(:, 1:it-1);
dprintf('Newton failed on iteration i = %s.', num2str(it-initialconditions.nobs));
ytm = DynareOutput.endo_simul(:,end);
xtt = DynareOutput.exo_simul(it,:);
ytm = oo_.endo_simul(:,end);
xtt = oo_.exo_simul(it,:);
skipline()
dprintf('Values of the endogenous variables before the nonlinear solver failure')
dprintf('----------------------------------------------------------------------')
skipline()
dyntable(DynareOptions, '', {'VARIABLES','VALUES'}, DynareModel.endo_names(1:DynareModel.orig_endo_nbr), ytm(1:DynareModel.orig_endo_nbr), [], [], 6)
dyntable(options_, '', {'VARIABLES','VALUES'}, M_.endo_names(1:M_.orig_endo_nbr), ytm(1:M_.orig_endo_nbr), [], [], 6)
skipline()
dprintf('Values of the exogenous variables before the nonlinear solver failure')
dprintf('---------------------------------------------------------------------')
skipline()
dyntable(DynareOptions, '', {'VARIABLES','VALUES'}, DynareModel.exo_names, transpose(DynareOutput.exo_simul(it,:)), [], [], 6)
dyntable(options_, '', {'VARIABLES','VALUES'}, M_.exo_names, transpose(oo_.exo_simul(it,:)), [], [], 6)
skipline(2)
%
% Get equation tags if any
%
if isfield(DynareModel, 'equations_tags')
etags = cell(DynareModel.orig_endo_nbr, 1);
for i = 1:DynareModel.orig_endo_nbr
equations_tags = DynareModel.equations_tags(cellfun(@(x) isequal(x, i), DynareModel.equations_tags(:,1)), :);
if isfield(M_, 'equations_tags')
etags = cell(M_.orig_endo_nbr, 1);
for i = 1:M_.orig_endo_nbr
equations_tags = M_.equations_tags(cellfun(@(x) isequal(x, i), M_.equations_tags(:,1)), :);
name = equations_tags(strcmpi(equations_tags(:,2), 'name'),:);
if isempty(name)
eqtags{i} = int2str(i);
@ -136,31 +138,31 @@ for it = initialconditions.nobs+(1:samplesize)
end
end
else
etags = split(int2str(1:DynareModel.orig_endo_nbr), ' ');
etags = split(int2str(1:M_.orig_endo_nbr), ' ');
end
%
% Evaluate and check the residuals
%
[r, J] = dynamic_backward_model_for_simulation(ytm, dynamic_resid, dynamic_g1, ytm, x, DynareModel.params, DynareOutput.steady_state, DynareModel.dynamic_g1_sparse_rowval, DynareModel.dynamic_g1_sparse_colval, DynareModel.dynamic_g1_sparse_colptr);
[r, J] = dynamic_backward_model_for_simulation(ytm, dynamic_resid, dynamic_g1, ytm, x, M_.params, oo_.steady_state, M_.dynamic_g1_sparse_rowval, M_.dynamic_g1_sparse_colval, M_.dynamic_g1_sparse_colptr);
residuals_evaluating_to_nan = isnan(r);
residuals_evaluating_to_inf = isinf(r);
residuals_evaluating_to_complex = ~isreal(r);
if any(residuals_evaluating_to_nan)
dprintf('Following equations are evaluating to NaN:')
skipline()
display_names_of_problematic_equations(DynareModel, eqtags, residuals_evaluating_to_nan);
display_names_of_problematic_equations(M_, eqtags, residuals_evaluating_to_nan);
skipline()
end
if any(residuals_evaluating_to_inf)
dprintf('Following equations are evaluating to Inf:')
skipline()
display_names_of_problematic_equations(DynareModel, eqtags, residuals_evaluating_to_inf);
display_names_of_problematic_equations(M_, eqtags, residuals_evaluating_to_inf);
skipline()
end
if any(residuals_evaluating_to_complex)
dprintf('Following equations are evaluating to a complex number:')
skipline()
display_names_of_problematic_equations(DynareModel, eqtags, residuals_evaluating_to_complex);
display_names_of_problematic_equations(M_, eqtags, residuals_evaluating_to_complex);
skipline()
end
dprintf('Newton failed in period %s with the following error message:', char(initialconditions.lastdate+(it-initialconditions.nobs)));
@ -173,20 +175,20 @@ for it = initialconditions.nobs+(1:samplesize)
end
end
ysim = DynareOutput.endo_simul(1:DynareModel.orig_endo_nbr,:);
xsim = DynareOutput.exo_simul;
ysim = oo_.endo_simul(1:M_.orig_endo_nbr,:);
xsim = oo_.exo_simul;
end
function display_names_of_problematic_equations(DynareModel, eqtags, TruthTable)
for i=1:DynareModel.orig_endo_nbr
function display_names_of_problematic_equations(M_, eqtags, TruthTable)
for i=1:M_.orig_endo_nbr
if TruthTable(i)
dprintf(' - %s', eqtags{i})
end
end
for i=DynareModel.orig_endo_nbr+1:DynareModel.endo_nbr
for i=M_.orig_endo_nbr+1:M_.endo_nbr
if TruthTable(i)
dprintf(' - Auxiliary equation for %s', DynareModel.endo_names{i})
dprintf(' - Auxiliary equation for %s', M_.endo_names{i})
end
end
end

View File

@ -1,12 +1,12 @@
function [trend_addition, trend_coeff]=compute_trend_coefficients(M_,DynareOptions,nvarobs,ntobs)
% [trend_addition, trend_coeff]=compute_trend_coefficients(M_,DynareOptions,nvarobs,ntobs)
function [trend_addition, trend_coeff]=compute_trend_coefficients(M_,options_,nvarobs,ntobs)
% [trend_addition, trend_coeff]=compute_trend_coefficients(M_,options_,nvarobs,ntobs)
% Computes the trend coefficiencts and the trend, accounting for
% prefiltering
%
% INPUTS
% M_ [structure] describing the model; called in the eval
% statement
% DynareOptions [structure] describing the options
% options_ [structure] describing the options
% nvarobs [scalar] number of observed variables
% ntobs [scalar] length of data sample for estimation
%
@ -18,7 +18,7 @@ function [trend_addition, trend_coeff]=compute_trend_coefficients(M_,DynareOptio
% SPECIAL REQUIREMENTS
% none
% Copyright © 2014-2016 Dynare Team
% Copyright © 2014-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -37,13 +37,13 @@ function [trend_addition, trend_coeff]=compute_trend_coefficients(M_,DynareOptio
trend_coeff = zeros(nvarobs,1);
t = DynareOptions.trend_coeffs;
t = options_.trend_coeffs;
for i=1:length(t)
if ~isempty(t{i})
trend_coeff(i) = eval(t{i});
end
end
trend_addition=trend_coeff*[DynareOptions.first_obs:DynareOptions.first_obs+ntobs-1];
if DynareOptions.prefilter
trend_addition=trend_coeff*[options_.first_obs:options_.first_obs+ntobs-1];
if options_.prefilter
trend_addition = bsxfun(@minus,trend_addition,mean(trend_addition,2));
end

View File

@ -1,5 +1,5 @@
function results_struct = geweke_chi2_test(results1,results2,results_struct,options)
% results_struct = geweke_chi2_test(results1,results2,results_struct,options)
function results_struct = geweke_chi2_test(results1,results2,results_struct,options_)
% results_struct = geweke_chi2_test(results1,results2,results_struct,options_)
% PURPOSE: computes Geweke's chi-squared test for two sets of MCMC sample draws
%
% INPUTS
@ -10,7 +10,7 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti
% std, NSE_iid, RNE_iid, and tapered NSE and RNE
% for chain part 2
% results_struct [structure] results structure generated by geweke_moments
% Dynareoptions [structure]
% options_ [structure]
%
% OUTPUTS
% results_struct [structure] containing the following fields:
@ -57,7 +57,7 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti
% based on code by James P. LeSage, who in turn
% drew on MATLAB programs written by Siddartha Chib
for k=1:length(options.convergence.geweke.taper_steps)+1
for k=1:length(options_.convergence.geweke.taper_steps)+1
NSE=[results1(:,3+(k-1)*2) results2(:,3+(k-1)*2)];
means=[results1(:,1) results2(:,1)];
diff_Means=means(:,1)-means(:,2);

View File

@ -1,11 +1,11 @@
function [results_vec, results_struct] = geweke_moments(draws,Dynareoptions)
%[results_vec, results_struct] = geweke_moments(draws,Dynareoptions)
function [results_vec, results_struct] = geweke_moments(draws,options_)
%[results_vec, results_struct] = geweke_moments(draws,options_)
% PURPOSE: computes Gewke's convergence diagnostics NSE and RNE
% (numerical std error and relative numerical efficiencies)
% INPUTS
% draws [ndraws by 1 vector]
% Dynareoptions [structure]
% options_ [structure]
%
% OUTPUTS
% results_vec
@ -22,7 +22,7 @@ function [results_vec, results_struct] = geweke_moments(draws,Dynareoptions)
% SPECIAL REQUIREMENTS
% None.
% Copyright © 2013-2017 Dynare Team
% Copyright © 2013-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -56,7 +56,7 @@ function [results_vec, results_struct] = geweke_moments(draws,Dynareoptions)
ndraw = size(draws,1);
n_groups=100;
taper_steps=Dynareoptions.convergence.geweke.taper_steps;
taper_steps=options_.convergence.geweke.taper_steps;
results_vec=zeros(1,4+2*length(taper_steps));
ns = floor(ndraw/n_groups); %step_size

View File

@ -1,12 +1,12 @@
function [dr, info] = dyn_first_order_solver(jacobia, DynareModel, dr, DynareOptions, task)
function [dr, info] = dyn_first_order_solver(jacobia, M_, dr, options_, task)
% [dr, info] = dyn_first_order_solver(jacobia, M_, dr, options_, task)
% Computes the first order reduced form of a DSGE model.
%
% INPUTS
% - jacobia [double] matrix, the jacobian of the dynamic model.
% - DynareModel [struct] Matlab's structre describing the model, M_ global.
% - M_ [struct] Matlab's structre describing the model
% - dr [struct] Matlab's structure describing the reduced form model.
% - DynareOptions [struct] Matlab's structure containing the current state of the options, oo_ global.
% - options_ [struct] Matlab's structure containing the current state of the options
% - task [integer] scalar, if task = 0 then decision rules are computed and if task = 1 then only eigenvales are computed.
%
% OUTPUTS
@ -21,7 +21,7 @@ function [dr, info] = dyn_first_order_solver(jacobia, DynareModel, dr, DynareOpt
% info=5 -> Blanchard and Kahn conditions are not satisfied: indeterminacy due to rank failure,
% info=7 -> One of the eigenvalues is close to 0/0 (infinity of complex solutions)
% Copyright © 2001-2020 Dynare Team
% Copyright © 2001-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -53,24 +53,24 @@ if ~nargin
return
end
exo_nbr = DynareModel.exo_nbr;
exo_nbr = M_.exo_nbr;
if isempty(reorder_jacobian_columns)
maximum_lag = DynareModel.maximum_endo_lag;
nfwrd = DynareModel.nfwrd;
nboth = DynareModel.nboth;
npred = DynareModel.npred;
nstatic = DynareModel.nstatic;
ndynamic = DynareModel.ndynamic;
nsfwrd = DynareModel.nsfwrd;
maximum_lag = M_.maximum_endo_lag;
nfwrd = M_.nfwrd;
nboth = M_.nboth;
npred = M_.npred;
nstatic = M_.nstatic;
ndynamic = M_.ndynamic;
nsfwrd = M_.nsfwrd;
k1 = 1:(npred+nboth);
k2 = 1:(nfwrd+nboth);
order_var = dr.order_var;
nd = npred+nfwrd+2*nboth;
lead_lag_incidence = DynareModel.lead_lag_incidence;
lead_lag_incidence = M_.lead_lag_incidence;
nz = nnz(lead_lag_incidence);
lead_id = find(lead_lag_incidence(maximum_lag+2,:));
@ -141,12 +141,12 @@ B(:,cols_b) = aa(:,index_c); % Jacobian matrix for contemporaneous endogeneous
C = aa(:,index_p); % Jacobain matrix for led endogeneous variables
info = 0;
if task ~= 1 && (DynareOptions.dr_cycle_reduction || DynareOptions.dr_logarithmic_reduction)
if n_current < DynareModel.endo_nbr
if DynareOptions.dr_cycle_reduction
if task ~= 1 && (options_.dr_cycle_reduction || options_.dr_logarithmic_reduction)
if n_current < M_.endo_nbr
if options_.dr_cycle_reduction
error(['The cycle reduction algorithme can''t be used when the ' ...
'coefficient matrix for current variables isn''t invertible'])
elseif DynareOptions.dr_logarithmic_reduction
elseif options_.dr_logarithmic_reduction
error(['The logarithmic reduction algorithme can''t be used when the ' ...
'coefficient matrix for current variables isn''t invertible'])
end
@ -154,10 +154,10 @@ if task ~= 1 && (DynareOptions.dr_cycle_reduction || DynareOptions.dr_logarithmi
A1 = [aa(row_indx,index_m ) zeros(ndynamic,nfwrd)];
B1 = [aa(row_indx,index_0m) aa(row_indx,index_0p) ];
C1 = [zeros(ndynamic,npred) aa(row_indx,index_p)];
if DynareOptions.dr_cycle_reduction
[ghx, info] = cycle_reduction(A1, B1, C1, DynareOptions.dr_cycle_reduction_tol);
if options_.dr_cycle_reduction
[ghx, info] = cycle_reduction(A1, B1, C1, options_.dr_cycle_reduction_tol);
else
[ghx, info] = logarithmic_reduction(C1, B1, A1, DynareOptions.dr_logarithmic_reduction_tol, DynareOptions.dr_logarithmic_reduction_maxiter);
[ghx, info] = logarithmic_reduction(C1, B1, A1, options_.dr_logarithmic_reduction_tol, options_.dr_logarithmic_reduction_maxiter);
end
if info
% cycle_reduction or logarithmic redution failed and set info
@ -174,7 +174,7 @@ else
E(row_indx_de_1,index_e1) = -aa(row_indx,index_e);
E(row_indx_de_2,index_e2) = eye(nboth);
[ss, tt, w, sdim, dr.eigval, info1] = mjdgges(E, D, DynareOptions.qz_criterium, DynareOptions.qz_zero_threshold);
[ss, tt, w, sdim, dr.eigval, info1] = mjdgges(E, D, options_.qz_criterium, options_.qz_zero_threshold);
if info1
if info1 == -30
@ -204,10 +204,10 @@ else
if nba ~= nsfwrd
temp = sort(abs(dr.eigval));
if nba > nsfwrd
temp = temp(nd-nba+1:nd-nsfwrd)-1-DynareOptions.qz_criterium;
temp = temp(nd-nba+1:nd-nsfwrd)-1-options_.qz_criterium;
info(1) = 3;
elseif nba < nsfwrd
temp = temp(nd-nsfwrd+1:nd-nba)-1-DynareOptions.qz_criterium;
temp = temp(nd-nsfwrd+1:nd-nba)-1-options_.qz_criterium;
info(1) = 4;
end
info(2) = temp'*temp;
@ -262,7 +262,7 @@ if nstatic > 0
b11 = b(1:nstatic, nstatic+1:end);
temp(:,index_m) = temp(:,index_m)-A(1:nstatic,:);
temp = b10\(temp-b11*ghx);
if DynareOptions.debug
if options_.debug
if any(any(~isfinite(temp)))
fprintf('\ndyn_first_order_solver: infinite/NaN elements encountered when solving for the static variables\n')
fprintf('dyn_first_order_solver: This often arises if there is a singularity.\n\n')
@ -288,7 +288,7 @@ end
dr.ghx = ghx;
dr.ghu = ghu;
if DynareOptions.aim_solver ~= 1
if options_.aim_solver ~= 1
% Necessary when using Sims' routines for QZ
dr.ghx = real(ghx);
dr.ghu = real(ghu);

View File

@ -1,11 +1,11 @@
function [info, info_irf, info_moment, data_irf, data_moment] = endogenous_prior_restrictions(T,R,Model,DynareOptions,dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
%[info, info_irf, info_moment, data_irf, data_moment] = endogenous_prior_restrictions(T,R,Model,DynareOptions,dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
function [info, info_irf, info_moment, data_irf, data_moment] = endogenous_prior_restrictions(T,R,M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
%[info, info_irf, info_moment, data_irf, data_moment] = endogenous_prior_restrictions(T,R,M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
% Check for prior (sign) restrictions on irf's and theoretical moments
% INPUTS
% T [double] n*n state space matrix
% R [double] n*k matrix of shocks
% Model [structure]
% DynareOptions [structure]
% M_ [structure]
% options_ [structure]
% dr [structure] Reduced form model.
% endo_steady_state [vector] steady state value for endogenous variables
% exo_steady_state [vector] steady state value for exogenous variables
@ -41,17 +41,17 @@ info_moment=[];
data_irf=[];
data_moment=[];
endo_prior_restrictions.irf= DynareOptions.endogenous_prior_restrictions.irf;
endo_prior_restrictions.moment= DynareOptions.endogenous_prior_restrictions.moment;
endo_prior_restrictions.irf= options_.endogenous_prior_restrictions.irf;
endo_prior_restrictions.moment= options_.endogenous_prior_restrictions.moment;
if ~isempty(endo_prior_restrictions.irf)
data_irf=cell(size(endo_prior_restrictions.irf,1),1);
if DynareOptions.order>1
if options_.order>1
error('The algorithm for prior (sign) restrictions on irf''s is currently restricted to first-order decision rules')
end
varlist = Model.endo_names(dr.order_var);
varlist = M_.endo_names(dr.order_var);
if isempty(T)
[T,R,SteadyState,infox,dr, Model.params] = dynare_resolve(Model,DynareOptions,dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
[T,R,SteadyState,infox,dr, M_.params] = dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
else % check if T and R are given in the restricted form!!!
if size(T,1)<length(varlist)
varlist = varlist(dr.restrict_var_list);
@ -64,8 +64,8 @@ if ~isempty(endo_prior_restrictions.irf)
end
end
if ~varlistok
varlist = Model.endo_names(dr.order_var);
[T,R,SteadyState,infox,dr, Model.params] = dynare_resolve(Model,DynareOptions,dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
varlist = M_.endo_names(dr.order_var);
[T,R,SteadyState,infox,dr, M_.params] = dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
end
end
NT=1;
@ -74,8 +74,8 @@ if ~isempty(endo_prior_restrictions.irf)
end
info_irf=ones(size(endo_prior_restrictions.irf,1),2);
for t=1:NT
if ~DynareOptions.relative_irf
RR = T^(t-1)*R*diag(sqrt(diag(Model.Sigma_e)));
if ~options_.relative_irf
RR = T^(t-1)*R*diag(sqrt(diag(M_.Sigma_e)));
else
RR = T^(t-1)*R*100;
end
@ -84,7 +84,7 @@ if ~isempty(endo_prior_restrictions.irf)
continue
end
iendo=strmatch(endo_prior_restrictions.irf{j,1}, varlist, 'exact');
iexo=strmatch(endo_prior_restrictions.irf{j,2}, Model.exo_names, 'exact');
iexo=strmatch(endo_prior_restrictions.irf{j,2}, M_.exo_names, 'exact');
data_irf{j}=[data_irf{j}; [t RR(iendo,iexo)]];
if (RR(iendo,iexo)>endo_prior_restrictions.irf{j,4}(1)) && (RR(iendo,iexo)<endo_prior_restrictions.irf{j,4}(2))
info_irf(j,:)=info_irf(j,:).*[0, 0];
@ -105,7 +105,7 @@ if ~isempty(endo_prior_restrictions.irf)
end
if ~isempty(endo_prior_restrictions.moment)
if DynareOptions.order>1
if options_.order>1
error('The algorithm for prior (sign) restrictions on moments is currently restricted to first-order decision rules')
end
data_moment=cell(size(endo_prior_restrictions.moment,1),1);
@ -130,15 +130,15 @@ if ~isempty(endo_prior_restrictions.moment)
nvar = size(var_list_,1);
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list_(i,:), Model.endo_names, 'exact');
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
DynareOptions.ar = max(abs(NTmin),NTmax);
[gamma_y,stationary_vars] = th_autocovariances(dr, ivar, Model, DynareOptions,1);
options_.ar = max(abs(NTmin),NTmax);
[gamma_y,stationary_vars] = th_autocovariances(dr, ivar, M_, options_,1);
for t=NTmin:NTmax
RR = gamma_y{abs(t)+1};
if t==0

View File

@ -5,22 +5,22 @@ function [llik,parameters] = evaluate_likelihood(parameters,M_,estim_params_,oo_
% INPUTS
% o parameters a string ('posterior mode','posterior mean','posterior median','prior mode','prior mean') or a vector of values for
% the (estimated) parameters of the model.
% o M_ [structure] Definition of the model
% o estim_params_ [structure] characterizing parameters to be estimated
% o oo_ [structure] Storage of results
% o options_ [structure] Options
% o bayestopt_ [structure] describing the priors
% o M_ [structure] Definition of the model
% o estim_params_ [structure] characterizing parameters to be estimated
% o oo_ [structure] Storage of results
% o options_ [structure] Options
% o bayestopt_ [structure] describing the priors
%
% OUTPUTS
% o ldens [double] value of the sample logged density at parameters.
% o parameters [double] vector of values for the estimated parameters.
% o ldens [double] value of the sample logged density at parameters.
% o parameters [double] vector of values for the estimated parameters.
%
% SPECIAL REQUIREMENTS
% None
%
% REMARKS
% [1] This function cannot evaluate the likelihood of a dsge-var model...
% [2] This function use persistent variables for the dataset and the description of the missing observations. Consequently, if this function
% [2] This function use persistent variables for the dataset_ and the description of the missing observations. Consequently, if this function
% is called more than once (by changing the value of parameters) the sample *must not* change.
% Copyright © 2009-2023 Dynare Team
@ -40,7 +40,7 @@ function [llik,parameters] = evaluate_likelihood(parameters,M_,estim_params_,oo_
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
persistent dataset dataset_info
persistent dataset_ dataset_info
if nargin==0
parameters = 'posterior mode';
@ -69,8 +69,8 @@ if ischar(parameters)
end
end
if isempty(dataset)
[dataset, dataset_info] = makedataset(options_);
if isempty(dataset_)
[dataset_, dataset_info] = makedataset(options_);
end
options_=select_qz_criterium_value(options_);
@ -88,9 +88,9 @@ end
if options_.occbin.likelihood.status && options_.occbin.likelihood.inversion_filter
llik = -occbin.IVF_posterior(parameters,dataset,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_.dr, oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
llik = -occbin.IVF_posterior(parameters,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_.dr, oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
else
llik = -dsge_likelihood(parameters,dataset,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_.dr, oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
llik = -dsge_likelihood(parameters,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_.dr, oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
end
ldens = evaluate_prior(parameters,M_,estim_params_,oo_,options_,bayestopt_);
llik = llik - ldens;

View File

@ -1,16 +1,16 @@
function message = get_error_message(info, DynareOptions)
function message = get_error_message(info, options_)
% Returns error messages
%
% INPUTS
% info [double] vector returned by resol.m
% DynareOptions [structure] --> options_
% options_ [structure] Dynare options
% OUTPUTS
% message [string] corresponding error message
%
% SPECIAL REQUIREMENTS
% none
% Copyright © 2005-2020 Dynare Team
% Copyright © 2005-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -43,7 +43,7 @@ switch info(1)
case 6
message = 'The Jacobian matrix evaluated at the steady state contains elements that are not real or are infinite.';
case 7
message = sprintf('One of the eigenvalues is close to 0/0 (the absolute value of numerator and denominator is smaller than %5.4f!\n If you believe that the model has a unique solution you can try to reduce the value of qz_zero_threshold.',DynareOptions.qz_zero_threshold);
message = sprintf('One of the eigenvalues is close to 0/0 (the absolute value of numerator and denominator is smaller than %5.4f!\n If you believe that the model has a unique solution you can try to reduce the value of qz_zero_threshold.',options_.qz_zero_threshold);
case 8
if size(info,2)>=2 && info(2)~=0
global M_;
@ -66,7 +66,7 @@ switch info(1)
case 19
message = 'The steadystate file did not compute the steady state';
case 20
if DynareOptions.linear
if options_.linear
message = sprintf('Impossible to find the steady state (the sum of squared residuals of the static equations is %5.4f). Either the model doesn''t have a steady state or there are an infinity of steady states. Check whether your model is truly linear or whether there is a mistake in linearization.', info(2));
else
message = sprintf('Impossible to find the steady state (the sum of squared residuals of the static equations is %5.4f). Either the model doesn''t have a steady state, there are an infinity of steady states, or the guess values are too far from the solution', info(2));

View File

@ -1,5 +1,5 @@
function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions)
%function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions)
function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,M_,options_)
% []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,M_,options_)
% Plots the results from the shock_decomposition command
%
% Inputs
@ -8,10 +8,10 @@ function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,DynareModel
% endo_names [exo_nbr*string length] variable names from M_.endo_names
% i_var [n_var*1] vector indices of requested variables in M_.endo_names and z
% initial_date [dseries object] first period of decomposition to plot
% DynareModel [structure] Dynare model structure
% DynareOptions [structure] Dynare options structure
% M_ [structure] Dynare model structure
% options_ [structure] Dynare options structure
% Copyright © 2010-2018 Dynare Team
% Copyright © 2010-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -28,10 +28,10 @@ function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,DynareModel
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if ~DynareOptions.plot_shock_decomp.expand
GraphDirectoryName = CheckPath('graphs',DynareModel.dname);
if ~options_.plot_shock_decomp.expand
GraphDirectoryName = CheckPath('graphs',M_.dname);
end
new_colormap = DynareOptions.plot_shock_decomp.colormap;
new_colormap = options_.plot_shock_decomp.colormap;
% number of components equals number of shocks + 1 (initial conditions)
comp_nbr = size(z,2)-1;
@ -41,7 +41,7 @@ fig_mode='';
fig_mode1='';
% fig_name='';
% screen_shocks=0;
opts_decomp = DynareOptions.plot_shock_decomp;
opts_decomp = options_.plot_shock_decomp;
if isfield(opts_decomp,'steady_state')
SteadyState = opts_decomp.steady_state;
end
@ -59,13 +59,13 @@ end
fig_name_long = opts_decomp.fig_name;
use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups;
use_shock_groups = options_.plot_shock_decomp.use_shock_groups;
screen_shocks = opts_decomp.screen_shocks;
if ~isempty(use_shock_groups) || comp_nbr<=18
screen_shocks=0;
end
if use_shock_groups
shock_groups = DynareModel.shock_groups.(use_shock_groups);
shock_groups = M_.shock_groups.(use_shock_groups);
shock_ind = fieldnames(shock_groups);
end
if screen_shocks
@ -96,8 +96,8 @@ end
nvar = length(i_var);
%% write LaTeX-Header
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format))) && ~DynareOptions.plot_shock_decomp.expand
fidTeX = fopen([GraphDirectoryName, filesep, DynareModel.fname '_shock_decomp' fig_mode1 fig_name '.tex'],'w');
if options_.TeX && any(strcmp('eps',cellstr(options_.plot_shock_decomp.graph_format))) && ~options_.plot_shock_decomp.expand
fidTeX = fopen([GraphDirectoryName, filesep, M_.fname '_shock_decomp' fig_mode1 fig_name '.tex'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by Dynare''s graph_decomp.m.\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
@ -143,12 +143,12 @@ for j=1:nvar
if ymax-ymin < 1e-6
continue
end
fhandle = dyn_figure(DynareOptions.plot_shock_decomp.nodisplay,'Name',[preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': ' endo_names{i_var(j)} '.'], 'PaperPositionMode', 'auto','PaperOrientation','landscape','renderermode','auto');
fhandle = dyn_figure(options_.plot_shock_decomp.nodisplay,'Name',[preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': ' endo_names{i_var(j)} '.'], 'PaperPositionMode', 'auto','PaperOrientation','landscape','renderermode','auto');
set(fhandle,'position' ,[50 50 1500 750])
ax=axes('Position',[0.1 0.1 0.6 0.8],'box','on');
% plot(ax,x(2:end),z1(end,:),'k-','LineWidth',2)
% axis(ax,[xmin xmax ymin ymax]);
if strcmp('aoa',DynareOptions.plot_shock_decomp.type)
if strcmp('aoa',options_.plot_shock_decomp.type)
bgap = 0.15;
else
bgap = 0;
@ -210,17 +210,17 @@ for j=1:nvar
ht = text(0.3,y1+0.3*height,labels(i,:),'Interpreter','none');
hold on
if interactive && (~isoctave && ~isempty(use_shock_groups))
mydata.fig_name = DynareOptions.plot_shock_decomp.fig_name(2:end);
mydata.use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups;
mydata.fig_name = options_.plot_shock_decomp.fig_name(2:end);
mydata.use_shock_groups = options_.plot_shock_decomp.use_shock_groups;
mydata.shock_group = shock_groups.(shock_ind{i});
mydata.shock_decomp = DynareOptions.shock_decomp;
mydata.plot_shock_decomp = DynareOptions.plot_shock_decomp;
mydata.first_obs = DynareOptions.first_obs;
mydata.nobs = DynareOptions.nobs;
mydata.plot_shock_decomp.zfull = DynareOptions.plot_shock_decomp.zfull(i_var(j),:,:);
mydata.shock_decomp = options_.shock_decomp;
mydata.plot_shock_decomp = options_.plot_shock_decomp;
mydata.first_obs = options_.first_obs;
mydata.nobs = options_.nobs;
mydata.plot_shock_decomp.zfull = options_.plot_shock_decomp.zfull(i_var(j),:,:);
mydata.endo_names = endo_names(i_var(j));
mydata.endo_names_tex = DynareModel.endo_names_tex(i_var(j));
mydata.exo_names = DynareModel.exo_names;
mydata.endo_names_tex = M_.endo_names_tex(i_var(j));
mydata.exo_names = M_.exo_names;
if ~isempty(mydata.shock_group.shocks)
c = uicontextmenu;
hl.UIContextMenu=c;
@ -242,28 +242,28 @@ for j=1:nvar
colormap(new_colormap)
end
hold off
if ~DynareOptions.plot_shock_decomp.expand
if ~options_.plot_shock_decomp.expand
dyn_saveas(fhandle,[GraphDirectoryName, filesep, DynareModel.fname,preamble_figname,endo_names{i_var(j)},fig_mode1,fig_name],DynareOptions.plot_shock_decomp.nodisplay,DynareOptions.plot_shock_decomp.graph_format);
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format)))
dyn_saveas(fhandle,[GraphDirectoryName, filesep, M_.fname,preamble_figname,endo_names{i_var(j)},fig_mode1,fig_name],options_.plot_shock_decomp.nodisplay,options_.plot_shock_decomp.graph_format);
if options_.TeX && any(strcmp('eps',cellstr(options_.plot_shock_decomp.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s/graphs/%s%s}\n',DynareModel.fname,DynareModel.fname,[preamble_figname endo_names{i_var(j)} fig_mode1 fig_name]);
fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s/graphs/%s%s}\n',M_.fname,M_.fname,[preamble_figname endo_names{i_var(j)} fig_mode1 fig_name]);
fprintf(fidTeX,'\\label{Fig:shock_decomp:%s}\n',[fig_mode endo_names{i_var(j)} fig_name]);
fprintf(fidTeX,['\\caption{' preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': $ %s $.}\n'],DynareModel.endo_names_tex{i_var(j)});
fprintf(fidTeX,['\\caption{' preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': $ %s $.}\n'],M_.endo_names_tex{i_var(j)});
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
end
else
if ~isempty(DynareOptions.plot_shock_decomp.filepath)
dyn_saveas(fhandle,[DynareOptions.plot_shock_decomp.filepath, filesep, DynareModel.fname,preamble_figname,endo_names{i_var(j)},fig_mode1,fig_name],DynareOptions.plot_shock_decomp.nodisplay,DynareOptions.plot_shock_decomp.graph_format);
if ~isempty(options_.plot_shock_decomp.filepath)
dyn_saveas(fhandle,[options_.plot_shock_decomp.filepath, filesep, M_.fname,preamble_figname,endo_names{i_var(j)},fig_mode1,fig_name],options_.plot_shock_decomp.nodisplay,options_.plot_shock_decomp.graph_format);
end
end
end
%% write LaTeX-Footer
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format))) && ~DynareOptions.plot_shock_decomp.expand
if options_.TeX && any(strcmp('eps',cellstr(options_.plot_shock_decomp.graph_format))) && ~options_.plot_shock_decomp.expand
fprintf(fidTeX,' \n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);

View File

@ -1,5 +1,5 @@
function []=graph_decomp_detail(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions)
%function []=graph_decomp_detail(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions)
function []=graph_decomp_detail(z,shock_names,endo_names,i_var,initial_date,M_,options_)
% []=graph_decomp_detail(z,shock_names,endo_names,i_var,initial_date,M_,options_)
% Plots the results from the shock_decomposition command
%
% Inputs
@ -8,10 +8,10 @@ function []=graph_decomp_detail(z,shock_names,endo_names,i_var,initial_date,Dyna
% endo_names [exo_nbr*string length] variable names from M_.endo_names
% i_var [n_var*1] vector indices of requested variables in M_.endo_names and z
% initial_date [dseries object] first period of decomposition to plot
% DynareModel [structure] Dynare model structure
% DynareOptions [structure] Dynare options structure
% M_ [structure] Dynare model structure
% options_ [structure] Dynare options structure
% Copyright © 2010-2018 Dynare Team
% Copyright © 2010-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -28,25 +28,25 @@ function []=graph_decomp_detail(z,shock_names,endo_names,i_var,initial_date,Dyna
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if ~DynareOptions.plot_shock_decomp.expand
GraphDirectoryName = CheckPath('graphs',DynareModel.dname);
if ~options_.plot_shock_decomp.expand
GraphDirectoryName = CheckPath('graphs',M_.dname);
end
% interactive = 0;
fig_mode='';
fig_mode1='';
% fig_name='';
% screen_shocks=0;
initval = DynareOptions.plot_shock_decomp.initval;
use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups;
initval = options_.plot_shock_decomp.initval;
use_shock_groups = options_.plot_shock_decomp.use_shock_groups;
if use_shock_groups
shock_groups = DynareModel.shock_groups.(use_shock_groups);
shock_groups = M_.shock_groups.(use_shock_groups);
shock_ind = fieldnames(shock_groups);
end
% number of components equals number of shocks + 1 (initial conditions)
comp_nbr = size(z,2)-1;
opts_decomp = DynareOptions.plot_shock_decomp;
opts_decomp = options_.plot_shock_decomp;
interactive = opts_decomp.interactive;
if ~isempty(opts_decomp.type)
@ -62,7 +62,7 @@ else
end
max_nrows = opts_decomp.max_nrows;
screen_shocks = opts_decomp.screen_shocks;
if ~isempty(DynareOptions.plot_shock_decomp.use_shock_groups) || comp_nbr<=18
if ~isempty(options_.plot_shock_decomp.use_shock_groups) || comp_nbr<=18
screen_shocks=0;
end
fig_name_long = opts_decomp.fig_name;
@ -118,8 +118,8 @@ end
nvar = length(i_var);
%% write LaTeX-Header
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format))) && ~DynareOptions.plot_shock_decomp.expand
fidTeX = fopen([GraphDirectoryName, filesep, DynareModel.fname '_shock_decomp' fig_mode1 fig_name '_detail.tex'],'w');
if options_.TeX && any(strcmp('eps',cellstr(options_.plot_shock_decomp.graph_format))) && ~options_.plot_shock_decomp.expand
fidTeX = fopen([GraphDirectoryName, filesep, M_.fname '_shock_decomp' fig_mode1 fig_name '_detail.tex'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by Dynare''s graph_decomp_detail.m.\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
@ -178,7 +178,7 @@ for j=1:nvar
continue
end
for jf = 1:nfigs
fhandle = dyn_figure(DynareOptions.plot_shock_decomp.nodisplay,'Name',[preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': ' endo_names{i_var(j)} ' (detail).'],'position',[200 100 650 850], 'PaperPositionMode', 'auto','PaperOrientation','portrait','renderermode','auto');
fhandle = dyn_figure(options_.plot_shock_decomp.nodisplay,'Name',[preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': ' endo_names{i_var(j)} ' (detail).'],'position',[200 100 650 850], 'PaperPositionMode', 'auto','PaperOrientation','portrait','renderermode','auto');
a0=zeros(1,4);
a0(3)=inf;
a0(4)=-inf;
@ -216,17 +216,17 @@ for j=1:nvar
set(gca,'ylim',a0(3:4))
hold on, h1=plot(x(2:end),z1(end,:),'k-','LineWidth',2);
if interactive && (~isoctave && ~isempty(use_shock_groups))
mydata.fig_name = DynareOptions.plot_shock_decomp.fig_name(2:end);
mydata.use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups;
mydata.fig_name = options_.plot_shock_decomp.fig_name(2:end);
mydata.use_shock_groups = options_.plot_shock_decomp.use_shock_groups;
mydata.shock_group = shock_groups.(shock_ind{ic});
mydata.shock_decomp = DynareOptions.shock_decomp;
mydata.plot_shock_decomp = DynareOptions.plot_shock_decomp;
mydata.first_obs = DynareOptions.first_obs;
mydata.nobs = DynareOptions.nobs;
mydata.plot_shock_decomp.zfull = DynareOptions.plot_shock_decomp.zfull(i_var(j),:,:);
mydata.shock_decomp = options_.shock_decomp;
mydata.plot_shock_decomp = options_.plot_shock_decomp;
mydata.first_obs = options_.first_obs;
mydata.nobs = options_.nobs;
mydata.plot_shock_decomp.zfull = options_.plot_shock_decomp.zfull(i_var(j),:,:);
mydata.endo_names = endo_names(i_var(j));
mydata.endo_names_tex = DynareModel.endo_names_tex(i_var(j));
mydata.exo_names = DynareModel.exo_names;
mydata.endo_names_tex = M_.endo_names_tex(i_var(j));
mydata.exo_names = M_.exo_names;
if ~isempty(mydata.shock_group.shocks)
c = uicontextmenu;
hax.UIContextMenu=c;
@ -271,28 +271,28 @@ for j=1:nvar
else
suffix = ['_detail'];
end
if ~DynareOptions.plot_shock_decomp.expand
dyn_saveas(fhandle,[GraphDirectoryName, filesep, DynareModel.fname, ...
preamble_figname, endo_names{i_var(j)}, fig_mode1,fig_name suffix],DynareOptions.plot_shock_decomp.nodisplay,DynareOptions.plot_shock_decomp.graph_format);
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format)))
if ~options_.plot_shock_decomp.expand
dyn_saveas(fhandle,[GraphDirectoryName, filesep, M_.fname, ...
preamble_figname, endo_names{i_var(j)}, fig_mode1,fig_name suffix],options_.plot_shock_decomp.nodisplay,options_.plot_shock_decomp.graph_format);
if options_.TeX && any(strcmp('eps',cellstr(options_.plot_shock_decomp.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s/graphs/%s%s}\n',DynareModel.fname,DynareModel.fname,[preamble_figname endo_names{i_var(j)} fig_mode1 fig_name suffix]);
fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s/graphs/%s%s}\n',M_.fname,M_.fname,[preamble_figname endo_names{i_var(j)} fig_mode1 fig_name suffix]);
fprintf(fidTeX,'\\label{Fig:shock_decomp_detail:%s}\n',[fig_mode endo_names{i_var(j)} fig_name suffix]);
fprintf(fidTeX,['\\caption{' preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': $ %s $ (detail).}\n'], DynareModel.endo_names_tex{i_var(j)});
fprintf(fidTeX,['\\caption{' preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': $ %s $ (detail).}\n'], M_.endo_names_tex{i_var(j)});
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
end
else
if ~isempty(DynareOptions.plot_shock_decomp.filepath)
dyn_saveas(fhandle,[DynareOptions.plot_shock_decomp.filepath, filesep, DynareModel.fname,preamble_figname,endo_names{i_var(j)},fig_mode1,fig_name suffix],DynareOptions.plot_shock_decomp.nodisplay,DynareOptions.plot_shock_decomp.graph_format);
if ~isempty(options_.plot_shock_decomp.filepath)
dyn_saveas(fhandle,[options_.plot_shock_decomp.filepath, filesep, M_.fname,preamble_figname,endo_names{i_var(j)},fig_mode1,fig_name suffix],options_.plot_shock_decomp.nodisplay,options_.plot_shock_decomp.graph_format);
end
end
end
end
%% write LaTeX-Footer
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format))) && ~DynareOptions.plot_shock_decomp.expand
if options_.TeX && any(strcmp('eps',cellstr(options_.plot_shock_decomp.graph_format))) && ~options_.plot_shock_decomp.expand
fprintf(fidTeX,' \n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);

View File

@ -7,7 +7,7 @@ function oo_ = initial_estimation_checks(objective_function,xparam1,dataset_,dat
% xparam1 [vector] of parameters to be estimated
% dataset_ [dseries] object storing the dataset
% dataset_info [structure] storing informations about the sample.
% M_ [structure] decribing the model
% M_ [structure] describing the model
% estim_params_ [structure] characterizing parameters to be estimated
% options_ [structure] describing the options
% bayestopt_ [structure] describing the priors

View File

@ -1,5 +1,5 @@
function P=lyapunov_solver(T,R,Q,DynareOptions)
% function P=lyapunov_solver(T,R,Q,DynareOptions)
function P=lyapunov_solver(T,R,Q,options_)
% function P=lyapunov_solver(T,R,Q,options_)
% Solves the Lyapunov equation P-T*P*T' = R*Q*R' arising in a state-space
% system, where P is the variance of the states
%
@ -7,7 +7,7 @@ function P=lyapunov_solver(T,R,Q,DynareOptions)
% T [double] n*n matrix.
% R [double] n*m matrix.
% Q [double] m*m matrix.
% DynareOptions [structure] Dynare options
% options_ [structure] Dynare options
%
% Outputs
% P [double] n*n matrix.
@ -15,11 +15,11 @@ function P=lyapunov_solver(T,R,Q,DynareOptions)
% Algorithms
% Default, if none of the other algorithms is selected:
% Reordered Schur decomposition (Bartels-Stewart algorithm)
% DynareOptions.lyapunov_fp == true
% options_.lyapunov_fp == true
% iteration-based fixed point algorithm
% DynareOptions.lyapunov_db == true
% options_.lyapunov_db == true
% doubling algorithm
% DynareOptions.lyapunov_srs == true
% options_.lyapunov_srs == true
% Square-root solver for discrete-time Lyapunov equations (requires Matlab System Control toolbox
% or Octave control package)
@ -40,14 +40,14 @@ function P=lyapunov_solver(T,R,Q,DynareOptions)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if DynareOptions.lyapunov_fp
P = lyapunov_symm(T,R*Q*R',DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold, 3, DynareOptions.debug);
elseif DynareOptions.lyapunov_db
[P, errorflag] = disclyap_fast(T,R*Q*R',DynareOptions.lyapunov_doubling_tol);
if options_.lyapunov_fp
P = lyapunov_symm(T,R*Q*R',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold, 3, options_.debug);
elseif options_.lyapunov_db
[P, errorflag] = disclyap_fast(T,R*Q*R',options_.lyapunov_doubling_tol);
if errorflag %use Schur-based method
P = lyapunov_symm(T,R*Q*R',DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold, [], DynareOptions.debug);
P = lyapunov_symm(T,R*Q*R',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold, [], options_.debug);
end
elseif DynareOptions.lyapunov_srs
elseif options_.lyapunov_srs
% works only with Matlab System Control toolbox or Octave control package,
if isoctave
if ~user_has_octave_forge_package('control')
@ -62,7 +62,7 @@ elseif DynareOptions.lyapunov_srs
R_P = dlyapchol(T,chol_Q);
P = R_P' * R_P;
else
P = lyapunov_symm(T,R*Q*R',DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold, [], DynareOptions.debug);
P = lyapunov_symm(T,R*Q*R',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold, [], options_.debug);
end
return % --*-- Unit tests --*--
@ -92,7 +92,7 @@ tmp2=randn(m_large,m_large);
Q_large=tmp2*tmp2';
R_large=randn(n_large,m_large);
% DynareOptions.lyapunov_fp == 1
% options_.lyapunov_fp == 1
options_.lyapunov_fp = true;
try
Pstar1_small = lyapunov_solver(T_small,R_small,Q_small,options_);
@ -102,7 +102,7 @@ catch
t(1) = 0;
end
% Dynareoptions.lyapunov_db == 1
% options_.lyapunov_db == 1
options_.lyapunov_fp = false;
options_.lyapunov_db = true;
try
@ -113,7 +113,7 @@ catch
t(2) = 0;
end
% Dynareoptions.lyapunov_srs == 1
% options_.lyapunov_srs == 1
if (isoctave && user_has_octave_forge_package('control')) || (~isoctave && user_has_matlab_license('control_toolbox'))
options_.lyapunov_db = false;
options_.lyapunov_srs = true;

View File

@ -1,5 +1,5 @@
function [xparams,lpd,hessian_mat] = ...
maximize_prior_density(iparams, prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound,DynareOptions,DynareModel,BayesInfo,EstimatedParams,DynareResults)
maximize_prior_density(iparams, prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound,options_,M_,bayestopt_,estim_params_,oo_)
% Maximizes the logged prior density using Chris Sims' optimization routine.
%
% INPUTS
@ -9,13 +9,18 @@ function [xparams,lpd,hessian_mat] = ...
% prior_hyperparameter_2 [double] vector, second hyperparameter.
% prior_inf_bound [double] vector, prior's lower bound.
% prior_sup_bound [double] vector, prior's upper bound.
% options_ [structure] describing the options
% bayestopt_ [structure] describing the priors
% M_ [structure] describing the model
% estim_params_ [structure] characterizing parameters to be estimated
% oo_ [structure] storing the results
%
% OUTPUTS
% xparams [double] vector, prior mode.
% lpd [double] scalar, value of the logged prior density at the mode.
% hessian_mat [double] matrix, Hessian matrix at the prior mode.
% Copyright © 2009-2017 Dynare Team
% Copyright © 2009-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -33,9 +38,9 @@ function [xparams,lpd,hessian_mat] = ...
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
[xparams, lpd, exitflag, hessian_mat]=dynare_minimize_objective('minus_logged_prior_density', ...
iparams, DynareOptions.mode_compute, DynareOptions, [prior_inf_bound, prior_sup_bound], ...
BayesInfo.name, BayesInfo, [], ...
iparams, options_.mode_compute, options_, [prior_inf_bound, prior_sup_bound], ...
bayestopt_.name, bayestopt_, [], ...
prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound, ...
DynareOptions,DynareModel,EstimatedParams,DynareResults);
options_,M_,estim_params_,oo_);
lpd = -lpd;

View File

@ -1,10 +1,10 @@
% W = k_order_welfare(dr, DynareModel, DynareOptions)
% W = k_order_welfare(dr, M_, options_)
% computes a k-th order approximation of welfare
%
% INPUTS
% dr: struct describing the reduced form solution of the model.
% DynareModel: struct jobs's parameters
% DynareOptions: struct job's options
% M_: struct jobs's parameters
% options_: struct job's options
%
% OUTPUTS
%

View File

@ -1,13 +1,19 @@
function [fval,info,exit_flag,fake_1,fake_2] = minus_logged_prior_density(xparams,pshape,p6,p7,p3,p4,DynareOptions,DynareModel,EstimatedParams,DynareResults)
function [fval,info,exit_flag,fake_1,fake_2] = minus_logged_prior_density(xparams,pshape,p6,p7,p3,p4,options_,M_,estim_params_,oo_)
% [fval,info,exit_flag,fake_1,fake_2] = minus_logged_prior_density(xparams,pshape,p6,p7,p3,p4,options_,M_,estim_params_,oo_)
% Evaluates minus the logged prior density.
%
% INPUTS
% xparams [double] vector of parameters.
% pshape [integer] vector specifying prior densities shapes.
% p6 [double] vector, first hyperparameter.
% p7 [double] vector, second hyperparameter.
% p3 [double] vector, prior's lower bound.
% p4 [double] vector, prior's upper bound.
% xparams [double] vector of parameters.
% pshape [integer] vector specifying prior densities shapes.
% p6 [double] vector, first hyperparameter.
% p7 [double] vector, second hyperparameter.
% p3 [double] vector, prior's lower bound.
% p4 [double] vector, prior's upper bound.
% prior_sup_bound [double] vector, prior's upper bound.
% options_ [structure] describing the options
% M_ [structure] describing the model
% estim_params_ [structure] characterizing parameters to be estimated
% oo_ [structure] storing the results
%
% OUTPUTS
% f [double] value of minus the logged prior density.
@ -41,7 +47,7 @@ info = zeros(4,1);
%------------------------------------------------------------------------------
% Return, with endogenous penalty, if some parameters are smaller than the lower bound of the prior domain.
if ~isequal(DynareOptions.mode_compute,1) && any(xparams<p3)
if ~isequal(options_.mode_compute,1) && any(xparams<p3)
k = find(xparams<p3);
fval = Inf;
exit_flag = 0;
@ -51,7 +57,7 @@ if ~isequal(DynareOptions.mode_compute,1) && any(xparams<p3)
end
% Return, with endogenous penalty, if some parameters are greater than the upper bound of the prior domain.
if ~isequal(DynareOptions.mode_compute,1) && any(xparams>p4)
if ~isequal(options_.mode_compute,1) && any(xparams>p4)
k = find(xparams>p4);
fval = Inf;
exit_flag = 0;
@ -61,13 +67,13 @@ if ~isequal(DynareOptions.mode_compute,1) && any(xparams>p4)
end
% Get the diagonal elements of the covariance matrices for the structural innovations (Q) and the measurement error (H).
DynareModel = set_all_parameters(xparams,EstimatedParams,DynareModel);
M_ = set_all_parameters(xparams,estim_params_,M_);
Q = DynareModel.Sigma_e;
H = DynareModel.H;
Q = M_.Sigma_e;
H = M_.H;
% Test if Q is positive definite.
if ~issquare(Q) || EstimatedParams.ncx || isfield(EstimatedParams,'calibrated_covariances')
if ~issquare(Q) || estim_params_.ncx || isfield(estim_params_,'calibrated_covariances')
% Try to compute the cholesky decomposition of Q (possible iff Q is positive definite)
[Q_is_positive_definite, penalty] = ispd(Q);
if ~Q_is_positive_definite
@ -78,22 +84,22 @@ if ~issquare(Q) || EstimatedParams.ncx || isfield(EstimatedParams,'calibrated_co
info(4) = penalty;
return
end
if isfield(EstimatedParams,'calibrated_covariances')
if isfield(estim_params_,'calibrated_covariances')
correct_flag=check_consistency_covariances(Q);
if ~correct_flag
penalty = sum(Q(EstimatedParams.calibrated_covariances.position).^2);
penalty = sum(Q(estim_params_.calibrated_covariances.position).^2);
fval = Inf;
exit_flag = 0;
info(1) = 71;
info(4) = penalty;
return
return4
end
end
end
% Test if H is positive definite.
if ~issquare(H) || EstimatedParams.ncn || isfield(EstimatedParams,'calibrated_covariances_ME')
if ~issquare(H) || estim_params_.ncn || isfield(estim_params_,'calibrated_covariances_ME')
[H_is_positive_definite, penalty] = ispd(H);
if ~H_is_positive_definite
% The variance-covariance matrix of the measurement errors is not definite positive. We have to compute the eigenvalues of this matrix in order to build the endogenous penalty.
@ -103,10 +109,10 @@ if ~issquare(H) || EstimatedParams.ncn || isfield(EstimatedParams,'calibrated_co
info(4) = penalty;
return
end
if isfield(EstimatedParams,'calibrated_covariances_ME')
if isfield(estim_params_,'calibrated_covariances_ME')
correct_flag=check_consistency_covariances(H);
if ~correct_flag
penalty = sum(H(EstimatedParams.calibrated_covariances_ME.position).^2);
penalty = sum(H(estim_params_.calibrated_covariances_ME.position).^2);
fval = Inf;
exit_flag = 0;
info(1) = 72;
@ -121,7 +127,7 @@ end
% 2. Check BK and steady state
%-----------------------------
[~,info] = resol(0,DynareModel,DynareOptions,DynareResults.dr,DynareResults.steady_state, DynareResults.exo_steady_state, DynareResults.exo_det_steady_state);
[~,info] = resol(0,M_,options_,oo_.dr,oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
% Return, with endogenous penalty when possible, if dynare_resolve issues an error code (defined in resol).
if info(1)

View File

@ -1,16 +1,16 @@
function [endogenousvariables, exogenousvariables] = model_inversion(constraints, ...
exogenousvariables, ...
initialconditions, DynareModel, DynareOptions, DynareOutput)
initialconditions, M_, options_, oo_)
% function [endogenousvariables, exogenousvariables] = model_inversion(constraints, ...
% exogenousvariables, ...
% initialconditions, DynareModel, DynareOptions, DynareOutput)
% initialconditions, M_, options_, oo_)
% INPUTS
% - constraints [dseries] with N constrained endogenous variables from t1 to t2.
% - exogenousvariables [dseries] with Q exogenous variables.
% - initialconditions [dseries] with M endogenous variables starting before t1 (M initialcond must contain at least the state variables).
% - DynareModel [struct] M_, Dynare global structure containing informations related to the model.
% - DynareOptions [struct] options_, Dynare global structure containing all the options.
% - DynareOutput [struct] oo_, Dynare global structure containing all the options.
% - M_ [struct] Dynare global structure containing informations related to the model.
% - options_ [struct] Dynare global structure containing all the options.
% - oo_ [struct] Dynare global structure containing all the options.
%
% OUTPUTS
% - endogenousvariables [dseries]
@ -18,7 +18,7 @@ function [endogenousvariables, exogenousvariables] = model_inversion(constraints
%
% REMARKS
% Copyright © 2018-2021 Dynare Team
% Copyright © 2018-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -51,7 +51,7 @@ if ~isempty(initialconditions) && ~isdseries(initialconditions)
error('model_inversion: Third input argument must be a dseries object!')
end
if ~isstruct(DynareModel)
if ~isstruct(M_)
error('model_inversion: Last input argument must be structures (M_)!')
end
@ -71,29 +71,29 @@ if exogenousvariables.vobs>constraints.vobs
observed_exogenous_variables_flag = true;
end
if DynareModel.maximum_lag
if M_.maximum_lag
% Add auxiliary variables in initialconditions object.
initialconditions = checkdatabase(initialconditions, DynareModel, true, false);
initialconditions = checkdatabase(initialconditions, M_, true, false);
end
% Get the list of endogenous and exogenous variables.
endo_names = DynareModel.endo_names;
exo_names = DynareModel.exo_names;
endo_names = M_.endo_names;
exo_names = M_.exo_names;
exogenousvariables = exogenousvariables{exo_names{:}};
% Use specidalized routine if the model is backward looking.
if ~DynareModel.maximum_lead
if DynareModel.maximum_lag
if ~M_.maximum_lead
if M_.maximum_lag
[endogenousvariables, exogenousvariables] = ...
backward_model_inversion(constraints, exogenousvariables, initialconditions, ...
endo_names, exo_names, freeinnovations, ...
DynareModel, DynareOptions, DynareOutput);
M_, options_, oo_);
else
[endogenousvariables, exogenousvariables] = ...
static_model_inversion(constraints, exogenousvariables, ...
endo_names, exo_names, freeinnovations, ...
DynareModel, DynareOptions, DynareOutput);
M_, options_, oo_);
end
return
end

View File

@ -1,5 +1,5 @@
function [fval,info,exit_flag,DLIK,Hess,ys,trend_coeff,M_,options_,bayestopt_,dr] = non_linear_dsge_likelihood(xparam1,dataset_,dataset_info,options_,M_,EstimatedParameters,bayestopt_,BoundsInfo,dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
% [fval,info,exit_flag,DLIK,Hess,ys,trend_coeff,M_,options_,bayestopt_,dr] = non_linear_dsge_likelihood(xparam1,dataset_,dataset_info,options_,M_,EstimatedParameters,bayestopt_,BoundsInfo,dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
function [fval,info,exit_flag,DLIK,Hess,ys,trend_coeff,M_,options_,bayestopt_,dr] = non_linear_dsge_likelihood(xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,BoundsInfo,dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
% [fval,info,exit_flag,DLIK,Hess,ys,trend_coeff,M_,options_,bayestopt_,dr] = non_linear_dsge_likelihood(xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,BoundsInfo,dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
% Evaluates the posterior kernel of a dsge model using a non linear filter.
%
% INPUTS
@ -8,7 +8,7 @@ function [fval,info,exit_flag,DLIK,Hess,ys,trend_coeff,M_,options_,bayestopt_,dr
% - dataset_info [struct] Matlab's structure describing the dataset
% - options_ [struct] Matlab's structure describing the options
% - M_ [struct] Matlab's structure describing the M_
% - EstimatedParameters [struct] Matlab's structure describing the estimated_parameters
% - estim_params_ [struct] Matlab's structure describing the estimated_parameters
% - bayestopt_ [struct] Matlab's structure describing the priors
% - BoundsInfo [struct] Matlab's structure specifying the bounds on the paramater values
% - dr [structure] Reduced form model.
@ -71,9 +71,9 @@ end
% 1. Get the structural parameters & define penalties
%------------------------------------------------------------------------------
M_ = set_all_parameters(xparam1,EstimatedParameters,M_);
M_ = set_all_parameters(xparam1,estim_params_,M_);
[fval,info,exit_flag,Q,H]=check_bounds_and_definiteness_estimation(xparam1, M_, EstimatedParameters, BoundsInfo);
[fval,info,exit_flag,Q,H]=check_bounds_and_definiteness_estimation(xparam1, M_, estim_params_, BoundsInfo);
if info(1)
return
end

View File

@ -3,13 +3,14 @@ function [f0, x, ig] = mr_gstep(h1,x,bounds,func0,penalty,htol0,Verbose,Save_fil
%
% Gibbs type step in optimisation
%
% varargin{1} --> DynareDataset
% varargin{2} --> DatasetInfo
% varargin{3} --> DynareOptions
% varargin{4} --> Model
% varargin{5} --> EstimatedParameters
% varargin{6} --> BayesInfo
% varargin{1} --> DynareResults
% varargin{1} --> dataset_
% varargin{2} --> dataset_info
% varargin{3} --> options_
% varargin{4} --> M_
% varargin{5} --> estim_params_
% varargin{6} --> bayestopt_
% varargin{7} --> BoundsInfo
% varargin{8} --> oo_
% Copyright © 2006-2020 Dynare Team
%

View File

@ -29,14 +29,14 @@ function [hessian_mat, gg, htol1, ihh, hh_mat0, hh1, hess_info] = mr_hessian(x,f
% - Save_files indicator whether files should be saved
% - varargin other inputs
% e.g. in dsge_likelihood
% varargin{1} --> DynareDataset
% varargin{2} --> DatasetInfo
% varargin{3} --> DynareOptions
% varargin{4} --> Model
% varargin{5} --> EstimatedParameters
% varargin{6} --> BayesInfo
% varargin{7} --> Bounds
% varargin{8} --> DynareResults
% varargin{1} --> dataset_
% varargin{2} --> dataset_info
% varargin{3} --> options_
% varargin{4} --> M_
% varargin{5} --> estim_params_
% varargin{6} --> bayestopt_
% varargin{7} --> BoundsInfo
% varargin{8} --> oo_
%
% Outputs
% - hessian_mat hessian

View File

@ -28,14 +28,14 @@ function [xparam1, hh, gg, fval, igg, hess_info] = newrat(func0, x, bounds, anal
% - parameter_names [cell] names of parameters for error messages
% - varargin other inputs
% e.g. in dsge_likelihood and others:
% varargin{1} --> DynareDataset
% varargin{2} --> DatasetInfo
% varargin{3} --> DynareOptions
% varargin{4} --> Model
% varargin{5} --> EstimatedParameters
% varargin{6} --> BayesInfo
% varargin{7} --> Bounds
% varargin{8} --> DynareResults
% varargin{1} --> dataset_
% varargin{2} --> dataset_info
% varargin{3} --> options_
% varargin{4} --> M_
% varargin{5} --> estim_params_
% varargin{6} --> bayestopt_
% varargin{7} --> BoundsInfo
% varargin{8} --> oo_
%
% Outputs
% - xparam1 parameter vector at optimum

View File

@ -15,13 +15,14 @@ function [x,fval,exitflag] = simplex_optimization_routine(objective_function,x,o
% for verbose output
% o varargin [cell of structures] Structures to be passed to the objective function.
%
% varargin{1} --> DynareDataset
% varargin{2} --> DatasetInfo
% varargin{3} --> DynareOptions
% varargin{4} --> Model
% varargin{5} --> EstimatedParameters
% varargin{6} --> BayesInfo
% varargin{1} --> DynareResults
% varargin{1} --> dataset_
% varargin{2} --> dataset_info
% varargin{3} --> options_
% varargin{4} --> M_
% varargin{5} --> estim_params_
% varargin{6} --> bayestopt_
% varargin{7} --> BoundsInfo
% varargin{8} --> oo_
%
% OUTPUTS
% o x [double] n*1 vector, estimate of the optimal inputs.

View File

@ -1,8 +1,15 @@
function optimize_prior(DynareOptions, ModelInfo, DynareResults, BayesInfo, EstimationInfo)
function optimize_prior(options_, M_, oo_, bayestopt_, estim_params_)
% optimize_prior(options_, M_, oo_, bayestopt_, estim_params_)
% This routine computes the mode of the prior density using an optimization algorithm.
%
% INPUTS
% options_ [structure] describing the options
% M_ [structure] describing the model
% oo_ [structure] storing the results
% bayestopt_ [structure] describing the priors
% estim_params_ [structure] characterizing parameters to be estimated
% Copyright © 2015-2017 Dynare Team
% Copyright © 2015-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -20,16 +27,16 @@ function optimize_prior(DynareOptions, ModelInfo, DynareResults, BayesInfo, Esti
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
% Initialize to the prior mean
DynareResults.dr = set_state_space(DynareResults.dr,ModelInfo);
xparam1 = BayesInfo.p1;
oo_.dr = set_state_space(oo_.dr,M_);
xparam1 = bayestopt_.p1;
% Pertubation of the initial condition.
look_for_admissible_initial_condition = 1; scale = 1.0; iter = 0;
while look_for_admissible_initial_condition
xinit = xparam1+scale*randn(size(xparam1));
if all(xinit(:)>BayesInfo.p3) && all(xinit(:)<BayesInfo.p4)
ModelInfo = set_all_parameters(xinit,EstimationInfo,ModelInfo);
[DynareResults.dr,INFO,ModelInfo.params] = resol(0,ModelInfo,DynareOptions,DynareResults.dr,DynareResults.steady_state, DynareResults.exo_steady_state, DynareResults.exo_det_steady_state);
if all(xinit(:)>bayestopt_.p3) && all(xinit(:)<bayestopt_.p4)
M_ = set_all_parameters(xinit,estim_params_,M_);
[oo_.dr,INFO,M_.params] = resol(0,M_,options_,oo_.dr,oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
if ~INFO(1)
look_for_admissible_initial_condition = 0;
end
@ -45,11 +52,11 @@ end
% Maximization of the prior density
[xparams, lpd, hessian_mat] = ...
maximize_prior_density(xinit, BayesInfo.pshape, ...
BayesInfo.p6, ...
BayesInfo.p7, ...
BayesInfo.p3, ...
BayesInfo.p4,DynareOptions,ModelInfo,BayesInfo,EstimationInfo,DynareResults);
maximize_prior_density(xinit, bayestopt_.pshape, ...
bayestopt_.p6, ...
bayestopt_.p7, ...
bayestopt_.p3, ...
bayestopt_.p4,options_,M_,bayestopt_,estim_params_,oo_);
% Display the results.
skipline(2)
@ -58,9 +65,9 @@ disp('PRIOR OPTIMIZATION')
disp('------------------')
skipline()
for i = 1:length(xparams)
disp(['deep parameter ' int2str(i) ': ' get_the_name(i,0,ModelInfo,EstimationInfo,DynareOptions) '.'])
disp(['deep parameter ' int2str(i) ': ' get_the_name(i,0,M_,estim_params_,options_) '.'])
disp([' Initial condition ....... ' num2str(xinit(i)) '.'])
disp([' Prior mode .............. ' num2str(BayesInfo.p5(i)) '.'])
disp([' Prior mode .............. ' num2str(bayestopt_.p5(i)) '.'])
disp([' Optimized prior mode .... ' num2str(xparams(i)) '.'])
skipline()
end

View File

@ -1,9 +1,13 @@
function check_input_arguments(DynareOptions, DynareModel, DynareResults)
%function check_input_arguments(DynareOptions, DynareModel, DynareResults)
function check_input_arguments(options_, M_, oo_)
%function check_input_arguments(options_, M_, oo_)
%Conducts checks for inconsistent/missing inputs to deterministic
%simulations
% Inputs:
% options_ [structure] describing the options
% M_ [structure] describing the model
% oo_ [structure] storing the results
% Copyright © 2015-2022 Dynare Team
% Copyright © 2015-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -20,34 +24,34 @@ function check_input_arguments(DynareOptions, DynareModel, DynareResults)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if DynareOptions.stack_solve_algo < 0 || DynareOptions.stack_solve_algo > 7
if options_.stack_solve_algo < 0 || options_.stack_solve_algo > 7
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: stack_solve_algo must be between 0 and 7')
end
if ~DynareOptions.block && ~DynareOptions.bytecode && DynareOptions.stack_solve_algo ~= 0 ...
&& DynareOptions.stack_solve_algo ~= 1 && DynareOptions.stack_solve_algo ~= 6 ...
&& DynareOptions.stack_solve_algo ~= 7
if ~options_.block && ~options_.bytecode && options_.stack_solve_algo ~= 0 ...
&& options_.stack_solve_algo ~= 1 && options_.stack_solve_algo ~= 6 ...
&& options_.stack_solve_algo ~= 7
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: you must use stack_solve_algo={0,1,6,7} when not using block nor bytecode option')
end
if DynareOptions.block && ~DynareOptions.bytecode && DynareOptions.stack_solve_algo == 5
if options_.block && ~options_.bytecode && options_.stack_solve_algo == 5
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: you can''t use stack_solve_algo = 5 without bytecode option')
end
if isempty(DynareResults.endo_simul) || any(size(DynareResults.endo_simul) ~= [ DynareModel.endo_nbr, DynareModel.maximum_lag+DynareOptions.periods+DynareModel.maximum_lead ])
if isempty(oo_.endo_simul) || any(size(oo_.endo_simul) ~= [ M_.endo_nbr, M_.maximum_lag+options_.periods+M_.maximum_lead ])
if DynareOptions.initval_file
fprintf('PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Check whether your initval-file provides %d periods.',DynareModel.maximum_endo_lag+DynareOptions.periods+DynareModel.maximum_endo_lead)
if options_.initval_file
fprintf('PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Check whether your initval-file provides %d periods.',M_.maximum_endo_lag+options_.periods+M_.maximum_endo_lead)
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')
else
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')
end
end
if (DynareModel.exo_nbr > 0) && ...
(isempty(DynareResults.exo_simul) || any(size(DynareResults.exo_simul) ~= [ DynareModel.maximum_lag+DynareOptions.periods+DynareModel.maximum_lead, DynareModel.exo_nbr ]))
if DynareOptions.initval_file
fprintf('PERFECT_FORESIGHT_SOLVER: ''oo_.exo_simul'' has wrong size. Check whether your initval-file provides %d periods.',DynareModel.maximum_endo_lag+DynareOptions.periods+DynareModel.maximum_endo_lead)
if (M_.exo_nbr > 0) && ...
(isempty(oo_.exo_simul) || any(size(oo_.exo_simul) ~= [ M_.maximum_lag+options_.periods+M_.maximum_lead, M_.exo_nbr ]))
if options_.initval_file
fprintf('PERFECT_FORESIGHT_SOLVER: ''oo_.exo_simul'' has wrong size. Check whether your initval-file provides %d periods.',M_.maximum_endo_lag+options_.periods+M_.maximum_endo_lead)
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.exo_simul'' has wrong size.')
else
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.exo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')

View File

@ -1,17 +1,18 @@
function print_info(info, noprint, DynareOptions)
function print_info(info, noprint, options_)
% print_info(info, noprint, options_)
% Prints error messages
%
% INPUTS
% info [double] vector returned by resol.m
% noprint [integer] equal to 0 if the error message has to be printed.
% DynareOptions [structure] --> options_
% options_ [structure] Dynare options
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
% Copyright © 2005-2020 Dynare Team
% Copyright © 2005-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -28,6 +29,6 @@ function print_info(info, noprint, DynareOptions)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if ~noprint
message = get_error_message(info, DynareOptions);
message = get_error_message(info, options_);
error(message);
end

View File

@ -1,8 +1,14 @@
function print_table_prior(lb, ub, DynareOptions, ModelInfo, BayesInfo, EstimationInfo)
function print_table_prior(lb, ub, options_, M_, bayestopt_, estim_params_)
% print_table_prior(lb, ub, options_, M_, bayestopt_, estim_params_)
% This routine prints in the command window some descriptive statistics about the prior distribution.
% Inputs:
% o lb [double] lower bound
% o ub [double] upper bound
% o M_ [structure] Definition of the model
% o bayestopt_ [structure] describing the priors
% o estim_params_ [structure] characterizing parameters to be estimated
% Copyright © 2015-2017 Dynare Team
% Copyright © 2015-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -28,7 +34,7 @@ PriorNames = strvcat(PriorNames,'Inverted Gamma -- 2');
PriorNames = strvcat(PriorNames,'Dirichlet');
PriorNames = strvcat(PriorNames,'Weibull');
n = size(BayesInfo.name,1); % Numbe rof estimated parameters.
n = size(bayestopt_.name,1); % Numbe rof estimated parameters.
l1 = printline(10, '-');
T1 = strvcat(l1, 'PARAMETER ');
@ -38,15 +44,15 @@ l2 = printline(133, '-');
T2 = strvcat(l2, sprintf('Prior shape \t Prior mean \t Prior mode \t Prior std. \t Prior lb \t Prior ub \t Prior HPD lb \t Prior HPH ub'));
T2 = strvcat(T2, l2);
prior_trunc_backup = DynareOptions.prior_trunc ;
DynareOptions.prior_trunc = (1-DynareOptions.prior_interval)/2 ;
PriorIntervals = prior_bounds(BayesInfo, DynareOptions.prior_trunc) ;
DynareOptions.prior_trunc = prior_trunc_backup ;
prior_trunc_backup = options_.prior_trunc ;
options_.prior_trunc = (1-options_.prior_interval)/2 ;
PriorIntervals = prior_bounds(bayestopt_, options_.prior_trunc) ;
options_.prior_trunc = prior_trunc_backup ;
RESIZE = false;
for i=1:size(BayesInfo.name,1)
[Name,tmp] = get_the_name(i,1,ModelInfo,EstimationInfo,DynareOptions);
for i=1:size(bayestopt_.name,1)
[Name,tmp] = get_the_name(i,1,M_,estim_params_,options_);
if length(Name)>size(T1,2)
resize = true;
else
@ -59,14 +65,14 @@ for i=1:size(BayesInfo.name,1)
T1(1,:) = l1;
T1(3,:) = l1;
end
PriorShape = PriorNames(BayesInfo.pshape(i),:);
PriorMean = BayesInfo.p1(i);
PriorMode = BayesInfo.p5(i);
PriorStandardDeviation = BayesInfo.p2(i);
switch BayesInfo.pshape(i)
PriorShape = PriorNames(bayestopt_.pshape(i),:);
PriorMean = bayestopt_.p1(i);
PriorMode = bayestopt_.p5(i);
PriorStandardDeviation = bayestopt_.p2(i);
switch bayestopt_.pshape(i)
case { 1 , 5 }
LowerBound = BayesInfo.p3(i);
UpperBound = BayesInfo.p4(i);
LowerBound = bayestopt_.p3(i);
UpperBound = bayestopt_.p4(i);
if ~isinf(lb(i))
LowerBound=max(LowerBound,lb(i));
end
@ -74,7 +80,7 @@ for i=1:size(BayesInfo.name,1)
UpperBound=min(UpperBound,ub(i));
end
case { 2 , 4 , 6 , 8}
LowerBound = BayesInfo.p3(i);
LowerBound = bayestopt_.p3(i);
if ~isinf(lb(i))
LowerBound=max(LowerBound,lb(i));
end
@ -84,18 +90,18 @@ for i=1:size(BayesInfo.name,1)
UpperBound = Inf;
end
case 3
if isinf(BayesInfo.p3(i)) && isinf(lb(i))
if isinf(bayestopt_.p3(i)) && isinf(lb(i))
LowerBound = -Inf;
else
LowerBound = BayesInfo.p3(i);
LowerBound = bayestopt_.p3(i);
if ~isinf(lb(i))
LowerBound=max(LowerBound,lb(i));
end
end
if isinf(BayesInfo.p4(i)) && isinf(ub(i))
if isinf(bayestopt_.p4(i)) && isinf(ub(i))
UpperBound = Inf;
else
UpperBound = BayesInfo.p4(i);
UpperBound = bayestopt_.p4(i);
if ~isinf(ub(i))
UpperBound=min(UpperBound,ub(i));
end

View File

@ -1,11 +1,14 @@
function [endogenousvariables, exogenousvariables] = static_model_inversion(constraints, exogenousvariables, endo_names, exo_names, freeinnovations, DynareModel, DynareOptions, DynareOutput)
function [endogenousvariables, exogenousvariables] = static_model_inversion(constraints, exogenousvariables, endo_names, exo_names, freeinnovations, M_, options_, oo_)
% [endogenousvariables, exogenousvariables] = static_model_inversion(constraints, exogenousvariables, endo_names, exo_names, freeinnovations, M_, options_, oo_)
% INPUTS
% - constraints [dseries] with N constrained endogenous variables from t1 to t2.
% - exogenousvariables [dseries] with Q exogenous variables.
% - endo_names [cell] list of endogenous variable names.
% - exo_names [cell] list of exogenous variable names.
% - freeinstruments [cell] list of exogenous variable names used to control the constrained endogenous variables.
% - M_ [structure] Definition of the model
% - options_ [structure] Options
% - oo_ [structure] Storage of results
%
% OUTPUTS
% - endogenous [dseries]
@ -32,7 +35,7 @@ function [endogenousvariables, exogenousvariables] = static_model_inversion(cons
% Get indices for the free innovations.
freeinnovations_id = zeros(length(freeinnovations), 1);
if length(freeinnovations)<DynareModel.exo_nbr
if length(freeinnovations)<M_.exo_nbr
for i=1:length(freeinnovations)
freeinnovations_id(i) = find(strcmp(freeinnovations{i}, exo_names));
end
@ -44,7 +47,7 @@ nxfree = length(freeinnovations_id);
% Get indices for the the controlled and free endogenous variables.
controlledendogenousvariables_id = zeros(length(freeinnovations), 1);
if length(freeinnovations)<DynareModel.endo_nbr
if length(freeinnovations)<M_.endo_nbr
for i=1:length(freeinnovations)
controlledendogenousvariables_id(i) = find(strcmp(constraints.name{i}, endo_names));
end
@ -64,14 +67,14 @@ ModelInversion.nxfree = nxfree;
ModelInversion.y_constrained_id = controlledendogenousvariables_id;
ModelInversion.y_free_id = freeendogenousvariables_id;
ModelInversion.x_free_id = freeinnovations_id;
ModelInversion.J_id = [DynareModel.endo_nbr+ModelInversion.y_free_id ; 3*DynareModel.endo_nbr+ModelInversion.x_free_id];
ModelInversion.J_id = [M_.endo_nbr+ModelInversion.y_free_id ; 3*M_.endo_nbr+ModelInversion.x_free_id];
% Get function handles to the dynamic model routines.
dynamic_resid = str2func([DynareModel.fname '.sparse.dynamic_resid']);
dynamic_g1 = str2func([DynareModel.fname '.sparse.dynamic_g1']);
dynamic_resid = str2func([M_.fname '.sparse.dynamic_resid']);
dynamic_g1 = str2func([M_.fname '.sparse.dynamic_g1']);
% Initialization of the returned simulations (endogenous variables).
Y = NaN(DynareModel.endo_nbr, nobs(constraints));
Y = NaN(M_.endo_nbr, nobs(constraints));
for i=1:nyctrl
Y(controlledendogenousvariables_id(i),1:end) = transpose(constraints.data(:,i));
@ -84,7 +87,7 @@ X = exogenousvariables.data;
ity = 1;
itx = find(exogenousvariables.dates==constraints.dates(1));
DynareOptions.solve_algo=4;
options_.solve_algo=4;
for t = 1:nobs(constraints)
% Set the current values of the constrained endogenous variables.
@ -93,8 +96,8 @@ for t = 1:nobs(constraints)
% values) and the free exogenous variables (initialized with 0).
z = [Y(freeendogenousvariables_id,ity); zeros(nxfree, 1)];
% Solves for z.
[z, errorflag, ~, ~, errorcode] = dynare_solve(@static_model_for_inversion, z, DynareOptions.simul.maxit, DynareOptions.dynatol.f, DynareOptions.dynatol.x, ...
DynareOptions, dynamic_resid, dynamic_g1, ycur, X(itx, :), DynareModel.params, DynareOutput.steady_state, DynareModel.dynamic_g1_sparse_rowval, DynareModel.dynamic_g1_sparse_colval, DynareModel.dynamic_g1_sparse_colptr, ModelInversion);
[z, errorflag, ~, ~, errorcode] = dynare_solve(@static_model_for_inversion, z, options_.simul.maxit, options_.dynatol.f, options_.dynatol.x, ...
options_, dynamic_resid, dynamic_g1, ycur, X(itx, :), M_.params, oo_.steady_state, M_.dynamic_g1_sparse_rowval, M_.dynamic_g1_sparse_colval, M_.dynamic_g1_sparse_colptr, ModelInversion);
if errorflag
error('Enable to solve the system of equations (with error code %i).', errorcode)

View File

@ -1,20 +1,18 @@
function [DynareDataset, DatasetInfo, newdatainterface] = makedataset(DynareOptions, initialconditions, gsa_flag)
function [dataset_, dataset_info, newdatainterface] = makedataset(options_, initialconditions, gsa_flag)
%[dataset_, dataset_info, newdatainterface] = makedataset(options_, initialconditions, gsa_flag)
% Initialize a dataset as a dseries object.
%
%
% INPUTS
% ======
%
% DynareOptions [struct] Structure of options built by Dynare's preprocessor.
% options_ [struct] Structure of options built by Dynare's preprocessor.
% initialconditions [double] number of lags for VAR and DSGE_VAR
% gsa_flag [integer] 1: GSA, 0: other
%
% OUTPUTS
% =======
%
% DynareDataset [dseries] The dataset.
% DatasetInfo [struct] Various informations about the dataset (descriptive statistics and missing observations).
% dataset_ [dseries] The dataset.
% dataset_info [struct] Various informations about the dataset (descriptive statistics and missing observations).
%
% EXAMPLE
% =======
@ -24,7 +22,7 @@ function [DynareDataset, DatasetInfo, newdatainterface] = makedataset(DynareOpti
%
% See also dynare_estimation_init
% Copyright © 2014-2018 Dynare Team
% Copyright © 2014-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -52,10 +50,10 @@ if nargin<2 || isempty(initialconditions)
initialconditions = 0;
end
if isempty(DynareOptions.datafile) && isempty(DynareOptions.dataset.file) && isempty(DynareOptions.dataset.series)
if isempty(options_.datafile) && isempty(options_.dataset.file) && isempty(options_.dataset.series)
if gsa_flag
DynareDataset = dseries();
DatasetInfo = struct('missing', struct('state', 0, 'aindex', [], 'vindex', [], 'number_of_observations', NaN, 'no_more_missing_observations', NaN), ...
dataset_ = dseries();
dataset_info = struct('missing', struct('state', 0, 'aindex', [], 'vindex', [], 'number_of_observations', NaN, 'no_more_missing_observations', NaN), ...
'descriptive', struct('mean', [], 'covariance', [], 'correlation', [], 'autocovariance', []));
newdatainterface=0;
return
@ -64,24 +62,24 @@ if isempty(DynareOptions.datafile) && isempty(DynareOptions.dataset.file) && ise
end
end
if isempty(DynareOptions.datafile) && ~isempty(DynareOptions.dataset.file)
datafile = DynareOptions.dataset.file;
if isempty(options_.datafile) && ~isempty(options_.dataset.file)
datafile = options_.dataset.file;
newdatainterface = 1;
elseif isempty(DynareOptions.datafile) && ~isempty(DynareOptions.dataset.series)
elseif isempty(options_.datafile) && ~isempty(options_.dataset.series)
try
dseriesobjectforuserdataset = evalin('base', DynareOptions.dataset.series);
dseriesobjectforuserdataset = evalin('base', options_.dataset.series);
catch
error(sprintf('makedataset: %s is unknown!', DynareOptions.dataset.series))
error(sprintf('makedataset: %s is unknown!', options_.dataset.series))
end
if ~isdseries(dseriesobjectforuserdataset)
error(sprintf('makedataset: %s has to be a dseries object!', DynareOptions.dataset.series))
error(sprintf('makedataset: %s has to be a dseries object!', options_.dataset.series))
end
datafile = [];
newdatainterface = 1;
elseif ~isempty(DynareOptions.datafile) && isempty(DynareOptions.dataset.file)
datafile = DynareOptions.datafile;
elseif ~isempty(options_.datafile) && isempty(options_.dataset.file)
datafile = options_.datafile;
newdatainterface = 0;
elseif ~isempty(DynareOptions.datafile) && ~isempty(DynareOptions.dataset.file)
elseif ~isempty(options_.datafile) && ~isempty(options_.dataset.file)
error('makedataset: You cannot simultaneously use the data command and the datafile option (in the estimation command)!')
else
error('makedataset: You have to specify the datafile!')
@ -119,42 +117,42 @@ end
% Load the data in a dseries object.
if ~isempty(datafile)
if ~(newdatainterface==0 && ((length(datafile)>2 && strcmp(datafile(end-1:end),'.m')) || (length(datafile)>4 && strcmp(datafile(end-3:end),'.mat'))))
DynareDataset = dseries(datafile);
dataset_ = dseries(datafile);
else
if length(datafile)>2 && strcmp(datafile(end-1:end),'.m')
% Load an m file with the old interface.
DynareDataset = load_m_file_data_legacy(datafile, DynareOptions.varobs);
dataset_ = load_m_file_data_legacy(datafile, options_.varobs);
elseif length(datafile)>4 && strcmp(datafile(end-3:end),'.mat')
% Load a mat file with the old interface.
DynareDataset = load_mat_file_data_legacy(datafile, DynareOptions.varobs);
dataset_ = load_mat_file_data_legacy(datafile, options_.varobs);
end
end
else
DynareDataset = dseriesobjectforuserdataset;
dataset_ = dseriesobjectforuserdataset;
clear('dseriesobjectforuserdataset');
end
if size(unique(DynareDataset.name),1)~=size(DynareDataset.name,1)
if size(unique(dataset_.name),1)~=size(dataset_.name,1)
error('makedataset: the data set must not contain two variables with the same name and must not contain empty/non-named columns.')
end
% Select a subset of the variables.
DynareDataset = DynareDataset{DynareOptions.varobs{:}};
dataset_ = dataset_{options_.varobs{:}};
% Apply log function if needed.
if DynareOptions.loglinear && ~DynareOptions.logdata
DynareDataset = DynareDataset.log();
if options_.loglinear && ~options_.logdata
dataset_ = dataset_.log();
end
% Test if an initial period (different from its default value) is explicitely defined in the datafile.
if isequal(DynareDataset.init, dates(1,1))
if isequal(dataset_.init, dates(1,1))
dataset_default_initial_period = 1;
else
dataset_default_initial_period = 0;
end
% Test if an initial period (different from its default value) is explicitely defined in the mod file with the set_time command.
if ~isdates(DynareOptions.initial_period) && isnan(DynareOptions.initial_period)
if ~isdates(options_.initial_period) && isnan(options_.initial_period)
set_time_default_initial_period = 1;
else
set_time_default_initial_period = 0;
@ -164,42 +162,42 @@ if ~set_time_default_initial_period && dataset_default_initial_period
% Overwrite the initial period in dataset (it was set to default).
% Note that the updates of freq and time members are auto-magically
% done by dseries::subsasgn overloaded method.
DynareDataset.init = DynareOptions.initial_period;
dataset_.init = options_.initial_period;
end
if set_time_default_initial_period && ~dataset_default_initial_period
% Overwrite the global initial period defined by set_time (it was set to default).
DynareOptions.initial_period = DynareDataset.init;
options_.initial_period = dataset_.init;
end
if ~set_time_default_initial_period && ~dataset_default_initial_period
% Check if dataset.init and options_.initial_period are identical.
if DynareOptions.initial_period<DynareDataset.init
if options_.initial_period<dataset_.init
error('makedataset: The date as defined by the set_time command is not consistent with the initial period in the database!')
end
end
% Set firstobs, lastobs and nobs
if newdatainterface
if isempty(DynareOptions.dataset.firstobs)
if isempty(options_.dataset.firstobs)
% first_obs option was not used in the data command.
firstobs = DynareDataset.init;
firstobs = dataset_.init;
else
firstobs = DynareOptions.dataset.firstobs;
firstobs = options_.dataset.firstobs;
end
if isnan(DynareOptions.dataset.nobs)
if isnan(options_.dataset.nobs)
% nobs option was not used in the data command.
if isempty(DynareOptions.dataset.lastobs)
if isempty(options_.dataset.lastobs)
% last_obs option was not used in the data command.
nobs = DynareDataset.nobs;
lastobs = DynareDataset.dates(end);
nobs = dataset_.nobs;
lastobs = dataset_.dates(end);
else
lastobs = DynareOptions.dataset.lastobs;
lastobs = options_.dataset.lastobs;
nobs = lastobs-firstobs+1;
end
else
nobs = DynareOptions.dataset.nobs;
if isempty(DynareOptions.dataset.lastobs)
nobs = options_.dataset.nobs;
if isempty(options_.dataset.lastobs)
% last_obs option was not used in the data command.
lastobs = firstobs+(nobs-1);
else
@ -210,16 +208,16 @@ if newdatainterface
end
end
else
if isnan(DynareOptions.first_obs)
firstobs = DynareDataset.init;
if isnan(options_.first_obs)
firstobs = dataset_.init;
else
firstobs = DynareDataset.dates(DynareOptions.first_obs);
firstobs = dataset_.dates(options_.first_obs);
end
if isnan(DynareOptions.nobs)
lastobs = DynareDataset.dates(end);
if isnan(options_.nobs)
lastobs = dataset_.dates(end);
nobs = lastobs-firstobs+1;
else
nobs = DynareOptions.nobs;
nobs = options_.nobs;
lastobs = firstobs+(nobs-1);
end
end
@ -227,62 +225,62 @@ end
% Add initial conditions if needed
FIRSTOBS = firstobs-initialconditions;
% Check that firstobs belongs to DynareDataset.dates
if firstobs<DynareDataset.init
error(sprintf('makedataset: first_obs (%s) cannot be less than the first date in the dataset (%s)!',char(firstobs),char(DynareDataset.init)))
% Check that firstobs belongs to dataset_.dates
if firstobs<dataset_.init
error(sprintf('makedataset: first_obs (%s) cannot be less than the first date in the dataset (%s)!',char(firstobs),char(dataset_.init)))
end
% Check that FIRSTOBS belongs to DynareDataset.dates
if initialconditions && FIRSTOBS<DynareDataset.init
error(sprintf('makedataset: first_obs (%s) - %i cannot be less than the first date in the dataset (%s)!\nReduce the number of lags in the VAR model or increase the value of first_obs\nto at least first_obs=%i.', char(firstobs), initialconditions, char(DynareDataset.init),initialconditions+1));
% Check that FIRSTOBS belongs to dataset_.dates
if initialconditions && FIRSTOBS<dataset_.init
error(sprintf('makedataset: first_obs (%s) - %i cannot be less than the first date in the dataset (%s)!\nReduce the number of lags in the VAR model or increase the value of first_obs\nto at least first_obs=%i.', char(firstobs), initialconditions, char(dataset_.init),initialconditions+1));
end
% Check that lastobs belongs to DynareDataset.dates...
% Check that lastobs belongs to dataset_.dates...
if newdatainterface
if lastobs>DynareDataset.dates(end)
error(sprintf('makedataset: last_obs (%s) cannot be greater than the last date in the dataset (%s)!',char(lastobs),char(DynareDataset.dates(end))))
if lastobs>dataset_.dates(end)
error(sprintf('makedataset: last_obs (%s) cannot be greater than the last date in the dataset (%s)!',char(lastobs),char(dataset_.dates(end))))
end
else
% ... or check that nobs is smaller than the number of observations in DynareDataset.
if nobs>DynareDataset.nobs
error(sprintf('makedataset: nobs (%s) cannot be greater than the last date in the dataset (%s)!', num2str(nobs), num2str(DynareDataset.nobs)))
% ... or check that nobs is smaller than the number of observations in dataset_.
if nobs>dataset_.nobs
error(sprintf('makedataset: nobs (%s) cannot be greater than the last date in the dataset (%s)!', num2str(nobs), num2str(dataset_.nobs)))
end
end
% Select a subsample.
DynareDataset = DynareDataset(FIRSTOBS:lastobs);
dataset_ = dataset_(FIRSTOBS:lastobs);
% Initialize DatasetInfo structure.
DatasetInfo = struct('missing', struct('state', NaN, 'aindex', [], 'vindex', [], 'number_of_observations', NaN, 'no_more_missing_observations', NaN), ...
% Initialize dataset_info structure.
dataset_info = struct('missing', struct('state', NaN, 'aindex', [], 'vindex', [], 'number_of_observations', NaN, 'no_more_missing_observations', NaN), ...
'descriptive', struct('mean', [], 'covariance', [], 'correlation', [], 'autocovariance', []));
% Fill DatasetInfo.missing if some observations are missing
DatasetInfo.missing.state = isanynan(DynareDataset.data);
if DatasetInfo.missing.state
[DatasetInfo.missing.aindex, DatasetInfo.missing.number_of_observations, DatasetInfo.missing.no_more_missing_observations, DatasetInfo.missing.vindex] = ...
describe_missing_data(DynareDataset.data);
% Fill dataset_info.missing if some observations are missing
dataset_info.missing.state = isanynan(dataset_.data);
if dataset_info.missing.state
[dataset_info.missing.aindex, dataset_info.missing.number_of_observations, dataset_info.missing.no_more_missing_observations, dataset_info.missing.vindex] = ...
describe_missing_data(dataset_.data);
else
DatasetInfo.missing.aindex = num2cell(transpose(repmat(1:DynareDataset.vobs,DynareDataset.nobs,1)),1);
DatasetInfo.missing.no_more_missing_observations = 1;
dataset_info.missing.aindex = num2cell(transpose(repmat(1:dataset_.vobs,dataset_.nobs,1)),1);
dataset_info.missing.no_more_missing_observations = 1;
end
% Compute the empirical mean of the observed variables.
DatasetInfo.descriptive.mean = nanmean(DynareDataset.data,1);
dataset_info.descriptive.mean = nanmean(dataset_.data,1);
% Compute the empirical covariance matrix of the observed variables.
DatasetInfo.descriptive.covariance = nancovariance(DynareDataset.data);
dataset_info.descriptive.covariance = nancovariance(dataset_.data);
% Compute the empirical correlation matrix of the observed variables.
normalization_matrix = diag(1./sqrt(diag(DatasetInfo.descriptive.covariance)));
DatasetInfo.descriptive.correlation = normalization_matrix*DatasetInfo.descriptive.covariance*normalization_matrix;
normalization_matrix = diag(1./sqrt(diag(dataset_info.descriptive.covariance)));
dataset_info.descriptive.correlation = normalization_matrix*dataset_info.descriptive.covariance*normalization_matrix;
% Compute autocorrelation function.
DatasetInfo.descriptive.autocovariance = nanautocovariance(DynareDataset.data, DynareOptions.ar);
dataset_info.descriptive.autocovariance = nanautocovariance(dataset_.data, options_.ar);
% Save raw data.
DatasetInfo.rawdata = DynareDataset.data;
dataset_info.rawdata = dataset_.data;
% Prefilter the data if needed (remove the mean).
if isequal(DynareOptions.prefilter, 1)
DynareDataset = DynareDataset.detrend();
if isequal(options_.prefilter, 1)
dataset_ = dataset_.detrend();
end