Merge branch 'variable_naming' into 'master'

Move many functions towards consistent naming

See merge request Dynare/dynare!2202
kalman-mex
Sébastien Villemot 2023-10-25 13:56:17 +00:00
commit 0295e5ede8
105 changed files with 1512 additions and 1444 deletions

View File

@ -1,5 +1,5 @@
function write(DynareModel)
function write(M_)
% write(M_)
% Writes the nonlinear problem to be solved for computing the growth
% rates and levels along the Balanced Growth Path. Note that for
% the variables growing along the BGP, the identified levels are
@ -7,7 +7,7 @@ function write(DynareModel)
% sharing the same trend(s) are relevant.
%
% INPUTS
% - DynareModel [struct] Dynare generated stucture describing the model (M_).
% - M_ [struct] Dynare generated stucture describing the model (M_).
%
% OUTPUTS
% None
@ -15,7 +15,7 @@ function write(DynareModel)
% REMARKS
% - The trends are assumed to be multiplicative.
% Copyright © 2019 Dynare Team
% Copyright © 2019-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -32,18 +32,18 @@ function write(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 DynareModel.maximum_lag && ~DynareModel.maximum_lead
i0 = transpose(DynareModel.lead_lag_incidence(1,:)); % Indices of the lagged variables.
i1 = transpose(DynareModel.lead_lag_incidence(2,:)); % Indices of the current variables.
if M_.maximum_lag && ~M_.maximum_lead
i0 = transpose(M_.lead_lag_incidence(1,:)); % Indices of the lagged variables.
i1 = transpose(M_.lead_lag_incidence(2,:)); % Indices of the current variables.
i2 = []; % Indices of the leaded variables.
elseif DynareModel.maximum_lag && DynareModel.maximum_lead
i0 = transpose(DynareModel.lead_lag_incidence(1,:)); % Indices of the lagged variables.
i1 = transpose(DynareModel.lead_lag_incidence(2,:)); % Indices of the current variables.
i2 = transpose(DynareModel.lead_lag_incidence(3,:)); % Indices of the leaded variables.
elseif ~DynareModel.maximum_lag && DynareModel.maximum_lead
elseif M_.maximum_lag && M_.maximum_lead
i0 = transpose(M_.lead_lag_incidence(1,:)); % Indices of the lagged variables.
i1 = transpose(M_.lead_lag_incidence(2,:)); % Indices of the current variables.
i2 = transpose(M_.lead_lag_incidence(3,:)); % Indices of the leaded variables.
elseif ~M_.maximum_lag && M_.maximum_lead
i0 = []; % Indices of the lagged variables.
i1 = transpose(DynareModel.lead_lag_incidence(1,:)); % Indices of the current variables.
i2 = transpose(DynareModel.lead_lag_incidence(2,:)); % Indices of the leaded variables.
i1 = transpose(M_.lead_lag_incidence(1,:)); % Indices of the current variables.
i2 = transpose(M_.lead_lag_incidence(2,:)); % Indices of the leaded variables.
else
error('The model is static. The BGP is trivial.')
end
@ -71,7 +71,7 @@ else
end
% Create function in mod namespace.
fid = fopen(sprintf('+%s/bgpfun.m', DynareModel.fname), 'w');
fid = fopen(sprintf('+%s/bgpfun.m', M_.fname), 'w');
% Write header.
fprintf(fid, 'function [F, JAC] = bgpfun(z)\n\n');
@ -80,8 +80,8 @@ fprintf(fid, '%% This file has been generated by dynare (%s).\n\n', datestr(now)
% The function admits a unique vector as input argument. The first
% half of the elements are for the levels of the endogenous
% variables, the second half for the growth factors.
fprintf(fid, 'y = z(1:%u);\n\n', DynareModel.endo_nbr);
fprintf(fid, 'g = z(%u:%u);\n', DynareModel.endo_nbr+1, 2*DynareModel.endo_nbr);
fprintf(fid, 'y = z(1:%u);\n\n', M_.endo_nbr);
fprintf(fid, 'g = z(%u:%u);\n', M_.endo_nbr+1, 2*M_.endo_nbr);
% Define the point where the dynamic model is to be evaluated.
fprintf(fid, 'Y = zeros(%u, 1);\n', 2*(n0+n1+n2));
@ -118,39 +118,39 @@ end
fprintf(fid, '\n');
% Define the vector of parameters.
fprintf(fid, 'p = zeros(%u, 1);\n', DynareModel.param_nbr);
for i = 1:DynareModel.param_nbr
fprintf(fid, 'p(%u) = %16.12f;\n', i, DynareModel.params(i));
fprintf(fid, 'p = zeros(%u, 1);\n', M_.param_nbr);
for i = 1:M_.param_nbr
fprintf(fid, 'p(%u) = %16.12f;\n', i, M_.params(i));
end
fprintf(fid, '\n');
% Initialize the vector holding the residuals over the two periods.
fprintf(fid, 'F = NaN(%u, 1);\n', 2*DynareModel.endo_nbr);
fprintf(fid, 'F = NaN(%u, 1);\n', 2*M_.endo_nbr);
% Set vector of exogenous variables to 0.
fprintf(fid, 'x = zeros(1, %u);\n\n', DynareModel.exo_nbr);
fprintf(fid, 'x = zeros(1, %u);\n\n', M_.exo_nbr);
% Evaluate the residuals and jacobian of the dynamic model in periods t and t+1.
fprintf(fid, 'if nargout>1\n');
fprintf(fid, ' J = zeros(%u, %u);\n', 2*DynareModel.endo_nbr, n0+n1+n2+DynareModel.endo_nbr);
fprintf(fid, ' [F(1:%u), tmp] = %s.dynamic(Y(1:%u), x, p, y, 1);\n', DynareModel.endo_nbr, DynareModel.fname, n0+n1+n2);
fprintf(fid, ' J(1:%u,1:%u) = tmp(:,1:%u);\n', DynareModel.endo_nbr, n0+n1+n2, n0+n1+n2);
fprintf(fid, ' [F(%u:%u), tmp] = %s.dynamic(Y(1+%u:%u), x, p, y, 1);\n', DynareModel.endo_nbr+1, 2*DynareModel.endo_nbr, DynareModel.fname, n0+n1+n2, 2*(n0+n1+n2));
fprintf(fid, ' J(%u:%u,1:%u) = tmp(:,1:%u);\n', DynareModel.endo_nbr+1, 2*DynareModel.endo_nbr, n0+n1+n2, n0+n1+n2);
fprintf(fid, ' J = zeros(%u, %u);\n', 2*M_.endo_nbr, n0+n1+n2+M_.endo_nbr);
fprintf(fid, ' [F(1:%u), tmp] = %s.dynamic(Y(1:%u), x, p, y, 1);\n', M_.endo_nbr, M_.fname, n0+n1+n2);
fprintf(fid, ' J(1:%u,1:%u) = tmp(:,1:%u);\n', M_.endo_nbr, n0+n1+n2, n0+n1+n2);
fprintf(fid, ' [F(%u:%u), tmp] = %s.dynamic(Y(1+%u:%u), x, p, y, 1);\n', M_.endo_nbr+1, 2*M_.endo_nbr, M_.fname, n0+n1+n2, 2*(n0+n1+n2));
fprintf(fid, ' J(%u:%u,1:%u) = tmp(:,1:%u);\n', M_.endo_nbr+1, 2*M_.endo_nbr, n0+n1+n2, n0+n1+n2);
fprintf(fid, 'else\n');
fprintf(fid, ' F(1:%u) = %s.dynamic(Y(1:%u), x, p, y, 1);\n', DynareModel.endo_nbr, DynareModel.fname, n0+n1+n2);
fprintf(fid, ' F(%u:%u) = %s.dynamic(Y(1+%u:%u), x, p, y, 1);\n', DynareModel.endo_nbr+1, 2*DynareModel.endo_nbr, DynareModel.fname, n0+n1+n2, 2*(n0+n1+n2));
fprintf(fid, ' F(1:%u) = %s.dynamic(Y(1:%u), x, p, y, 1);\n', M_.endo_nbr, M_.fname, n0+n1+n2);
fprintf(fid, ' F(%u:%u) = %s.dynamic(Y(1+%u:%u), x, p, y, 1);\n', M_.endo_nbr+1, 2*M_.endo_nbr, M_.fname, n0+n1+n2, 2*(n0+n1+n2));
fprintf(fid, 'end\n\n');
% Compute the jacobian if required.
fprintf(fid, 'if nargout>1\n');
fprintf(fid, ' JAC = zeros(%u,%u);\n', 2*DynareModel.endo_nbr, 2*DynareModel.endo_nbr);
fprintf(fid, ' JAC = zeros(%u,%u);\n', 2*M_.endo_nbr, 2*M_.endo_nbr);
% Compute the derivatives of the first block of equations (period t)
% with respect to the endogenous variables.
if purely_backward_model || purely_forward_model
for i=1:DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
for i=1:M_.eq_nbr
for j=1:M_.endo_nbr
if I1(j)
if I0(j)
fprintf(fid, ' JAC(%u,%u) = J(%u,%u)+J(%u,%u)*g(%u);\n', i, j, i, I0(j), i, I1(j), j);
@ -165,8 +165,8 @@ if purely_backward_model || purely_forward_model
end
end
else
for i=1:DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
for i=1:M_.eq_nbr
for j=1:M_.endo_nbr
if I2(j)
if I1(j)
if I0(j)
@ -201,8 +201,8 @@ end
% Compute the derivatives of the second block of equations (period t+1)
% with respect to the endogenous variables.
if purely_backward_model || purely_forward_model
for i=DynareModel.eq_nbr+1:2*DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
for i=M_.eq_nbr+1:2*M_.eq_nbr
for j=1:M_.endo_nbr
if I1(j)
if I0(j)
fprintf(fid, ' JAC(%u,%u) = J(%u,%u)*g(%u)+J(%u,%u)*g(%u)*g(%u);\n', i, j, i, I0(j), j, i, I1(j), j, j);
@ -217,8 +217,8 @@ if purely_backward_model || purely_forward_model
end
end
else
for i=DynareModel.eq_nbr+1:2*DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
for i=M_.eq_nbr+1:2*M_.eq_nbr
for j=1:M_.endo_nbr
if I2(j)
if I1(j)
if I0(j)
@ -253,16 +253,16 @@ end
% Compute the derivatives of the first block of equations (period t)
% with respect to the growth factors.
if purely_backward_model || purely_forward_model
for i=1:DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
for i=1:M_.eq_nbr
for j=1:M_.endo_nbr
if I1(j)
fprintf(fid, ' J(%u,%u) = J(%u,%u)*y(%u);\n', i, n0+n1+n2+j, i, I1(j), j);
end
end
end
else
for i=1:DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
for i=1:M_.eq_nbr
for j=1:M_.endo_nbr
if I2(j)
if I1(j)
fprintf(fid, ' J(%u,%u) = J(%u,%u)*y(%u)+J(%u,%u)*2*g(%u)*y(%u);\n', i, n0+n1+n2+j, i, I1(j), j, i, I2(j), j, j);
@ -281,8 +281,8 @@ end
% Compute the derivatives of the second block of equations (period t+1)
% with respect to the endogenous variables.
if purely_backward_model || purely_forward_model
for i=DynareModel.eq_nbr+1:2*DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
for i=M_.eq_nbr+1:2*M_.eq_nbr
for j=1:M_.endo_nbr
if I0(j)
fprintf(fid, ' J(%u,%u) = J(%u,%u)+J(%u,%u)*y(%u);\n', i, n0+n1+n2+j, i, n0+n1+n2+j, i, I0(j), j);
end
@ -292,8 +292,8 @@ if purely_backward_model || purely_forward_model
end
end
else
for i=DynareModel.eq_nbr+1:2*DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
for i=M_.eq_nbr+1:2*M_.eq_nbr
for j=1:M_.endo_nbr
if I2(j)
if I1(j)
if I0(j)
@ -325,7 +325,7 @@ else
end
end
fprintf(fid, ' JAC(:,%u:%u) = J(:,%u:%u);\n', DynareModel.endo_nbr+1, 2*DynareModel.endo_nbr, n0+n1+n2+1, n0+n1+n2+DynareModel.endo_nbr);
fprintf(fid, ' JAC(:,%u:%u) = J(:,%u:%u);\n', M_.endo_nbr+1, 2*M_.endo_nbr, n0+n1+n2+1, n0+n1+n2+M_.endo_nbr);
fprintf(fid,'end\n');
fclose(fid);

View File

@ -554,7 +554,7 @@ if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_meth
[xparam1, oo_, Woptflag] = mom.mode_compute_gmm_smm(xparam0, objective_function, oo_, M_, options_mom_, estim_params_, bayestopt_, Bounds);
% compute standard errors at mode
options_mom_.mom.vector_output = false; % make sure flag is reset
M_ = set_all_parameters(xparam1,estim_params_,M_); % update M_ and DynareResults (in particular to get oo_.mom.model_moments)
M_ = set_all_parameters(xparam1,estim_params_,M_); % update M_ and oo_ (in particular to get oo_.mom.model_moments)
if strcmp(options_mom_.mom.mom_method,'GMM') && options_mom_.mom.analytic_standard_errors
options_mom_.mom.compute_derivs = true; % for GMM we compute derivatives analytically in the objective function with this flag
end

View File

@ -1,11 +1,11 @@
function DynareModel = parameters(pacname, DynareModel, DynareOutput, verbose)
function M_ = parameters(pacname, M_, oo_, verbose)
% M_ = parameters(pacname, M_, oo_, verbose)
% Updates the parameters of a PAC equation.
%
% INPUTS
% - pacname [string] Name of the pac equation.
% - DynareModel [struct] M_ global structure (model properties)
% - DynareOutput [struct] oo_ global structure (model results)
% - M_ [struct] M_ global structure (model properties)
% - oo_ [struct] oo_ global structure (model results)
%
% OUTPUTS
% - none
@ -13,7 +13,7 @@ function DynareModel = parameters(pacname, DynareModel, DynareOutput, verbose)
% SPECIAL REQUIREMENTS
% none
% Copyright © 2018-2021 Dynare Team
% Copyright © 2018-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -40,27 +40,27 @@ if ~isrow(pacname)==1 || ~ischar(pacname)
end
% Check the name of the PAC model.
if ~isfield(DynareModel.pac, pacname)
if ~isfield(M_.pac, pacname)
error('PAC model %s is not defined in the model block!', pacname)
end
% Get PAC model description
pacmodel = DynareModel.pac.(pacname);
pacmodel = M_.pac.(pacname);
if pacmodel.model_consistent_expectations
error('This function cannot be used with Model Consistent Expectation. Try pac.mce.parameters instead.')
end
% Get the name of the associated auxiliary model (VAR or TREND_COMPONENT) model and test its existence.
if ~isfield(DynareModel.(pacmodel.auxiliary_model_type), pacmodel.auxiliary_model_name)
if ~isfield(M_.(pacmodel.auxiliary_model_type), pacmodel.auxiliary_model_name)
error('Unknown auxiliary model (%s) in PAC model (%s)!', pacmodel.auxiliary_model_name, pacname)
end
varmodel = DynareModel.(pacmodel.auxiliary_model_type).(pacmodel.auxiliary_model_name);
varmodel = M_.(pacmodel.auxiliary_model_type).(pacmodel.auxiliary_model_name);
% Check that we have the values of the VAR or TREND_COMPONENT matrices.
if ~isfield(DynareOutput.(pacmodel.auxiliary_model_type), pacmodel.auxiliary_model_name)
if ~isfield(oo_.(pacmodel.auxiliary_model_type), pacmodel.auxiliary_model_name)
error('Auxiliary model %s has to be estimated first!', pacmodel.auxiliary_model_name)
end
varcalib = DynareOutput.(pacmodel.auxiliary_model_type).(pacmodel.auxiliary_model_name);
varcalib = oo_.(pacmodel.auxiliary_model_type).(pacmodel.auxiliary_model_name);
if ~isfield(varcalib, 'CompanionMatrix') || any(isnan(varcalib.CompanionMatrix(:)))
error('Auxiliary model %s has to be estimated first.', pacmodel.auxiliary_model_name)
end
@ -79,13 +79,13 @@ else
end
% Build the vector of PAC parameters (ECM parameter + autoregressive parameters).
pacvalues = DynareModel.params([pacmodel.ec.params; pacmodel.ar.params(1:pacmodel.max_lag)']);
pacvalues = M_.params([pacmodel.ec.params; pacmodel.ar.params(1:pacmodel.max_lag)']);
% Get the indices for the stationary/nonstationary variables in the VAR system.
if numberofcomponents
id = cell(numberofcomponents, 1);
for i=1:numberofcomponents
id(i) = {find(strcmp(DynareModel.endo_names{pacmodel.components(i).endo_var}, varmodel.list_of_variables_in_companion_var))};
id(i) = {find(strcmp(M_.endo_names{pacmodel.components(i).endo_var}, varmodel.list_of_variables_in_companion_var))};
if isempty(id{i})
% Find the auxiliary variables if any
ad = find(cell2mat(cellfun(@(x) isauxiliary(x, [8 10]), varmodel.list_of_variables_in_companion_var, 'UniformOutput', false)));
@ -93,7 +93,7 @@ if numberofcomponents
error('Cannot find the trend variable in the Companion VAR/VECM model.')
else
for j=1:length(ad)
auxinfo = DynareModel.aux_vars(get_aux_variable_id(varmodel.list_of_variables_in_companion_var{ad(j)}));
auxinfo = M_.aux_vars(get_aux_variable_id(varmodel.list_of_variables_in_companion_var{ad(j)}));
if isequal(auxinfo.endo_index, pacmodel.components(i).endo_var)
id(i) = {ad(j)};
break
@ -110,7 +110,7 @@ if numberofcomponents
end
end
else
id = {find(strcmp(DynareModel.endo_names{pacmodel.ec.vars(pacmodel.ec.istarget)}, varmodel.list_of_variables_in_companion_var))};
id = {find(strcmp(M_.endo_names{pacmodel.ec.vars(pacmodel.ec.istarget)}, varmodel.list_of_variables_in_companion_var))};
if isempty(id{1})
% Find the auxiliary variables if any
ad = find(cell2mat(cellfun(@(x) isauxiliary(x, [8 10]), varmodel.list_of_variables_in_companion_var, 'UniformOutput', false)));
@ -118,7 +118,7 @@ else
error('Cannot find the trend variable in the Companion VAR/VECM model.')
else
for i=1:length(ad)
auxinfo = DynareModel.aux_vars(get_aux_variable_id(varmodel.list_of_variables_in_companion_var{ad(i)}));
auxinfo = M_.aux_vars(get_aux_variable_id(varmodel.list_of_variables_in_companion_var{ad(i)}));
if isequal(auxinfo.endo_index, pacmodel.ec.vars(pacmodel.ec.istarget))
id = {ad(i)};
break
@ -180,7 +180,7 @@ else
end
% Get the value of the discount factor.
beta = DynareModel.params(pacmodel.discount_index);
beta = M_.params(pacmodel.discount_index);
% Is growth argument passed to pac_expectation?
if isfield(pacmodel, 'growth_str')
@ -197,7 +197,7 @@ end
% Do we have rule of thumb agents? γ is the share of optimizing agents.
if isfield(pacmodel, 'non_optimizing_behaviour')
gamma = DynareModel.params(pacmodel.share_of_optimizing_agents_index);
gamma = M_.params(pacmodel.share_of_optimizing_agents_index);
else
gamma = 1.0;
end
@ -218,29 +218,29 @@ end
% Update M_.params with h
if isequal(pacmodel.auxiliary_model_type, 'var')
if DynareModel.var.(pacmodel.auxiliary_model_name).isconstant
if M_.var.(pacmodel.auxiliary_model_name).isconstant
if isfield(pacmodel, 'h_param_indices')
% No decomposition
DynareModel.params(pacmodel.h_param_indices) = h{1};
M_.params(pacmodel.h_param_indices) = h{1};
else
for i=1:numberofcomponents
DynareModel.params(pacmodel.components(i).h_param_indices) = h{i};
M_.params(pacmodel.components(i).h_param_indices) = h{i};
end
end
else
if isfield(pacmodel, 'h_param_indices')
% No decomposition
DynareModel.params(pacmodel.h_param_indices(1)) = .0;
DynareModel.params(pacmodel.h_param_indices(2:end)) = h{1};
M_.params(pacmodel.h_param_indices(1)) = .0;
M_.params(pacmodel.h_param_indices(2:end)) = h{1};
else
for i=1:numberofcomponents
DynareModel.params(pacmodel.components(i).h_param_indices(1)) = .0;
DynareModel.params(pacmodel.components(i).h_param_indices(2:end)) = h{i};
M_.params(pacmodel.components(i).h_param_indices(1)) = .0;
M_.params(pacmodel.components(i).h_param_indices(2:end)) = h{i};
end
end
end % If the auxiliary model (VAR) has no constant.
else
DynareModel.params(pacmodel.h_param_indices) = h{1};
M_.params(pacmodel.h_param_indices) = h{1};
end % if auxiliary model is a VAR
% Update the parameter related to the growth neutrality correction.
@ -263,7 +263,7 @@ if growth_flag
if isnan(pacmodel.optim_additive.params(i)) && islogical(pacmodel.optim_additive.bgp{i}) && pacmodel.optim_additive.bgp{i}
tmp0 = tmp0 + pacmodel.optim_additive.scaling_factor(i);
elseif ~isnan(pacmodel.optim_additive.params(i)) && islogical(pacmodel.optim_additive.bgp{i}) && pacmodel.optim_additive.bgp{i}
tmp0 = tmp0 + DynareModel.params(pacmodel.optim_additive.params(i))*pacmodel.optim_additive.scaling_factor(i);
tmp0 = tmp0 + M_.params(pacmodel.optim_additive.params(i))*pacmodel.optim_additive.scaling_factor(i);
elseif ~islogical(pacmodel.optim_additive.bgp{i})
error('It is not possible to provide a value for the mean of an exogenous variable appearing in the optimal part of the PAC equation.')
end
@ -279,7 +279,7 @@ if growth_flag
if isnan(pacmodel.non_optimizing_behaviour.params(i)) && islogical(pacmodel.non_optimizing_behaviour.bgp{i}) && pacmodel.non_optimizing_behaviour.bgp{i}
tmp0 = tmp0 + pacmodel.non_optimizing_behaviour.scaling_factor(i);
elseif ~isnan(pacmodel.non_optimizing_behaviour.params(i)) && islogical(pacmodel.non_optimizing_behaviour.bgp{i}) && pacmodel.non_optimizing_behaviour.bgp{i}
tmp0 = tmp0 + DynareModel.params(pacmodel.non_optimizing_behaviour.params(i))*pacmodel.non_optimizing_behaviour.scaling_factor(i);
tmp0 = tmp0 + M_.params(pacmodel.non_optimizing_behaviour.params(i))*pacmodel.non_optimizing_behaviour.scaling_factor(i);
elseif ~islogical(pacmodel.non_optimizing_behaviour.bgp{i}) && isnumeric(pacmodel.non_optimizing_behaviour.bgp{i}) && isnan(pacmodel.non_optimizing_behaviour.params(i))
tmp1 = tmp1 + pacmodel.non_optimizing_behaviour.scaling_factor(i)*pacmodel.non_optimizing_behaviour.bgp{i};
elseif ~islogical(pacmodel.non_optimizing_behaviour.bgp{i}) && isnumeric(pacmodel.non_optimizing_behaviour.bgp{i}) && ~isnan(pacmodel.non_optimizing_behaviour.params(i))
@ -298,7 +298,7 @@ if growth_flag
if isnan(pacmodel.additive.params(i)) && islogical(pacmodel.additive.bgp{i}) && pacmodel.additive.bgp{i}
tmp0 = tmp0 + pacmodel.additive.scaling_factor(i);
elseif ~isnan(pacmodel.additive.params(i)) && islogical(pacmodel.additive.bgp{i}) && pacmodel.additive.bgp{i}
tmp0 = tmp0 + DynareModel.params(pacmodel.additive.params(i))*pacmodel.additive.scaling_factor(i);
tmp0 = tmp0 + M_.params(pacmodel.additive.params(i))*pacmodel.additive.scaling_factor(i);
elseif ~islogical(pacmodel.additive.bgp{i}) && isnumeric(pacmodel.additive.bgp{i}) && isnan(pacmodel.additive.params(i))
tmp1 = tmp1 + pacmodel.additive.scaling_factor(i)*pacmodel.additive.bgp{i};
elseif ~islogical(pacmodel.additive.bgp{i}) && isnumeric(pacmodel.additive.bgp{i}) && ~isnan(pacmodel.additive.params(i))
@ -309,9 +309,9 @@ if growth_flag
ll = ll - tmp1/gamma; % TODO: ll should be added as a constant in the PAC equation (under the λ part) when unrolling pac_expectation.
end
if isfield(pacmodel, 'growth_neutrality_param_index')
DynareModel.params(pacmodel.growth_neutrality_param_index) = cc/gamma; % Multiplies the variable or expression provided though the growth option in command pac_model.
M_.params(pacmodel.growth_neutrality_param_index) = cc/gamma; % Multiplies the variable or expression provided though the growth option in command pac_model.
else
DynareModel.params(pacmodel.components(j).growth_neutrality_param_index) = cc/gamma; % Multiplies the variable or expression provided though the growth option in command pac_model.
M_.params(pacmodel.components(j).growth_neutrality_param_index) = cc/gamma; % Multiplies the variable or expression provided though the growth option in command pac_model.
end
end
end

View File

@ -1,19 +1,19 @@
function DynareModel = update_parameters(varexpectationmodelname, DynareModel, DynareOutput)
function M_ = update_parameters(varexpectationmodelname, M_, oo_)
% function M_ = update_parameters(varexpectationmodelname, M_, oo_)
% Updates the VAR expectation reduced form parameters.
%
% INPUTS
% - varexpectationmodelname [string] Name of the pac equation.
% - DynareModel [struct] M_ global structure (model properties)
% - DynareOutput [struct] oo_ global structure (model results)
% - M_ [struct] global structure (model properties)
% - oo_ [struct] oo_ global structure (model results)
%
% OUTPUTS
% - DynareModel [struct] M_ global structure (with updated params field)
% - M_ [struct] M_ global structure (with updated params field)
%
% SPECIAL REQUIREMENTS
% none
% Copyright © 2018-2021 Dynare Team
% Copyright © 2018-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -36,26 +36,26 @@ if ~isrow(varexpectationmodelname)==1 || ~ischar(varexpectationmodelname)
end
% Check that the model exists.
if ~isfield(DynareModel.var_expectation, varexpectationmodelname)
if ~isfield(M_.var_expectation, varexpectationmodelname)
error('VAR_EXPECTATION_MODEL %s is not defined!', varexpectationmodelname)
end
% Get the VAR model description
varexpectationmodel = DynareModel.var_expectation.(varexpectationmodelname);
varexpectationmodel = M_.var_expectation.(varexpectationmodelname);
% Get the name of the associated VAR model and test its existence.
if ~isfield(DynareModel.(varexpectationmodel.auxiliary_model_type), varexpectationmodel.auxiliary_model_name)
if ~isfield(M_.(varexpectationmodel.auxiliary_model_type), varexpectationmodel.auxiliary_model_name)
error('Unknown VAR (%s) in VAR_EXPECTATION_MODEL (%s)!', varexpectationmodel.auxiliary_model_name, varexpectationmodelname)
end
auxmodel = DynareModel.(varexpectationmodel.auxiliary_model_type).(varexpectationmodel.auxiliary_model_name);
auxmodel = M_.(varexpectationmodel.auxiliary_model_type).(varexpectationmodel.auxiliary_model_name);
% Check that we have the values of the VAR matrices.
if ~isfield(DynareOutput.(varexpectationmodel.auxiliary_model_type), varexpectationmodel.auxiliary_model_name)
if ~isfield(oo_.(varexpectationmodel.auxiliary_model_type), varexpectationmodel.auxiliary_model_name)
error('Auxiliary model %s has to be estimated or calibrated first!', varexpectationmodel.auxiliary_model_name)
end
auxcalib = DynareOutput.(varexpectationmodel.auxiliary_model_type).(varexpectationmodel.auxiliary_model_name);
auxcalib = oo_.(varexpectationmodel.auxiliary_model_type).(varexpectationmodel.auxiliary_model_name);
if ~isfield(auxcalib, 'CompanionMatrix') || any(isnan(auxcalib.CompanionMatrix(:)))
message = sprintf('Auxiliary model %s has to be estimated first.', varexpectationmodel.auxiliary_model_name);
@ -68,7 +68,7 @@ if isfield(varexpectationmodel, 'discount_value')
discountfactor = varexpectationmodel.discount_value;
else
if isfield(varexpectationmodel, 'discount_index')
discountfactor = DynareModel.params(varexpectationmodel.discount_index);
discountfactor = M_.params(varexpectationmodel.discount_index);
else
error('This is most likely a bug. Pleasse conntact the Dynare Team.')
end
@ -100,11 +100,11 @@ end
m = length(varexpectationmodel.expr.vars);
variables_id_in_var = NaN(m,1);
for i = 1:m
j = find(strcmp(auxmodel.list_of_variables_in_companion_var, DynareModel.endo_names{varexpectationmodel.expr.vars(i)}));
j = find(strcmp(auxmodel.list_of_variables_in_companion_var, M_.endo_names{varexpectationmodel.expr.vars(i)}));
if isempty(j)
error('Cannot find variable %s in the companion VAR', DynareModel.endo_names{varexpectationmodel.expr.vars(i)})
error('Cannot find variable %s in the companion VAR', M_.endo_names{varexpectationmodel.expr.vars(i)})
else
variables_id_in_var(i) = find(strcmp(auxmodel.list_of_variables_in_companion_var, DynareModel.endo_names{varexpectationmodel.expr.vars(i)}));
variables_id_in_var(i) = find(strcmp(auxmodel.list_of_variables_in_companion_var, M_.endo_names{varexpectationmodel.expr.vars(i)}));
end
end
@ -210,12 +210,12 @@ end
% Update reduced form parameters in M_.params.
if isequal(varexpectationmodel.auxiliary_model_type, 'var')
if DynareModel.var.(varexpectationmodel.auxiliary_model_name).isconstant
DynareModel.params(varexpectationmodel.param_indices) = parameters;
if M_.var.(varexpectationmodel.auxiliary_model_name).isconstant
M_.params(varexpectationmodel.param_indices) = parameters;
else
DynareModel.params(varexpectationmodel.param_indices(1)) = .0;
DynareModel.params(varexpectationmodel.param_indices(2:end)) = parameters;
M_.params(varexpectationmodel.param_indices(1)) = .0;
M_.params(varexpectationmodel.param_indices(2:end)) = parameters;
end
else
DynareModel.params(varexpectationmodel.param_indices) = parameters;
M_.params(varexpectationmodel.param_indices) = parameters;
end

View File

@ -25,11 +25,11 @@ classdef dprior
methods
function o = dprior(BayesInfo, PriorTrunc, Uniform)
function o = dprior(bayestopt_, PriorTrunc, Uniform)
% Class constructor.
%
% INPUTS
% - BayesInfo [struct] Informations about the prior distribution, aka bayestopt_.
% - bayestopt_ [struct] Informations about the prior distribution, aka bayestopt_.
% - PriorTrunc [double] scalar, probability mass to be excluded, aka options_.prior_trunc
% - Uniform [logical] scalar, produce uniform random deviates on the prior support.
%
@ -38,17 +38,17 @@ classdef dprior
%
% REQUIREMENTS
% None.
o.p6 = BayesInfo.p6;
o.p7 = BayesInfo.p7;
o.p3 = BayesInfo.p3;
o.p4 = BayesInfo.p4;
bounds = prior_bounds(BayesInfo, PriorTrunc);
o.p6 = bayestopt_.p6;
o.p7 = bayestopt_.p7;
o.p3 = bayestopt_.p3;
o.p4 = bayestopt_.p4;
bounds = prior_bounds(bayestopt_, PriorTrunc);
o.lb = bounds.lb;
o.ub = bounds.ub;
if nargin>2 && Uniform
prior_shape = repmat(5, length(o.p6), 1);
else
prior_shape = BayesInfo.pshape;
prior_shape = bayestopt_.pshape;
end
o.beta_index = find(prior_shape==1);
if ~isempty(o.beta_index)
@ -246,23 +246,23 @@ end % classdef --*-- Unit tests --*--
%$ end
%$ end
%$
%$ BayesInfo.pshape = p0;
%$ BayesInfo.p1 = p1;
%$ BayesInfo.p2 = p2;
%$ BayesInfo.p3 = p3;
%$ BayesInfo.p4 = p4;
%$ BayesInfo.p5 = p5;
%$ BayesInfo.p6 = p6;
%$ BayesInfo.p7 = p7;
%$ bayestopt_.pshape = p0;
%$ bayestopt_.p1 = p1;
%$ bayestopt_.p2 = p2;
%$ bayestopt_.p3 = p3;
%$ bayestopt_.p4 = p4;
%$ bayestopt_.p5 = p5;
%$ bayestopt_.p6 = p6;
%$ bayestopt_.p7 = p7;
%$
%$ ndraws = 1e5;
%$ m0 = BayesInfo.p1; %zeros(14,1);
%$ v0 = diag(BayesInfo.p2.^2); %zeros(14);
%$ m0 = bayestopt_.p1; %zeros(14,1);
%$ v0 = diag(bayestopt_.p2.^2); %zeros(14);
%$
%$ % Call the tested routine
%$ try
%$ % Instantiate dprior object
%$ o = dprior(BayesInfo, prior_trunc, false);
%$ o = dprior(bayestopt_, prior_trunc, false);
%$ % Do simulations in a loop and estimate recursively the mean and the variance.
%$ for i = 1:ndraws
%$ draw = o.draw();
@ -277,8 +277,8 @@ end % classdef --*-- Unit tests --*--
%$ end
%$
%$ if t(1)
%$ t(2) = all(abs(m0-BayesInfo.p1)<3e-3);
%$ t(3) = all(all(abs(v0-diag(BayesInfo.p2.^2))<5e-3));
%$ t(2) = all(abs(m0-bayestopt_.p1)<3e-3);
%$ t(3) = all(all(abs(v0-diag(bayestopt_.p2.^2))<5e-3));
%$ end
%$ T = all(t);
%@eof:1
@ -345,21 +345,21 @@ end % classdef --*-- Unit tests --*--
%$ end
%$ end
%$
%$ BayesInfo.pshape = p0;
%$ BayesInfo.p1 = p1;
%$ BayesInfo.p2 = p2;
%$ BayesInfo.p3 = p3;
%$ BayesInfo.p4 = p4;
%$ BayesInfo.p5 = p5;
%$ BayesInfo.p6 = p6;
%$ BayesInfo.p7 = p7;
%$ bayestopt_.pshape = p0;
%$ bayestopt_.p1 = p1;
%$ bayestopt_.p2 = p2;
%$ bayestopt_.p3 = p3;
%$ bayestopt_.p4 = p4;
%$ bayestopt_.p5 = p5;
%$ bayestopt_.p6 = p6;
%$ bayestopt_.p7 = p7;
%$
%$ ndraws = 1e5;
%$
%$ % Call the tested routine
%$ try
%$ % Instantiate dprior object.
%$ o = dprior(BayesInfo, prior_trunc, false);
%$ o = dprior(bayestopt_, prior_trunc, false);
%$ X = o.draws(ndraws);
%$ m = mean(X, 2);
%$ v = var(X, 0, 2);
@ -369,8 +369,8 @@ end % classdef --*-- Unit tests --*--
%$ end
%$
%$ if t(1)
%$ t(2) = all(abs(m-BayesInfo.p1)<3e-3);
%$ t(3) = all(all(abs(v-BayesInfo.p2.^2)<5e-3));
%$ t(2) = all(abs(m-bayestopt_.p1)<3e-3);
%$ t(3) = all(all(abs(v-bayestopt_.p2.^2)<5e-3));
%$ end
%$ T = all(t);
%@eof:2

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
@ -63,7 +63,7 @@ for i=1:M_.exo_nbr
end
% Set up initial conditions
[initialcondition, periods, innovations, DynareOptions, DynareModel, DynareOutput, endonames, exonames, dynamic_resid, dynamic_g1, y] = ...
[initialcondition, periods, innovations, options_local, M_local, oo_local, endonames, exonames, dynamic_resid, dynamic_g1, y] = ...
simul_backward_model_init(initialcondition, periods, options_, M_, oo_, zeros(periods, M_.exo_nbr));
% Get vector of indices for the selected endogenous variables.
@ -90,9 +90,9 @@ end
% Compute forecast without shock
if options_.linear
[ysim__0, errorflag] = simul_backward_linear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, dynamic_resid, dynamic_g1);
[ysim__0, errorflag] = simul_backward_linear_model_(initialcondition, periods, options_local, M_local, oo_local, innovations, dynamic_resid, dynamic_g1);
else
[ysim__0, errorflag] = simul_backward_nonlinear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, dynamic_resid, dynamic_g1);
[ysim__0, errorflag] = simul_backward_nonlinear_model_(initialcondition, periods, options_local, M_local, oo_local, innovations, dynamic_resid, dynamic_g1);
end
if errorflag
@ -110,9 +110,9 @@ if withuncertainty
for i=1:B
innovations = transpose(sigma*randn(M_.exo_nbr, periods));
if options_.linear
[ysim__, xsim__, errorflag] = simul_backward_linear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, dynamic_resid, dynamic_g1);
[ysim__, xsim__, errorflag] = simul_backward_linear_model_(initialcondition, periods, options_local, M_local, oo_local, innovations, dynamic_resid, dynamic_g1);
else
[ysim__, xsim__, errorflag] = simul_backward_nonlinear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, dynamic_resid, dynamic_g1);
[ysim__, xsim__, errorflag] = simul_backward_nonlinear_model_(initialcondition, periods, options_local, M_local, oo_local, innovations, dynamic_resid, dynamic_g1);
end
if errorflag
error('Simulation failed.')

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
@ -139,7 +139,7 @@ if ~isempty(innovationbaseline)
end
% Set up initial conditions
[initialcondition, periods, Innovations, DynareOptions, DynareModel, DynareOutput, endonames, exonames, dynamic_resid, dynamic_g1, y] = ...
[initialcondition, periods, Innovations, options_local, M_local, oo_local, endonames, exonames, dynamic_resid, dynamic_g1, y] = ...
simul_backward_model_init(initialcondition, periods, options_, M_, oo_, Innovations);
% Get the covariance matrix of the shocks.
@ -161,9 +161,9 @@ irfs = struct();
% Baseline paths (get transition paths induced by the initial condition and
% baseline innovations).
if options_.linear
[ysim__0, errorflag] = simul_backward_linear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, Innovations, dynamic_resid, dynamic_g1);
[ysim__0, errorflag] = simul_backward_linear_model_(initialcondition, periods, options_local, M_local, oo_local, Innovations, dynamic_resid, dynamic_g1);
else
[ysim__0, errorflag] = simul_backward_nonlinear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, Innovations, dynamic_resid, dynamic_g1);
[ysim__0, errorflag] = simul_backward_nonlinear_model_(initialcondition, periods, options_local, M_local, oo_local, Innovations, dynamic_resid, dynamic_g1);
end
if errorflag
@ -200,9 +200,9 @@ for i=1:length(listofshocks)
innovations(1,:) = innovations(1,:) + transpose(C(:,j));
end
if options_.linear
[ysim__1, errorflag] = simul_backward_linear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, dynamic_resid, dynamic_g1);
[ysim__1, errorflag] = simul_backward_linear_model_(initialcondition, periods, options_local, M_local, oo_local, innovations, dynamic_resid, dynamic_g1);
else
[ysim__1, errorflag] = simul_backward_nonlinear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, dynamic_resid, dynamic_g1);
[ysim__1, errorflag] = simul_backward_nonlinear_model_(initialcondition, periods, options_local, M_local, oo_local, innovations, dynamic_resid, dynamic_g1);
end
if errorflag
warning('Simulation failed. Cannot compute IRF for %s.', listofshocks{i})
@ -215,9 +215,9 @@ for i=1:length(listofshocks)
endo_simul__1 = feval(transform, ysim__1);
end
% Instantiate a dseries object (with all the endogenous variables)
alldeviations = dseries(transpose(endo_simul__1-endo_simul__0), initialcondition.init, endonames(1:M_.orig_endo_nbr), DynareModel.endo_names_tex(1:M_.orig_endo_nbr));
alldeviations = dseries(transpose(endo_simul__1-endo_simul__0), initialcondition.init, endonames(1:M_.orig_endo_nbr), M_local.endo_names_tex(1:M_.orig_endo_nbr));
if nargout>2
allirfs = dseries(transpose(endo_simul__1), initialcondition.init, endonames(1:M_.orig_endo_nbr), DynareModel.endo_names_tex(1:M_.orig_endo_nbr));
allirfs = dseries(transpose(endo_simul__1), initialcondition.init, endonames(1:M_.orig_endo_nbr), M_local.endo_names_tex(1:M_.orig_endo_nbr));
end
% Extract a sub-dseries object
if deterministicshockflag
@ -234,6 +234,6 @@ for i=1:length(listofshocks)
end
if nargout>1
baseline = dseries(transpose(endo_simul__0), initialcondition.init, endonames(1:M_.orig_endo_nbr), DynareModel.endo_names_tex(1:M_.orig_endo_nbr));
baseline = dseries(transpose(endo_simul__0), initialcondition.init, endonames(1:M_.orig_endo_nbr), M_local.endo_names_tex(1:M_.orig_endo_nbr));
baseline = merge(baseline, innovationbaseline);
end

View File

@ -1,5 +1,5 @@
function [residuals, info] = calibrateresiduals(dbase, info, DynareModel)
function [residuals, info] = calibrateresiduals(dbase, info, M_)
% [residuals, info] = calibrateresiduals(dbase, info, M_)
% Compute residuals in a backward model. Residuals are unobserved exogenous
% variables appearing additively in equations and without lags. An equation
% cannot have more than one residual, and a residual cannot appear in more
@ -8,7 +8,7 @@ function [residuals, info] = calibrateresiduals(dbase, info, DynareModel)
% INPUTS
% - dbase [dseries] Object containing all the endogenous and observed exogenous variables.
% - info [struct] Informations about the residuals.
% - DynareModel [struct] M_ as produced by the preprocessor.
% - M_ [struct] M_ as produced by the preprocessor.
%
% OUTPUTS
% - residuals [dseries] Object containing the identified residuals.
@ -38,13 +38,13 @@ function [residuals, info] = calibrateresiduals(dbase, info, DynareModel)
displayresidualsequationmapping = false;
% Get function handle for the dynamic model
dynamic_resid = str2func([DynareModel.fname,'.sparse.dynamic_resid']);
dynamic_resid = str2func([M_.fname,'.sparse.dynamic_resid']);
% Get data for all the endogenous variables.
ydata = dbase{info.endonames{:}}.data;
% Define function to retrieve an equation name
eqname = @(z) DynareModel.equations_tags{cellfun(@(x) x==z, DynareModel.equations_tags(:,1)) & cellfun(@(x) isequal(x, 'name'), DynareModel.equations_tags(:,2)),3};
eqname = @(z) M_.equations_tags{cellfun(@(x) x==z, M_.equations_tags(:,1)) & cellfun(@(x) isequal(x, 'name'), M_.equations_tags(:,2)),3};
% Get data for all the exogenous variables. Missing exogenous variables, to be solved for, have NaN values.
exogenousvariablesindbase = intersect(info.exonames, dbase.name);
@ -56,7 +56,7 @@ xdata = allexogenousvariables.data;
% Evaluate the dynamic equation
n = size(ydata, 2);
y = [ydata(1,:)'; ydata(2,:)'; NaN(n, 1)];
r = dynamic_resid(y, xdata(2,:), DynareModel.params, zeros(n, 1));
r = dynamic_resid(y, xdata(2,:), M_.params, zeros(n, 1));
% Check that the number of equations evaluating to NaN matches the number of residuals
idr = find(isnan(r));
@ -102,7 +102,7 @@ for i = 1:residuals.vobs
info.residualindex(i) = {strmatch(residualname, allexogenousvariables.name, 'exact')};
tmpxdata = xdata;
tmpxdata(2, info.residualindex{i}) = 0;
r = dynamic_resid(y, tmpxdata(2,:), DynareModel.params, zeros(n, 1));
r = dynamic_resid(y, tmpxdata(2,:), M_.params, zeros(n, 1));
info.equations(i) = { idr(find(~isnan(r(idr))))};
end
@ -130,7 +130,7 @@ xdata(:,cell2mat(info.residualindex)) = 0;
rdata = NaN(residuals.nobs, residuals.vobs);
for t=2:size(xdata, 1)
y = [ydata(t-1,:)'; ydata(t,:)'; NaN(n, 1)];
r = dynamic_resid(y, xdata(t,:), DynareModel.params, zeros(n, 1));
r = dynamic_resid(y, xdata(t,:), M_.params, zeros(n, 1));
rdata(t,:) = transpose(r(cell2mat(info.equations)));
end
residuals = dseries(rdata, dbase.init, info.residuals);

View File

@ -1,12 +1,12 @@
function [dbase, info] = checkdatabase(dbase, DynareModel, inversionflag, simulationflag)
function [dbase, info] = checkdatabase(dbase, M_, inversionflag, simulationflag)
% [dbase, info] = checkdatabase(dbase, M_, inversionflag, simulationflag)
% Check that dbase contains all the endogenous variables of the model, and
% reorder the endogenous variables as declared in the mod file. If Dynare
% adds auxiliary variables, for lags greater than 1 on endogenous variables,
% endogenous variables in difference (which may be lagged), or lags on the
% exogenous variables, then thee routine complete the database.
% Copyright © 2018-2021 Dynare Team
% Copyright © 2018-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -23,42 +23,42 @@ function [dbase, info] = checkdatabase(dbase, DynareModel, inversionflag, simula
% 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_endo_lead
% error('The model (%s) is assumed to be backward!', DynareModel.fname)
% if M_.maximum_endo_lead
% error('The model (%s) is assumed to be backward!', M_.fname)
% end
if nargin<3
inversionflag = false;
end
if exist(sprintf('+%s/dynamic_set_auxiliary_series.m', DynareModel.fname), 'file')
dbase = feval(sprintf('%s.dynamic_set_auxiliary_series', DynareModel.fname), dbase, DynareModel.params);
if exist(sprintf('+%s/dynamic_set_auxiliary_series.m', M_.fname), 'file')
dbase = feval(sprintf('%s.dynamic_set_auxiliary_series', M_.fname), dbase, M_.params);
end
listoflaggedexogenousvariables = {};
if ~isempty(DynareModel.aux_vars)
listoflaggedexogenousvariables = DynareModel.exo_names([DynareModel.aux_vars(find([DynareModel.aux_vars.type]==3)).orig_index]);
if ~isempty(M_.aux_vars)
listoflaggedexogenousvariables = M_.exo_names([M_.aux_vars(find([M_.aux_vars.type]==3)).orig_index]);
end
listoflaggedendogenousvariables = {};
laggedendogenousvariablesidx = find(DynareModel.lead_lag_incidence(1,1:DynareModel.orig_endo_nbr));
laggedendogenousvariablesidx = find(M_.lead_lag_incidence(1,1:M_.orig_endo_nbr));
if ~isempty(laggedendogenousvariablesidx)
listoflaggedendogenousvariables = DynareModel.endo_names(laggedendogenousvariablesidx);
listoflaggedendogenousvariables = M_.endo_names(laggedendogenousvariablesidx);
end
if ~isempty(DynareModel.aux_vars)
laggedendogenousvariablesidx = find([DynareModel.aux_vars.type]==1);
if ~isempty(M_.aux_vars)
laggedendogenousvariablesidx = find([M_.aux_vars.type]==1);
if ~isempty(laggedendogenousvariablesidx)
listoflaggedendogenousvariables = union(listoflaggedendogenousvariables, DynareModel.endo_names([DynareModel.aux_vars(laggedendogenousvariablesidx).orig_index]));
listoflaggedendogenousvariables = union(listoflaggedendogenousvariables, M_.endo_names([M_.aux_vars(laggedendogenousvariablesidx).orig_index]));
end
laggedendogenousvariablesidx = find([DynareModel.aux_vars.type]==8);
laggedendogenousvariablesidx = find([M_.aux_vars.type]==8);
if ~isempty(laggedendogenousvariablesidx)
listoflaggedendogenousvariables = union(listoflaggedendogenousvariables, DynareModel.endo_names([DynareModel.aux_vars(laggedendogenousvariablesidx).orig_index]));
listoflaggedendogenousvariables = union(listoflaggedendogenousvariables, M_.endo_names([M_.aux_vars(laggedendogenousvariablesidx).orig_index]));
end
end
info = struct;
info.endonames = DynareModel.endo_names;
info.exonames = DynareModel.exo_names;
info.endonames = M_.endo_names;
info.exonames = M_.exo_names;
info.computeresiduals = false;
% Check that all the endogenous variables are defined in dbase.

View File

@ -1,11 +1,11 @@
function [dbase, info] = checkdatabaseforinversion(dbase, DynareModel)
function [dbase, info] = checkdatabaseforinversion(dbase, M_)
% [dbase, info] = checkdatabaseforinversion(dbase, M_)
% Check that dbase contains all the endogenous variables of the model, and
% reorder the endogenous variables as declared in the mod file. If Dynare
% adds auxiliary variables, for lags greater than 1 on endogebnous variables
% or lags on the exogenous variables.
% Copyright © 2017-2018 Dynare Team
% Copyright © 2017-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -22,4 +22,4 @@ function [dbase, info] = checkdatabaseforinversion(dbase, DynareModel)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
[dbase, info] = checkdatabase(dbase, DynareModel, true, false);
[dbase, info] = checkdatabase(dbase, M_, true, false);

View File

@ -1,8 +1,8 @@
function l = get_lags_on_endogenous_variables(DynareModel)
function l = get_lags_on_endogenous_variables(M_)
% l = get_lags_on_endogenous_variables(M_)
% Returns a vector with the max lag for each endogenous variable.
% Copyright © 2017 Dynare Team
% Copyright © 2017-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -19,13 +19,13 @@ function l = get_lags_on_endogenous_variables(DynareModel)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
l = zeros(DynareModel.orig_endo_nbr, 1);
l(find(DynareModel.lead_lag_incidence(1,1:DynareModel.orig_endo_nbr))) = -1;
l = zeros(M_.orig_endo_nbr, 1);
l(find(M_.lead_lag_incidence(1,1:M_.orig_endo_nbr))) = -1;
if ~isempty(DynareModel.aux_vars)
aux_var_for_lagged_endogenous = find([DynareModel.aux_vars(:).type]==1);
if ~isempty(M_.aux_vars)
aux_var_for_lagged_endogenous = find([M_.aux_vars(:).type]==1);
for i=1:length(aux_var_for_lagged_endogenous)
l(DynareModel.aux_vars(aux_var_for_lagged_endogenous(i)).orig_index) = ...
DynareModel.aux_vars(aux_var_for_lagged_endogenous(i)).orig_lead_lag;
l(M_.aux_vars(aux_var_for_lagged_endogenous(i)).orig_index) = ...
M_.aux_vars(aux_var_for_lagged_endogenous(i)).orig_lead_lag;
end
end

View File

@ -1,8 +1,8 @@
function l = get_lags_on_exogenous_variables(DynareModel)
function l = get_lags_on_exogenous_variables(M_)
% l = get_lags_on_exogenous_variables(M_)
% Returns a vector with the max lag for each exogenous variable.
% Copyright © 2017 Dynare Team
% Copyright © 2017-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -19,12 +19,12 @@ function l = get_lags_on_exogenous_variables(DynareModel)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
l = zeros(DynareModel.exo_nbr, 1);
l = zeros(M_.exo_nbr, 1);
if ~isempty(DynareModel.aux_vars)
aux_var_for_lagged_exogenous = find([DynareModel.aux_vars(:).type]==3);
if ~isempty(M_.aux_vars)
aux_var_for_lagged_exogenous = find([M_.aux_vars(:).type]==3);
for i=1:length(aux_var_for_lagged_exogenous)
l(DynareModel.aux_vars(aux_var_for_lagged_exogenous(i)).orig_index) = ...
DynareModel.aux_vars(aux_var_for_lagged_exogenous(i)).orig_lead_lag-1;
l(M_.aux_vars(aux_var_for_lagged_exogenous(i)).orig_index) = ...
M_.aux_vars(aux_var_for_lagged_exogenous(i)).orig_lead_lag-1;
end
end

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

@ -12,8 +12,8 @@ function [simulation, errorflag] = simul_backward_model(initialconditions, sampl
% - 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

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,4 +1,4 @@
function check_dsge_var_model(Model, EstimatedParameters, BayesInfo)
function check_dsge_var_model(M_, estim_params_, bayestopt_)
% Check if the dsge model can be estimated with the DSGE-VAR approach.
@ -19,26 +19,26 @@ function check_dsge_var_model(Model, EstimatedParameters, BayesInfo)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if EstimatedParameters.nvn
if estim_params_.nvn
error('Estimation::DsgeVarLikelihood: Measurement errors are not allowed!')
end
if EstimatedParameters.ncn
if estim_params_.ncn
error('Estimation::DsgeVarLikelihood: Measurement errors are not allowed!')
end
if any(vec(Model.H))
if any(vec(M_.H))
error('Estimation::DsgeVarLikelihood: Measurement errors are not allowed!')
end
if EstimatedParameters.ncx
if estim_params_.ncx
error('Estimation::DsgeVarLikelihood: Structural innovations cannot be correlated using Dynare''s interface! Introduce the correlations in the model block instead.')
end
if Model.exo_nbr>1 && any(vec(tril(Model.Sigma_e,-1)))
if M_.exo_nbr>1 && any(vec(tril(M_.Sigma_e,-1)))
error('Estimation::DsgeVarLikelihood: Structural innovations cannot be correlated using Dynare''s interface! Introduce the correlations in the model block instead.')
end
if isequal(BayesInfo.with_trend,1)
if isequal(bayestopt_.with_trend,1)
error('Estimation::DsgeVarLikelihood: Linear trend is not yet implemented!')
end

View File

@ -61,7 +61,7 @@ if (size(estim_params_.var_endo,1) || size(estim_params_.corrn,1))
end
% Fill or update bayestopt_ structure
[xparam1, estim_params_, BayesOptions, lb, ub, Model] = set_prior(estim_params_, M_, options_);
[xparam1, estim_params_, BayesOptions, lb, ub, M_local] = set_prior(estim_params_, M_, options_);
% Set restricted state space
options_plot_priors_old=options_.plot_priors;
options_.plot_priors=0;
@ -77,27 +77,27 @@ if isempty(options_.qz_criterium)
changed_qz_criterium_flag = 1;
end
Model.dname = Model.fname;
M_local.dname = M_local.fname;
% Temporarly set options_.order equal to one
order = options_.order;
options_.order = 1;
if ismember('plot', varargin)
plot_priors(BayesOptions, Model, estim_params_, options_)
plot_priors(BayesOptions, M_local, estim_params_, options_)
donesomething = true;
end
if ismember('table', varargin)
print_table_prior(lb, ub, options_, Model, BayesOptions, estim_params_);
print_table_prior(lb, ub, options_, M_local, BayesOptions, estim_params_);
donesomething = true;
end
if ismember('simulate', varargin) % Prior simulations (BK).
if ismember('moments(distribution)', varargin)
results = prior_sampler(1, Model, BayesOptions, options_, oo_, estim_params_);
results = prior_sampler(1, M_local, BayesOptions, options_, oo_, estim_params_);
else
results = prior_sampler(0, Model, BayesOptions, options_, oo_, estim_params_);
results = prior_sampler(0, M_local, BayesOptions, options_, oo_, estim_params_);
end
% Display prior mass info
skipline(2)
@ -119,7 +119,7 @@ if ismember('simulate', varargin) % Prior simulations (BK).
end
if ismember('optimize', varargin) % Prior optimization.
optimize_prior(options_, Model, oo_, BayesOptions, estim_params_);
optimize_prior(options_, M_local, oo_, BayesOptions, estim_params_);
donesomething = true;
end
@ -130,16 +130,16 @@ if ismember('moments', varargin) % Prior simulations (2nd order moments).
k = find(isnan(xparam1));
xparam1(k) = BayesOptions.p1(k);
% Update vector of parameters and covariance matrices
Model = set_all_parameters(xparam1, estim_params_, Model);
M_local = set_all_parameters(xparam1, estim_params_, M_local);
% Check model.
check_model(Model);
check_model(M_local);
% Compute state space representation of the model.
oo__ = oo_;
oo__.dr = set_state_space(oo__.dr, Model);
oo__.dr = set_state_space(oo__.dr, M_local);
% Solve model
[T,R,~,info,oo__.dr, Model.params] = dynare_resolve(Model , options_ , oo__.dr, oo__.steady_state, oo__.exo_steady_state, oo__.exo_det_steady_state,'restrict');
[T,R,~,info,oo__.dr, M_local.params] = dynare_resolve(M_local , options_ , oo__.dr, oo__.steady_state, oo__.exo_steady_state, oo__.exo_det_steady_state,'restrict');
if ~info(1)
info=endogenous_prior_restrictions(T,R,Model , options__ , oo__.dr,oo__.steady_state,oo__.exo_steady_state,oo__.exo_det_steady_state);
info=endogenous_prior_restrictions(T,R,M_local , options__ , oo__.dr,oo__.steady_state,oo__.exo_steady_state,oo__.exo_det_steady_state);
end
if info
skipline()
@ -149,19 +149,19 @@ if ismember('moments', varargin) % Prior simulations (2nd order moments).
return
end
% Compute and display second order moments
oo__ = disp_th_moments(oo__.dr, [], Model, options__, oo__);
oo__ = disp_th_moments(oo__.dr, [], M_local, options__, oo__);
skipline(2)
donesomething = true;
end
if ismember('moments(distribution)', varargin) % Prior simulations (BK).
if ~ismember('simulate', varargin)
results = prior_sampler(1, Model, BayesOptions, options_, oo_, estim_params_);
results = prior_sampler(1, M_local, BayesOptions, options_, oo_, estim_params_);
end
priorpath = [Model.dname filesep() 'prior' filesep() 'draws' filesep()];
priorpath = [M_local.dname filesep() 'prior' filesep() 'draws' filesep()];
list_of_files = dir([priorpath 'prior_draws*']);
FirstOrderMoments = NaN(Model.orig_endo_nbr, options_.prior_mc);
SecondOrderMoments = NaN(Model.orig_endo_nbr, Model.orig_endo_nbr, options_.prior_mc);
FirstOrderMoments = NaN(M_local.orig_endo_nbr, options_.prior_mc);
SecondOrderMoments = NaN(M_local.orig_endo_nbr, M_local.orig_endo_nbr, options_.prior_mc);
iter = 1;
noprint = options_.noprint;
options_.noprint = 1;
@ -172,8 +172,8 @@ if ismember('moments(distribution)', varargin) % Prior simulations (BK).
dr = tmp.pdraws{j,3};
oo__ = oo_;
oo__.dr = dr;
Model=set_parameters_locally(Model,tmp.pdraws{j,1});% Needed to update the covariance matrix of the state innovations.
oo__ = disp_th_moments(oo__.dr, [], Model, options_, oo__);
M_local=set_parameters_locally(M_local,tmp.pdraws{j,1});% Needed to update the covariance matrix of the state innovations.
oo__ = disp_th_moments(oo__.dr, [], M_local, options_, oo__);
FirstOrderMoments(:,iter) = oo__.mean;
SecondOrderMoments(:,:,iter) = oo__.var;
iter = iter+1;

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,11 +1,11 @@
function disp_steady_state(M,oo,options)
% function disp_steady_state(M,oo,options)
function disp_steady_state(M_,oo_,options_)
% function disp_steady_state(M_,oo_,options_)
% computes and prints the steady state calculations
%
% INPUTS
% M structure of parameters
% oo structure of results
% options structure of options
% M_ structure of parameters
% oo_ structure of results
% options_ structure of options
%
% OUTPUTS
% none
@ -13,7 +13,7 @@ function disp_steady_state(M,oo,options)
% SPECIAL REQUIREMENTS
% none
% Copyright © 2001-2020 Dynare Team
% Copyright © 2001-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -31,15 +31,15 @@ function disp_steady_state(M,oo,options)
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
skipline()
if options.loglinear
if options_.loglinear
disp('STEADY-STATE RESULTS FOR THE UNLOGGED VARIABLES:')
else
disp('STEADY-STATE RESULTS:')
end
skipline()
endo_names = char(M.endo_names);
steady_state = oo.steady_state;
endo_names = char(M_.endo_names);
steady_state = oo_.steady_state;
for i = 1:M.orig_endo_nbr
for i = 1:M_.orig_endo_nbr
fprintf('%s \t\t %g\n', endo_names(i,:), steady_state(i));
end

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,15 +1,15 @@
function forecast = dyn_forecast(var_list,M,options,oo,task,dataset_info)
% function forecast = dyn_forecast(var_list,M,options,oo,task,dataset_info)
function forecast = dyn_forecast(var_list,M_,options_,oo_,task,dataset_info)
% function forecast = dyn_forecast(var_list,M_,options_,oo_,task,dataset_info)
% computes mean forecast for a given value of the parameters
% computes also confidence bands for the forecast
%
% INPUTS
% var_list: list of variables (character matrix)
% M: Dynare model structure
% options: Dynare options structure
% oo: Dynare results structure
% task: indicates how to initialize the forecast
% either 'simul' or 'smoother'
% var_list: list of variables (character matrix)
% M_: Dynare model structure
% options_: Dynare options structure
% oo_: Dynare results structure
% task: indicates how to initialize the forecast
% either 'simul' or 'smoother'
% dataset_info: Various informations about the dataset (descriptive statistics and missing observations).
% OUTPUTS
@ -27,7 +27,7 @@ function forecast = dyn_forecast(var_list,M,options,oo,task,dataset_info)
% SPECIAL REQUIREMENTS
% none
% Copyright © 2003-2022 Dynare Team
% Copyright © 2003-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -44,23 +44,23 @@ function forecast = dyn_forecast(var_list,M,options,oo,task,dataset_info)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if ~isfield(oo,'dr') || isempty(oo.dr)
if ~isfield(oo_,'dr') || isempty(oo_.dr)
error('dyn_forecast: the decision rules have not been computed. Did you forget a stoch_simul-command?')
end
if nargin<6 && options.prefilter
if nargin<6 && options_.prefilter
error('The prefiltering option is not allowed without providing a dataset')
elseif nargin==6
mean_varobs=dataset_info.descriptive.mean';
end
oo=make_ex_(M,options,oo);
oo_=make_ex_(M_,options_,oo_);
maximum_lag = M.maximum_lag;
maximum_lag = M_.maximum_lag;
endo_names = M.endo_names;
endo_names = M_.endo_names;
if isempty(var_list)
var_list = endo_names(1:M.orig_endo_nbr);
var_list = endo_names(1:M_.orig_endo_nbr);
end
i_var = [];
for i = 1:length(var_list)
@ -76,108 +76,108 @@ n_var = length(i_var);
trend = 0;
switch task
case 'simul'
horizon = options.periods;
horizon = options_.periods;
if horizon == 0
horizon = 5;
end
if isempty(M.endo_histval)
if options.loglinear && ~options.logged_steady_state
y0 = repmat(log(oo.dr.ys),1,maximum_lag);
if isempty(M_.endo_histval)
if options_.loglinear && ~options_.logged_steady_state
y0 = repmat(log(oo_.dr.ys),1,maximum_lag);
else
y0 = repmat(oo.dr.ys,1,maximum_lag);
y0 = repmat(oo_.dr.ys,1,maximum_lag);
end
else
if options.loglinear
y0 = log_variable(1:M.endo_nbr,M.endo_histval,M);
if options_.loglinear
y0 = log_variable(1:M_.endo_nbr,M_.endo_histval,M_);
else
y0 = M.endo_histval;
y0 = M_.endo_histval;
end
end
case 'smoother'
horizon = options.forecast;
if isnan(options.first_obs)
horizon = options_.forecast;
if isnan(options_.first_obs)
first_obs=1;
else
first_obs=options.first_obs;
first_obs=options_.first_obs;
end
if isfield(oo.SmoothedVariables,'Mean')
y_smoothed = oo.SmoothedVariables.Mean;
if isfield(oo_.SmoothedVariables,'Mean')
y_smoothed = oo_.SmoothedVariables.Mean;
else
y_smoothed = oo.SmoothedVariables;
y_smoothed = oo_.SmoothedVariables;
end
y0 = zeros(M.endo_nbr,maximum_lag);
for i = 1:M.endo_nbr
v_name = M.endo_names{i};
y0 = zeros(M_.endo_nbr,maximum_lag);
for i = 1:M_.endo_nbr
v_name = M_.endo_names{i};
y0(i,:) = y_smoothed.(v_name)(end-maximum_lag+1:end); %includes steady state or mean, but simult_ will subtract only steady state
% 2. Subtract mean/steady state and add steady state; takes care of prefiltering
if isfield(oo.Smoother,'Constant') && isfield(oo.Smoother.Constant,v_name)
y0(i,:)=y0(i,:)-oo.Smoother.Constant.(v_name)(end-maximum_lag+1:end); %subtract mean or steady state
if options.loglinear
y0(i,:)=y0(i,:)+log_variable(i,oo.dr.ys,M);
if isfield(oo_.Smoother,'Constant') && isfield(oo_.Smoother.Constant,v_name)
y0(i,:)=y0(i,:)-oo_.Smoother.Constant.(v_name)(end-maximum_lag+1:end); %subtract mean or steady state
if options_.loglinear
y0(i,:)=y0(i,:)+log_variable(i,oo_.dr.ys,M_);
else
y0(i,:)=y0(i,:)+oo.dr.ys(strmatch(v_name, M.endo_names, 'exact'));
y0(i,:)=y0(i,:)+oo_.dr.ys(strmatch(v_name, M_.endo_names, 'exact'));
end
end
% 2. Subtract trend
if isfield(oo.Smoother,'Trend') && isfield(oo.Smoother.Trend,v_name)
y0(i,:)=y0(i,:)-oo.Smoother.Trend.(v_name)(end-maximum_lag+1:end); %subtract trend, which is not subtracted by simult_
if isfield(oo_.Smoother,'Trend') && isfield(oo_.Smoother.Trend,v_name)
y0(i,:)=y0(i,:)-oo_.Smoother.Trend.(v_name)(end-maximum_lag+1:end); %subtract trend, which is not subtracted by simult_
end
end
gend = options.nobs;
if isfield(oo.Smoother,'TrendCoeffs')
var_obs = options.varobs;
endo_names = M.endo_names;
gend = options_.nobs;
if isfield(oo_.Smoother,'TrendCoeffs')
var_obs = options_.varobs;
endo_names = M_.endo_names;
i_var_obs = [];
trend_coeffs = [];
for i=1:length(var_obs)
tmp = strmatch(var_obs{i}, endo_names(i_var), 'exact');
trend_var_index = strmatch(var_obs{i}, M.endo_names, 'exact');
trend_var_index = strmatch(var_obs{i}, M_.endo_names, 'exact');
if ~isempty(tmp)
i_var_obs = [ i_var_obs; tmp];
trend_coeffs = [trend_coeffs; oo.Smoother.TrendCoeffs(trend_var_index)];
trend_coeffs = [trend_coeffs; oo_.Smoother.TrendCoeffs(trend_var_index)];
end
end
if ~isempty(trend_coeffs)
trend = trend_coeffs*(first_obs+gend-1+(1-M.maximum_lag:horizon));
if options.prefilter
trend = trend_coeffs*(first_obs+gend-1+(1-M_.maximum_lag:horizon));
if options_.prefilter
trend = trend - repmat(mean(trend_coeffs*[first_obs:first_obs+gend-1],2),1,horizon+1); %subtract mean trend
end
end
else
trend_coeffs=zeros(length(options.varobs),1);
trend_coeffs=zeros(length(options_.varobs),1);
end
otherwise
error('Wrong flag value')
end
if M.exo_det_nbr == 0
if isequal(M.H,0)
[yf,int_width] = forcst(oo.dr,y0,horizon,var_list,M,oo,options);
if M_.exo_det_nbr == 0
if isequal(M_.H,0)
[yf,int_width] = forcst(oo_.dr,y0,horizon,var_list,M_,oo_,options_);
else
[yf,int_width,int_width_ME] = forcst(oo.dr,y0,horizon,var_list,M,oo,options);
[yf,int_width,int_width_ME] = forcst(oo_.dr,y0,horizon,var_list,M_,oo_,options_);
end
else
exo_det_length = size(oo.exo_det_simul,1)-M.maximum_lag;
exo_det_length = size(oo_.exo_det_simul,1)-M_.maximum_lag;
if horizon > exo_det_length
ex = zeros(horizon,M.exo_nbr);
oo.exo_det_simul = [ oo.exo_det_simul;...
repmat(oo.exo_det_steady_state',...
ex = zeros(horizon,M_.exo_nbr);
oo_.exo_det_simul = [ oo_.exo_det_simul;...
repmat(oo_.exo_det_steady_state',...
horizon- ...
exo_det_length,1)];
elseif horizon <= exo_det_length
ex = zeros(exo_det_length,M.exo_nbr);
ex = zeros(exo_det_length,M_.exo_nbr);
end
if options.linear
if options_.linear
iorder = 1;
else
iorder = options.order;
iorder = options_.order;
end
if isequal(M.H,0)
[yf,int_width] = simultxdet(y0,ex,oo.exo_det_simul,...
iorder,var_list,M,oo,options);
if isequal(M_.H,0)
[yf,int_width] = simultxdet(y0,ex,oo_.exo_det_simul,...
iorder,var_list,M_,oo_,options_);
else
[yf,int_width,int_width_ME] = simultxdet(y0,ex,oo.exo_det_simul,...
iorder,var_list,M,oo,options);
[yf,int_width,int_width_ME] = simultxdet(y0,ex,oo_.exo_det_simul,...
iorder,var_list,M_,oo_,options_);
end
end
@ -185,13 +185,13 @@ if ~isscalar(trend) %add trend back to forecast
yf(i_var_obs,:) = yf(i_var_obs,:) + trend;
end
if options.loglinear
if options.prefilter == 1 %subtract steady state and add mean for observables
yf(i_var_obs,:)=yf(i_var_obs,:)-repmat(log(oo.dr.ys(i_var_obs)),1,horizon+M.maximum_lag)+ repmat(mean_varobs,1,horizon+M.maximum_lag);
if options_.loglinear
if options_.prefilter == 1 %subtract steady state and add mean for observables
yf(i_var_obs,:)=yf(i_var_obs,:)-repmat(log(oo_.dr.ys(i_var_obs)),1,horizon+M_.maximum_lag)+ repmat(mean_varobs,1,horizon+M_.maximum_lag);
end
else
if options.prefilter == 1 %subtract steady state and add mean for observables
yf(i_var_obs,:)=yf(i_var_obs,:)-repmat(oo.dr.ys(i_var_obs),1,horizon+M.maximum_lag)+ repmat(mean_varobs,1,horizon+M.maximum_lag);
if options_.prefilter == 1 %subtract steady state and add mean for observables
yf(i_var_obs,:)=yf(i_var_obs,:)-repmat(oo_.dr.ys(i_var_obs),1,horizon+M_.maximum_lag)+ repmat(mean_varobs,1,horizon+M_.maximum_lag);
end
end
@ -200,17 +200,17 @@ for i=1:n_var
forecast.Mean.(vname) = yf(i,maximum_lag+(1:horizon))';
forecast.HPDinf.(vname)= yf(i,maximum_lag+(1:horizon))' - int_width(1:horizon,i);
forecast.HPDsup.(vname) = yf(i,maximum_lag+(1:horizon))' + int_width(1:horizon,i);
if ~isequal(M.H,0) && ismember(var_list{i},options.varobs)
if ~isequal(M_.H,0) && ismember(var_list{i},options_.varobs)
forecast.HPDinf_ME.(vname)= yf(i,maximum_lag+(1:horizon))' - int_width_ME(1:horizon,i);
forecast.HPDsup_ME.(vname) = yf(i,maximum_lag+(1:horizon))' + int_width_ME(1:horizon,i);
end
end
for i=1:M.exo_det_nbr
forecast.Exogenous.(M.exo_det_names{i}) = oo.exo_det_simul(maximum_lag+(1:horizon),i);
for i=1:M_.exo_det_nbr
forecast.Exogenous.(M_.exo_det_names{i}) = oo_.exo_det_simul(maximum_lag+(1:horizon),i);
end
if ~options.nograph
oo.forecast = forecast;
forecast_graphs(var_list, M, oo, options)
if ~options_.nograph
oo_.forecast = forecast;
forecast_graphs(var_list, M_, oo_, options_)
end

View File

@ -1,11 +1,11 @@
function [lnpriormom] = endogenous_prior(data,dataset_info, Pstar,BayesInfo,H)
function [lnpriormom] = endogenous_prior(data,dataset_info, Pstar,bayestopt_,H)
% Computes the endogenous log prior addition to the initial prior
%
% INPUTS
% data [double] n*T vector of data observations
% dataset_info [structure] various information about the dataset
% Pstar [double] k*k matrix of
% BayesInfo [structure]
% bayestopt_ [structure]
%
% OUTPUTS
% lnpriormom [double] scalar of log endogenous prior value
@ -80,7 +80,7 @@ Shat=C0 +(1-1/(2+1))*(C1+C1')...
+(1-2/(2+1))*(C2+C2');
% Model variances below:
mf=BayesInfo.mf1;
mf=bayestopt_.mf1;
II=eye(size(Pstar,2));
Z=II(mf,:);
% This is Ftheta, variance of model variables, given param vector theta:

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

@ -1,15 +1,33 @@
function e = ep_accuracy_check(M,options,oo)
function e = ep_accuracy_check(M_,options_,oo_)
% e = ep_accuracy_check(M_,options_,oo_)
endo_simul = oo.endo_simul;
% Copyright © 2016-2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
endo_simul = oo_.endo_simul;
n = size(endo_simul,2);
[initialconditions, innovations, pfm, ep, verbosity, options, oo] = ...
extended_path_initialization([], n-1, [], options, M, oo);
[initialconditions, innovations, pfm, ep, verbosity, options_, oo_] = ...
extended_path_initialization([], n-1, [], options_, M_, oo_);
options.ep.accuracy.stochastic.order = options.ep.stochastic.order;
[nodes,weights,nnodes] = setup_integration_nodes(options.ep.accuracy,pfm);
options_.ep.accuracy.stochastic.order = options_.ep.stochastic.order;
[nodes,weights,nnodes] = setup_integration_nodes(options_.ep.accuracy,pfm);
e = zeros(M.endo_nbr,n);
e = zeros(M_.endo_nbr,n);
for i=1:n
e(:,i) = euler_equation_error(endo_simul(:,i),oo.exo_simul, ...
innovations, M, options,oo,pfm,nodes,weights);
e(:,i) = euler_equation_error(endo_simul(:,i),oo_.exo_simul, ...
innovations, M_, options_,oo_,pfm,nodes,weights);
end

View File

@ -55,9 +55,9 @@ solve_algo:
stack_solve_algo:
ut: (unscented free parameter)
pfm.stochastic_order = DynareOptions.ep.stochastic.order;
pfm.periods = DynareOptions.ep.periods;
pfm.verbose = DynareOptions.ep.verbosity;
pfm.stochastic_order = options_.ep.stochastic.order;
pfm.periods = options_.ep.periods;
pfm.verbose = options_.ep.verbosity;
* in extended_path_core, one passes options.ep and individual options

View File

@ -1,6 +1,7 @@
function e = euler_equation_error(y0,x,innovations,M,options,oo,pfm,nodes,weights)
function e = euler_equation_error(y0,x,innovations,M_,options_,oo_,pfm,nodes,weights)
% e = euler_equation_error(y0,x,innovations,M_,options_,oo_,pfm,nodes,weights)
% Copyright © 2016-2020 Dynare Team
% Copyright © 2016-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -17,34 +18,34 @@ function e = euler_equation_error(y0,x,innovations,M,options,oo,pfm,nodes,weight
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
dynamic_model = str2func([M.fname '.dynamic']);
ep = options.ep;
dynamic_model = str2func([M_.fname '.dynamic']);
ep = options_.ep;
[y1, info_convergence, endogenousvariablespaths] = extended_path_core(ep.periods, ...
M.endo_nbr, M.exo_nbr, ...
M_.endo_nbr, M_.exo_nbr, ...
innovations.positive_var_indx, ...
x, ep.init, y0, oo.steady_state, ...
x, ep.init, y0, oo_.steady_state, ...
0, ...
ep.stochastic.order, M, ...
ep.stochastic.order, M_, ...
pfm, ep.stochastic.algo, ...
ep.solve_algo, ...
ep.stack_solve_algo, ...
options.lmmcp, options, oo, ...
options_.lmmcp, options_, oo_, ...
[]);
i_pred = find(M.lead_lag_incidence(1,:));
i_fwrd = find(M.lead_lag_incidence(3,:));
x1 = [x(2:end,:); zeros(1,M.exo_nbr)];
i_pred = find(M_.lead_lag_incidence(1,:));
i_fwrd = find(M_.lead_lag_incidence(3,:));
x1 = [x(2:end,:); zeros(1,M_.exo_nbr)];
for i=1:length(nodes)
x2 = x1;
x2(2,:) = x2(2,:) + nodes(i,:);
[y2, info_convergence, endogenousvariablespaths] = ...
extended_path_core(ep.periods, M.endo_nbr, M.exo_nbr, ...
extended_path_core(ep.periods, M_.endo_nbr, M_.exo_nbr, ...
innovations.positive_var_indx, x2, ep.init, ...
y1, oo.steady_state, 0, ...
ep.stochastic.order, M, pfm, ep.stochastic.algo, ...
ep.solve_algo, ep.stack_solve_algo, options.lmmcp, ...
options, oo, []);
y1, oo_.steady_state, 0, ...
ep.stochastic.order, M_, pfm, ep.stochastic.algo, ...
ep.solve_algo, ep.stack_solve_algo, options_.lmmcp, ...
options_, oo_, []);
z = [y0(i_pred); y1; y2(i_fwrd)];
res(:,i) = dynamic_model(z,x,M.params,oo.steady_state,2);
res(:,i) = dynamic_model(z,x,M_.params,oo_.steady_state,2);
end
e = res*weights;

View File

@ -1,5 +1,5 @@
function [ts, DynareResults] = extended_path(initialconditions, samplesize, exogenousvariables, DynareOptions, DynareModel, DynareResults)
function [ts, oo_] = extended_path(initialconditions, samplesize, exogenousvariables, options_, M_, oo_)
% [ts, oo_] = extended_path(initialconditions, samplesize, exogenousvariables, options_, M_, oo_)
% Stochastic simulation of a non linear DSGE model using the Extended Path method (Fair and Taylor 1983). A time
% series of size T is obtained by solving T perfect foresight models.
%
@ -7,9 +7,9 @@ function [ts, DynareResults] = extended_path(initialconditions, samplesize, exog
% o initialconditions [double] m*1 array, where m is the number of endogenous variables in the model.
% o samplesize [integer] scalar, size of the sample to be simulated.
% o exogenousvariables [double] T*n array, values for the structural innovations.
% o DynareOptions [struct] options_
% o DynareModel [struct] M_
% o DynareResults [struct] oo_
% o options_ [struct] options_
% o M_ [struct] Dynare's model structure
% o oo_ [struct] Dynare's results structure
%
% OUTPUTS
% o ts [dseries] m*samplesize array, the simulations.
@ -36,13 +36,13 @@ function [ts, DynareResults] = extended_path(initialconditions, samplesize, exog
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
[initialconditions, innovations, pfm, ep, verbosity, DynareOptions, DynareResults] = ...
extended_path_initialization(initialconditions, samplesize, exogenousvariables, DynareOptions, DynareModel, DynareResults);
[initialconditions, innovations, pfm, ep, verbosity, options_, oo_] = ...
extended_path_initialization(initialconditions, samplesize, exogenousvariables, options_, M_, oo_);
[shocks, spfm_exo_simul, innovations, DynareResults] = extended_path_shocks(innovations, ep, exogenousvariables, samplesize,DynareModel,DynareOptions,DynareResults);
[shocks, spfm_exo_simul, innovations, oo_] = extended_path_shocks(innovations, ep, exogenousvariables, samplesize,M_,options_,oo_);
% Initialize the matrix for the paths of the endogenous variables.
endogenous_variables_paths = NaN(DynareModel.endo_nbr,samplesize+1);
endogenous_variables_paths = NaN(M_.endo_nbr,samplesize+1);
endogenous_variables_paths(:,1) = initialconditions;
% Set waitbar (graphic or text mode)
@ -63,18 +63,18 @@ while (t <= samplesize)
if t>2
% Set initial guess for the solver (using the solution of the
% previous period problem).
initialguess = [endogenousvariablespaths(:, 2:end), DynareResults.steady_state];
initialguess = [endogenousvariablespaths(:, 2:end), oo_.steady_state];
else
initialguess = [];
end
[endogenous_variables_paths(:,t), info_convergence, endogenousvariablespaths] = extended_path_core(ep.periods, DynareModel.endo_nbr, DynareModel.exo_nbr, innovations.positive_var_indx, ...
[endogenous_variables_paths(:,t), info_convergence, endogenousvariablespaths] = extended_path_core(ep.periods, M_.endo_nbr, M_.exo_nbr, innovations.positive_var_indx, ...
spfm_exo_simul, ep.init, endogenous_variables_paths(:,t-1), ...
DynareResults.steady_state, ...
oo_.steady_state, ...
verbosity, ep.stochastic.order, ...
DynareModel, pfm, ep.stochastic.algo, ep.solve_algo, ep.stack_solve_algo, ...
DynareOptions.lmmcp, ...
DynareOptions, ...
DynareResults, initialguess);
M_, pfm, ep.stochastic.algo, ep.solve_algo, ep.stack_solve_algo, ...
options_.lmmcp, ...
options_, ...
oo_, initialguess);
if ~info_convergence
msg = sprintf('No convergence of the (stochastic) perfect foresight solver (in period %s)!', int2str(t));
warning(msg)
@ -86,13 +86,13 @@ end % (while) loop over t
dyn_waitbar_close(hh_fig);
% Set the initial period.
if isdates(DynareOptions.initial_period)
if ischar(DynareOptions.initial_period)
initial_period = dates(DynareOptions.initial_period);
if isdates(options_.initial_period)
if ischar(options_.initial_period)
initial_period = dates(options_.initial_period);
else
initial_period = DynareOptions.initial_period;
initial_period = options_.initial_period;
end
elseif isnan(DynareOptions.initial_period)
elseif isnan(options_.initial_period)
initial_period = dates(1,1);
else
error('Type of option initial_period is wrong.')
@ -104,11 +104,11 @@ if any(isnan(endogenous_variables_paths(:)))
nn = size(endogenous_variables_paths, 1);
endogenous_variables_paths = reshape(endogenous_variables_paths(sl), nn, length(sl)/nn);
end
ts = dseries(transpose(endogenous_variables_paths), initial_period, DynareModel.endo_names);
ts = dseries(transpose(endogenous_variables_paths), initial_period, M_.endo_names);
DynareResults.endo_simul = transpose(ts.data);
oo_.endo_simul = transpose(ts.data);
assignin('base', 'Simulated_time_series', ts);
if ~nargout || nargout<2
assignin('base', 'oo_', DynareResults);
assignin('base', 'oo_', oo_);
end

View File

@ -1,8 +1,8 @@
function [y, info_convergence, endogenousvariablespaths] = extended_path_core(periods,endo_nbr,exo_nbr,positive_var_indx, ...
exo_simul,init,initial_conditions,...
steady_state, ...
debug,order,M,pfm,algo,solve_algo,stack_solve_algo,...
olmmcp,options,oo,initialguess)
debug,order,M_,pfm,algo,solve_algo,stack_solve_algo,...
olmmcp,options_,oo_,initialguess)
% Copyright © 2016-2023 Dynare Team
%
@ -21,10 +21,10 @@ function [y, info_convergence, endogenousvariablespaths] = extended_path_core(pe
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
ep = options.ep;
ep = options_.ep;
if init% Compute first order solution (Perturbation)...
endo_simul = simult_(M,options,initial_conditions,oo.dr,exo_simul(2:end,:),1);
endo_simul = simult_(M_,options_,initial_conditions,oo_.dr,exo_simul(2:end,:),1);
else
if nargin==19 && ~isempty(initialguess)
% Note that the first column of initialguess should be equal to initial_conditions.
@ -34,29 +34,29 @@ else
end
end
oo.endo_simul = endo_simul;
oo_.endo_simul = endo_simul;
if debug
save ep_test_1.mat endo_simul exo_simul
end
if options.bytecode && order > 0
if options_.bytecode && order > 0
error('Option order > 0 of extended_path command is not compatible with bytecode option.')
end
if options.block && order > 0
if options_.block && order > 0
error('Option order > 0 of extended_path command is not compatible with block option.')
end
if order == 0
options.periods = periods;
options.block = pfm.block;
oo.endo_simul = endo_simul;
oo.exo_simul = exo_simul;
oo.steady_state = steady_state;
options.lmmcp = olmmcp;
options.solve_algo = solve_algo;
options.stack_solve_algo = stack_solve_algo;
[endogenousvariablespaths, info_convergence] = perfect_foresight_solver_core(oo.endo_simul, oo.exo_simul, oo.steady_state, oo.exo_steady_state, M, options);
options_.periods = periods;
options_.block = pfm.block;
oo_.endo_simul = endo_simul;
oo_.exo_simul = exo_simul;
oo_.steady_state = steady_state;
options_.lmmcp = olmmcp;
options_.solve_algo = solve_algo;
options_.stack_solve_algo = stack_solve_algo;
[endogenousvariablespaths, info_convergence] = perfect_foresight_solver_core(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, oo_.exo_steady_state, M_, options_);
else
switch(algo)
case 0
@ -64,13 +64,13 @@ else
solve_stochastic_perfect_foresight_model(endo_simul, exo_simul, pfm, ep.stochastic.quadrature.nodes, ep.stochastic.order);
case 1
[flag, endogenousvariablespaths] = ...
solve_stochastic_perfect_foresight_model_1(endo_simul, exo_simul, options, pfm, ep.stochastic.order);
solve_stochastic_perfect_foresight_model_1(endo_simul, exo_simul, options_, pfm, ep.stochastic.order);
end
info_convergence = ~flag;
end
if ~info_convergence && ~options.no_homotopy
[info_convergence, endogenousvariablespaths] = extended_path_homotopy(endo_simul, exo_simul, M, options, oo, pfm, ep, order, algo, 2, debug);
if ~info_convergence && ~options_.no_homotopy
[info_convergence, endogenousvariablespaths] = extended_path_homotopy(endo_simul, exo_simul, M_, options_, oo_, pfm, ep, order, algo, 2, debug);
end
if info_convergence

View File

@ -1,4 +1,4 @@
function [info_convergence, endo_simul] = extended_path_homotopy(endo_simul, exo_simul, M, options, oo, pfm, ep, order, algo, method, debug)
function [info_convergence, endo_simul] = extended_path_homotopy(endo_simul, exo_simul, M_, options_, oo_, pfm, ep, order, algo, method, debug)
% Copyright © 2016-2023 Dynare Team
%
@ -31,11 +31,11 @@ if ismember(method, [1, 2])
oldweight = weight;
while noconvergence
iteration = iteration + 1;
oo.endo_simul = endo_simul;
oo.endo_simul(:,1) = oo.steady_state + weight*(endo_simul0(:,1) - oo.steady_state);
oo.exo_simul = bsxfun(@plus, weight*exo_simul, (1-weight)*transpose(oo.exo_steady_state));
oo_.endo_simul = endo_simul;
oo_.endo_simul(:,1) = oo_.steady_state + weight*(endo_simul0(:,1) - oo_.steady_state);
oo_.exo_simul = bsxfun(@plus, weight*exo_simul, (1-weight)*transpose(oo_.exo_steady_state));
if order==0
[endo_simul_new, success] = perfect_foresight_solver_core(oo.endo_simul, oo.exo_simul, oo.steady_state, oo.exo_steady_state, M, options);
[endo_simul_new, success] = perfect_foresight_solver_core(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, oo_.exo_steady_state, M_, options_);
else
switch(algo)
case 0
@ -43,7 +43,7 @@ if ismember(method, [1, 2])
solve_stochastic_perfect_foresight_model(endo_simul, exo_simul, pfm, ep.stochastic.quadrature.nodes, ep.stochastic.order);
case 1
[flag, endo_simul_new] = ...
solve_stochastic_perfect_foresight_model_1(endo_simul, exo_simul, options, pfm, ep.stochastic.order);
solve_stochastic_perfect_foresight_model_1(endo_simul, exo_simul, options_, pfm, ep.stochastic.order);
end
end
if isequal(order, 0)
@ -99,10 +99,10 @@ if isequal(method, 3) || (isequal(method, 2) && noconvergence)
nweights = length(weights);
while noconvergence
weight = weights(index);
oo.endo_simul = endo_simul;
oo.exo_simul = bsxfun(@plus, weight*exo_simul, (1-weight)*transpose(oo.exo_steady_state));
oo_.endo_simul = endo_simul;
oo_.exo_simul = bsxfun(@plus, weight*exo_simul, (1-weight)*transpose(oo_.exo_steady_state));
if order==0
[endo_simul_new, success] = perfect_foresight_solver_core(oo.endo_simul, oo.exo_simul, oo.steady_state, oo.exo_steady_state, M, options);
[endo_simul_new, success] = perfect_foresight_solver_core(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, oo_.exo_steady_state, M_, options_);
else
switch(algo)
case 0
@ -110,7 +110,7 @@ if isequal(method, 3) || (isequal(method, 2) && noconvergence)
solve_stochastic_perfect_foresight_model(endo_simul, exo_simul, pfm, ep.stochastic.quadrature.nodes, ep.stochastic.order);
case 1
[flag, endo_simul_new] = ...
solve_stochastic_perfect_foresight_model_1(endo_simul, exo_simul, options, pfm, ep.stochastic.order);
solve_stochastic_perfect_foresight_model_1(endo_simul, exo_simul, options_, pfm, ep.stochastic.order);
end
end
if isequal(order, 0)

View File

@ -1,14 +1,14 @@
function [initial_conditions, innovations, pfm, ep, verbosity, DynareOptions, DynareResults] = extended_path_initialization(initial_conditions, sample_size, exogenousvariables, DynareOptions, DynareModel, DynareResults)
function [initial_conditions, innovations, pfm, ep, verbosity, options_, oo_] = extended_path_initialization(initial_conditions, sample_size, exogenousvariables, options_, M_, oo_)
% [initial_conditions, innovations, pfm, ep, verbosity, options_, oo_] = extended_path_initialization(initial_conditions, sample_size, exogenousvariables, options_, M_, oo_)
% Initialization of the extended path routines.
%
% INPUTS
% o initial_conditions [double] m*1 array, where m is the number of endogenous variables in the model.
% o sample_size [integer] scalar, size of the sample to be simulated.
% o exogenousvariables [double] T*n array, values for the structural innovations.
% o DynareOptions [struct] options_
% o DynareModel [struct] M_
% o DynareResults [struct] oo_
% o options_ [struct] Dynare's options structure
% o M_ [struct] Dynare's model structure
% o oo_ [struct] Dynare's result structure
%
% OUTPUTS
%
@ -16,7 +16,7 @@ function [initial_conditions, innovations, pfm, ep, verbosity, DynareOptions, Dy
%
% SPECIAL REQUIREMENTS
% Copyright © 2016-2020 Dynare Team
% Copyright © 2016-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -33,29 +33,29 @@ function [initial_conditions, innovations, pfm, ep, verbosity, DynareOptions, Dy
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
ep = DynareOptions.ep;
ep = options_.ep;
% Set verbosity levels.
DynareOptions.verbosity = ep.verbosity;
options_.verbosity = ep.verbosity;
verbosity = ep.verbosity+ep.debug;
% Set maximum number of iterations for the deterministic solver.
DynareOptions.simul.maxit = ep.maxit;
options_.simul.maxit = ep.maxit;
% Prepare a structure needed by the matlab implementation of the perfect foresight model solver
pfm = setup_stochastic_perfect_foresight_model_solver(DynareModel, DynareOptions, DynareResults);
pfm = setup_stochastic_perfect_foresight_model_solver(M_, options_, oo_);
% Check that the user did not use varexo_det
if DynareModel.exo_det_nbr~=0
if M_.exo_det_nbr~=0
error('Extended path does not support varexo_det.')
end
% Set default initial conditions.
if isempty(initial_conditions)
if isempty(DynareModel.endo_histval)
initial_conditions = DynareResults.steady_state;
if isempty(M_.endo_histval)
initial_conditions = oo_.steady_state;
else
initial_conditions = DynareModel.endo_histval;
initial_conditions = M_.endo_histval;
end
end
@ -64,10 +64,10 @@ pfm.periods = ep.periods;
pfm.i_upd = pfm.ny+(1:pfm.periods*pfm.ny);
pfm.block = DynareOptions.block;
pfm.block = options_.block;
% Set the algorithm for the perfect foresight solver
DynareOptions.stack_solve_algo = ep.stack_solve_algo;
options_.stack_solve_algo = ep.stack_solve_algo;
% Compute the first order reduced form if needed.
%
@ -76,20 +76,20 @@ DynareOptions.stack_solve_algo = ep.stack_solve_algo;
dr = struct();
if ep.init
DynareOptions.order = 1;
DynareResults.dr=set_state_space(dr,DynareModel);
[DynareResults.dr,Info,DynareModel.params] = resol(0,DynareModel,DynareOptions,DynareResults.dr,DynareResults.steady_state, DynareResults.exo_steady_state, DynareResults.exo_det_steady_state);
options_.order = 1;
oo_.dr=set_state_space(dr,M_);
[oo_.dr,Info,M_.params] = resol(0,M_,options_,oo_.dr,oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
end
% Do not use a minimal number of perdiods for the perfect foresight solver (with bytecode and blocks)
DynareOptions.minimal_solving_period = DynareOptions.ep.periods;
options_.minimal_solving_period = options_.ep.periods;
% Set the covariance matrix of the structural innovations.
if isempty(exogenousvariables)
innovations = struct();
innovations.positive_var_indx = find(diag(DynareModel.Sigma_e)>0);
innovations.positive_var_indx = find(diag(M_.Sigma_e)>0);
innovations.effective_number_of_shocks = length(innovations.positive_var_indx);
innovations.covariance_matrix = DynareModel.Sigma_e(innovations.positive_var_indx,innovations.positive_var_indx);
innovations.covariance_matrix = M_.Sigma_e(innovations.positive_var_indx,innovations.positive_var_indx);
innovations.covariance_matrix_upper_cholesky = chol(innovations.covariance_matrix);
else
innovations = struct();
@ -97,26 +97,26 @@ end
% Set seed.
if ep.set_dynare_seed_to_default
DynareOptions=set_dynare_seed_local_options(DynareOptions,'default');
options_=set_dynare_seed_local_options(options_,'default');
end
% hybrid correction
pfm.hybrid_order = ep.stochastic.hybrid_order;
if pfm.hybrid_order
DynareResults.dr = set_state_space(DynareResults.dr, DynareModel);
options = DynareOptions;
oo_.dr = set_state_space(oo_.dr, M_);
options = options_;
options.order = pfm.hybrid_order;
[pfm.dr, DynareModel.params] = resol(0, DynareModel, options, DynareResults.dr, DynareResults.steady_state, DynareResults.exo_steady_state, DynareResults.exo_det_steady_state);
[pfm.dr, M_.params] = resol(0, M_, options, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
else
pfm.dr = [];
end
% number of nonzero derivatives
pfm.nnzA = DynareModel.NNZDerivatives(1);
pfm.nnzA = M_.NNZDerivatives(1);
% setting up integration nodes if order > 0
if ep.stochastic.order > 0
[nodes,weights,nnodes] = setup_integration_nodes(DynareOptions.ep,pfm);
[nodes,weights,nnodes] = setup_integration_nodes(options_.ep,pfm);
pfm.nodes = nodes;
pfm.weights = weights;
pfm.nnodes = nnodes;
@ -127,12 +127,12 @@ else
end
% set boundaries if mcp
[lb,ub,pfm.eq_index] = get_complementarity_conditions(DynareModel, DynareOptions.ramsey_policy);
if DynareOptions.ep.solve_algo == 10
DynareOptions.lmmcp.lb = repmat(lb,block_nbr,1);
DynareOptions.lmmcp.ub = repmat(ub,block_nbr,1);
elseif DynareOptions.ep.solve_algo == 11
DynareOptions.mcppath.lb = repmat(lb,block_nbr,1);
DynareOptions.mcppath.ub = repmat(ub,block_nbr,1);
[lb,ub,pfm.eq_index] = get_complementarity_conditions(M_, options_.ramsey_policy);
if options_.ep.solve_algo == 10
options_.lmmcp.lb = repmat(lb,block_nbr,1);
options_.lmmcp.ub = repmat(ub,block_nbr,1);
elseif options_.ep.solve_algo == 11
options_.mcppath.lb = repmat(lb,block_nbr,1);
options_.mcppath.ub = repmat(ub,block_nbr,1);
end
pfm.block_nbr = block_nbr;

View File

@ -1,15 +1,15 @@
function Simulations = extended_path_mc(initialconditions, samplesize, replic, exogenousvariables, DynareOptions, DynareModel, DynareResults)
function Simulations = extended_path_mc(initialconditions, samplesize, replic, exogenousvariables, options_, M_, oo_)
% Simulations = extended_path_mc(initialconditions, samplesize, replic, exogenousvariables, options_, M_, oo_)
% Stochastic simulation of a non linear DSGE model using the Extended Path method (Fair and Taylor 1983). A time
% series of size T is obtained by solving T perfect foresight models.
%
% INPUTS
% o initialconditions [double] m*1 array, where m is the number of endogenous variables in the model.
% o samplesize [integer] scalar, size of the sample to be simulated.
% o samplesize [integer] scalar, size of the sample to be simulated.
% o exogenousvariables [double] T*n array, values for the structural innovations.
% o DynareOptions [struct] options_
% o DynareModel [struct] M_
% o DynareResults [struct] oo_
% o options_ [struct] Dynare's options structure
% o M_ [struct] Dynare's model structure
% o oo_ [struct] Dynare's results structure
%
% OUTPUTS
% o ts [dseries] m*samplesize array, the simulations.
@ -19,7 +19,7 @@ function Simulations = extended_path_mc(initialconditions, samplesize, replic, e
%
% SPECIAL REQUIREMENTS
% Copyright © 2016-2020 Dynare Team
% Copyright © 2016-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -36,8 +36,8 @@ function Simulations = extended_path_mc(initialconditions, samplesize, replic, e
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
[initialconditions, innovations, pfm, ep, verbosity, DynareOptions, DynareResults] = ...
extended_path_initialization(initialconditions, samplesize, exogenousvariables, DynareOptions, DynareModel, DynareResults);
[initialconditions, innovations, pfm, ep, verbosity, options_, oo_] = ...
extended_path_initialization(initialconditions, samplesize, exogenousvariables, options_, M_, oo_);
% Check the dimension of the first input argument
if isequal(size(initialconditions, 2), 1)
@ -68,9 +68,9 @@ if ep.parallel
% Use the Parallel toolbox.
parfor i=1:replic
innovations_ = innovations;
DynareResults_ = DynareResults;
[shocks, spfm_exo_simul, innovations_, DynareResults_] = extended_path_shocks(innovations_, ep, exogenousvariables(:,:,i), samplesize, DynareModel, DynareOptions, DynareResults_);
endogenous_variables_paths = NaN(DynareModel.endo_nbr,samplesize+1);
oo__ = oo_;
[shocks, spfm_exo_simul, innovations_, oo__] = extended_path_shocks(innovations_, ep, exogenousvariables(:,:,i), samplesize, M_, options_, oo__);
endogenous_variables_paths = NaN(M_.endo_nbr,samplesize+1);
endogenous_variables_paths(:,1) = initialconditions(:,1);
exogenous_variables_paths = NaN(innovations_.effective_number_of_shocks,samplesize+1);
exogenous_variables_paths(:,1) = 0;
@ -80,12 +80,12 @@ if ep.parallel
t = t+1;
spfm_exo_simul(2,:) = shocks(t-1,:);
exogenous_variables_paths(:,t) = shocks(t-1,:);
[endogenous_variables_paths(:,t), info_convergence] = extended_path_core(ep.periods, DynareModel.endo_nbr, DynareModel.exo_nbr, innovations_.positive_var_indx, ...
[endogenous_variables_paths(:,t), info_convergence] = extended_path_core(ep.periods, M_.endo_nbr, M_.exo_nbr, innovations_.positive_var_indx, ...
spfm_exo_simul, ep.init, endogenous_variables_paths(:,t-1), ...
DynareResults_.steady_state, ...
oo__.steady_state, ...
ep.verbosity, ep.stochastic.order, ...
DynareModel, pfm,ep.stochastic.algo, ep.solve_algo, ep.stack_solve_algo, ...
DynareOptions.lmmcp, DynareOptions, DynareResults_);
M_, pfm,ep.stochastic.algo, ep.solve_algo, ep.stack_solve_algo, ...
options_.lmmcp, options_, oo__);
if ~info_convergence
msg = sprintf('No convergence of the (stochastic) perfect foresight solver (in period %s, iteration %s)!', int2str(t), int2str(i));
warning(msg)
@ -99,8 +99,8 @@ if ep.parallel
else
% Sequential approach.
for i=1:replic
[shocks, spfm_exo_simul, innovations, DynareResults] = extended_path_shocks(innovations, ep, exogenousvariables(:,:,i), samplesize, DynareModel, DynareOptions, DynareResults);
endogenous_variables_paths = NaN(DynareModel.endo_nbr,samplesize+1);
[shocks, spfm_exo_simul, innovations, oo_] = extended_path_shocks(innovations, ep, exogenousvariables(:,:,i), samplesize, M_, options_, oo_);
endogenous_variables_paths = NaN(M_.endo_nbr,samplesize+1);
endogenous_variables_paths(:,1) = initialconditions(:,1);
exogenous_variables_paths = NaN(innovations.effective_number_of_shocks,samplesize+1);
exogenous_variables_paths(:,1) = 0;
@ -109,12 +109,12 @@ else
t = t+1;
spfm_exo_simul(2,:) = shocks(t-1,:);
exogenous_variables_paths(:,t) = shocks(t-1,:);
[endogenous_variables_paths(:,t), info_convergence] = extended_path_core(ep.periods, DynareModel.endo_nbr, DynareModel.exo_nbr, innovations.positive_var_indx, ...
[endogenous_variables_paths(:,t), info_convergence] = extended_path_core(ep.periods, M_.endo_nbr, M_.exo_nbr, innovations.positive_var_indx, ...
spfm_exo_simul, ep.init, endogenous_variables_paths(:,t-1), ...
DynareResults.steady_state, ...
oo_.steady_state, ...
ep.verbosity, ep.stochastic.order, ...
DynareModel, pfm,ep.stochastic.algo, ep.solve_algo, ep.stack_solve_algo, ...
DynareOptions.lmmcp, DynareOptions, DynareResults);
M_, pfm,ep.stochastic.algo, ep.solve_algo, ep.stack_solve_algo, ...
options_.lmmcp, options_, oo_);
if ~info_convergence
msg = sprintf('No convergence of the (stochastic) perfect foresight solver (in period %s, iteration %s)!', int2str(t), int2str(i));
warning(msg)

View File

@ -1,6 +1,6 @@
function [shocks, spfm_exo_simul, innovations, DynareResults] = extended_path_shocks(innovations, ep, exogenousvariables, sample_size,DynareModel,DynareOptions, DynareResults)
% Copyright © 2016-2017 Dynare Team
function [shocks, spfm_exo_simul, innovations, oo_] = extended_path_shocks(innovations, ep, exogenousvariables, sample_size,M_,options_, oo_)
% [shocks, spfm_exo_simul, innovations, oo_] = extended_path_shocks(innovations, ep, exogenousvariables, sample_size,M_,options_, oo_)
% Copyright © 2016-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -21,13 +21,13 @@ function [shocks, spfm_exo_simul, innovations, DynareResults] = extended_path_sh
if isempty(exogenousvariables)
switch ep.innovation_distribution
case 'gaussian'
shocks = zeros(sample_size, DynareModel.exo_nbr);
shocks = zeros(sample_size, M_.exo_nbr);
shocks(:,innovations.positive_var_indx) = transpose(transpose(innovations.covariance_matrix_upper_cholesky)*randn(innovations.effective_number_of_shocks,sample_size));
case 'calibrated'
options = DynareOptions;
options = options_;
options.periods = options.ep.periods;
oo = make_ex_(DynareModel,options,DynareResults);
shocks = oo.exo_simul(2:end,:);
oo_local = make_ex_(M_,options,oo_);
shocks = oo_local.exo_simul(2:end,:);
otherwise
error(['extended_path:: ' ep.innovation_distribution ' distribution for the structural innovations is not (yet) implemented!'])
end
@ -37,5 +37,5 @@ else
end
% Copy the shocks in exo_simul
DynareResults.exo_simul = shocks;
spfm_exo_simul = repmat(DynareResults.exo_steady_state',ep.periods+2,1);
oo_.exo_simul = shocks;
spfm_exo_simul = repmat(oo_.exo_steady_state',ep.periods+2,1);

View File

@ -1,6 +1,11 @@
function pfm = setup_stochastic_perfect_foresight_model_solver(DynareModel,DynareOptions,DynareOutput)
function pfm = setup_stochastic_perfect_foresight_model_solver(M_,options_,oo_)
% pfm = setup_stochastic_perfect_foresight_model_solver(M_,options_,oo_)
% INPUTS
% o M_ [struct] Dynare's model structure
% o options_ [struct] Dynare's options structure
% o oo_ [struct] Dynare's results structure
% Copyright © 2013-2020 Dynare Team
% Copyright © 2013-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -17,15 +22,15 @@ function pfm = setup_stochastic_perfect_foresight_model_solver(DynareModel,Dynar
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
pfm.lead_lag_incidence = DynareModel.lead_lag_incidence;
pfm.ny = DynareModel.endo_nbr;
pfm.Sigma = DynareModel.Sigma_e;
pfm.lead_lag_incidence = M_.lead_lag_incidence;
pfm.ny = M_.endo_nbr;
pfm.Sigma = M_.Sigma_e;
if det(pfm.Sigma) > 0
pfm.Omega = chol(pfm.Sigma,'upper'); % Sigma = Omega'*Omega
end
pfm.number_of_shocks = length(pfm.Sigma);
pfm.stochastic_order = DynareOptions.ep.stochastic.order;
pfm.max_lag = DynareModel.maximum_endo_lag;
pfm.stochastic_order = options_.ep.stochastic.order;
pfm.max_lag = M_.maximum_endo_lag;
if pfm.max_lag > 0
pfm.nyp = nnz(pfm.lead_lag_incidence(1,:));
pfm.iyp = find(pfm.lead_lag_incidence(1,:)>0);
@ -35,7 +40,7 @@ else
end
pfm.ny0 = nnz(pfm.lead_lag_incidence(pfm.max_lag+1,:));
pfm.iy0 = find(pfm.lead_lag_incidence(pfm.max_lag+1,:)>0);
if DynareModel.maximum_endo_lead
if M_.maximum_endo_lead
pfm.nyf = nnz(pfm.lead_lag_incidence(pfm.max_lag+2,:));
pfm.iyf = find(pfm.lead_lag_incidence(pfm.max_lag+2,:)>0);
else
@ -49,10 +54,10 @@ pfm.is = [pfm.nyp+1:pfm.ny+pfm.nyp];
pfm.isf = pfm.iyf+pfm.nyp;
pfm.isf1 = [pfm.nyp+pfm.ny+1:pfm.nyf+pfm.nyp+pfm.ny+1];
pfm.iz = [1:pfm.ny+pfm.nyp+pfm.nyf];
pfm.periods = DynareOptions.ep.periods;
pfm.steady_state = DynareOutput.steady_state;
pfm.params = DynareModel.params;
if DynareModel.maximum_endo_lead
pfm.periods = options_.ep.periods;
pfm.steady_state = oo_.steady_state;
pfm.params = M_.params;
if M_.maximum_endo_lead
pfm.i_cols_1 = nonzeros(pfm.lead_lag_incidence(pfm.max_lag+(1:2),:)');
pfm.i_cols_A1 = find(pfm.lead_lag_incidence(pfm.max_lag+(1:2),:)');
else
@ -66,9 +71,9 @@ else
end
pfm.i_cols_j = 1:pfm.nd;
pfm.i_upd = pfm.ny+(1:pfm.periods*pfm.ny);
if ~DynareOptions.bytecode
pfm.dynamic_model = str2func([DynareModel.fname,'.dynamic']);
if ~options_.bytecode
pfm.dynamic_model = str2func([M_.fname,'.dynamic']);
end
pfm.verbose = DynareOptions.ep.verbosity;
pfm.maxit_ = DynareOptions.simul.maxit;
pfm.tolerance = DynareOptions.dynatol.f;
pfm.verbose = options_.ep.verbosity;
pfm.maxit_ = options_.simul.maxit;
pfm.tolerance = options_.dynatol.f;

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,15 +1,15 @@
function eqnumber = get_equation_number_by_tag(eqname, M_)
% eqnumber = get_equation_number_by_tag(eqname, M_)
% Translates an equation name into an equation number.
%
% INPUTS
% - eqname [char] 1×n array, name of the equation.
% - DynareModel [struct] Structure describing the model, aka M_.
% - M_ [struct] Structure describing the model
%
% OUTPUTS
% - eqnumber [integer] Equation number.
% Copyright © 2018-2022 Dynare Team
% Copyright © 2018-2023 Dynare Team
%
% This file is part of Dynare.
%

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,10 +1,10 @@
function [lhs, rhs, json] = get_lhs_and_rhs(eqname, DynareModel, original, json)
function [lhs, rhs, json] = get_lhs_and_rhs(eqname, M_, original, json)
% [lhs, rhs, json] = get_lhs_and_rhs(eqname, M_, original, json)
% Returns the left and right handsides of an equation.
%
% INPUTS
% - eqname [char] Name of the equation.
% - DynareModel [struct] Structure describing the current model (M_).
% - M_ [struct] Structure describing the current model.
% - original [logical] fetch equation in modfile-original.json or modfile.json
% - json [char] content of the JSON file
%
@ -23,7 +23,7 @@ function [lhs, rhs, json] = get_lhs_and_rhs(eqname, DynareModel, original, json)
% [name='Phillips curve']
% pi = beta*pi(1) + slope*y + lam;
% Copyright © 2018-2020 Dynare Team
% Copyright © 2018-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -47,9 +47,9 @@ end
% Load JSON file if nargin<4
if nargin<4
if original
json = loadjson_([DynareModel.fname filesep() 'model' filesep() 'json' filesep() 'modfile-original.json']);
json = loadjson_([M_.fname filesep() 'model' filesep() 'json' filesep() 'modfile-original.json']);
else
json = loadjson_([DynareModel.fname filesep() 'model' filesep() 'json' filesep() 'modfile.json']);
json = loadjson_([M_.fname filesep() 'model' filesep() 'json' filesep() 'modfile.json']);
end
end

View File

@ -1,11 +1,11 @@
function [pnames, enames, xnames, pid, eid, xid] = get_variables_and_parameters_in_equation(lhs, rhs, DynareModel)
function [pnames, enames, xnames, pid, eid, xid] = get_variables_and_parameters_in_equation(lhs, rhs, M_)
% [pnames, enames, xnames, pid, eid, xid] = get_variables_and_parameters_in_equation(lhs, rhs, M_)
% Returns the lists of parameters, endogenous variables and exogenous variables in an equation.
%
% INPUTS
% - lhs [string] Left hand side of an equation.
% - rhs [string] Right hand side of an equation.
% - DynareModel [struct] Structure describing the current model (M_).
% - M_ [struct] Structure describing the current model.
%
% OUTPUTS
% - pnames [cell] Cell of row char arrays (p elements), names of the parameters.
@ -39,33 +39,33 @@ rhs_ = get_variables_and_parameters_in_expression(rhs);
lhs_ = get_variables_and_parameters_in_expression(lhs);
% Get list of parameters.
pnames = DynareModel.param_names;
pnames = M_.param_names;
pnames = intersect([rhs_, lhs_], pnames);
if nargout>1
% Get list of endogenous variables.
enames = DynareModel.endo_names;
enames = M_.endo_names;
enames = intersect([rhs_, lhs_], enames);
if nargout>2
% Get list of exogenous variables
xnames = DynareModel.exo_names;
xnames = M_.exo_names;
xnames = intersect([rhs_,lhs_], xnames);
if nargout>3
% Returns vector of indices for parameters endogenous and exogenous variables if required.
p = length(pnames);
pid = zeros(p, 1);
for i = 1:p
pid(i) = find(strcmp(pnames{i}, DynareModel.param_names));
pid(i) = find(strcmp(pnames{i}, M_.param_names));
end
p = length(enames);
eid = zeros(p, 1);
for i = 1:p
eid(i) = find(strcmp(enames{i}, DynareModel.endo_names));
eid(i) = find(strcmp(enames{i}, M_.endo_names));
end
p = length(xnames);
xid = zeros(p, 1);
for i = 1:p
xid(i) = find(strcmp(xnames{i}, DynareModel.exo_names));
xid(i) = find(strcmp(xnames{i}, M_.exo_names));
end
end
end

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

@ -1,5 +1,6 @@
function map_calibration(OutputDirectoryName, Model, DynareOptions, DynareResults, EstimatedParameters, BayesInfo)
% map_calibration(OutputDirectoryName, Model, DynareOptions, DynareResults, EstimatedParameters, BayesInfo)
function map_calibration(OutputDirectoryName, M_, options_, oo_, estim_params_, bayestopt_)
% map_calibration(OutputDirectoryName, M_, options_, oo_, estim_params_, bayestopt_)
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
@ -23,33 +24,33 @@ function map_calibration(OutputDirectoryName, Model, DynareOptions, DynareResult
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
fname_ = Model.fname;
fname_ = M_.fname;
np = EstimatedParameters.np;
nshock = EstimatedParameters.nvx + EstimatedParameters.nvn + EstimatedParameters.ncx + EstimatedParameters.ncn;
np = estim_params_.np;
nshock = estim_params_.nvx + estim_params_.nvn + estim_params_.ncx + estim_params_.ncn;
pnames=cell(np,1);
pnames_tex=cell(np,1);
for jj=1:np
if DynareOptions.TeX
[param_name_temp, param_name_tex_temp]= get_the_name(nshock+jj, DynareOptions.TeX, Model, EstimatedParameters, DynareOptions);
if options_.TeX
[param_name_temp, param_name_tex_temp]= get_the_name(nshock+jj, options_.TeX, M_, estim_params_, options_);
pnames_tex{jj,1} = strrep(param_name_tex_temp,'$','');
pnames{jj,1} = param_name_temp;
else
param_name_temp = get_the_name(nshock+jj, DynareOptions.TeX, Model, EstimatedParameters, DynareOptions);
param_name_temp = get_the_name(nshock+jj, options_.TeX, M_, estim_params_, options_);
pnames{jj,1} = param_name_temp;
end
end
pvalue_ks = DynareOptions.opt_gsa.pvalue_ks;
pvalue_ks = options_.opt_gsa.pvalue_ks;
indx_irf = [];
indx_moment = [];
init = ~DynareOptions.opt_gsa.load_stab;
init = ~options_.opt_gsa.load_stab;
options_mcf.pvalue_ks = DynareOptions.opt_gsa.pvalue_ks;
options_mcf.pvalue_corr = DynareOptions.opt_gsa.pvalue_corr;
options_mcf.alpha2 = DynareOptions.opt_gsa.alpha2_stab;
options_mcf.pvalue_ks = options_.opt_gsa.pvalue_ks;
options_mcf.pvalue_corr = options_.opt_gsa.pvalue_corr;
options_mcf.alpha2 = options_.opt_gsa.alpha2_stab;
options_mcf.param_names = pnames;
if DynareOptions.TeX
if options_.TeX
options_mcf.param_names_tex = pnames_tex;
end
options_mcf.fname_ = fname_;
@ -58,17 +59,17 @@ options_mcf.OutputDirectoryName = OutputDirectoryName;
skipline()
disp('Sensitivity analysis for calibration criteria')
if DynareOptions.opt_gsa.ppost
filetoload=dir([Model.dname filesep 'metropolis' filesep fname_ '_param_irf*.mat']);
if options_.opt_gsa.ppost
filetoload=dir([M_.dname filesep 'metropolis' filesep fname_ '_param_irf*.mat']);
lpmat=[];
for j=1:length(filetoload)
load([Model.dname filesep 'metropolis' filesep fname_ '_param_irf',int2str(j),'.mat'])
load([M_.dname filesep 'metropolis' filesep fname_ '_param_irf',int2str(j),'.mat'])
lpmat = [lpmat; stock];
clear stock
end
type = 'post';
else
if DynareOptions.opt_gsa.pprior
if options_.opt_gsa.pprior
filetoload=[OutputDirectoryName '/' fname_ '_prior'];
load(filetoload,'lpmat','lpmat0','istable','iunstable','iindeterm','iwrong' ,'infox')
lpmat = [lpmat0 lpmat];
@ -84,31 +85,31 @@ end
npar = size(pnames,1);
nshock = np - npar;
nbr_irf_restrictions = size(DynareOptions.endogenous_prior_restrictions.irf,1);
nbr_moment_restrictions = size(DynareOptions.endogenous_prior_restrictions.moment,1);
nbr_irf_restrictions = size(options_.endogenous_prior_restrictions.irf,1);
nbr_moment_restrictions = size(options_.endogenous_prior_restrictions.moment,1);
if init
mat_irf=cell(nbr_irf_restrictions,1);
for ij=1:nbr_irf_restrictions
mat_irf{ij}=NaN(Nsam,length(DynareOptions.endogenous_prior_restrictions.irf{ij,3}));
mat_irf{ij}=NaN(Nsam,length(options_.endogenous_prior_restrictions.irf{ij,3}));
end
mat_moment=cell(nbr_moment_restrictions,1);
for ij=1:nbr_moment_restrictions
mat_moment{ij}=NaN(Nsam,length(DynareOptions.endogenous_prior_restrictions.moment{ij,3}));
mat_moment{ij}=NaN(Nsam,length(options_.endogenous_prior_restrictions.moment{ij,3}));
end
irestrictions = [1:Nsam];
h = dyn_waitbar(0,'Please wait...');
for j=1:Nsam
Model = set_all_parameters(lpmat(j,:)',EstimatedParameters,Model);
M_ = set_all_parameters(lpmat(j,:)',estim_params_,M_);
if nbr_moment_restrictions
[Tt,Rr,SteadyState,info,DynareResults.dr, Model.params] = dynare_resolve(Model,DynareOptions,DynareResults.dr, DynareResults.steady_state, DynareResults.exo_steady_state, DynareResults.exo_det_steady_state);
[Tt,Rr,SteadyState,info,oo_.dr, M_.params] = dynare_resolve(M_,options_,oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
else
[Tt,Rr,SteadyState,info,DynareResults.dr, Model.params] = dynare_resolve(Model,DynareOptions,DynareResults.dr, DynareResults.steady_state, DynareResults.exo_steady_state, DynareResults.exo_det_steady_state,'restrict');
[Tt,Rr,SteadyState,info,oo_.dr, M_.params] = dynare_resolve(M_,options_,oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state,'restrict');
end
if info(1)==0
[info, info_irf, info_moment, data_irf, data_moment]=endogenous_prior_restrictions(Tt,Rr,Model,DynareOptions,DynareResults.dr,DynareResults.steady_state,DynareResults.exo_steady_state,DynareResults.exo_det_steady_state);
[info, info_irf, info_moment, data_irf, data_moment]=endogenous_prior_restrictions(Tt,Rr,M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
if ~isempty(info_irf)
for ij=1:nbr_irf_restrictions
mat_irf{ij}(j,:)=data_irf{ij}(:,2)';
@ -131,7 +132,7 @@ if init
irestrictions=irestrictions(find(irestrictions));
xmat=lpmat(irestrictions,:);
skipline()
endo_prior_restrictions=DynareOptions.endogenous_prior_restrictions;
endo_prior_restrictions=options_.endogenous_prior_restrictions;
save([OutputDirectoryName,filesep,fname_,'_',type,'_restrictions'],'xmat','mat_irf','mat_moment','irestrictions','indx_irf','indx_moment','endo_prior_restrictions');
else
load([OutputDirectoryName,filesep,fname_,'_',type,'_restrictions'],'xmat','mat_irf','mat_moment','irestrictions','indx_irf','indx_moment','endo_prior_restrictions');
@ -190,8 +191,8 @@ if ~isempty(indx_irf)
iplot_indx = ones(size(plot_indx));
indx_irf = indx_irf(irestrictions,:);
if ~DynareOptions.nograph
h1=dyn_figure(DynareOptions.nodisplay,'name',[type ' evaluation of irf restrictions']);
if ~options_.nograph
h1=dyn_figure(options_.nodisplay,'name',[type ' evaluation of irf restrictions']);
nrow=ceil(sqrt(nbr_irf_couples));
ncol=nrow;
if nrow*(nrow-1)>nbr_irf_couples
@ -204,7 +205,7 @@ if ~isempty(indx_irf)
indx_irf_matrix(:,plot_indx(ij)) = indx_irf_matrix(:,plot_indx(ij)) + indx_irf(:,ij);
for ik=1:size(mat_irf{ij},2)
[Mean,Median,Var,HPD,Distrib] = ...
posterior_moments(mat_irf{ij}(:,ik),0,DynareOptions.mh_conf_sig);
posterior_moments(mat_irf{ij}(:,ik),0,options_.mh_conf_sig);
irf_mean{plot_indx(ij)} = [irf_mean{plot_indx(ij)}; Mean];
irf_median{plot_indx(ij)} = [irf_median{plot_indx(ij)}; Median];
irf_var{plot_indx(ij)} = [irf_var{plot_indx(ij)}; Var];
@ -218,7 +219,7 @@ if ~isempty(indx_irf)
aleg = [aleg,'-' ,num2str(endo_prior_restrictions.irf{ij,3}(end))];
iplot_indx(ij)=0;
end
if ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1
if ~options_.nograph && length(time_matrix{plot_indx(ij)})==1
set(0,'currentfigure',h1),
subplot(nrow,ncol, plot_indx(ij)),
hc = cumplot(mat_irf{ij}(:,ik));
@ -258,7 +259,7 @@ if ~isempty(indx_irf)
options_mcf.nobeha_title = 'NO IRF restriction';
options_mcf.title = atitle0;
if ~isempty(indx1) && ~isempty(indx2)
mcf_analysis(xmat(:,nshock+1:end), indx1, indx2, options_mcf, DynareOptions);
mcf_analysis(xmat(:,nshock+1:end), indx1, indx2, options_mcf, options_);
end
% [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0);
@ -269,7 +270,7 @@ if ~isempty(indx_irf)
end
for ij=1:nbr_irf_couples
if length(time_matrix{ij})>1
if ~DynareOptions.nograph
if ~options_.nograph
set(0,'currentfigure',h1);
subplot(nrow,ncol, ij)
itmp = (find(plot_indx==ij));
@ -319,14 +320,14 @@ if ~isempty(indx_irf)
options_mcf.nobeha_title = 'NO IRF restriction';
options_mcf.title = atitle0;
if ~isempty(indx1) && ~isempty(indx2)
mcf_analysis(xmat(:,nshock+1:end), indx1, indx2, options_mcf, DynareOptions);
mcf_analysis(xmat(:,nshock+1:end), indx1, indx2, options_mcf, options_);
end
end
end
end
if ~DynareOptions.nograph
dyn_saveas(h1,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],DynareOptions.nodisplay,DynareOptions.graph_format);
create_TeX_loader(DynareOptions,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],[type ' evaluation of irf restrictions'],'irf_restrictions',type,DynareOptions.figures.textwidth*min(ij/ncol,1))
if ~options_.nograph
dyn_saveas(h1,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],options_.nodisplay,options_.graph_format);
create_TeX_loader(options_,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],[type ' evaluation of irf restrictions'],'irf_restrictions',type,options_.figures.textwidth*min(ij/ncol,1))
end
skipline()
end
@ -362,24 +363,24 @@ if ~isempty(indx_moment)
skipline()
%get parameter names including standard deviations
np=size(BayesInfo.name,1);
np=size(bayestopt_.name,1);
name=cell(np,1);
name_tex=cell(np,1);
for jj=1:np
if DynareOptions.TeX
[param_name_temp, param_name_tex_temp]= get_the_name(jj,DynareOptions.TeX,Model,EstimatedParameters,DynareOptions);
if options_.TeX
[param_name_temp, param_name_tex_temp]= get_the_name(jj,options_.TeX,M_,estim_params_,options_);
name_tex{jj,1} = strrep(param_name_tex_temp,'$','');
name{jj,1} = param_name_temp;
else
param_name_temp = get_the_name(jj,DynareOptions.TeX,Model,EstimatedParameters,DynareOptions);
param_name_temp = get_the_name(jj,options_.TeX,M_,estim_params_,options_);
name{jj,1} = param_name_temp;
end
end
options_mcf.param_names = name;
if DynareOptions.TeX
if options_.TeX
options_mcf.param_names_tex = name_tex;
end
options_mcf.param_names = BayesInfo.name;
options_mcf.param_names = bayestopt_.name;
all_moment_couples = cellstr([char(endo_prior_restrictions.moment(:,1)) char(endo_prior_restrictions.moment(:,2))]);
moment_couples = unique(all_moment_couples);
nbr_moment_couples = size(moment_couples,1);
@ -405,8 +406,8 @@ if ~isempty(indx_moment)
iplot_indx = ones(size(plot_indx));
indx_moment = indx_moment(irestrictions,:);
if ~DynareOptions.nograph
h2=dyn_figure(DynareOptions.nodisplay,'name',[type ' evaluation of moment restrictions']);
if ~options_.nograph
h2=dyn_figure(options_.nodisplay,'name',[type ' evaluation of moment restrictions']);
nrow=ceil(sqrt(nbr_moment_couples));
ncol=nrow;
if nrow*(nrow-1)>nbr_moment_couples
@ -420,7 +421,7 @@ if ~isempty(indx_moment)
indx_moment_matrix(:,plot_indx(ij)) = indx_moment_matrix(:,plot_indx(ij)) + indx_moment(:,ij);
for ik=1:size(mat_moment{ij},2)
[Mean,Median,Var,HPD,Distrib] = ...
posterior_moments(mat_moment{ij}(:,ik),0,DynareOptions.mh_conf_sig);
posterior_moments(mat_moment{ij}(:,ik),0,options_.mh_conf_sig);
moment_mean{plot_indx(ij)} = [moment_mean{plot_indx(ij)}; Mean];
moment_median{plot_indx(ij)} = [moment_median{plot_indx(ij)}; Median];
moment_var{plot_indx(ij)} = [moment_var{plot_indx(ij)}; Var];
@ -434,7 +435,7 @@ if ~isempty(indx_moment)
aleg = [aleg,'_' ,num2str(endo_prior_restrictions.moment{ij,3}(end))];
iplot_indx(ij)=0;
end
if ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1
if ~options_.nograph && length(time_matrix{plot_indx(ij)})==1
set(0,'currentfigure',h2);
subplot(nrow,ncol,plot_indx(ij)),
hc = cumplot(mat_moment{ij}(:,ik));
@ -469,7 +470,7 @@ if ~isempty(indx_moment)
options_mcf.nobeha_title = 'NO moment restriction';
options_mcf.title = atitle0;
if ~isempty(indx1) && ~isempty(indx2)
mcf_analysis(xmat, indx1, indx2, options_mcf, DynareOptions);
mcf_analysis(xmat, indx1, indx2, options_mcf, options_);
end
% [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0);
@ -481,7 +482,7 @@ if ~isempty(indx_moment)
for ij=1:nbr_moment_couples
time_matrix{ij} = sort(time_matrix{ij});
if length(time_matrix{ij})>1
if ~DynareOptions.nograph
if ~options_.nograph
itmp = (find(plot_indx==ij));
set(0,'currentfigure',h2);
subplot(nrow,ncol, ij)
@ -531,14 +532,14 @@ if ~isempty(indx_moment)
options_mcf.nobeha_title = 'NO moment restriction';
options_mcf.title = atitle0;
if ~isempty(indx1) && ~isempty(indx2)
mcf_analysis(xmat, indx1, indx2, options_mcf, DynareOptions);
mcf_analysis(xmat, indx1, indx2, options_mcf, options_);
end
end
end
end
if ~DynareOptions.nograph
dyn_saveas(h2,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],DynareOptions.nodisplay,DynareOptions.graph_format);
create_TeX_loader(DynareOptions,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],[type ' evaluation of moment restrictions'],'moment_restrictions',type,DynareOptions.figures.textwidth*min(ij/ncol,1))
if ~options_.nograph
dyn_saveas(h2,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],options_.nodisplay,options_.graph_format);
create_TeX_loader(options_,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],[type ' evaluation of moment restrictions'],'moment_restrictions',type,options_.figures.textwidth*min(ij/ncol,1))
end
skipline()

View File

@ -1,12 +1,13 @@
function indmcf = mcf_analysis(lpmat, ibeha, inobeha, options_mcf, DynareOptions)
%
function indmcf = mcf_analysis(lpmat, ibeha, inobeha, options_mcf, options_)
% indmcf = mcf_analysis(lpmat, ibeha, inobeha, options_mcf, options_)
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
% marco.ratto@ec.europa.eu
%
% Copyright © 2014 European Commission
% Copyright © 2016-2018 Dynare Team
% Copyright © 2016-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -28,7 +29,7 @@ pvalue_corr = options_mcf.pvalue_corr;
alpha2 = options_mcf.alpha2;
param_names = options_mcf.param_names;
if DynareOptions.TeX
if options_.TeX
if ~isfield(options_mcf,'param_names_tex')
param_names_tex = options_mcf.param_names;
else
@ -60,7 +61,7 @@ if ~isempty(indmcf)
data_mat=[dproba(indmcf)' proba(indmcf)'];
options_temp.noprint=0;
dyntable(options_temp,['Smirnov statistics in driving ', title],headers,labels,data_mat,size(labels,2)+2,16,3);
if DynareOptions.TeX
if options_.TeX
labels_TeX=param_names_tex(indmcf);
M_temp.dname=OutputDirectoryName ;
M_temp.fname=fname_;
@ -76,11 +77,11 @@ if length(ibeha)>10 && length(inobeha)>10
indcorr = indcorr(~ismember(indcorr(:),indmcf));
indmcf = [indmcf(:); indcorr(:)];
end
if ~isempty(indmcf) && ~DynareOptions.nograph
if ~isempty(indmcf) && ~options_.nograph
skipline()
xx=[];
if ~ isempty(xparam1), xx=xparam1(indmcf); end
scatter_mcf(lpmat(ibeha,indmcf),lpmat(inobeha,indmcf), param_names_tex(indmcf), ...
'.', [fname_,'_',amcf_name], OutputDirectoryName, amcf_title,xx, DynareOptions, ...
'.', [fname_,'_',amcf_name], OutputDirectoryName, amcf_title,xx, options_, ...
beha_title, nobeha_title)
end

View File

@ -1,4 +1,4 @@
function indmcf = scatter_analysis(lpmat, xdata, options_scatter, DynareOptions)
function indmcf = scatter_analysis(lpmat, xdata, options_scatter, options_)
%
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
@ -25,7 +25,7 @@ function indmcf = scatter_analysis(lpmat, xdata, options_scatter, DynareOptions)
param_names = options_scatter.param_names;
if DynareOptions.TeX
if options_.TeX
if ~isfield(options_scatter,'param_names_tex')
param_names_tex = options_scatter.param_names;
else
@ -42,11 +42,11 @@ if isfield(options_scatter,'xparam1')
end
OutputDirectoryName = options_scatter.OutputDirectoryName;
if ~DynareOptions.nograph
if ~options_.nograph
skipline()
xx=[];
if ~isempty(xparam1)
xx=xparam1;
end
scatter_plots(lpmat, xdata, param_names, '.', [fname_, '_', amcf_name], OutputDirectoryName, amcf_title, xx, DynareOptions)
scatter_plots(lpmat, xdata, param_names, '.', [fname_, '_', amcf_name], OutputDirectoryName, amcf_title, xx, options_)
end

View File

@ -1,4 +1,5 @@
function scatter_mcf(X,Y,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, DynareOptions, beha_name, non_beha_name)
function scatter_mcf(X,Y,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, options_, beha_name, non_beha_name)
% scatter_mcf(X,Y,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, options_, beha_name, non_beha_name)
%
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
@ -84,7 +85,7 @@ figtitle_tex=strrep(figtitle,'_','\_');
fig_nam_=[fnam];
if ~nograph
hh_fig=dyn_figure(DynareOptions.nodisplay,'name',figtitle);
hh_fig=dyn_figure(options_.nodisplay,'name',figtitle);
end
bf = 0.1;
@ -166,8 +167,8 @@ if ~isoctave
end
if ~nograph
dyn_saveas(hh_fig,[dirname,filesep,fig_nam_],DynareOptions.nodisplay,DynareOptions.graph_format);
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
dyn_saveas(hh_fig,[dirname,filesep,fig_nam_],options_.nodisplay,options_.graph_format);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([dirname,'/',fig_nam_ '.tex'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by scatter_mcf.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);

View File

@ -1,4 +1,4 @@
function scatter_plots(X,xp,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, DynareOptions)
function scatter_plots(X,xp,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, options_)
%
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
@ -58,7 +58,7 @@ end
if nargin<6 || isempty(dirname)
dirname='';
nograph=1;
DynareOptions.nodisplay=0;
options_.nodisplay=0;
else
nograph=0;
end
@ -73,7 +73,7 @@ figtitle_tex=strrep(figtitle,'_','\_');
fig_nam_=[fnam];
hh_fig=dyn_figure(DynareOptions.nodisplay,'name',figtitle);
hh_fig=dyn_figure(options_.nodisplay,'name',figtitle);
set(hh_fig,'userdata',{X,xp})
bf = 0.1;
@ -172,8 +172,8 @@ end
% end
if ~nograph
dyn_saveas(hh_fig,[dirname,filesep,fig_nam_],DynareOptions.nodisplay,DynareOptions.graph_format);
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
dyn_saveas(hh_fig,[dirname,filesep,fig_nam_],options_.nodisplay,options_.graph_format);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([dirname,'/',fig_nam_ '.tex'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by scatter_plots.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);

View File

@ -1,10 +1,10 @@
function [series, p] = histvalf_initvalf(caller, DynareModel, options)
function [series, p] = histvalf_initvalf(caller, M_, options)
% [series, p] = histvalf_initvalf(caller, M_, options)
% Handles options for histval_file and initval_file
%
% INPUTS
% - caller [char] row array, name of calling function
% - DynareModel [struct] model description, a.k.a M_
% - M_ [struct] model description, a.k.a
% - options [struct] options specific to histval_file and initval_file
%
% OUTPUTS
@ -79,23 +79,23 @@ end
% checking that all variable are present
error_flag = false;
for i = 1:DynareModel.orig_endo_nbr
if ~series.exist(DynareModel.endo_names{i})
dprintf('%s_FILE: endogenous variable %s is missing', caller, DynareModel.endo_names{i})
for i = 1:M_.orig_endo_nbr
if ~series.exist(M_.endo_names{i})
dprintf('%s_FILE: endogenous variable %s is missing', caller, M_.endo_names{i})
error_flag = true;
end
end
for i = 1:DynareModel.exo_nbr
if ~series.exist(DynareModel.exo_names{i})
dprintf('%s_FILE: exogenous variable %s is missing', caller, DynareModel.exo_names{i})
for i = 1:M_.exo_nbr
if ~series.exist(M_.exo_names{i})
dprintf('%s_FILE: exogenous variable %s is missing', caller, M_.exo_names{i})
error_flag = true;
end
end
for i = 1:DynareModel.exo_det_nbr
if ~series.exist(DynareModel.exo_det_names{i})
dprintf('%s_FILE: exo_det variable %s is missing', caller, DynareModel.exo_det_names{i})
for i = 1:M_.exo_det_nbr
if ~series.exist(M_.exo_det_names{i})
dprintf('%s_FILE: exo_det variable %s is missing', caller, M_.exo_det_names{i})
error_flag = true;
end
end
@ -104,8 +104,8 @@ if error_flag
error('%s_FILE: some variables are missing', caller)
end
if exist(sprintf('+%s/dynamic_set_auxiliary_series.m', DynareModel.fname), 'file')
series = feval(sprintf('%s.dynamic_set_auxiliary_series', DynareModel.fname), series, DynareModel.params);
if exist(sprintf('+%s/dynamic_set_auxiliary_series.m', M_.fname), 'file')
series = feval(sprintf('%s.dynamic_set_auxiliary_series', M_.fname), series, M_.params);
end
% selecting observations
@ -129,18 +129,18 @@ if isfield(options, 'first_obs') && ~isempty(options.first_obs)
error('%s_FILE: first_obs = %d is larger than the number of observations in the data file (%d)', ...
caller, options.first_obs, nobs0)
elseif isfield(options, 'first_simulation_period')
if options.first_obs == options.first_simulation_period - DynareModel.orig_maximum_lag
if options.first_obs == options.first_simulation_period - M_.orig_maximum_lag
first_obs = periods(options.first_obs);
else
error('%s_FILE: first_obs = %d and first_simulation_period = %d have values inconsistent with a maximum lag of %d periods', ...
caller, options.first_obs, options.first_simulation_period, DynareModel.orig_maximum_lag)
caller, options.first_obs, options.first_simulation_period, M_.orig_maximum_lag)
end
elseif isfield(options, 'firstsimulationperiod')
if periods(options.first_obs) == options.firstsimulationperiod - DynareModel.orig_maximum_lag
if periods(options.first_obs) == options.firstsimulationperiod - M_.orig_maximum_lag
first_obs = periods(options.first_obs);
else
error('%s_FILE: first_obs = %d and first_simulation_period = %s have values inconsistent with a maximum lag of %d periods', ...
caller, options.first_obs, options.firstsimulationperiod, DynareModel.orig_maximum_lag)
caller, options.first_obs, options.firstsimulationperiod, M_.orig_maximum_lag)
end
else
first_obs = periods(options.first_obs);
@ -150,18 +150,18 @@ end
if isfield(options, 'firstobs') && ~isempty(options.firstobs)
if isfield(options, 'first_simulation_period')
if options.firstobs == periods(options.first_simulation_period) - DynareModel.orig_maximum_lag
if options.firstobs == periods(options.first_simulation_period) - M_.orig_maximum_lag
first_obs = options.firstobs;
else
error('%s_FILE: first_obs = %s and first_simulation_period = %d have values inconsistent with a maximum lag of %d periods', ...
caller, options.firstobs, options.first_simulation_period, DynareModel.orig_maximum_lag)
caller, options.firstobs, options.first_simulation_period, M_.orig_maximum_lag)
end
elseif isfield(options, 'firstsimulationperiod')
if options.firstobs == options.firstsimulationperiod - DynareModel.orig_maximum_lag
if options.firstobs == options.firstsimulationperiod - M_.orig_maximum_lag
first_obs = options.firstobs;
else
error('%s_FILE: firstobs = %s and first_simulation_period = %s have values inconsistent with a maximum lag of %d periods', ...
caller, options.firstobs, options.firstsimulationperiod, DynareModel.orig_maximum_lag)
caller, options.firstobs, options.firstsimulationperiod, M_.orig_maximum_lag)
end
else
first_obs = options.firstobs;
@ -171,18 +171,18 @@ end
if ~first_obs_ispresent
if isfield(options, 'first_simulation_period')
if options.first_simulation_period < DynareModel.orig_maximum_lag
if options.first_simulation_period < M_.orig_maximum_lag
error('%s_FILE: first_simulation_period = %d must be larger than the maximum lag (%d)', ...
caller, options.first_simulation_period, DynareModel.orig_maximum_lag)
caller, options.first_simulation_period, M_.orig_maximum_lag)
elseif options.first_simulation_period > nobs0
error('%s_FILE: first_simulations_period = %d is larger than the number of observations in the data file (%d)', ...
caller, options.first_obs, nobs0)
else
first_obs = periods(options.first_simulation_period) - DynareModel.orig_maximum_lag;
first_obs = periods(options.first_simulation_period) - M_.orig_maximum_lag;
end
first_obs_ispresent = true;
elseif isfield(options, 'firstsimulationperiod')
first_obs = options.firstsimulationperiod - DynareModel.orig_maximum_lag;
first_obs = options.firstsimulationperiod - M_.orig_maximum_lag;
first_obs_ispresent = true;
end
end
@ -237,8 +237,8 @@ end
if exist('lastsimulationperiod', 'var')
if lastsimulationperiod<=last_obs-DynareModel.orig_maximum_lead
last_obs = lastsimulationperiod+DynareModel.orig_maximum_lead;
if lastsimulationperiod<=last_obs-M_.orig_maximum_lead
last_obs = lastsimulationperiod+M_.orig_maximum_lead;
else
error('%s_FILE: LAST_SIMULATION_PERIOD is too large compared to the available data.', caller)
end
@ -247,11 +247,11 @@ end
if exist('lastsimulationperiod', 'var') && exist('firstsimulationperiod', 'var')
p = lastsimulationperiod-firstsimulationperiod+1;
elseif exist('lastsimulationperiod', 'var')
p = lastsimulationperiod-(first_obs+DynareModel.orig_maximum_lag)+1;
p = lastsimulationperiod-(first_obs+M_.orig_maximum_lag)+1;
elseif exist('firstsimulationperiod', 'var')
p = (last_obs-DynareModel.orig_maximum_lead)-firstsimulationperiod+1;
p = (last_obs-M_.orig_maximum_lead)-firstsimulationperiod+1;
else
p = (last_obs-DynareModel.orig_maximum_lead)-(first_obs+DynareModel.orig_maximum_lag)+1;
p = (last_obs-M_.orig_maximum_lead)-(first_obs+M_.orig_maximum_lag)+1;
end
series = series(first_obs:last_obs);

View File

@ -99,10 +99,10 @@ if ~isfield(oo_,'initval_decomposition') || isequal(varlist,0)
with_epilogue = options_.initial_condition_decomp.with_epilogue;
options_.selected_variables_only = 0; %make sure all variables are stored
options_.plot_priors=0;
[oo,M,~,~,Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_);
[oo_local,M,~,~,Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_);
% reduced form
dr = oo.dr;
dr = oo_local.dr;
% data reordering
order_var = dr.order_var;
@ -114,7 +114,7 @@ if ~isfield(oo_,'initval_decomposition') || isequal(varlist,0)
B = dr.ghu;
% initialization
gend = length(oo.SmoothedShocks.(M_.exo_names{1})); %+options_.forecast;
gend = length(oo_local.SmoothedShocks.(M_.exo_names{1})); %+options_.forecast;
z = zeros(endo_nbr,endo_nbr+2,gend);
z(:,end,:) = Smoothed_Variables_deviation_from_mean;
@ -155,15 +155,15 @@ end
if ~isequal(varlist,0)
% if ~options_.no_graph.shock_decomposition
oo=oo_;
oo.shock_decomposition = oo_.initval_decomposition;
oo_local=oo_;
oo_local.shock_decomposition = oo_.initval_decomposition;
if ~isempty(init2shocks)
init2shocks = M_.init2shocks.(init2shocks);
n=size(init2shocks,1);
for i=1:n
j=strmatch(init2shocks{i}{1},M_.endo_names,'exact');
oo.shock_decomposition(:,end-1,:)=oo.shock_decomposition(:,j,:)+oo.shock_decomposition(:,end-1,:);
oo.shock_decomposition(:,j,:)=0;
oo_local.shock_decomposition(:,end-1,:)=oo_local.shock_decomposition(:,j,:)+oo_local.shock_decomposition(:,end-1,:);
oo_local.shock_decomposition(:,j,:)=0;
end
end
M_.exo_names = M_.endo_names;
@ -173,5 +173,5 @@ if ~isequal(varlist,0)
options_.plot_shock_decomp.use_shock_groups = '';
options_.plot_shock_decomp.init_cond_decomp = 1; % private flag to plotting utilities
plot_shock_decomposition(M_,oo,options_,varlist);
plot_shock_decomposition(M_,oo_local,options_,varlist);
end

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,14 +1,14 @@
function Qvec=get_Qvec_heteroskedastic_filter(Q,smpl,Model)
% function Qvec=get_Qvec_heteroskedastic_filter(Q,smpl,Model)
function Qvec=get_Qvec_heteroskedastic_filter(Q,smpl,M_)
% function Qvec=get_Qvec_heteroskedastic_filter(Q,smpl,M_)
%
% INPUTS
% Q: baseline non-heteroskadastic covariance matrix of shocks
% smpl: scalar storing end of sample
% Model: structure storing the model information
% M_: structure storing the model information
% Outputs:
% Qvec: [n_exo by n_exo by smpl] array of covariance matrices
% Copyright © 2020-21 Dynare Team
% Copyright © 2020-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -28,31 +28,31 @@ function Qvec=get_Qvec_heteroskedastic_filter(Q,smpl,Model)
isqdiag = all(all(abs(Q-diag(diag(Q)))<1e-14)); % ie, the covariance matrix is diagonal...
Qvec=repmat(Q,[1 1 smpl+1]);
for k=1:smpl
inx = ~isnan(Model.heteroskedastic_shocks.Qvalue(:,k));
inx = ~isnan(M_.heteroskedastic_shocks.Qvalue(:,k));
if any(inx)
if isqdiag
Qvec(inx,inx,k)=diag(Model.heteroskedastic_shocks.Qvalue(inx,k));
Qvec(inx,inx,k)=diag(M_.heteroskedastic_shocks.Qvalue(inx,k));
else
inx = find(inx);
for s=1:length(inx)
if Q(inx(s),inx(s))>1.e-14
tmpscale = sqrt(Model.heteroskedastic_shocks.Qvalue(inx(s),k)./Q(inx(s),inx(s)));
tmpscale = sqrt(M_.heteroskedastic_shocks.Qvalue(inx(s),k)./Q(inx(s),inx(s)));
Qvec(inx(s),:,k) = Qvec(inx(s),:,k).*tmpscale;
Qvec(:,inx(s),k) = Qvec(:,inx(s),k).*tmpscale;
else
Qvec(inx(s),inx(s),k)=Model.heteroskedastic_shocks.Qvalue(inx(s),k);
Qvec(inx(s),inx(s),k)=M_.heteroskedastic_shocks.Qvalue(inx(s),k);
end
end
end
end
inx = ~isnan(Model.heteroskedastic_shocks.Qscale(:,k));
inx = ~isnan(M_.heteroskedastic_shocks.Qscale(:,k));
if any(inx)
if isqdiag
Qvec(inx,inx,k)=Qvec(inx,inx,k).*diag(Model.heteroskedastic_shocks.Qscale(inx,k));
Qvec(inx,inx,k)=Qvec(inx,inx,k).*diag(M_.heteroskedastic_shocks.Qscale(inx,k));
else
inx = find(inx);
for s=1:length(inx)
tmpscale = sqrt(Model.heteroskedastic_shocks.Qscale(inx(s),k));
tmpscale = sqrt(M_.heteroskedastic_shocks.Qscale(inx(s),k));
Qvec(inx(s),:,k) = Qvec(inx(s),:,k).*tmpscale;
Qvec(:,inx(s),k) = Qvec(:,inx(s),k).*tmpscale;
end

View File

@ -1,6 +1,7 @@
function [endo_simul,info] = dyn_lmmcp(M,options,oo)
function [endo_simul,info] = dyn_lmmcp(M_,options,oo_)
% [endo_simul,info] = dyn_lmmcp(M_,options,oo_)
% Copyright © 2014 Dynare Team
% Copyright © 2014-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -17,13 +18,13 @@ function [endo_simul,info] = dyn_lmmcp(M,options,oo)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
[lb,ub,eq_index] = get_complementarity_conditions(M);
[lb,ub,eq_index] = get_complementarity_conditions(M_);
lead_lag_incidence = M.lead_lag_incidence;
lead_lag_incidence = M_.lead_lag_incidence;
ny = M.endo_nbr;
ny = M_.endo_nbr;
max_lag = M.maximum_endo_lag;
max_lag = M_.maximum_endo_lag;
nyp = nnz(lead_lag_incidence(1,:)) ;
iyp = find(lead_lag_incidence(1,:)>0) ;
@ -42,10 +43,10 @@ stop = 0 ;
iz = [1:ny+nyp+nyf];
periods = options.periods;
steady_state = oo.steady_state;
params = M.params;
endo_simul = oo.endo_simul;
exo_simul = oo.exo_simul;
steady_state = oo_.steady_state;
params = M_.params;
endo_simul = oo_.endo_simul;
exo_simul = oo_.exo_simul;
i_cols_1 = nonzeros(lead_lag_incidence(2:3,:)');
i_cols_A1 = find(lead_lag_incidence(2:3,:)');
i_cols_T = nonzeros(lead_lag_incidence(1:2,:)');
@ -54,7 +55,7 @@ i_upd = ny+(1:periods*ny);
x = endo_simul(:);
model_dynamic = str2func([M.fname,'.dynamic']);
model_dynamic = str2func([M_.fname,'.dynamic']);
z = x(find(lead_lag_incidence'));
[res,A] = model_dynamic(z, exo_simul, params, steady_state,2);
nnzA = nnz(A);

View File

@ -56,18 +56,18 @@ if ~isfinite(summ)
end
eq_number_string=[eq_number_string, num2str(j1(end))];
var_string=[];
Model=evalin('base','M_');
M_=evalin('base','M_');
for ii=1:length(j2)-1
var_string=[var_string, Model.endo_names{j2(ii)}, ', '];
var_string=[var_string, M_.endo_names{j2(ii)}, ', '];
end
var_string=[var_string, Model.endo_names{j2(end)}];
var_string=[var_string, M_.endo_names{j2(end)}];
fprintf('\nAn infinite element was encountered when trying to solve equation(s) %s \n',eq_number_string)
fprintf('with respect to the variable(s): %s.\n',var_string)
fprintf('The values of the endogenous variables when the problem was encountered were:\n')
label_width=size(char(Model.endo_names),2)+2;
label_width=size(char(M_.endo_names),2)+2;
label_string=sprintf('%%-%us %%8.4g \\n',label_width);
for ii=1:length(xold)
fprintf(label_string, Model.endo_names{ii}, xold(ii));
fprintf(label_string, M_.endo_names{ii}, xold(ii));
end
skipline();
end

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 @@
% [dynpp_derivs, dyn_derivs] = k_order_perturbation(dr,DynareModel,DynareOptions)
% [dynpp_derivs, dyn_derivs] = k_order_perturbation(dr,M_,options_)
% computes a k-th order perturbation solution
%
% 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
% dynpp_derivs struct Derivatives of the decision rule in Dynare++ format.
@ -25,7 +25,7 @@
% dynare/mex/sources/k_order_perturbation.cc and it uses code provided by
% dynare++
% Copyright © 2013-2021 Dynare Team
% Copyright © 2013-2023 Dynare Team
%
% This file is part of Dynare.
%

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,17 +1,17 @@
function oo = model_comparison(ModelNames,ModelPriors,oo,options_,fname)
% function oo = model_comparison(ModelNames,ModelPriors,oo,options_,fname)
function oo_ = model_comparison(ModelNames,ModelPriors,oo_,options_,fname)
% function oo_ = model_comparison(ModelNames,ModelPriors,oo_,options_,fname)
% Conducts Bayesian model comparison. This function computes Odds ratios and
% estimates a posterior density over a collection of models.
%
% INPUTS
% ModelNames [string] m*1 cell array of string.
% ModelPriors [double] m*1 vector of prior probabilities
% oo [struct] Dynare results structure
% oo_ [struct] Dynare results structure
% options_ [struct] Dynare options structure
% fname [string] name of the current mod-file
%
% OUTPUTS
% oo [struct] Dynare results structure containing the
% oo_ [struct] Dynare results structure containing the
% results in a field PosteriorOddsTable
%
% ALGORITHM
@ -20,7 +20,7 @@ function oo = model_comparison(ModelNames,ModelPriors,oo,options_,fname)
% SPECIAL REQUIREMENTS
% none
% Copyright © 2007-2018 Dynare Team
% Copyright © 2007-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -78,7 +78,7 @@ iname = strmatch(fname,ShortModelNames,'exact');
for i=1:NumberOfModels
if i==iname
mstruct.oo_ = oo;
mstruct.oo_ = oo_;
else
if length(ModelNames{i})>3 && (strcmpi(ModelNames{i}(end-3:end),'.mod') || strcmpi(ModelNames{i}(end-3:end),'.dyn'))
mstruct = load([ModelNames{i}(1:end-4) filesep 'Output' ModelNames{i}(1:end-4) '_results.mat' ],'oo_');
@ -127,7 +127,7 @@ end
for model_iter = 1:NumberOfModels
for var_iter = 1:length(labels)
oo.Model_Comparison.(headers{1+model_iter}).(field_labels{var_iter}) = values(var_iter, model_iter);
oo_.Model_Comparison.(headers{1+model_iter}).(field_labels{var_iter}) = values(var_iter, model_iter);
end
end

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

@ -46,7 +46,7 @@ if isempty(init_flag)
init_flag = 1;
end
order = DynareOptions.order;
order = options_.order;
% Set local state space model (first order approximation).
ghx = ReducedForm.ghx;
@ -83,7 +83,7 @@ state_variance_rank = size(StateVectorVarianceSquareRoot,2);
%end
% Set seed for randn().
DynareOptions=set_dynare_seed_local_options(DynareOptions,'default');
options_=set_dynare_seed_local_options(options_,'default');
% Initialization of the likelihood.
const_lik = log(2*pi)*number_of_observed_variables;

View File

@ -1,9 +1,9 @@
function [LIK,lik] = auxiliary_particle_filter(ReducedForm,Y,start,ParticleOptions,ThreadsOptions, DynareOptions, Model)
function [LIK,lik] = auxiliary_particle_filter(ReducedForm,Y,start,ParticleOptions,ThreadsOptions, options_, M_)
% [LIK,lik] = auxiliary_particle_filter(ReducedForm,Y,start,ParticleOptions,ThreadsOptions, options_, M_)
% Evaluates the likelihood of a nonlinear model with the auxiliary particle filter
% allowing eventually resampling.
%
% Copyright © 2011-2022 Dynare Team
% Copyright © 2011-2023 Dynare Team
%
% This file is part of Dynare (particles module).
%
@ -25,7 +25,7 @@ if isempty(start)
start = 1;
end
% Get perturbation order
order = DynareOptions.order;
order = options_.order;
% Set flag for prunning
pruning = ParticleOptions.pruning;
@ -77,7 +77,7 @@ state_variance_rank = size(StateVectorVarianceSquareRoot,2);
Q_lower_triangular_cholesky = chol(Q)';
% Set seed for randn().
DynareOptions=set_dynare_seed_local_options(DynareOptions,'default');
options_=set_dynare_seed_local_options(options_,'default');
% Initialization of the likelihood.
const_lik = log(2*pi)*number_of_observed_variables+log(det(H));
@ -119,7 +119,7 @@ for t=1:sample_size
end
else
if ReducedForm.use_k_order_solver
tmp = local_state_space_iteration_k(yhat, zeros(number_of_structural_innovations,number_of_particles), dr, Model, DynareOptions, udr);
tmp = local_state_space_iteration_k(yhat, zeros(number_of_structural_innovations,number_of_particles), dr, M_, options_, udr);
else
if order == 2
tmp = local_state_space_iteration_2(yhat,zeros(number_of_structural_innovations,number_of_particles),ghx,ghu,constant,ghxx,ghuu,ghxu,ThreadsOptions.local_state_space_iteration_2);
@ -152,7 +152,7 @@ for t=1:sample_size
StateVectors_ = tmp_(mf0_,:);
else
if ReducedForm.use_k_order_solver
tmp = local_state_space_iteration_k(yhat, epsilon, dr, Model, DynareOptions, udr);
tmp = local_state_space_iteration_k(yhat, epsilon, dr, M_, options_, udr);
else
if order == 2
tmp = local_state_space_iteration_2(yhat, epsilon, ghx, ghu, constant, ghxx, ghuu, ghxu, ThreadsOptions.local_state_space_iteration_2);

View File

@ -1,5 +1,5 @@
function [ProposalStateVector, Weights, flag] = conditional_filter_proposal(ReducedForm, y, StateVectors, SampleWeights, Q_lower_triangular_cholesky, H_lower_triangular_cholesky, ...
H, ParticleOptions, ThreadsOptions, DynareOptions, Model)
H, ParticleOptions, ThreadsOptions, options_, M_)
% Computes the proposal for each past particle using Gaussian approximations
% for the state errors and the Kalman filter
@ -14,8 +14,8 @@ function [ProposalStateVector, Weights, flag] = conditional_filter_proposal(Redu
% - H
% - ParticleOptions
% - ThreadsOptions
% - DynareOptions
% - Model
% - options_
% - M_
%
% OUTPUTS
% - ProposalStateVector
@ -41,7 +41,7 @@ function [ProposalStateVector, Weights, flag] = conditional_filter_proposal(Redu
flag = false;
order = DynareOptions.order;
order = options_.order;
if ReducedForm.use_k_order_solver
dr = ReducedForm.dr;
@ -93,7 +93,7 @@ epsilon = Q_lower_triangular_cholesky*nodes';
yhat = repmat(StateVectors-state_variables_steady_state, 1, size(epsilon, 2));
if ReducedForm.use_k_order_solver
tmp = local_state_space_iteration_k(yhat, epsilon, dr, Model, DynareOptions, udr);
tmp = local_state_space_iteration_k(yhat, epsilon, dr, M_, options_, udr);
else
if order == 2
tmp = local_state_space_iteration_2(yhat, epsilon, ghx, ghu, constant, ghxx, ghuu, ghxu, ThreadsOptions.local_state_space_iteration_2);
@ -159,6 +159,6 @@ if ParticleOptions.cpf_weights_method.murrayjonesparslow
end
Prior = probability2(PredictedStateMean, PredictedStateVarianceSquareRoot, ProposalStateVector);
Posterior = probability2(StateVectorMean, StateVectorVarianceSquareRoot, ProposalStateVector);
Likelihood = probability2(y, H_lower_triangular_cholesky, measurement_equations(ProposalStateVector, ReducedForm, ThreadsOptions, DynareOptions, Model));
Likelihood = probability2(y, H_lower_triangular_cholesky, measurement_equations(ProposalStateVector, ReducedForm, ThreadsOptions, options_, M_));
Weights = SampleWeights.*Likelihood.*(Prior./Posterior);
end

View File

@ -1,4 +1,4 @@
function [LIK,lik] = conditional_particle_filter(ReducedForm, Y, s, ParticleOptions, ThreadsOptions, DynareOptions, Model)
function [LIK,lik] = conditional_particle_filter(ReducedForm, Y, s, ParticleOptions, ThreadsOptions, options_, M_)
% Evaluates the likelihood of a non-linear model with a particle filter
%
@ -8,8 +8,8 @@ function [LIK,lik] = conditional_particle_filter(ReducedForm, Y, s, ParticleOpti
% - s [integer] scalar, likelihood evaluation starts at s (has to be smaller than T, the sample length provided in Y).
% - ParticlesOptions [struct]
% - ThreadsOptions [struct]
% - DynareOptions [struct]
% - Model [struct]
% - options_ [struct]
% - M_ [struct]
%
% OUTPUTS
% - LIK [double] scalar, likelihood
@ -78,7 +78,7 @@ state_variance_rank = size(StateVectorVarianceSquareRoot, 2);
Q_lower_triangular_cholesky = chol(Q)';
% Set seed for randn().
DynareOptions=set_dynare_seed_local_options(DynareOptions,'default');
options_=set_dynare_seed_local_options(options_,'default');
% Initialization of the likelihood.
lik = NaN(T, 1);
@ -90,7 +90,7 @@ for t=1:T
flags = false(n, 1);
for i=1:n
[StateParticles(:,i), SampleWeights(i), flags(i)] = ...
conditional_filter_proposal(ReducedForm, Y(:,t), StateParticles(:,i), SampleWeights(i), Q_lower_triangular_cholesky, H_lower_triangular_cholesky, H, ParticleOptions, ThreadsOptions, DynareOptions, Model);
conditional_filter_proposal(ReducedForm, Y(:,t), StateParticles(:,i), SampleWeights(i), Q_lower_triangular_cholesky, H_lower_triangular_cholesky, H, ParticleOptions, ThreadsOptions, options_, M_);
end
if any(flags)
LIK = -Inf;

View File

@ -1,5 +1,5 @@
function IncrementalWeights = gaussian_densities(obs,mut_t,sqr_Pss_t_t,st_t_1,sqr_Pss_t_t_1,particles,H,normconst,weigths1,weigths2,ReducedForm,ThreadsOptions,DynareOptions, Model)
%
function IncrementalWeights = gaussian_densities(obs,mut_t,sqr_Pss_t_t,st_t_1,sqr_Pss_t_t_1,particles,H,normconst,weigths1,weigths2,ReducedForm,ThreadsOptions,options_, M_)
% IncrementalWeights = gaussian_densities(obs,mut_t,sqr_Pss_t_t,st_t_1,sqr_Pss_t_t_1,particles,H,normconst,weigths1,weigths2,ReducedForm,ThreadsOptions,options_, M_)
% Elements to calculate the importance sampling ratio
%
% INPUTS
@ -20,7 +20,7 @@ function IncrementalWeights = gaussian_densities(obs,mut_t,sqr_Pss_t_t,st_t_1,sq
% NOTES
% The vector "lik" is used to evaluate the jacobian of the likelihood.
% Copyright © 2009-2019 Dynare Team
% Copyright © 2009-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -44,7 +44,7 @@ proposal = probability2(mut_t, sqr_Pss_t_t, particles);
prior = probability2(st_t_1, sqr_Pss_t_t_1, particles);
% likelihood
yt_t_1_i = measurement_equations(particles, ReducedForm, ThreadsOptions, DynareOptions, Model);
yt_t_1_i = measurement_equations(particles, ReducedForm, ThreadsOptions, options_, M_);
likelihood = probability2(obs, sqrt(H), yt_t_1_i);
IncrementalWeights = likelihood.*prior./proposal;

View File

@ -1,5 +1,5 @@
function [LIK,lik] = gaussian_filter(ReducedForm, Y, start, ParticleOptions, ThreadsOptions, DynareOptions, Model)
function [LIK,lik] = gaussian_filter(ReducedForm, Y, start, ParticleOptions, ThreadsOptions, options_, M_)
% [LIK,lik] = gaussian_filter(ReducedForm, Y, start, ParticleOptions, ThreadsOptions, options_, M_)
% Evaluates the likelihood of a non-linear model approximating the
% predictive (prior) and filtered (posterior) densities for state variables
% by gaussian distributions.
@ -74,7 +74,7 @@ else
end
if ParticleOptions.distribution_approximation.montecarlo
DynareOptions=set_dynare_seed_local_options(DynareOptions,'default');
options_=set_dynare_seed_local_options(options_,'default');
end
% Get covariance matrices
@ -101,20 +101,20 @@ LIK = NaN;
for t=1:sample_size
[PredictedStateMean, PredictedStateVarianceSquareRoot, StateVectorMean, StateVectorVarianceSquareRoot] = ...
gaussian_filter_bank(ReducedForm, Y(:,t), StateVectorMean, StateVectorVarianceSquareRoot, Q_lower_triangular_cholesky, H_lower_triangular_cholesky, ...
H, ParticleOptions, ThreadsOptions, DynareOptions, Model);
H, ParticleOptions, ThreadsOptions, options_, M_);
if ParticleOptions.distribution_approximation.cubature || ParticleOptions.distribution_approximation.unscented
StateParticles = bsxfun(@plus, StateVectorMean, StateVectorVarianceSquareRoot*nodes2');
IncrementalWeights = gaussian_densities(Y(:,t), StateVectorMean, StateVectorVarianceSquareRoot, PredictedStateMean, ...
PredictedStateVarianceSquareRoot, StateParticles, H, const_lik, ...
weights2, weights_c2, ReducedForm, ThreadsOptions, ...
DynareOptions, Model);
options_, M_);
SampleWeights = weights2.*IncrementalWeights;
else
StateParticles = bsxfun(@plus, StateVectorVarianceSquareRoot*randn(state_variance_rank, number_of_particles), StateVectorMean) ;
IncrementalWeights = gaussian_densities(Y(:,t), StateVectorMean, StateVectorVarianceSquareRoot, PredictedStateMean, ...
PredictedStateVarianceSquareRoot,StateParticles,H,const_lik, ...
1/number_of_particles,1/number_of_particles,ReducedForm,ThreadsOptions, ...
DynareOptions, Model);
options_, M_);
SampleWeights = IncrementalWeights/number_of_particles;
end
SampleWeights = SampleWeights + 1e-6*ones(size(SampleWeights, 1), 1);

View File

@ -1,6 +1,6 @@
function [PredictedStateMean, PredictedStateVarianceSquareRoot, StateVectorMean, StateVectorVarianceSquareRoot] = ...
gaussian_filter_bank(ReducedForm, obs, StateVectorMean, StateVectorVarianceSquareRoot, Q_lower_triangular_cholesky, H_lower_triangular_cholesky, H, ...
ParticleOptions, ThreadsOptions, DynareOptions, Model)
ParticleOptions, ThreadsOptions, options_, M_)
%
% Computes the proposal with a gaussian approximation for importance
% sampling
@ -39,7 +39,7 @@ function [PredictedStateMean, PredictedStateVarianceSquareRoot, StateVectorMean,
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
order = DynareOptions.order;
order = options_.order;
if ReducedForm.use_k_order_solver
dr = ReducedForm.dr;
@ -95,7 +95,7 @@ StateVectors = sigma_points(1:number_of_state_variables,:);
epsilon = sigma_points(number_of_state_variables+1:number_of_state_variables+number_of_structural_innovations,:);
yhat = bsxfun(@minus, StateVectors, state_variables_steady_state);
if ReducedForm.use_k_order_solver
tmp = local_state_space_iteration_k(yhat, epsilon, dr, Model, DynareOptions, udr);
tmp = local_state_space_iteration_k(yhat, epsilon, dr, M_, options_, udr);
else
if order == 2
tmp = local_state_space_iteration_2(yhat, epsilon, ghx, ghu, constant, ghxx, ghuu, ghxu, ThreadsOptions.local_state_space_iteration_2);

View File

@ -1,6 +1,6 @@
function IncrementalWeights = gaussian_mixture_densities(obs, StateMuPrior, StateSqrtPPrior, StateWeightsPrior, ...
StateMuPost, StateSqrtPPost, StateWeightsPost, StateParticles, H, ...
ReducedForm, ThreadsOptions, DynareOptions, Model)
ReducedForm, ThreadsOptions, options_, M_)
% Elements to calculate the importance sampling ratio
%
@ -22,7 +22,7 @@ function IncrementalWeights = gaussian_mixture_densities(obs, StateMuPrior, Sta
% NOTES
% The vector "lik" is used to evaluate the jacobian of the likelihood.
% Copyright © 2009-2019 Dynare Team
% Copyright © 2009-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -48,7 +48,7 @@ prior = prior';
proposal = proposal';
% Compute the density of the current observation conditionally to each particle
yt_t_1_i = measurement_equations(StateParticles, ReducedForm, ThreadsOptions, DynareOptions, Model);
yt_t_1_i = measurement_equations(StateParticles, ReducedForm, ThreadsOptions, options_, M_);
% likelihood
likelihood = probability2(obs, sqrt(H), yt_t_1_i);

View File

@ -1,4 +1,4 @@
function [LIK, lik] = gaussian_mixture_filter(ReducedForm, Y, start, ParticleOptions, ThreadsOptions, DynareOptions, Model)
function [LIK, lik] = gaussian_mixture_filter(ReducedForm, Y, start, ParticleOptions, ThreadsOptions, options_, M_)
% Evaluates the likelihood of a non-linear model approximating the state
% variables distributions with gaussian mixtures. Gaussian Mixture allows reproducing
@ -79,7 +79,7 @@ else
end
if ParticleOptions.distribution_approximation.montecarlo
DynareOptions=set_dynare_seed_local_options(DynareOptions,'default');
options_=set_dynare_seed_local_options(options_,'default');
end
% Get covariance matrices
@ -178,7 +178,7 @@ for t=1:sample_size
gaussian_mixture_filter_bank(ReducedForm,Y(:,t), StateMu(:,g), StateSqrtP(:,:,g), StateWeights(g),...
StructuralShocksMu(:,i), StructuralShocksSqrtP(:,:,i), StructuralShocksWeights(i),...
ObservationShocksWeights(j), H, H_lower_triangular_cholesky, const_lik, ...
ParticleOptions, ThreadsOptions, DynareOptions, Model);
ParticleOptions, ThreadsOptions, options_, M_);
end
end
end
@ -192,7 +192,7 @@ for t=1:sample_size
StateParticles = bsxfun(@plus, StateMuPost(:,i), StateSqrtPPost(:,:,i)*nodes');
IncrementalWeights = gaussian_mixture_densities(Y(:,t), StateMuPrior, StateSqrtPPrior, StateWeightsPrior, ...
StateMuPost, StateSqrtPPost, StateWeightsPost, StateParticles, H, ...
ReducedForm, ThreadsOptions, DynareOptions, Model);
ReducedForm, ThreadsOptions, options_, M_);
SampleWeights(i) = sum(StateWeightsPost(i)*weights.*IncrementalWeights);
end
SumSampleWeights = sum(SampleWeights);
@ -210,7 +210,7 @@ for t=1:sample_size
StateParticles = importance_sampling(StateMuPost,StateSqrtPPost,StateWeightsPost',number_of_particles);
IncrementalWeights = gaussian_mixture_densities(Y(:,t), StateMuPrior, StateSqrtPPrior, StateWeightsPrior, ...
StateMuPost, StateSqrtPPost, StateWeightsPost, StateParticles, H, ...
ReducedForm, ThreadsOptions, DynareOptions, Model);
ReducedForm, ThreadsOptions, options_, M_);
SampleWeights = IncrementalWeights/number_of_particles;
SumSampleWeights = sum(SampleWeights,1);
SampleWeights = SampleWeights./SumSampleWeights;

View File

@ -2,7 +2,7 @@ function [StateMuPrior,StateSqrtPPrior,StateWeightsPrior,StateMuPost,StateSqrtPP
gaussian_mixture_filter_bank(ReducedForm, obs, StateMu, StateSqrtP, StateWeights, ...
StructuralShocksMu, StructuralShocksSqrtP, StructuralShocksWeights, ...
ObservationShocksWeights, H, H_lower_triangular_cholesky, normfactO, ...
ParticleOptions, ThreadsOptions, DynareOptions, Model)
ParticleOptions, ThreadsOptions, options_, M_)
% Computes the proposal with a gaussian approximation for importance
% sampling
@ -41,7 +41,7 @@ function [StateMuPrior,StateSqrtPPrior,StateWeightsPrior,StateMuPost,StateSqrtPP
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
order = DynareOptions.order;
order = options_.order;
if ReducedForm.use_k_order_solver
dr = ReducedForm.dr;
@ -91,7 +91,7 @@ epsilon = bsxfun(@plus, StructuralShocksSqrtP*nodes3(:,number_of_state_variables
StateVectors = bsxfun(@plus, StateSqrtP*nodes3(:,1:number_of_state_variables)', StateMu);
yhat = bsxfun(@minus, StateVectors, state_variables_steady_state);
if ReducedForm.use_k_order_solver
tmp = local_state_space_iteration_k(yhat, epsilon, dr, Model, DynareOptions, udr);
tmp = local_state_space_iteration_k(yhat, epsilon, dr, M_, options_, udr);
else
if order == 2
tmp = local_state_space_iteration_2(yhat, epsilon, ghx, ghu, constant, ghxx, ghuu, ghxu, ThreadsOptions.local_state_space_iteration_2);

View File

@ -1,4 +1,4 @@
function measure = measurement_equations(StateVectors,ReducedForm,ThreadsOptions, DynareOptions, Model)
function measure = measurement_equations(StateVectors,ReducedForm,ThreadsOptions, options_, M_)
% Copyright © 2013-2022 Dynare Team
%
@ -17,7 +17,7 @@ function measure = measurement_equations(StateVectors,ReducedForm,ThreadsOptions
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
order = DynareOptions.order;
order = options_.order;
mf1 = ReducedForm.mf1;
if ReducedForm.use_k_order_solver
dr = ReducedForm.dr;
@ -44,7 +44,7 @@ state_variables_steady_state = ReducedForm.state_variables_steady_state;
number_of_structural_innovations = length(ReducedForm.Q);
yhat = bsxfun(@minus, StateVectors, state_variables_steady_state);
if ReducedForm.use_k_order_solver
tmp = local_state_space_iteration_k(yhat, zeros(number_of_structural_innovations, size(yhat,2)), dr, Model, DynareOptions, udr);
tmp = local_state_space_iteration_k(yhat, zeros(number_of_structural_innovations, size(yhat,2)), dr, M_, options_, udr);
measure = tmp(mf1,:);
else
if order == 2

View File

@ -1,4 +1,4 @@
function [LIK,lik] = nonlinear_kalman_filter(ReducedForm, Y, start, ParticleOptions, ThreadsOptions, DynareOptions, Model)
function [LIK,lik] = nonlinear_kalman_filter(ReducedForm, Y, start, ParticleOptions, ThreadsOptions, options_, M_)
% Evaluates the likelihood of a non-linear model approximating the
% predictive (prior) and filtered (posterior) densities for state variables
@ -54,7 +54,7 @@ if isempty(start)
start = 1;
end
order = DynareOptions.order;
order = options_.order;
if ReducedForm.use_k_order_solver
dr = ReducedForm.dr;
@ -105,7 +105,7 @@ else
end
if ParticleOptions.distribution_approximation.montecarlo
DynareOptions=set_dynare_seed_local_options(DynareOptions,'default');
options_=set_dynare_seed_local_options(options_,'default');
end
% Get covariance matrices
@ -130,7 +130,7 @@ for t=1:sample_size
epsilon = sigma_points(number_of_state_variables+1:number_of_state_variables+number_of_structural_innovations,:);
yhat = bsxfun(@minus,StateVectors,state_variables_steady_state);
if ReducedForm.use_k_order_solver
tmp = local_state_space_iteration_k(yhat, epsilon, dr, Model, DynareOptions, udr);
tmp = local_state_space_iteration_k(yhat, epsilon, dr, M_, options_, udr);
else
if order == 2
tmp = local_state_space_iteration_2(yhat, epsilon, ghx, ghu, constant, ghxx, ghuu, ghxu, ThreadsOptions.local_state_space_iteration_2);

View File

@ -1,16 +1,16 @@
function [pmean, pmode, pmedian, pstdev, p025, p975, covariance] = online_auxiliary_filter(xparam1, DynareDataset, DynareOptions, Model, EstimatedParameters, BayesInfo, DynareResults)
function [pmean, pmode, pmedian, pstdev, p025, p975, covariance] = online_auxiliary_filter(xparam1, dataset_, options_, M_, estim_params_, bayestopt_, oo_)
% [pmean, pmode, pmedian, pstdev, p025, p975, covariance] = online_auxiliary_filter(xparam1, dataset_, options_, M_, estim_params_, bayestopt_, oo_)
% Liu & West particle filter = auxiliary particle filter including Liu & West filter on parameters.
%
% INPUTS
% - xparam1 [double] n×1 vector, Initial condition for the estimated parameters.
% - DynareDataset [dseries] Sample used for estimation.
% - dataset_ [dseries] Sample used for estimation.
% - dataset_info [struct] Description of the sample.
% - DynareOptions [struct] Option values (options_).
% - Model [struct] Description of the model (M_).
% - EstimatedParameters [struct] Description of the estimated parameters (estim_params_).
% - BayesInfo [struct] Prior definition (bayestopt_).
% - DynareResults [struct] Results (oo_).
% - options_ [struct] Option values.
% - M_ [struct] Description of the model.
% - estim_params_ [struct] Description of the estimated parameters.
% - bayestopt_ [struct] Prior definition.
% - oo_ [struct] Results.
%
% OUTPUTS
% - pmean [double] n×1 vector, mean of the particles at the end of the sample (for the parameters).
@ -39,26 +39,26 @@ function [pmean, pmode, pmedian, pstdev, p025, p975, covariance] = online_auxili
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
% Set seed for randn().
DynareOptions=set_dynare_seed_local_options(DynareOptions,'default');
pruning = DynareOptions.particle.pruning;
second_resample = DynareOptions.particle.resampling.status.systematic;
options_=set_dynare_seed_local_options(options_,'default');
pruning = options_.particle.pruning;
second_resample = options_.particle.resampling.status.systematic;
variance_update = true;
bounds = prior_bounds(BayesInfo, DynareOptions.prior_trunc); % Reset bounds as lb and ub must only be operational during mode-finding
bounds = prior_bounds(bayestopt_, options_.prior_trunc); % Reset bounds as lb and ub must only be operational during mode-finding
% initialization of state particles
[~, Model, DynareOptions, DynareResults, ReducedForm] = solve_model_for_online_filter(true, xparam1, DynareDataset, DynareOptions, Model, EstimatedParameters, BayesInfo, bounds, DynareResults);
[~, M_, options_, oo_, ReducedForm] = solve_model_for_online_filter(true, xparam1, dataset_, options_, M_, estim_params_, bayestopt_, bounds, oo_);
order = DynareOptions.order;
order = options_.order;
mf0 = ReducedForm.mf0;
mf1 = ReducedForm.mf1;
number_of_particles = DynareOptions.particle.number_of_particles;
number_of_particles = options_.particle.number_of_particles;
number_of_parameters = size(xparam1,1);
Y = DynareDataset.data;
Y = dataset_.data;
sample_size = size(Y,1);
number_of_observed_variables = length(mf1);
number_of_structural_innovations = length(ReducedForm.Q);
liu_west_delta = DynareOptions.particle.liu_west_delta;
liu_west_delta = options_.particle.liu_west_delta;
% Get initial conditions for the state particles
StateVectorMean = ReducedForm.StateVectorMean;
@ -81,12 +81,12 @@ b_square = 1-small_a*small_a;
% Initialization of parameter particles
xparam = zeros(number_of_parameters,number_of_particles);
Prior = dprior(BayesInfo, DynareOptions.prior_trunc);
Prior = dprior(bayestopt_, options_.prior_trunc);
for i=1:number_of_particles
info = 12042009;
while info
candidate = Prior.draw();
[info, Model, DynareOptions, DynareResults] = solve_model_for_online_filter(false, xparam1, DynareDataset, DynareOptions, Model, EstimatedParameters, BayesInfo, bounds, DynareResults);
[info, M_, options_, oo_] = solve_model_for_online_filter(false, xparam1, dataset_, options_, M_, estim_params_, bayestopt_, bounds, oo_);
if ~info
xparam(:,i) = candidate(:);
end
@ -124,8 +124,8 @@ for t=1:sample_size
tau_tilde = zeros(1,number_of_particles);
for i=1:number_of_particles
% model resolution
[info, Model, DynareOptions, DynareResults, ReducedForm] = ...
solve_model_for_online_filter(false, fore_xparam(:,i), DynareDataset, DynareOptions, Model, EstimatedParameters, BayesInfo, bounds, DynareResults);
[info, M_, options_, oo_, ReducedForm] = ...
solve_model_for_online_filter(false, fore_xparam(:,i), dataset_, options_, M_, estim_params_, bayestopt_, bounds, oo_);
if ~info(1)
steadystate = ReducedForm.steadystate;
state_variables_steady_state = ReducedForm.state_variables_steady_state;
@ -167,22 +167,22 @@ for t=1:sample_size
% particle likelihood contribution
yhat = bsxfun(@minus, StateVectors(:,i), state_variables_steady_state);
if ReducedForm.use_k_order_solver
tmp = local_state_space_iteration_k(yhat, zeros(number_of_structural_innovations, 1), dr, Model, DynareOptions, udr);
tmp = local_state_space_iteration_k(yhat, zeros(number_of_structural_innovations, 1), dr, M_, options_, udr);
else
if pruning
yhat_ = bsxfun(@minus,StateVectors_(:,i),state_variables_steady_state_);
if order == 2
[tmp, ~] = local_state_space_iteration_2(yhat, zeros(number_of_structural_innovations, 1), ghx, ghu, constant, ghxx, ghuu, ghxu, yhat_, steadystate, DynareOptions.threads.local_state_space_iteration_2);
[tmp, ~] = local_state_space_iteration_2(yhat, zeros(number_of_structural_innovations, 1), ghx, ghu, constant, ghxx, ghuu, ghxu, yhat_, steadystate, options_.threads.local_state_space_iteration_2);
elseif order == 3
[tmp, tmp_] = local_state_space_iteration_3(yhat_, zeros(number_of_structural_innovations, 1), ghx, ghu, ghxx, ghuu, ghxu, ghs2, ghxxx, ghuuu, ghxxu, ghxuu, ghxss, ghuss, steadystate, DynareOptions.threads.local_state_space_iteration_3, pruning);
[tmp, tmp_] = local_state_space_iteration_3(yhat_, zeros(number_of_structural_innovations, 1), ghx, ghu, ghxx, ghuu, ghxu, ghs2, ghxxx, ghuuu, ghxxu, ghxuu, ghxss, ghuss, steadystate, options_.threads.local_state_space_iteration_3, pruning);
else
error('Pruning is not available for orders > 3');
end
else
if order == 2
tmp = local_state_space_iteration_2(yhat, zeros(number_of_structural_innovations, 1), ghx, ghu, constant, ghxx, ghuu, ghxu, DynareOptions.threads.local_state_space_iteration_2);
tmp = local_state_space_iteration_2(yhat, zeros(number_of_structural_innovations, 1), ghx, ghu, constant, ghxx, ghuu, ghxu, options_.threads.local_state_space_iteration_2);
elseif order == 3
tmp = local_state_space_iteration_3(yhat, zeros(number_of_structural_innovations, 1), ghx, ghu, ghxx, ghuu, ghxu, ghs2, ghxxx, ghuuu, ghxxu, ghxuu, ghxss, ghuss, steadystate, DynareOptions.threads.local_state_space_iteration_3, pruning);
tmp = local_state_space_iteration_3(yhat, zeros(number_of_structural_innovations, 1), ghx, ghu, ghxx, ghuu, ghxu, ghs2, ghxxx, ghuuu, ghxxu, ghxuu, ghxss, ghuss, steadystate, options_.threads.local_state_space_iteration_3, pruning);
else
error('Order > 3: use_k_order_solver should be set to true');
end
@ -196,7 +196,7 @@ for t=1:sample_size
end
% particles selection
tau_tilde = tau_tilde/sum(tau_tilde);
indx = resample(0, tau_tilde', DynareOptions.particle);
indx = resample(0, tau_tilde', options_.particle);
StateVectors = StateVectors(:,indx);
xparam = fore_xparam(:,indx);
if pruning
@ -208,13 +208,13 @@ for t=1:sample_size
for i=1:number_of_particles
info = 12042009;
counter=0;
while info(1) && counter <DynareOptions.particle.liu_west_max_resampling_tries
while info(1) && counter <options_.particle.liu_west_max_resampling_tries
counter=counter+1;
candidate = xparam(:,i) + chol_sigma_bar*randn(number_of_parameters, 1);
if all(candidate>=bounds.lb) && all(candidate<=bounds.ub)
% model resolution for new parameters particles
[info, Model, DynareOptions, DynareResults, ReducedForm] = ...
solve_model_for_online_filter(false, candidate, DynareDataset, DynareOptions, Model, EstimatedParameters, BayesInfo, bounds, DynareResults) ;
[info, M_, options_, oo_, ReducedForm] = ...
solve_model_for_online_filter(false, candidate, dataset_, options_, M_, estim_params_, bayestopt_, bounds, oo_) ;
if ~info(1)
xparam(:,i) = candidate ;
steadystate = ReducedForm.steadystate;
@ -263,23 +263,23 @@ for t=1:sample_size
% compute particles likelihood contribution
yhat = bsxfun(@minus,StateVectors(:,i), state_variables_steady_state);
if ReducedForm.use_k_order_solver
tmp = local_state_space_iteration_k(yhat, epsilon, dr, Model, DynareOptions, udr);
tmp = local_state_space_iteration_k(yhat, epsilon, dr, M_, options_, udr);
else
if pruning
yhat_ = bsxfun(@minus,StateVectors_(:,i), state_variables_steady_state_);
if order == 2
[tmp, tmp_] = local_state_space_iteration_2(yhat, epsilon, ghx, ghu, constant, ghxx, ghuu, ghxu, yhat_, steadystate, DynareOptions.threads.local_state_space_iteration_2);
[tmp, tmp_] = local_state_space_iteration_2(yhat, epsilon, ghx, ghu, constant, ghxx, ghuu, ghxu, yhat_, steadystate, options_.threads.local_state_space_iteration_2);
elseif order == 3
[tmp, tmp_] = local_state_space_iteration_3(yhat_, epsilon, ghx, ghu, ghxx, ghuu, ghxu, ghs2, ghxxx, ghuuu, ghxxu, ghxuu, ghxss, ghuss, steadystate, DynareOptions.threads.local_state_space_iteration_3, pruning);
[tmp, tmp_] = local_state_space_iteration_3(yhat_, epsilon, ghx, ghu, ghxx, ghuu, ghxu, ghs2, ghxxx, ghuuu, ghxxu, ghxuu, ghxss, ghuss, steadystate, options_.threads.local_state_space_iteration_3, pruning);
else
error('Pruning is not available for orders > 3');
end
StateVectors_(:,i) = tmp_(mf0_,:);
else
if order == 2
tmp = local_state_space_iteration_2(yhat, epsilon, ghx, ghu, constant, ghxx, ghuu, ghxu, DynareOptions.threads.local_state_space_iteration_2);
tmp = local_state_space_iteration_2(yhat, epsilon, ghx, ghu, constant, ghxx, ghuu, ghxu, options_.threads.local_state_space_iteration_2);
elseif order == 3
tmp = local_state_space_iteration_3(yhat, epsilon, ghx, ghu, ghxx, ghuu, ghxu, ghs2, ghxxx, ghuuu, ghxxu, ghxuu, ghxss, ghuss, steadystate, DynareOptions.threads.local_state_space_iteration_3, pruning);
tmp = local_state_space_iteration_3(yhat, epsilon, ghx, ghu, ghxx, ghuu, ghxu, ghs2, ghxxx, ghuuu, ghxxu, ghxuu, ghxss, ghuss, steadystate, options_.threads.local_state_space_iteration_3, pruning);
else
error('Order > 3: use_k_order_solver should be set to true');
end
@ -290,8 +290,8 @@ for t=1:sample_size
wtilde(i) = w_stage1(i)*exp(-.5*(const_lik+log(det(ReducedForm.H))+sum(PredictionError.*(ReducedForm.H\PredictionError), 1)));
end
end
if counter==DynareOptions.particle.liu_west_max_resampling_tries
fprintf('\nLiu & West particle filter: I haven''t been able to solve the model in %u tries.\n',DynareOptions.particle.liu_west_max_resampling_tries)
if counter==options_.particle.liu_west_max_resampling_tries
fprintf('\nLiu & West particle filter: I haven''t been able to solve the model in %u tries.\n',options_.particle.liu_west_max_resampling_tries)
fprintf('Liu & West particle filter: The last error message was: %s\n',get_error_message(info))
fprintf('Liu & West particle filter: You can try to increase liu_west_max_resampling_tries, but most\n')
fprintf('Liu & West particle filter: likely there is an issue with the model.\n')
@ -301,14 +301,14 @@ for t=1:sample_size
end
% normalization
weights = wtilde/sum(wtilde);
if variance_update && (neff(weights)<DynareOptions.particle.resampling.threshold*sample_size)
if variance_update && (neff(weights)<options_.particle.resampling.threshold*sample_size)
variance_update = false;
end
% final resampling (not advised)
if second_resample
[~, idmode] = max(weights);
mode_xparam(:,t) = xparam(:,idmode);
indx = resample(0, weights,DynareOptions.particle);
indx = resample(0, weights,options_.particle);
StateVectors = StateVectors(:,indx) ;
if pruning
StateVectors_ = StateVectors_(:,indx);
@ -372,24 +372,24 @@ pmedian = median_xparam(:,sample_size) ;
covariance = mat_var_cov;
%% Plot parameters trajectory
TeX = DynareOptions.TeX;
TeX = options_.TeX;
nr = ceil(sqrt(number_of_parameters)) ;
nc = floor(sqrt(number_of_parameters));
nbplt = 1 ;
if TeX
fidTeX = fopen([Model.fname '_param_traj.tex'],'w');
fidTeX = fopen([M_.fname '_param_traj.tex'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by online_auxiliary_filter.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
end
for plt = 1:nbplt
hh_fig = dyn_figure(DynareOptions.nodisplay,'Name','Parameters Trajectories');
hh_fig = dyn_figure(options_.nodisplay,'Name','Parameters Trajectories');
for k=1:length(pmean)
subplot(nr,nc,k)
[name,texname] = get_the_name(k,TeX,Model,EstimatedParameters,DynareOptions);
[name,texname] = get_the_name(k,TeX,M_,estim_params_,options_);
% Draw the surface for an interval containing 95% of the particles.
area(1:sample_size, ub95_xparam(k,:), 'FaceColor', [.9 .9 .9], 'BaseValue', min(lb95_xparam(k,:)));
hold on
@ -405,12 +405,12 @@ for plt = 1:nbplt
axis tight
drawnow
end
dyn_saveas(hh_fig, [Model.fname '_param_traj' int2str(plt)], DynareOptions.nodisplay, DynareOptions.graph_format);
dyn_saveas(hh_fig, [M_.fname '_param_traj' int2str(plt)], options_.nodisplay, options_.graph_format);
if TeX
% TeX eps loader file
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_ParamTraj%s}\n',Model.fname,int2str(plt));
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_ParamTraj%s}\n',M_.fname,int2str(plt));
fprintf(fidTeX,'\\caption{Parameters trajectories.}');
fprintf(fidTeX,'\\label{Fig:ParametersPlots:%s}\n',int2str(plt));
fprintf(fidTeX,'\\end{figure}\n');
@ -423,10 +423,10 @@ number_of_grid_points = 2^9; % 2^9 = 512 !... Must be a power of two.
bandwidth = 0; % Rule of thumb optimal bandwidth parameter.
kernel_function = 'gaussian'; % Gaussian kernel for Fast Fourier Transform approximation.
for plt = 1:nbplt
hh_fig = dyn_figure(DynareOptions.nodisplay,'Name','Parameters Densities');
hh_fig = dyn_figure(options_.nodisplay,'Name','Parameters Densities');
for k=1:length(pmean)
subplot(nr,nc,k)
[name,texname] = get_the_name(k,TeX,Model,EstimatedParameters,DynareOptions);
[name,texname] = get_the_name(k,TeX,M_,estim_params_,options_);
optimal_bandwidth = mh_optimal_bandwidth(xparam(k,:)',number_of_particles,bandwidth,kernel_function);
[density(:,1),density(:,2)] = kernel_density_estimate(xparam(k,:)', number_of_grid_points, ...
number_of_particles, optimal_bandwidth, kernel_function);
@ -441,8 +441,8 @@ for plt = 1:nbplt
axis tight
drawnow
end
dyn_saveas(hh_fig,[ Model.fname '_param_density' int2str(plt) ],DynareOptions.nodisplay,DynareOptions.graph_format);
if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
dyn_saveas(hh_fig,[ M_.fname '_param_density' int2str(plt) ],options_.nodisplay,options_.graph_format);
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
% TeX eps loader file
fprintf(fidTeX, '\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');

View File

@ -1,4 +1,4 @@
function [LIK,lik] = sequential_importance_particle_filter(ReducedForm,Y,start,ParticleOptions,ThreadsOptions, DynareOptions, Model)
function [LIK,lik] = sequential_importance_particle_filter(ReducedForm,Y,start,ParticleOptions,ThreadsOptions, options_, M_)
% Evaluates the likelihood of a nonlinear model with a particle filter (optionally with resampling).
@ -37,7 +37,7 @@ steadystate = ReducedForm.steadystate;
constant = ReducedForm.constant;
state_variables_steady_state = ReducedForm.state_variables_steady_state;
order = DynareOptions.order;
order = options_.order;
% Set persistent variables (if needed).
if isempty(init_flag)
@ -101,7 +101,7 @@ state_variance_rank = size(StateVectorVarianceSquareRoot,2);
Q_lower_triangular_cholesky = chol(Q)';
% Set seed for randn().
DynareOptions=set_dynare_seed_local_options(DynareOptions,'default');
options_=set_dynare_seed_local_options(options_,'default');
% Initialization of the weights across particles.
weights = ones(1,number_of_particles)/number_of_particles ;
@ -139,7 +139,7 @@ for t=1:sample_size
end
else
if ReducedForm.use_k_order_solver
tmp = local_state_space_iteration_k(yhat, epsilon, dr, Model, DynareOptions, udr);
tmp = local_state_space_iteration_k(yhat, epsilon, dr, M_, options_, udr);
else
if order == 2
tmp = local_state_space_iteration_2(yhat,epsilon,ghx,ghu,constant,ghxx,ghuu,ghxu,ThreadsOptions.local_state_space_iteration_2);

View File

@ -1,23 +1,23 @@
function [info, Model, DynareOptions, DynareResults, ReducedForm] = ...
solve_model_for_online_filter(setinitialcondition, xparam1, DynareDataset, DynareOptions, Model, EstimatedParameters, BayesInfo, bounds, DynareResults)
function [info, M_, options_, oo_, ReducedForm] = ...
solve_model_for_online_filter(setinitialcondition, xparam1, dataset_, options_, M_, estim_params_, bayestopt_, bounds, oo_)
% Solves the dsge model for an particular parameters set.
%
% INPUTS
% - setinitialcondition [logical] return initial condition if true.
% - xparam1 [double] n×1 vector, parameter values.
% - DynareDataset [struct] Dataset for estimation (dataset_).
% - DynareOptions [struct] Dynare options (options_).
% - Model [struct] Model description (M_).
% - EstimatedParameters [struct] Estimated parameters (estim_params_).
% - BayesInfo [struct] Prior definition (bayestopt_).
% - DynareResults [struct] Dynare results (oo_).
% - dataset_ [struct] Dataset for estimation.
% - options_ [struct] Dynare options.
% - M_ [struct] Model description.
% - estim_params_ [struct] Estimated parameters.
% - bayestopt_ [struct] Prior definition.
% - oo_ [struct] Dynare results.
%
% OUTPUTS
% - info [integer] scalar, nonzero if any problem occur when computing the reduced form.
% - Model [struct] Model description (M_).
% - DynareOptions [struct] Dynare options (options_).
% - DynareResults [struct] Dynare results (oo_).
% - M_ [struct] M_ description.
% - options_ [struct] Dynare options.
% - oo_ [struct] Dynare results.
% - ReducedForm [struct] Reduced form model.
% Copyright © 2013-2023 Dynare Team
@ -58,27 +58,27 @@ if any(xparam1>bounds.ub)
end
% Get the diagonal elements of the covariance matrices for the structural innovations (Q) and the measurement error (H).
Q = Model.Sigma_e;
H = Model.H;
for i=1:EstimatedParameters.nvx
k =EstimatedParameters.var_exo(i,1);
Q = M_.Sigma_e;
H = M_.H;
for i=1:estim_params_.nvx
k =estim_params_.var_exo(i,1);
Q(k,k) = xparam1(i)*xparam1(i);
end
offset = EstimatedParameters.nvx;
if EstimatedParameters.nvn
for i=1:EstimatedParameters.nvn
offset = estim_params_.nvx;
if estim_params_.nvn
for i=1:estim_params_.nvn
H(i,i) = xparam1(i+offset)*xparam1(i+offset);
end
offset = offset+EstimatedParameters.nvn;
offset = offset+estim_params_.nvn;
else
H = zeros(size(DynareDataset.data, 2));
H = zeros(size(dataset_.data, 2));
end
% Get the off-diagonal elements of the covariance matrix for the structural innovations. Test if Q is positive definite.
if EstimatedParameters.ncx
for i=1:EstimatedParameters.ncx
k1 =EstimatedParameters.corrx(i,1);
k2 =EstimatedParameters.corrx(i,2);
if estim_params_.ncx
for i=1:estim_params_.ncx
k1 =estim_params_.corrx(i,1);
k2 =estim_params_.corrx(i,2);
Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
Q(k2,k1) = Q(k1,k2);
end
@ -89,13 +89,13 @@ if EstimatedParameters.ncx
info = 43;
return
end
offset = offset+EstimatedParameters.ncx;
offset = offset+estim_params_.ncx;
end
% Get the off-diagonal elements of the covariance matrix for the measurement errors. Test if H is positive definite.
if EstimatedParameters.ncn
corrn_observable_correspondence = EstimatedParameters.corrn_observable_correspondence;
for i=1:EstimatedParameters.ncn
if estim_params_.ncn
corrn_observable_correspondence = estim_params_.corrn_observable_correspondence;
for i=1:estim_params_.ncn
k1 = corrn_observable_correspondence(i,1);
k2 = corrn_observable_correspondence(i,2);
H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
@ -108,25 +108,25 @@ if EstimatedParameters.ncn
info = 44;
return
end
offset = offset+EstimatedParameters.ncn;
offset = offset+estim_params_.ncn;
end
% Update estimated structural parameters in Mode.params.
if EstimatedParameters.np > 0
Model.params(EstimatedParameters.param_vals(:,1)) = xparam1(offset+1:end);
if estim_params_.np > 0
M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
end
% Update Model.Sigma_e and Model.H.
Model.Sigma_e = Q;
Model.H = H;
% Update M_.Sigma_e and M_.H.
M_.Sigma_e = Q;
M_.H = H;
%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------
warning('off', 'MATLAB:nearlySingularMatrix')
[~, ~, ~, info, DynareResults.dr, Model.params] = ...
dynare_resolve(Model, DynareOptions, DynareResults.dr, DynareResults.steady_state, DynareResults.exo_steady_state, DynareResults.exo_det_steady_state, 'restrict');
[~, ~, ~, info, oo_.dr, M_.params] = ...
dynare_resolve(M_, options_, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state, 'restrict');
warning('on', 'MATLAB:nearlySingularMatrix')
if info(1)~=0
@ -137,12 +137,12 @@ if info(1)~=0
end
% Get decision rules and transition equations.
dr = DynareResults.dr;
dr = oo_.dr;
% Set persistent variables (first call).
if isempty(init_flag)
mf0 = BayesInfo.mf0;
mf1 = BayesInfo.mf1;
mf0 = bayestopt_.mf0;
mf1 = bayestopt_.mf1;
restrict_variables_idx = dr.restrict_var_list;
state_variables_idx = restrict_variables_idx(mf0);
number_of_state_variables = length(mf0);
@ -155,17 +155,17 @@ if nargout>4
ReducedForm.ghx = dr.ghx(restrict_variables_idx,:);
ReducedForm.ghu = dr.ghu(restrict_variables_idx,:);
ReducedForm.steadystate = dr.ys(dr.order_var(restrict_variables_idx));
if DynareOptions.order==2
if options_.order==2
ReducedForm.use_k_order_solver = false;
ReducedForm.ghxx = dr.ghxx(restrict_variables_idx,:);
ReducedForm.ghuu = dr.ghuu(restrict_variables_idx,:);
ReducedForm.ghxu = dr.ghxu(restrict_variables_idx,:);
ReducedForm.constant = ReducedForm.steadystate + .5*dr.ghs2(restrict_variables_idx);
ReducedForm.ghs2 = dr.ghs2(restrict_variables_idx,:);
elseif DynareOptions.order>=3
elseif options_.order>=3
ReducedForm.use_k_order_solver = true;
ReducedForm.dr = dr;
ReducedForm.udr = folded_to_unfolded_dr(dr, Model, DynareOptions);
ReducedForm.udr = folded_to_unfolded_dr(dr, M_, options_);
else
n_states=size(dr.ghx,2);
n_shocks=size(dr.ghu,2);
@ -184,28 +184,28 @@ end
% Set initial condition
if setinitialcondition
switch DynareOptions.particle.initialization
switch options_.particle.initialization
case 1% Initial state vector covariance is the ergodic variance associated to the first order Taylor-approximation of the model.
StateVectorMean = ReducedForm.state_variables_steady_state;%.constant(mf0);
[A,B] = kalman_transition_matrix(dr,dr.restrict_var_list,dr.restrict_columns);
StateVectorVariance = lyapunov_symm(A, B*ReducedForm.Q*B', DynareOptions.lyapunov_fixed_point_tol, ...
DynareOptions.qz_criterium, DynareOptions.lyapunov_complex_threshold, [], DynareOptions.debug);
StateVectorVariance = lyapunov_symm(A, B*ReducedForm.Q*B', options_.lyapunov_fixed_point_tol, ...
options_.qz_criterium, options_.lyapunov_complex_threshold, [], options_.debug);
StateVectorVariance = StateVectorVariance(mf0,mf0);
case 2% Initial state vector covariance is a monte-carlo based estimate of the ergodic variance (consistent with a k-order Taylor-approximation of the model).
StateVectorMean = ReducedForm.state_variables_steady_state;%.constant(mf0);
old_DynareOptionsperiods = DynareOptions.periods;
DynareOptions.periods = 5000;
old_DynareOptionspruning = DynareOptions.pruning;
DynareOptions.pruning = DynareOptions.particle.pruning;
y_ = simult(dr.ys, dr, Model, DynareOptions);
y_ = y_(dr.order_var(state_variables_idx),2001:DynareOptions.periods);
old_DynareOptionsperiods = options_.periods;
options_.periods = 5000;
old_DynareOptionspruning = options_.pruning;
options_.pruning = options_.particle.pruning;
y_ = simult(dr.ys, dr, M_, options_);
y_ = y_(dr.order_var(state_variables_idx),2001:options_.periods);
StateVectorVariance = cov(y_');
DynareOptions.periods = old_DynareOptionsperiods;
DynareOptions.pruning = old_DynareOptionspruning;
options_.periods = old_DynareOptionsperiods;
options_.pruning = old_DynareOptionspruning;
clear('old_DynareOptionsperiods','y_');
case 3% Initial state vector covariance is a diagonal matrix.
StateVectorMean = ReducedForm.state_variables_steady_state;%.constant(mf0);
StateVectorVariance = DynareOptions.particle.initial_state_prior_std*eye(number_of_state_variables);
StateVectorVariance = options_.particle.initial_state_prior_std*eye(number_of_state_variables);
otherwise
error('Unknown initialization option!')
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,9 +1,9 @@
function print_moments_implied_prior(ModelInfo, mm, vm, mv, vv)
%function print_moments_implied_prior(ModelInfo, mm, vm, mv, vv)
function print_moments_implied_prior(M_, mm, vm, mv, vv)
%function print_moments_implied_prior(M_, mm, vm, mv, vv)
% This routine prints in the command window some descriptive statistics
% about the endogenous variables implied prior moments.
% Inputs:
% - ModelInfo [structure] Dynare's model structure
% - M_ [structure] Dynare's model structure
% - mm [endo_nbr*1] mean first moments of the endogenous
% variables
% - vm [endo_nbr*1] variance of the first moments of the
@ -14,7 +14,7 @@ function print_moments_implied_prior(ModelInfo, mm, vm, mv, vv)
% endogenous variables
% Copyright © 2016-2018 Dynare Team
% Copyright © 2016-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -39,14 +39,14 @@ disp(printline(64, '-'))
T1 = 'VARIABLE ';
T2 = sprintf('Prior mean \t Prior st. dev.');
for i=1:ModelInfo.orig_endo_nbr
Name = ModelInfo.endo_names{i};
for i=1:M_.orig_endo_nbr
Name = M_.endo_names{i};
T1 = strvcat(T1, Name);
str = sprintf(' %6.4f \t %6.4f', mm(i), sqrt(vm(i)));
T2 = strvcat(T2, str);
end
T0 = repmat(' ', ModelInfo.orig_endo_nbr+1, 1);
T0 = repmat(' ', M_.orig_endo_nbr+1, 1);
TT = [T1, T0, T2];
l0 = printline(size(TT, 2)+1, '-');
@ -64,10 +64,10 @@ T1b = 'VARIABLE-2';
T2a = 'Prior mean';
T2b = 'Prior st.dev.';
for i=1:ModelInfo.orig_endo_nbr
for j=i:ModelInfo.orig_endo_nbr
Name1 = ModelInfo.endo_names{i};
Name2 = ModelInfo.endo_names{j};
for i=1:M_.orig_endo_nbr
for j=i:M_.orig_endo_nbr
Name1 = M_.endo_names{i};
Name2 = M_.endo_names{j};
T1a = strvcat(T1a, Name1);
T1b = strvcat(T1b, Name2);
sta = sprintf('%12.8f', mv(i,j));
@ -77,7 +77,7 @@ for i=1:ModelInfo.orig_endo_nbr
end
end
T0 = repmat(' ', ModelInfo.orig_endo_nbr*(ModelInfo.orig_endo_nbr+1)/2+1, 1);
T0 = repmat(' ', M_.orig_endo_nbr*(M_.orig_endo_nbr+1)/2+1, 1);
TT = [T1a, T0, T1b, T0, T2a, T0, T2b];
l0 = printline(size(TT, 2)+1, '-');

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,5 +1,5 @@
function pdraw = prior_draw(BayesInfo, prior_trunc, uniform)
function pdraw = prior_draw(bayestopt_, prior_trunc, uniform)
% pdraw = prior_draw(bayestopt_, prior_trunc, uniform)
% This function generate one draw from the joint prior distribution and
% allows sampling uniformly from the prior support (uniform==1 when called with init==1)
%
@ -48,18 +48,18 @@ persistent uniform_index gaussian_index gamma_index beta_index inverse_gamma_1_i
persistent uniform_draws gaussian_draws gamma_draws beta_draws inverse_gamma_1_draws inverse_gamma_2_draws weibull_draws
if nargin>0
p6 = BayesInfo.p6;
p7 = BayesInfo.p7;
p3 = BayesInfo.p3;
p4 = BayesInfo.p4;
bounds = prior_bounds(BayesInfo, prior_trunc);
p6 = bayestopt_.p6;
p7 = bayestopt_.p7;
p3 = bayestopt_.p3;
p4 = bayestopt_.p4;
bounds = prior_bounds(bayestopt_, prior_trunc);
lb = bounds.lb;
ub = bounds.ub;
number_of_estimated_parameters = length(p6);
if nargin>2 && uniform
prior_shape = repmat(5,number_of_estimated_parameters,1);
else
prior_shape = BayesInfo.pshape;
prior_shape = bayestopt_.pshape;
end
beta_index = find(prior_shape==1);
if isempty(beta_index)
@ -238,23 +238,23 @@ for i=1:14
end
end
BayesInfo.pshape = p0;
BayesInfo.p1 = p1;
BayesInfo.p2 = p2;
BayesInfo.p3 = p3;
BayesInfo.p4 = p4;
BayesInfo.p5 = p5;
BayesInfo.p6 = p6;
BayesInfo.p7 = p7;
bayestopt_.pshape = p0;
bayestopt_.p1 = p1;
bayestopt_.p2 = p2;
bayestopt_.p3 = p3;
bayestopt_.p4 = p4;
bayestopt_.p5 = p5;
bayestopt_.p6 = p6;
bayestopt_.p7 = p7;
ndraws = 1e5;
m0 = BayesInfo.p1; %zeros(14,1);
v0 = diag(BayesInfo.p2.^2); %zeros(14);
m0 = bayestopt_.p1; %zeros(14,1);
v0 = diag(bayestopt_.p2.^2); %zeros(14);
% Call the tested routine
try
% Initialization of prior_draws.
prior_draw(BayesInfo, prior_trunc, false);
prior_draw(bayestopt_, prior_trunc, false);
% Do simulations in a loop and estimate recursively the mean and teh variance.
for i = 1:ndraws
draw = transpose(prior_draw());
@ -269,8 +269,8 @@ catch
end
if t(1)
t(2) = all(abs(m0-BayesInfo.p1)<3e-3);
t(3) = all(all(abs(v0-diag(BayesInfo.p2.^2))<5e-3));
t(2) = all(abs(m0-bayestopt_.p1)<3e-3);
t(3) = all(all(abs(v0-diag(bayestopt_.p2.^2))<5e-3));
end
T = all(t);
%@eof:1

View File

@ -135,8 +135,8 @@ for j=presample+1:nobs
% evalin('base',['options_.nobs=' int2str(j) ';'])
options_.nobs=j;
if isequal(fast_realtime,0)
[oo,M_,~,~,Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_);
gend = size(oo.SmoothedShocks.(M_.exo_names{1}),1);
[oo_local,M_,~,~,Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_);
gend = size(oo_local.SmoothedShocks.(M_.exo_names{1}),1);
else
if j<min(fast_realtime) && gend0<j
options_.nobs=min(fast_realtime);
@ -146,10 +146,10 @@ for j=presample+1:nobs
end
if ismember(j,fast_realtime) && gend0<j
[oo,M_,~,~,Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_);
gend = size(oo.SmoothedShocks.(M_.exo_names{1}),1);
[oo_local,M_,~,~,Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_);
gend = size(oo_local.SmoothedShocks.(M_.exo_names{1}),1);
gend0 = gend;
oo0=oo;
oo0=oo_local;
Smoothed_Variables_deviation_from_mean0=Smoothed_Variables_deviation_from_mean;
else
if j>gend0
@ -164,13 +164,13 @@ for j=presample+1:nobs
end
gend = j;
oo=oo0;
oo_local=oo0;
Smoothed_Variables_deviation_from_mean = Smoothed_Variables_deviation_from_mean0(:,1:gend);
end
end
% reduced form
dr = oo.dr;
dr = oo_local.dr;
% data reordering
order_var = dr.order_var;
@ -194,7 +194,7 @@ for j=presample+1:nobs
% initialization
epsilon=NaN(nshocks,gend);
for i = 1:nshocks
epsilon(i,:) = oo.SmoothedShocks.(M_.exo_names{i})(1:gend);
epsilon(i,:) = oo_local.SmoothedShocks.(M_.exo_names{i})(1:gend);
end
epsilon=[epsilon zeros(nshocks,forecast_)];

View File

@ -1,6 +1,7 @@
function expression = remove_aux_variables_from_expression(expression, DynareModel)
function expression = remove_aux_variables_from_expression(expression, M_)
% expression = remove_aux_variables_from_expression(expression, M_)
% Copyright © 2022 Dynare Team
% Copyright © 2022-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -19,17 +20,17 @@ function expression = remove_aux_variables_from_expression(expression, DynareMod
% Get list of endogenous variables in expression
list_of_words = regexp(expression, '\<\w*\>', 'match');
list_of_words = setdiff(list_of_words, DynareModel.param_names);
list_of_words = setdiff(list_of_words, DynareModel.exo_names);
list_of_words = setdiff(list_of_words, M_.param_names);
list_of_words = setdiff(list_of_words, M_.exo_names);
isnotanumber = isnan(str2double(list_of_words));
list_of_words = list_of_words(isnotanumber);
list_of_words = setdiff(list_of_words, {'diff','log','exp'});
for i=1:length(list_of_words)
id = find(strcmp(list_of_words{i}, DynareModel.endo_names));
if isempty(id) || id<=DynareModel.orig_endo_nbr
id = find(strcmp(list_of_words{i}, M_.endo_names));
if isempty(id) || id<=M_.orig_endo_nbr
continue
end
auxinfo = DynareModel.aux_vars(get_aux_variable_id(id));
auxinfo = M_.aux_vars(get_aux_variable_id(id));
expression = regexprep(expression, sprintf('\\<%s\\>', list_of_words{i}), auxinfo.orig_expr);
end

View File

@ -1,17 +1,17 @@
function DynareModel = set_exogenous_variables_for_simulation(DynareModel)
function M_ = set_exogenous_variables_for_simulation(M_)
% M_ = set_exogenous_variables_for_simulation(M_)
% Appends the list of observed exogenous variables in Dynare's model structure (if any).
%
% INPUTS
% - DynareModel [struct] Dynare's model global structure, M_.
% - M_ [struct] Dynare's model global structure.
%
% OUTPUTS
% - DynareModel [struct] Dynare's model global structure, M_.
% - M_ [struct] Dynare's model global structure.
%
% SPECIAL REQUIREMENTS
% none
% Copyright © 2019 Dynare Team
% Copyright © 2019-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -28,8 +28,8 @@ function DynareModel = set_exogenous_variables_for_simulation(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 isfield(DynareModel, 'exo_partitions')
if isfield(DynareModel.exo_partitions, 'used')
DynareModel.simulation_exo_names = DynareModel.exo_names(~strcmpi('estimationonly', DynareModel.exo_partitions.used));
if isfield(M_, 'exo_partitions')
if isfield(M_.exo_partitions, 'used')
M_.simulation_exo_names = M_.exo_names(~strcmpi('estimationonly', M_.exo_partitions.used));
end
end

View File

@ -1,17 +1,17 @@
function DynareModel = set_observed_exogenous_variables(DynareModel)
function M_ = set_observed_exogenous_variables(M_)
% M_ = set_observed_exogenous_variables(M_)
% Appends the list of observed exogenous variables in Dynare's model structure (if any).
%
% INPUTS
% - DynareModel [struct] Dynare's model global structure, M_.
% - M_ [struct] Dynare's model global structure.
%
% OUTPUTS
% - DynareModel [struct] Dynare's model global structure, M_.
% - M_ [struct] Dynare's model global structure.
%
% SPECIAL REQUIREMENTS
% none
% Copyright © 2019 Dynare Team
% Copyright © 2019-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -28,8 +28,8 @@ function DynareModel = set_observed_exogenous_variables(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 isfield(DynareModel, 'exo_partitions')
if isfield(DynareModel.exo_partitions, 'status')
DynareModel.observed_exo_names = DynareModel.exo_names(strcmpi('observed', DynareModel.exo_partitions.status));
if isfield(M_, 'exo_partitions')
if isfield(M_.exo_partitions, 'status')
M_.observed_exo_names = M_.exo_names(strcmpi('observed', M_.exo_partitions.status));
end
end

View File

@ -10,8 +10,8 @@ function simulation = simul_static_model(samplesize, innovations)
% - simulation [dseries] Simulated endogenous and exogenous variables.
%
% 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.
@ -62,7 +62,7 @@ if nargin<2 || isempty(innovations)
otherwise
error('%s distribution for the structural innovations is not (yet) implemented!', options_.bnlms.innovation_distribution)
end
% Put the simulated innovations in 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 = [];

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,8 +1,8 @@
function update_all_parameters_in_workspace(DynareModel)
function update_all_parameters_in_workspace(M_)
% update_all_parameters_in_workspace(M_)
% Updates all parameter values in Matlab/Octave base workspace.
% Copyright © 2018 Dynare Team
% Copyright © 2018-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -19,6 +19,6 @@ function update_all_parameters_in_workspace(DynareModel)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
for i=1:length(DynareModel.params)
assignin('base', DynareModel.param_names{i}, DynareModel.params(i));
for i=1:length(M_.params)
assignin('base', M_.param_names{i}, M_.params(i));
end

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

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