Merge branch 'master' into new_ep

time-shift
Michel Juillard 2015-02-14 11:54:57 +01:00
commit 21f009a531
40 changed files with 605 additions and 818 deletions

View File

@ -137,6 +137,7 @@ apt-get build-dep dynare
Alternatively, if you want to build everything, manually install the following packages:
- `build-essential` (for gcc, g++ and make)
- `gfortran`
- `liboctave-dev` or `octave3.2-headers` (will install ATLAS)
- `libboost-graph-dev`
- `libgsl0-dev`

View File

@ -11422,7 +11422,7 @@ Report Title. Default: @code{none}
@end defmethod
@anchor{addPage}
@defmethod Report addPage footnote, orientation, paper, title, titleFormat
@defmethod Report addPage footnote, orientation, paper, title, titleFormat, titleTruncate
Adds a @code{Page} to the @code{Report}.
@optionshead
@table @code
@ -11449,6 +11449,12 @@ number of cell array entries must be equal to that of the @ref{title}
option if you do not want to use the default value for the title (and
subtitles). Default: @code{\large\bfseries}
@item titleTruncate, @code{INTEGER}
Useful when automatically generating page titles that may become too
long, @code{titleTruncate} can be used to truncate a title (and
subsequent subtitles) when they pass the specified number of
characters. Default: @code{off}
@end table
@end defmethod

View File

@ -1,6 +1,6 @@
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Dynare
Upstream-Contact: Dynare Team, whose members in 2014 are:
Upstream-Contact: Dynare Team, whose members in 2015 are:
Stéphane Adjemian <stephane.adjemian@univ-lemans.fr>
Houtan Bastani <houtan@dynare.org>
Michel Juillard <michel.juillard@mjui.fr>
@ -14,7 +14,7 @@ Upstream-Contact: Dynare Team, whose members in 2014 are:
Source: http://www.dynare.org
Files: *
Copyright: 1996-2014 Dynare Team
Copyright: 1996-2015 Dynare Team
License: GPL-3+
Files: matlab/AIM/SP*
@ -126,7 +126,7 @@ License: permissive
distribute this software.
Files: doc/dynare.texi doc/*.tex doc/*.svg doc/*.dia doc/*.pdf doc/*.bib
Copyright: 1996-2014 Dynare Team
Copyright: 1996-2015 Dynare Team
License: GFDL-NIV-1.3+
Files: doc/userguide/*.tex doc/userguide/*.bib doc/userguide/*.pdf

View File

@ -1,163 +0,0 @@
function det_cond_forecast(constrained_paths, constrained_vars, options_cond_fcst, constrained_perfect_foresight)
% Computes forecasts using the schocks retrieved from a condition forecast for a deterministic model.
%
% INPUTS
% o constrained_paths [double] m*p array, where m is the number of constrained endogenous variables and p is the number of constrained periods.
% o constrained_vars [char] m*x array holding the names of the controlled endogenous variables.
% o options_cond_fcst [structure] containing the options. The fields are:
% + replic [integer] scalar, number of monte carlo simulations.
% + parameter_set [char] values of the estimated parameters:
% "posterior_mode",
% "posterior_mean",
% "posterior_median",
% "prior_mode" or
% "prior mean".
% [double] np*1 array, values of the estimated parameters.
% + controlled_varexo [char] m*x array, list of controlled exogenous variables.
% + conf_sig [double] scalar in [0,1], probability mass covered by the confidence bands.
% o constrained_perfect_foresight [double] m*1 array indicating if the endogenous variables path is perfectly foresight (1) or is a surprise (0)
%
%
% OUTPUTS
% None.
%
% SPECIAL REQUIREMENTS
% This routine has to be called after an estimation statement or an estimated_params block.
%
% REMARKS
% [1] Results are stored in a structure which is saved in a mat file called conditional_forecasts.mat.
% [2] Use the function plot_icforecast to plot the results.
% Copyright (C) 2013 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_ oo_ M_
if ~isfield(options_cond_fcst,'periods') || isempty(options_cond_fcst.periods)
options_cond_fcst.periods = 60;
end
maximum_lag = M_.maximum_lag;
maximum_lead = M_.maximum_lead;
ys = oo_.steady_state;
ny = size(ys,1);
xs = [oo_.exo_steady_state ; oo_.exo_det_steady_state];
nx = size(xs,1);
constrained_periods = size(constrained_paths,2);
n_endo_constrained = size(constrained_vars,1);
if isfield(options_cond_fcst,'controlled_varexo')
n_control_exo = size(options_cond_fcst.controlled_varexo, 1);
if n_control_exo ~= n_endo_constrained
error(['det_cond_forecast:: the number of exogenous controlled variables (' int2str(n_control_exo) ') has to be equal to the number of constrained endogenous variabes (' int2str(n_endo_constrained) ')'])
end;
else
error('det_cond_forecast:: to run a deterministic conditional forecast you have to specified the exogenous variables controlled using the option controlled_varex in forecast command');
end;
exo_names = M_.exo_names;
controlled_varexo = zeros(1,n_control_exo);
for i = 1:nx
for j=1:n_control_exo
if strcmp(exo_names(i,:), options_cond_fcst.controlled_varexo(j,:))
controlled_varexo(j) = i;
end
end
end
save_options_initval_file = options_.initval_file;
options_.initval_file = '__';
[pos_constrained_pf, junk] = find(constrained_perfect_foresight);
indx_endo_solve_pf = constrained_vars(pos_constrained_pf);
if isempty(indx_endo_solve_pf)
pf = 0;
else
pf = length(indx_endo_solve_pf);
end;
indx_endo_solve_surprise = setdiff(constrained_vars, indx_endo_solve_pf);
if isempty(indx_endo_solve_surprise)
surprise = 0;
else
surprise = length(indx_endo_solve_surprise);
end;
eps = options_.solve_tolf;
maxit = options_.simul.maxit;
% Check the solution using a unconditional forecast (soft tune)
initial_conditions = oo_.steady_state;
terminal_conditions = oo_.steady_state;
exo = oo_.exo_simul;
T = options_.periods + 2;
endo_simul = zeros(ny, T);
endo_simul(:,1) = initial_conditions;
endo_simul(:,T) = initial_conditions;
exo_simul = zeros(T, nx);
exo_simul(1,:) = [oo_.exo_steady_state' oo_.exo_det_steady_state'];
exo_simul(T,:) = [oo_.exo_steady_state' oo_.exo_det_steady_state'];
past_val = 0;
if pf && ~surprise
make_ex_;
make_y_;
oo_.endo_simul(:,1) = initial_conditions;
oo_.endo_simul(:,options_.periods + 2) = terminal_conditions;
%oo_.exo_simul = repmat(oo_.exo_steady_state, options_.periods + 2, 1);
oo_.exo_simul = exo;
simul();
endo_simul = oo_.endo_simul;
exo_simul = oo_.exo_simul;
else
for t=1:constrained_periods
make_ex_;
make_y_;
disp(['t=' int2str(t) ' constrained_periods=' int2str(constrained_periods)]);
oo_.endo_simul(:,1) = initial_conditions;
oo_.endo_simul(:,options_.periods + 2) = terminal_conditions;
time_index_constraint = maximum_lag + 1:maximum_lag + constrained_periods - t + 1;
if t <= constrained_periods
for j = controlled_varexo
if constrained_perfect_foresight(j)
for time = time_index_constraint;
oo_.exo_simul(time,j) = exo(past_val + time,j);
end;
oo_.exo_simul(time+1, j)= oo_.exo_steady_state(j);
else
oo_.exo_simul(maximum_lag + 1,j) = exo(maximum_lag + t,j);
end;
end;
else
tmp = size(oo_.exo_simul,1);
oo_.exo_simul = repmat(oo_.exo_steady_state',tmp,1);
end;
past_val = past_val + length(time_index_constraint);
simul();
initial_conditions = oo_.endo_simul(:,2);
if t < constrained_periods
endo_simul(:,t+1) = initial_conditions;
exo_simul(t+1,:) = oo_.exo_simul(2,:);
else
endo_simul(:,t + 1:t + options_cond_fcst.periods + maximum_lead) = oo_.endo_simul(:,maximum_lag + 1:maximum_lag + options_cond_fcst.periods + maximum_lead);
exo_simul(t+1,:) = oo_.exo_simul(2,:);
end;
end;
end;
oo_.endo_simul = endo_simul;
oo_.exo_simul = exo_simul;

View File

@ -1,4 +1,4 @@
function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_)
function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_,varargin)
% function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_)
% computes the reduced form solution of a rational expectation model (first
% approximation of the stochastic model around the deterministic steady state).
@ -51,7 +51,11 @@ function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_)
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
info = 0;
verbose = options_.verbosity;
verbose = 0;
if nargin > 5
verbose = varargin{1};
end
%verbose = options_.verbosity;
if options_.order > 1
error('2nd and 3rd order approximation not implemented with block option')
end

View File

@ -50,6 +50,7 @@ addpath([dynareroot '/kalman/'])
addpath([dynareroot '/kalman/likelihood'])
addpath([dynareroot '/AIM/'])
addpath([dynareroot '/partial_information/'])
addpath([dynareroot '/perfect-foresight-models/'])
addpath([dynareroot '/ms-sbvar/'])
addpath([dynareroot '/ms-sbvar/identification/'])
addpath([dynareroot '../contrib/ms-sbvar/TZcode/MatlabFiles/'])
@ -60,6 +61,7 @@ addpath([dynareroot '/ep/'])
addpath([dynareroot '/lmmcp/'])
addpath([dynareroot '/modules/dates/src/'])
addpath([dynareroot '/modules/dseries/src/'])
addpath([dynareroot '/modules/dseries/src/read'])
addpath([dynareroot '/utilities/doc/'])
addpath([dynareroot '/utilities/tests/src/'])
addpath([dynareroot '/utilities/dataset/'])

View File

@ -12,7 +12,7 @@ function dynare_estimation_1(var_list_,dname)
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2013 Dynare Team
% Copyright (C) 2003-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -71,26 +71,18 @@ end
if ~options_.dsge_var
if options_.particle.status
objective_function = str2func('non_linear_dsge_likelihood');
if options_.particle.filter_algorithm.sis == 1
if strcmpi(options_.particle.filter_algorithm, 'sis')
options_.particle.algorithm = 'sequential_importance_particle_filter';
elseif strcmpi(options_.particle.filter_algorithm, 'apf')
options_.particle.algorithm = 'auxiliary_particle_filter';
elseif strcmpi(options_.particle.filter_algorithm, 'gf')
options_.particle.algorithm = 'gaussian_filter';
elseif strcmpi(options_.particle.filter_algorithm, 'gmf')
options_.particle.algorithm = 'gaussian_mixture_filter';
elseif strcmpi(options_.particle.filter_algorithm, 'cpf')
options_.particle.algorithm = 'conditional_particle_filter';
else
if options_.particle.filter_algorithm.apf == 1
options_.particle.algorithm = 'auxiliary_particle_filter';
else
if options_.particle.filter_algorithm.gf == 1
options_.particle.algorithm = 'gaussian_filter';
else
if options_.particle.filter_algorithm.gmf == 1
options_.particle.algorithm = 'gaussian_mixture_filter';
else
if options_.particle.filter_algorithm.cpf == 1
options_.particle.algorithm = 'conditional_particle_filter';
else
error('Estimation: Unknown filter!')
end
end
end
end
error(['Estimation: Unknown filter ' options_.particle.filter_algorithm])
end
else
objective_function = str2func('dsge_likelihood');

35
matlab/ep/ep_notes.org Normal file
View File

@ -0,0 +1,35 @@
debug: 0
memory: 0
verbosity: 0
use_bytecode: 0
init: 0
maxit: 500
periods: 200
step: 50
check_stability: 0
lp: 5
fp: 2
innovation_distribution: 'gaussian'
set_dynare_seed_to_default: 1
stack_solve_algo: 4
stochastic: [1x1 struct]
IntegrationAlgorithm: 'Tensor-Gaussian-Quadrature'
stochastic:
method: ''
algo: 0
quadrature: [1x1 struct]
order: 1
hybrid_order: 0
homotopic_steps: 1
nodes: 3
quadrature:
ortpol: 'hermite'
nodes: 5
pruned: [1x1 struct]
pruned:
ortpol: 'hermite'
nodes: 5
pruned: [1x1 struct]

View File

@ -11,7 +11,7 @@ function global_initialization()
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2014 Dynare Team
% Copyright (C) 2003-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -245,11 +245,7 @@ particle.resampling.method.kitagawa = 1;
particle.resampling.method.smooth = 0;
particle.resampling.method.stratified = 0;
% Set default algorithm
particle.filter_algorithm.sis = 1;
particle.filter_algorithm.apf = 0;
particle.filter_algorithm.gf = 0;
particle.filter_algorithm.gmf = 0;
particle.filter_algorithm.cpf = 0;
particle.filter_algorithm = 'sis';
% Approximation of the proposal distribution
particle.proposal_approximation.cubature = 1;
particle.proposal_approximation.unscented = 0;

View File

@ -44,8 +44,26 @@ if DynareDataset.vobs>length(find(diag(Model.Sigma_e)))+EstimatedParameters.nvn
error(['initial_estimation_checks:: Estimation can''t take place because too many shocks have been calibrated with a zero variance!'])
end
% check if steady state solves static model (except if diffuse_filter == 1)
[DynareResults.steady_state] = evaluate_steady_state(DynareResults.steady_state,Model,DynareOptions,DynareResults,DynareOptions.diffuse_filter==0);
old_steady_params=Model.params; %save initial parameters for check if steady state changes param values
% % check if steady state solves static model (except if diffuse_filter == 1)
[DynareResults.steady_state, new_steady_params] = evaluate_steady_state(DynareResults.steady_state,Model,DynareOptions,DynareResults,DynareOptions.diffuse_filter==0);
%check whether steady state file changes estimated parameters
Model_par_varied=Model; %store Model structure
Model_par_varied.params(EstimatedParameters.param_vals(:,1))=Model_par_varied.params(EstimatedParameters.param_vals(:,1))*1.01; %vary parameters
[junk, new_steady_params_2] = evaluate_steady_state(DynareResults.steady_state,Model_par_varied,DynareOptions,DynareResults,DynareOptions.diffuse_filter==0);
changed_par_indices=find((old_steady_params(EstimatedParameters.param_vals(:,1))-new_steady_params(EstimatedParameters.param_vals(:,1))) ...
| (Model_par_varied.params(EstimatedParameters.param_vals(:,1))-new_steady_params_2(EstimatedParameters.param_vals(:,1))));
if ~isempty(changed_par_indices)
fprintf('\nThe steady state file internally changed the values of the following estimated parameters:\n')
disp(Model.param_names(changed_par_indices,:));
fprintf('This will override the parameter values drawn from the proposal density and may lead to wrong results.\n')
fprintf('Check whether this is really intended.\n')
warning('The steady state file internally changes the values of the estimated parameters.')
end
if any(BayesInfo.pshape) % if Bayesian estimation
nvx=EstimatedParameters.nvx;

View File

@ -1,83 +0,0 @@
function [freq, init, data, varlist] = load_csv_file_data(file)
% Loads data in a csv file.
%
% INPUTS
% o file string, name of the csv file (with path).
%
% OUTPUTS
% o freq integer scalar equal to 1, 4, 12 or 52 (for annual, quaterly, monthly or weekly frequencies).
% o init dates object, initial date in the dataset.
% o data matrix of doubles, the data.
% o varlist cell of strings, names of the variables.
%
% REMARKS
% The varlist output will be set only if the first line contains variable
% names. Similarly, if the first column does not contain dates, then
% freq will be 1 and init will be year 1.
% Copyright (C) 2012-2013 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% Output initialization
freq = 1; % Default frequency is annual.
init = dates(1,1); % Default initial date is year one.
varlist = [];
assert(exist(file, 'file') == 2, ['load_csv_file_data: I can''t find file ' file '!']);
if isoctave
if ~user_has_octave_forge_package('io')
try
pkg load io
catch
error(['The io package is required to read CSV files from Octave. ' ...
'It can be installed by running the following from the Octave ' ...
' command line: pkg install -forge io']);
end
end
A = csv2cell(file);
[data, T, L] = parsecell(A);
withvars = L.numlimits(2,1) > L.txtlimits(2,1);
withtime = L.numlimits(1,1) > L.txtlimits(1,1);
else
A = importdata(file, ',');
if ~isstruct(A)
data = A;
T = {};
withvars = 0;
withtime = 0;
else
data = A.data;
T = A.textdata;
% importdata() allows text only at the top and the left, so the following
% tests are sufficient.
withvars = size(T, 2) >= size(data, 2);
withtime = size(T, 1) >= size(data, 1);
end
end
if withvars
varlist = T(1, 2:end);
T = T(2:end, :);
end
if withtime
init = dates(T{1, 1});
freq = init.freq;
end
varlist = transpose(varlist);

View File

@ -1,158 +0,0 @@
function [freq,init,data,varlist,tex] = load_m_file_data(file)
% Loads data in a matlab/octave script.
%
% INPUTS
% o file string, name of the matlab/octave script (with path)
%
% OUTPUTS
% o freq integer scalar equal to 1, 4, 12 or 52 (for annual, quaterly, monthly or weekly frequencies).
% o init dates object, initial date in the dataset.
% o data matrix of doubles, the data.
% o varlist cell of strings, names of the variables.
%
% REMARKS
% The frequency and initial date can be specified with variables FREQ__ and INIT__ in the matlab/octave script. FREQ__ must
% be a scalar integer and INIT__ a string like '1938M11', '1945Q3', '1973W3' or '2009A'. If these variables are not specified
% default values for freq and init are 1 and dates(1,1).
% Copyright (C) 2012-2013 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if isoctave
run(file);
else
basename = file(1:end-2);
run(basename);
end
if exist('INIT__','var')
if isdate(INIT__)
init = dates(INIT__);
clear('INIT__')
else
error('load_m_file_data: INIT__ cannot be interpreted as a date.')
end
else
init = dates(1,1); % Default initial date is year one.
end
if exist('FREQ__','var')
freq = FREQ__;
clear('FREQ__');
else
freq = init.freq;
end
if ~isequal(freq,init.freq)
error('load_m_file_data: INIT__ and FREQ__ are not consistent!')
end
if exist('NAMES__','var')
varlist0 = NAMES__;
clear('NAMES__');
else
varlist0 = [];
list_of_variables = [];
end
if exist('TEX__','var')
tex = TEX__;
clear('TEX__');
else
tex = [];
end
if isempty(varlist0)
list_of_variables = whos();
end
data = [];
varlist = {};
if isempty(varlist0)
for current_variable_index=1:length(list_of_variables)
if isequal(list_of_variables(current_variable_index).name,'freq') ...
|| isequal(list_of_variables(current_variable_index).name,'time') ...
|| isequal(list_of_variables(current_variable_index).name,'data') ...
|| isequal(list_of_variables(current_variable_index).name,'varlist') ...
|| isequal(list_of_variables(current_variable_index).name,'varlist0') ...
|| isequal(list_of_variables(current_variable_index).name,'list_of_variables') ...
|| isequal(list_of_variables(current_variable_index).name,'tex') ...
continue
end
if list_of_variables(current_variable_index).global || list_of_variables(current_variable_index).persistent
% A variable cannot be a global or persistent variable.
continue
end
if list_of_variables(current_variable_index).complex || ~strcmp(list_of_variables(current_variable_index).class,'double')
% A variable cannot be complex.
continue
end
if list_of_variables(current_variable_index).size(2)>1
% A variable must be passed as a column vector.
continue
end
try
eval(['data = [data, ' list_of_variables(current_variable_index).name '];'])
eval(['varlist = {varlist{:}, ''' list_of_variables(current_variable_index).name '''};'])
catch
error(['load_m_file:: All the vectors (variables) in ' inputname(1) ' must have the same number of rows (observations)!'])
end
end
else
for current_variable_index=1:length(varlist0)
eval(['data = [data, ' varlist0{current_variable_index} '];'])
end
varlist = varlist0;
end
%@test:1
%$ % Create a data m-file
%$ fid = fopen('data_m_file.m','w');
%$ fprintf(fid,'FREQ__ = 4;');
%$ fprintf(fid,'INIT__ = ''1938Q4'';');
%$ fprintf(fid,'NAMES__ = {''azert'';''yuiop''};');
%$ fprintf(fid,'TEX__ = {''azert'';''yuiop''};');
%$ fprintf(fid,'azert = [1; 2; 3; 4; 5];');
%$ fprintf(fid,'yuiop = [2; 3; 4; 5; 6];');
%$ fclose(fid);
%$
%$ % Try to read the data m-file
%$ try
%$ datafile = 'data_m_file';
%$ [freq,init,data,varlist,tex] = load_m_file_data(datafile);
%$ t(1) = 1;
%$ catch exception
%$ t(1) = 0;
%$ T = all(t);
%$ LOG = getReport(exception,'extended');
%$ return
%$ end
%$
%$ % Check the results.
%$ t(2) = dassert(freq,4);
%$ t(3) = dassert(isa(init,'dates'),1);
%$ t(4) = dassert(init.freq,4);
%$ t(5) = dassert(init.time,[1938 4]);
%$ t(6) = dassert(varlist,{'azert';'yuiop'});
%$ t(7) = dassert(tex,{'azert';'yuiop'});
%$ t(8) = dassert(data(:,1),[1;2;3;4;5]);
%$ t(9) = dassert(data(:,2),[2;3;4;5;6]);
%$ T = all(t);
%@eof:1

View File

@ -1,154 +0,0 @@
function [freq,init,data,varlist,tex] = load_mat_file_data(file) % --*-- Unitary tests --*--
% Loads data in a matlab/octave mat-file.
%
% INPUTS
% o file string, name of the matlab/octave mat file (with path)
%
% OUTPUTS
% o freq integer scalar equal to 1, 4, 12 or 52 (for annual, quaterly, monthly or weekly frequencies).
% o init dates object, initial date in the dataset.
% o data matrix of doubles, the data.
% o varlist cell of strings, names of the variables.
%
% REMARKS
% The frequency and initial date can be specified with variables FREQ__ and INIT__ in the matlab/octave binary file. FREQ__ must
% be a scalar integer and INIT__ a string like '1938M11', '1945Q3', '1973W3' or '2009A'. If these variables are not specified
% default values for freq and init are 1 and dates(1,1).
% Copyright (C) 2012-2014 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
datafile = load(file);
if isfield(datafile,'INIT__')
if isdate(datafile.INIT__)
init = dates(datafile.INIT__);
datafile = rmfield(datafile, 'INIT__');
else
error('load_mat_file_data: INIT__ cannot be interpreted as a date.')
end
else
init = dates(1,1);
end
if isfield(datafile,'FREQ__')
freq = datafile.FREQ__;
datafile = rmfield(datafile, 'FREQ__');
else
freq = init.freq;
end
if ~isequal(freq,init.freq)
error('load_mat_file_data: INIT__ and FREQ__ are not consistent!')
end
if isfield(datafile,'NAMES__')
varlist = datafile.NAMES__;
datafile = rmfield(datafile, 'NAMES__');
else
varlist = [];
end
if isfield(datafile,'TEX__')
tex = datafile.TEX__;
datafile = rmfield(datafile, 'TEX__');
else
tex = [];
end
data = [];
if isempty(varlist)
varlist = fieldnames(datafile);
end
for i=1:length(varlist)
try
tmp = getfield(datafile,varlist{i});
data = [data, tmp(:)];
catch
error(['load_mat_file:: All the vectors (variables) in ' inputname(1) ' must have the same number of rows (observations)!'])
end
end
%@test:1
%$ % Create a data mat-file
%$ FREQ__ = 12;
%$ INIT__ = '1938M11';
%$ NAMES__ = {'hagop'; 'bedros'};
%$ TEX__ = NAMES__;
%$ hagop = [1; 2; 3; 4; 5];
%$ bedros = [2; 3; 4; 5; 6];
%$ save('datafile_for_test');
%$
%$ % Try to read the data mat-file
%$ t = zeros(8,1);
%$ try
%$ [freq,init,data,varlist,tex] = load_mat_file_data('datafile_for_test');
%$ t(1) = 1;
%$ catch exception
%$ t = t(1);
%$ T = all(t);
%$ LOG = getReport(exception,'extended');
%$ return
%$ end
%$
%$ % Check the results.
%$ t(2) = dassert(freq,12);
%$ t(3) = dassert(isa(init,'dates'),true);
%$ t(4) = dassert(init.freq,12);
%$ t(5) = dassert(init.time,[1938 11]);
%$ t(6) = dassert(varlist,{'hagop';'bedros'});
%$ t(7) = dassert(varlist,{'hagop';'bedros'});
%$ t(8) = dassert(data(:,1),[1;2;3;4;5]);
%$ t(9) = dassert(data(:,2),[2;3;4;5;6]);
%$ T = all(t);
%@eof:1
%@test:2
%$ % Create a data mat-file
%$ FREQ__ = 12;
%$ INIT__ = '1938M11';
%$ NAMES__ = {'hagop'; 'bedros'};
%$ TEX__ = NAMES__;
%$ hagop = [1, 2, 3, 4, 5];
%$ bedros = [2, 3, 4, 5, 6];
%$ save('datafile_for_test');
%$
%$ % Try to read the data mat-file
%$ t = zeros(8,1);
%$ try
%$ [freq,init,data,varlist,tex] = load_mat_file_data('datafile_for_test');
%$ t(1) = 1;
%$ catch exception
%$ t = t(1);
%$ T = all(t);
%$ LOG = getReport(exception,'extended');
%$ return
%$ end
%$
%$ % Check the results.
%$ t(2) = dassert(freq,12);
%$ t(3) = dassert(isa(init,'dates'),true);
%$ t(4) = dassert(init.freq,12);
%$ t(5) = dassert(init.time,[1938 11]);
%$ t(6) = dassert(varlist,{'hagop';'bedros'});
%$ t(7) = dassert(varlist,{'hagop';'bedros'});
%$ t(8) = dassert(data(:,1),[1;2;3;4;5]);
%$ t(9) = dassert(data(:,2),[2;3;4;5;6]);
%$ T = all(t);
%@eof:2

View File

@ -1,138 +0,0 @@
function [freq, init, data, varlist] = load_xls_file_data(file, sheet, range)
% Loads data in a xls file.
%
% INPUTS
% o file string, name of the file (with extension).
% o sheet string, name of the sheet to be read.
% o range string of the form 'B2:D6'
%
% OUTPUTS
% o freq integer scalar (1, 4, 12 or 52), code for frequency.
% o init dates object, initial date of the sample.
% o data matrix of doubles, the raw data.
% o varlist cell of strings (column), names of the variables in the database.
%
% REMARKS
% The range argument is only available on windows platform (with Excel installed).
% Copyright (C) 2013 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% Set defaults.
if nargin<3 || isempty(range)
range = '';
if nargin<2 || isempty(sheet)
sheet = 1;
if nargin<1 || isempty(file)
error('load_xls_file_data:: I need at least one input (name of the xls or xlsx file)!')
end
end
end
% Check file extension.
if ~(check_file_extension(file,'xls') || check_file_extension(file,'xlsx'))
ext = get_file_extension(file);
if isempty(ext)
if exist([file '.xls'],'file')
file = [file '.xls'];
elseif exist([file '.xlsx'],'file')
file = [file '.xlsx'];
else
error(['load_xls_file_data:: Unable to find the data file ' file ' with an xls or xlsx extension!'])
end
else
error(['load_xls_file_data:: The data file ' file ' has wrong extension (must be either xls or xlsx)!'])
end
end
% load excel file.
if isoctave && ~user_has_octave_forge_package('io')
error('The io package is required to read XLS/XLSX files from Octave')
end
[num,txt,raw] = xlsread(file, sheet, range);
% Get dimensions of num, txt and raw
[n1, n2] = size(num);
[t1, t2] = size(txt);
[r1, r2] = size(raw);
% Check the content of the file.
if isequal(t1,0) && isequal(t2,0)
% The file contains no informations about the variables and dates.
notime = 1;
noname = 1;
elseif isequal(t2,1) && t1>=t2 && n2~=t2 %only one column present, but no var name in header text
% The file contains no informations about the dates.
notime = 0;
noname = 1;
elseif isequal(t2,1) && t1>=t2 && n2==t2 %only one column present with var name in header text
% The file contains no informations about the variables.
notime = 1;
noname = 0;
elseif isequal(t1,1) && t2>=t1
% The file contains no informations about the dates.
notime = 1;
noname = 0;
else
% The file contains informations about the variables and dates.
notime = 0;
noname = 0;
end
% Output initialization.
freq = 1;
init = dates(1,1);
varlist = [];
data = num;
% Update freq.
if ~notime
if isempty(txt{1,1})
first_date = txt{2,1};
else
first_date = txt{1,1};
end
if isnumeric(first_date) && isint(first_date)
first_date = [num2str(first_date) 'Y'];
end
if isdate(first_date)
init = dates(first_date);
freq = init.freq;
else
error('load_xls_file_data: I am not able to read the dates!')
end
end
% Update varlist.
if ~noname
if notime
varlist = transpose(txt);
else
varlist = transpose(txt(1,2:end));
end
% Remove leading and trailing white spaces
for i=1:length(varlist)
varlist(i) = {strtrim(varlist{i})};
end
else
% set default names
varlist = cell(n2,1);
for i=1:n2
varlist(i) = {['Variable_' int2str(i)]};
end
end

View File

@ -0,0 +1,167 @@
function perfect_foresight_solver()
% Computes deterministic simulations
%
% INPUTS
% None
%
% OUTPUTS
% none
%
% ALGORITHM
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 1996-2014 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ oo_
check_input_arguments(options_, M_, oo_);
if isempty(options_.scalv) || options_.scalv == 0
options_.scalv = oo_.steady_state;
end
options_.scalv= 1;
if options_.debug
model_static = str2func([M_.fname,'_static']);
for ii=1:size(oo_.exo_simul,1)
[residual(:,ii)] = model_static(oo_.steady_state, oo_.exo_simul(ii,:),M_.params);
end
problematic_periods=find(any(isinf(residual)) | any(isnan(residual)))-M_.maximum_endo_lag;
if ~isempty(problematic_periods)
period_string=num2str(problematic_periods(1));
for ii=2:length(problematic_periods)
period_string=[period_string, ', ', num2str(problematic_periods(ii))];
end
fprintf('\n\nWARNING: Value for the exogenous variable(s) in period(s) %s inconsistent with the static model.\n',period_string);
fprintf('WARNING: Check for division by 0.\n')
end
end
initperiods = 1:M_.maximum_lag;
lastperiods = (M_.maximum_endo_lag+options_.periods+1):(M_.maximum_endo_lag+options_.periods+M_.maximum_endo_lead);
% Disable warnings if homotopy
if ~options_.no_homotopy
warning off all
end
[oo_.endo_simul,oo_.deterministic_simulation.status] = perfect_foresight_solver_core(M_,options_,oo_);
% If simulation failed try homotopy.
if ~oo_.deterministic_simulation.status && ~options_.no_homotopy
disp('Simulation of the perfect foresight model failed!')
skipline()
exosim = oo_.exo_simul;
exoinit = repmat(oo_.exo_steady_state',M_.maximum_lag+options_.periods+M_.maximum_lead,1);
endosim = oo_.endo_simul;
endoinit = repmat(oo_.steady_state, 1,M_.maximum_lag+options_.periods+M_.maximum_lead);
current_weight = 0; % Current weight of target point in convex combination
step = .5;
success_counter = 0;
iteration = 0;
fprintf('Iter. \t | Lambda \t | status \t | Max. residual\n')
fprintf('++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n')
while (step > options_.dynatol.x)
if ~isequal(step,1)
options_.verbosity = 0;
end
iteration = iteration+1;
new_weight = current_weight + step; % Try this weight, and see if it succeeds
if new_weight >= 1
new_weight = 1; % Don't go beyond target point
step = new_weight - current_weight;
end
% Compute convex combination for exo path and initial/terminal endo conditions
% But take care of not overwriting the computed part of oo_.endo_simul
oo_.exo_simul = exosim*new_weight + exoinit*(1-new_weight);
oo_.endo_simul(:,[initperiods, lastperiods]) = ...
new_weight*oo_.endo_simul(:,[initperiods, lastperiods])+(1-new_weight)*endoinit(:,[initperiods, lastperiods]);
path_with_nans = any(any(isnan(oo_.endo_simul)));
path_with_cplx = any(any(~isreal(oo_.endo_simul)));
if isequal(iteration,1) && (path_with_nans || path_with_cplx)
oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead) = endoinit(:,1:options_.periods);
elseif path_with_nans || path_with_cplx
oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead) = saved_endo_simul(:,1+M_.maximum_endo_lag:end-M_.maximum_endo_lead);
end
saved_endo_simul = oo_.endo_simul;
[oo_.endo_simul,oo_.deterministic_simulation.status,me] = perfect_foresight_solver_core(M_,options_,oo_);
if oo_.deterministic_simulation.status == 1
current_weight = new_weight;
if current_weight >= 1
fprintf('%i \t | %1.5f \t | %s \t | %e\n', iteration, new_weight, 'succeeded', me)
break
end
success_counter = success_counter + 1;
if success_counter >= 3
success_counter = 0;
step = step * 2;
fprintf('%i \t | %1.5f \t | %s \t | %e\n', iteration, new_weight, 'succeeded', me)
else
fprintf('%i \t | %1.5f \t | %s \t | %e\n', iteration, new_weight, 'succeeded', me)
end
else
oo_.endo_simul = saved_endo_simul;
success_counter = 0;
step = step / 2;
fprintf('%i \t | %1.5f \t | %s \t | %e\n', iteration, new_weight, 'failed', me)
end
end
fprintf('++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n')
skipline()
end
if ~options_.no_homotopy
warning off all
end
if oo_.deterministic_simulation.status == 1
disp('Perfect foresight solution found.')
skipline()
else
warning('Failed to solve perfect foresight model')
end
dyn2vec;
if ~isdates(options_.initial_period) && isnan(options_.initial_period)
initial_period = dates(1,1);
else
initial_period = options_.initial_period;
end
ts = dseries(transpose(oo_.endo_simul),initial_period,cellstr(M_.endo_names));
assignin('base', 'Simulated_time_series', ts);

View File

@ -0,0 +1,95 @@
function [endo_simul,status, maxerror] = perfect_foresight_simulation_core(M_, options_, oo_)
status = false;
if options_.block
if options_.bytecode
try
[info, tmp] = bytecode('dynamic', oo_.endo_simul, oo_.exo_simul, M_.params, repmat(oo_.steady_state,1,options_.periods+2), options_.periods);
catch
info = 0;
end
if info
status = false;
else
endo_simul = tmp;
status = true;
end
mexErrCheck('bytecode', info);
else
eval([M_.fname '_dynamic']);
end
else
if options_.bytecode
try
[info, tmp] = bytecode('dynamic', oo_.endo_simul, oo_.exo_simul, M_.params, repmat(oo_.steady_state,1,options_.periods+2), options_.periods);
catch
info = 0;
end
if info
status = false;
else
endo_simul = tmp;
status = true;
end;
mexErrCheck('bytecode', info);
else
if M_.maximum_endo_lead == 0 % Purely backward model
oo_ = sim1_purely_backward(options_, M_, oo_);
elseif M_.maximum_endo_lag == 0 % Purely forward model
oo_ = sim1_purely_forward(options_, M_, oo_);
else % General case
if options_.stack_solve_algo == 0
oo_ = sim1(options_, M_, oo_);
elseif options_.stack_solve_algo == 6
oo_ = sim1_lbj(options_, M_, oo_);
elseif options_.stack_solve_algo == 7
periods = options_.periods;
if ~isfield(options_.lmmcp,'lb')
[lb,ub,pfm.eq_index] = get_complementarity_conditions(M_);
options_.lmmcp.lb = repmat(lb,periods,1);
options_.lmmcp.ub = repmat(ub,periods,1);
end
y = oo_.endo_simul;
y0 = y(:,1);
yT = y(:,periods+2);
z = y(:,2:periods+1);
illi = M_.lead_lag_incidence';
[i_cols,~,i_cols_j] = find(illi(:));
illi = illi(:,2:3);
[i_cols_J1,~,i_cols_1] = find(illi(:));
i_cols_T = nonzeros(M_.lead_lag_incidence(1:2,:)');
[y,info] = dynare_solve(@perfect_foresight_problem,z(:),1, ...
str2func([M_.fname '_dynamic']),y0,yT, ...
oo_.exo_simul,M_.params,oo_.steady_state, ...
options_.periods,M_.endo_nbr,i_cols, ...
i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ...
M_.NNZDerivatives(1));
endo_simul = [y0 reshape(y,M_.endo_nbr,periods) yT];
if info == 1
status = false;
else
status = true;
end
end
end
end
end
if nargout>1
y0 = oo_.endo_simul(:,1);
yT = oo_.endo_simul(:,options_.periods+2);
yy = oo_.endo_simul(:,2:options_.periods+1);
if ~exist('illi')
illi = M_.lead_lag_incidence';
[i_cols,~,i_cols_j] = find(illi(:));
illi = illi(:,2:3);
[i_cols_J1,~,i_cols_1] = find(illi(:));
i_cols_T = nonzeros(M_.lead_lag_incidence(1:2,:)');
end
residuals = perfect_foresight_problem(yy(:),str2func([M_.fname '_dynamic']), y0, yT, ...
oo_.exo_simul,M_.params,oo_.steady_state, ...
options_.periods,M_.endo_nbr,i_cols, ...
i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ...
M_.NNZDerivatives(1));
maxerror = max(max(abs(residuals)));
end

View File

@ -0,0 +1,48 @@
function check_input_arguments(DynareOptions, DynareModel, DynareResults)
% Copyright (C) 2014 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if DynareOptions.stack_solve_algo < 0 || DynareOptions.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 ~= 6 && DynareOptions.stack_solve_algo ~= 7
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: you must use stack_solve_algo=0 or stack_solve_algo=6 when not using block nor bytecode option')
end
if DynareOptions.block && ~DynareOptions.bytecode && DynareOptions.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 (DynareOptions.block || DynareOptions.bytecode) && DynareOptions.stack_solve_algo == 6
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: you can''t use stack_solve_algo = 6 with block or bytecode option')
end
if isoctave && DynareOptions.stack_solve_algo == 2
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: you can''t use stack_solve_algo = 2 under Octave')
end
if isempty(DynareResults.endo_simul) || any(size(DynareResults.endo_simul) ~= [ DynareModel.endo_nbr, DynareModel.maximum_lag+DynareOptions.periods+DynareModel.maximum_lead ])
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')
end
if isempty(DynareResults.exo_simul) || any(size(DynareResults.exo_simul) ~= [ DynareModel.maximum_lag+DynareOptions.periods+DynareModel.maximum_lead, DynareModel.exo_nbr ])
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.exo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')
end

View File

@ -0,0 +1,94 @@
function [oo_, maxerror] = simulation_core(options_, M_, oo_)
if options_.block
if options_.bytecode
try
[info, tmp] = bytecode('dynamic', oo_.endo_simul, oo_.exo_simul, M_.params, repmat(oo_.steady_state,1,options_.periods+2), options_.periods);
catch
info = 0;
end
if info
oo_.deterministic_simulation.status = false;
else
oo_.endo_simul = tmp;
oo_.deterministic_simulation.status = true;
end
mexErrCheck('bytecode', info);
else
eval([M_.fname '_dynamic']);
end
else
if options_.bytecode
try
[info, tmp] = bytecode('dynamic', oo_.endo_simul, oo_.exo_simul, M_.params, repmat(oo_.steady_state,1,options_.periods+2), options_.periods);
catch
info = 0;
end
if info
oo_.deterministic_simulation.status = false;
else
oo_.endo_simul = tmp;
oo_.deterministic_simulation.status = true;
end;
mexErrCheck('bytecode', info);
else
if M_.maximum_endo_lead == 0 % Purely backward model
oo_ = sim1_purely_backward(options_, M_, oo_);
elseif M_.maximum_endo_lag == 0 % Purely forward model
oo_ = sim1_purely_forward(options_, M_, oo_);
else % General case
if options_.stack_solve_algo == 0
oo_ = sim1(options_, M_, oo_);
elseif options_.stack_solve_algo == 6
oo_ = sim1_lbj(options_, M_, oo_);
elseif options_.stack_solve_algo == 7
periods = options_.periods;
if ~isfield(options_.lmmcp,'lb')
[lb,ub,pfm.eq_index] = get_complementarity_conditions(M_);
options_.lmmcp.lb = repmat(lb,periods,1);
options_.lmmcp.ub = repmat(ub,periods,1);
end
y = oo_.endo_simul;
y0 = y(:,1);
yT = y(:,periods+2);
z = y(:,2:periods+1);
illi = M_.lead_lag_incidence';
[i_cols,~,i_cols_j] = find(illi(:));
illi = illi(:,2:3);
[i_cols_J1,~,i_cols_1] = find(illi(:));
i_cols_T = nonzeros(M_.lead_lag_incidence(1:2,:)');
[y,info] = dynare_solve(@perfect_foresight_problem,z(:),1, ...
str2func([M_.fname '_dynamic']),y0,yT, ...
oo_.exo_simul,M_.params,oo_.steady_state, ...
options_.periods,M_.endo_nbr,i_cols, ...
i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ...
M_.NNZDerivatives(1));
oo_.endo_simul = [y0 reshape(y,M_.endo_nbr,periods) yT];
if info == 1
oo_.deterministic_simulation.status = false;
else
oo_.deterministic_simulation.status = true;
end
end
end
end
end
if nargout>1
y0 = oo_.endo_simul(:,1);
yT = oo_.endo_simul(:,options_.periods+2);
yy = oo_.endo_simul(:,2:options_.periods+1);
if ~exist('illi')
illi = M_.lead_lag_incidence';
[i_cols,~,i_cols_j] = find(illi(:));
illi = illi(:,2:3);
[i_cols_J1,~,i_cols_1] = find(illi(:));
i_cols_T = nonzeros(M_.lead_lag_incidence(1:2,:)');
end
residuals = perfect_foresight_problem(yy(:),str2func([M_.fname '_dynamic']), y0, yT, ...
oo_.exo_simul,M_.params,oo_.steady_state, ...
options_.periods,M_.endo_nbr,i_cols, ...
i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ...
M_.NNZDerivatives(1));
maxerror = max(max(abs(residuals)));
end

View File

@ -1,4 +1,4 @@
function oo=sim1(M,options,oo)
function oo_ = sim1(options_, M_, oo_)
% function sim1
% Performs deterministic simulations with lead or lag on one period.
% Uses sparse matrices.
@ -31,6 +31,8 @@ function oo=sim1(M,options,oo)
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
verbose = options_.no_homotopy;
endogenous_terminal_period = options.endogenous_terminal_period;
vperiods = options.periods*ones(1,options.simul.maxit);
azero = options.dynatol.f/1e7;
@ -73,9 +75,11 @@ i_upd = maximum_lag*ny+(1:periods*ny);
Y = endo_simul(:);
skipline()
disp (['-----------------------------------------------------']) ;
fprintf('MODEL SIMULATION:\n');
if verbose
skipline()
disp (['-----------------------------------------------------']) ;
fprintf('MODEL SIMULATION:\n');
end
model_dynamic = str2func([M.fname,'_dynamic']);
z = Y(find(lead_lag_incidence'));
@ -166,42 +170,51 @@ end
if stop
if any(isnan(res)) || any(isinf(res)) || any(isnan(Y)) || any(isinf(Y)) || ~isreal(res) || ~isreal(Y)
oo.deterministic_simulation.status = 0;% NaN or Inf occurred
oo.deterministic_simulation.error = err;
oo.deterministic_simulation.iterations = iter;
oo.deterministic_simulation.periods = vperiods(1:iter);
oo.endo_simul = reshape(Y,ny,periods+maximum_lag+M.maximum_lead);
oo_.deterministic_simulation.status = false;% NaN or Inf occurred
oo_.deterministic_simulation.error = err;
oo_.deterministic_simulation.iterations = iter;
oo_.deterministic_simulation.periods = vperiods(1:iter);
oo_.endo_simul = reshape(Y,ny,periods+maximum_lag+M_.maximum_lead);
if verbose
skipline();
fprintf('\nSimulation terminated after %d iterations.\n',iter);
fprintf('Total time of simulation: %16.13f\n',etime(clock,h1));
if ~isreal(res) || ~isreal(Y)
fprintf('WARNING: Simulation terminated with imaginary parts in the residuals or endogenous variables.\n');
else
fprintf('WARNING: Simulation terminated with NaN or Inf in the residuals or endogenous variables.\n');
end
fprintf('WARNING: There is most likely something wrong with your model. Try model_diagnostics.\n');
end
else
if verbose
skipline();
fprintf('\nSimulation concluded successfully after %d iterations.\n',iter);
fprintf('Total time of simulation: %16.13f\n',etime(clock,h1));
fprintf('Max. Abs. Error : %16.13f\n',err);
fprintf('Convergency obtained!\n');
end
oo_.deterministic_simulation.status = true;% Convergency obtained.
oo_.deterministic_simulation.error = err;
oo_.deterministic_simulation.iterations = iter;
oo_.deterministic_simulation.periods = vperiods(1:iter);
oo_.endo_simul = reshape(Y,ny,periods+maximum_lag+M_.maximum_lead);
end
elseif ~stop
if verbose
skipline();
fprintf('\nSimulation terminated after %d iterations.\n',iter);
fprintf('Total time of simulation: %16.13f\n',etime(clock,h1));
if ~isreal(res) || ~isreal(Y)
fprintf('WARNING: Simulation terminated with imaginary parts in the residuals or endogenous variables.\n');
else
fprintf('WARNING: Simulation terminated with NaN or Inf in the residuals or endogenous variables.\n');
end
fprintf('WARNING: There is most likely something wrong with your model. Try model_diagnostics.\n');
else
skipline();
fprintf('\nSimulation concluded successfully after %d iterations.\n',iter);
fprintf('Total time of simulation: %16.13f\n',etime(clock,h1));
fprintf('Max. Abs. Error : %16.13f\n',err);
fprintf('Convergency obtained!\n');
oo.deterministic_simulation.status = 1;% Convergency obtained.
oo.deterministic_simulation.error = err;
oo.deterministic_simulation.iterations = iter;
oo.deterministic_simulation.periods = vperiods(1:iter);
oo.endo_simul = reshape(Y,ny,periods+maximum_lag+M.maximum_lead);
fprintf('WARNING : maximum number of iterations is reached (modify option maxit).\n') ;
end
elseif ~stop
skipline();
fprintf('\nSimulation terminated after %d iterations.\n',iter);
fprintf('Total time of simulation: %16.13f\n',etime(clock,h1));
fprintf('Max. Abs. Error : %16.13f\n',err);
fprintf('WARNING : maximum number of iterations is reached (modify option maxit).\n') ;
oo.deterministic_simulation.status = 0;% more iterations are needed.
oo.deterministic_simulation.error = err;
oo.deterministic_simulation.periods = vperiods(1:iter);
oo.deterministic_simulation.iterations = options.simul.maxit;
oo_.deterministic_simulation.status = false;% more iterations are needed.
oo_.deterministic_simulation.error = err;
oo_.deterministic_simulation.periods = vperiods(1:iter);
oo_.deterministic_simulation.iterations = options_.simul.maxit;
end
disp (['-----------------------------------------------------']) ;
skipline();
if verbose
disp (['-----------------------------------------------------']) ;
skipline();
end

View File

@ -1,4 +1,4 @@
function sim1_lbj()
function oo_ = sim1_lbj(options_, M_, oo_)
% function sim1_lbj
% performs deterministic simulations with lead or lag on one period
% using the historical LBJ algorithm
@ -33,8 +33,6 @@ function sim1_lbj()
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ oo_
lead_lag_incidence = M_.lead_lag_incidence;
ny = size(oo_.endo_simul,1) ;

View File

@ -1,4 +1,4 @@
function sim1_purely_backward()
function oo_ = sim1_purely_backward(options_, M_, oo_)
% Performs deterministic simulation of a purely backward model
% Copyright (C) 2012-2014 Dynare Team
@ -18,7 +18,6 @@ function sim1_purely_backward()
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ oo_
if size(M_.lead_lag_incidence,1) > 1
ny0 = nnz(M_.lead_lag_incidence(2,:)); % Number of variables at current period
nyb = nnz(M_.lead_lag_incidence(1,:)); % Number of variables at previous period
@ -53,5 +52,4 @@ function sim1_purely_backward()
end
oo_.endo_simul(:,it) = tmp(nyb+1:nyb+M_.endo_nbr);
end
end

View File

@ -1,4 +1,4 @@
function sim1_purely_forward()
function oo_ = sim1_purely_forward(options_, M_, oo_)
% Performs deterministic simulation of a purely forward model
% Copyright (C) 2012-2014 Dynare Team
@ -18,8 +18,6 @@ function sim1_purely_forward()
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ oo_
ny0 = nnz(M_.lead_lag_incidence(1,:)); % Number of variables at current period
iyf = find(M_.lead_lag_incidence(2,:)>0); % Indices of variables at next period
@ -46,5 +44,4 @@ function sim1_purely_forward()
end
oo_.endo_simul(:,it) = tmp(1:M_.endo_nbr);
end
end

View File

@ -12,7 +12,7 @@ function o = page(varargin)
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2013-2014 Dynare Team
% Copyright (C) 2013-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -34,6 +34,7 @@ o.paper = '';
o.title = {''};
titleFormatDefalut = {'\large\bfseries'};
o.titleFormat = titleFormatDefalut;
o.titleTruncate = '';
o.orientation = '';
o.footnote = {};
o.sections = {};
@ -77,6 +78,9 @@ assert(iscellstr(o.title), ...
'@page.page: title must be a cell array of strings');
assert(iscellstr(o.titleFormat), ...
'@page.page: titleFormat must be a cell array of strings');
assert((ischar(o.titleTruncate) && isempty(o.titleTruncate)) || ...
isint(o.titleTruncate), ...
'@page.page: titleTruncate must be empty or an integer.');
valid_paper = {'a4', 'letter'};
assert(any(strcmp(o.paper, valid_paper)), ...

View File

@ -13,7 +13,7 @@ function o = write(o, fid, pg)
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2013-2014 Dynare Team
% Copyright (C) 2013-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -44,6 +44,11 @@ fprintf(fid,'\n');
fprintf(fid, '\\begin{tabular}[t]{c}\n');
for i=1:length(o.title)
if isint(o.titleTruncate)
if length(o.title{i}) > o.titleTruncate
o.title{i} = o.title{i}(1:o.titleTruncate);
end
end
fprintf(fid,'\\multicolumn{1}{c}{%s %s}\\\\\n', o.titleFormat{i}, o.title{i});
end

View File

@ -15,7 +15,7 @@ function y_=simult_(y0,dr,ex_,iorder)
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2001-2013 Dynare Team
% Copyright (C) 2001-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -41,12 +41,6 @@ exo_nbr = M_.exo_nbr;
y_ = zeros(size(y0,1),iter+M_.maximum_lag);
y_(:,1) = y0;
% stoch_simul sets k_order_solver=1 if order=3, but does so only locally, so we
% have to do it here also
if options_.order == 3
options_.k_order_solver = 1;
end
if ~options_.k_order_solver || (options_.k_order_solver && options_.pruning) %if k_order_pert is not used or if we do not use Dynare++ with k_order_pert
if iorder==1
y_(:,1) = y_(:,1)-dr.ys;

View File

@ -1,6 +1,6 @@
function info=stoch_simul(var_list)
% Copyright (C) 2001-2013 Dynare Team
% Copyright (C) 2001-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -34,8 +34,6 @@ if options_.linear
end
if options_.order == 1
options_.replic = 1;
elseif options_.order == 3
options_.k_order_solver = 1;
end
if isempty(options_.qz_criterium)

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2003-2014 Dynare Team
* Copyright (C) 2003-2015 Dynare Team
*
* This file is part of Dynare.
*
@ -168,6 +168,13 @@ StochSimulStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
void
StochSimulStatement::writeOutput(ostream &output, const string &basename) const
{
// Ensure that order 3 implies k_order (#844)
OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("k_order_solver");
if ((it1 != options_list.num_options.end() && it1->second == "1")
|| (it != options_list.num_options.end() && atoi(it->second.c_str()) >= 3))
output << "options_.k_order_solver = 1;" << endl;
options_list.writeOutput(output);
symbol_list.writeOutput("var_list_", output);
output << "info = stoch_simul(var_list_);" << endl;
@ -234,6 +241,13 @@ RamseyModelStatement::writeOutput(ostream &output, const string &basename) const
// this affects the computation of the steady state that uses a special algorithm
// It should probably rather be a M_ field, but we leave it in options_ for historical reason
// Ensure that order 3 implies k_order (#844)
OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("k_order_solver");
if ((it1 != options_list.num_options.end() && it1->second == "1")
|| (it != options_list.num_options.end() && atoi(it->second.c_str()) >= 3))
output << "options_.k_order_solver = 1;" << endl;
output << "options_.ramsey_policy = 1;" << endl;
options_list.writeOutput(output);
}
@ -284,6 +298,13 @@ RamseyPolicyStatement::checkPass(ModFileStructure &mod_file_struct, WarningConso
void
RamseyPolicyStatement::writeOutput(ostream &output, const string &basename) const
{
// Ensure that order 3 implies k_order (#844)
OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("k_order_solver");
if ((it1 != options_list.num_options.end() && it1->second == "1")
|| (it != options_list.num_options.end() && atoi(it->second.c_str()) >= 3))
output << "options_.k_order_solver = 1;" << endl;
options_list.writeOutput(output);
symbol_list.writeOutput("var_list_", output);
output << "ramsey_policy(var_list_);" << endl;
@ -337,6 +358,13 @@ DiscretionaryPolicyStatement::checkPass(ModFileStructure &mod_file_struct, Warni
void
DiscretionaryPolicyStatement::writeOutput(ostream &output, const string &basename) const
{
// Ensure that order 3 implies k_order (#844)
OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("k_order_solver");
if ((it1 != options_list.num_options.end() && it1->second == "1")
|| (it != options_list.num_options.end() && atoi(it->second.c_str()) >= 3))
output << "options_.k_order_solver = 1;" << endl;
options_list.writeOutput(output);
symbol_list.writeOutput("var_list_", output);
output << "discretionary_policy(var_list_);" << endl;
@ -914,6 +942,13 @@ OsrStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation
void
OsrStatement::writeOutput(ostream &output, const string &basename) const
{
// Ensure that order 3 implies k_order (#844)
OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("k_order_solver");
if ((it1 != options_list.num_options.end() && it1->second == "1")
|| (it != options_list.num_options.end() && atoi(it->second.c_str()) >= 3))
output << "options_.k_order_solver = 1;" << endl;
options_list.writeOutput(output);
symbol_list.writeOutput("var_list_", output);
output << "oo_.osr = osr(var_list_,osr_params_,obj_var_,optim_weights_);" << endl;

View File

@ -3253,12 +3253,13 @@ DynamicModel::collect_block_first_order_derivatives()
int var = symbol_table.getTypeSpecificID(getSymbIDByDerivID(it2->first.second));
int lag = getLagByDerivID(it2->first.second);
int block_eq = equation_2_block[eq];
int block_var = variable_2_block[var];
int block_var=0;
derivative_t tmp_derivative;
lag_var_t lag_var;
switch (getTypeByDerivID(it2->first.second))
{
case eEndogenous:
block_var = variable_2_block[var];
if (block_eq == block_var)
{
if (lag < 0 && lag < -endo_max_leadlag_block[block_eq].first)

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2003-2014 Dynare Team
* Copyright (C) 2003-2015 Dynare Team
*
* This file is part of Dynare.
*
@ -108,7 +108,7 @@ class ParsingDriver;
%token MODE_CHECK MODE_CHECK_NEIGHBOURHOOD_SIZE MODE_CHECK_SYMMETRIC_PLOTS MODE_CHECK_NUMBER_OF_POINTS MODE_COMPUTE MODE_FILE MODEL MODEL_COMPARISON MODEL_INFO MSHOCKS ABS SIGN
%token MODEL_DIAGNOSTICS MODIFIEDHARMONICMEAN MOMENTS_VARENDO DIFFUSE_FILTER SUB_DRAWS TAPER_STEPS GEWEKE_INTERVAL MCMC_JUMPING_COVARIANCE MOMENT_CALIBRATION
%token NUMBER_OF_PARTICLES RESAMPLING SYSTEMATIC GENERIC RESAMPLING_THRESHOLD RESAMPLING_METHOD KITAGAWA STRATIFIED SMOOTH
%token FILTER_ALGORITHM SIS APF GF GMF CPF PROPOSAL_APPROXIMATION CUBATURE UNSCENTED MONTECARLO DISTRIBUTION_APPROXIMATION
%token FILTER_ALGORITHM PROPOSAL_APPROXIMATION CUBATURE UNSCENTED MONTECARLO DISTRIBUTION_APPROXIMATION
%token <string_val> NAME
%token NAN_CONSTANT NO_STATIC NOBS NOCONSTANT NODISPLAY NOCORR NODIAGNOSTIC NOFUNCTIONS NO_HOMOTOPY
%token NOGRAPH NOMOMENTS NOPRINT NORMAL_PDF SAVE_DRAWS
@ -2671,11 +2671,7 @@ o_resampling_threshold : RESAMPLING_THRESHOLD EQUAL non_negative_number { driver
o_resampling_method : RESAMPLING_METHOD EQUAL KITAGAWA {driver.option_num("particle.resampling.method.kitagawa", "1"); driver.option_num("particle.resampling.method.smooth", "0"); driver.option_num("particle.resampling.smethod.stratified", "0"); }
| RESAMPLING_METHOD EQUAL SMOOTH {driver.option_num("particle.resampling.method.kitagawa", "0"); driver.option_num("particle.resampling.method.smooth", "1"); driver.option_num("particle.resampling.smethod.stratified", "0"); }
| RESAMPLING_METHOD EQUAL STRATIFIED {driver.option_num("particle.resampling.method.kitagawa", "0"); driver.option_num("particle.resampling.method.smooth", "0"); driver.option_num("particle.resampling.method.stratified", "1"); };
o_filter_algorithm : FILTER_ALGORITHM EQUAL SIS {driver.option_num("particle.filter_algorithm.sis", "1"); driver.option_num("particle.filter_algorithm.apf", "0"); driver.option_num("particle.filter_algorithm.gf", "0"); driver.option_num("particle.filter_algorithm.gmf", "0");driver.option_num("particle.filter_algorithm.cpf", "0");}
| FILTER_ALGORITHM EQUAL APF {driver.option_num("particle.filter_algorithm.sis", "0"); driver.option_num("particle.filter_algorithm.apf", "1"); driver.option_num("particle.filter_algorithm.gf", "0"); driver.option_num("particle.filter_algorithm.gmf", "0"); driver.option_num("particle.filter_algorithm.cpf", "0");}
| FILTER_ALGORITHM EQUAL GF {driver.option_num("particle.filter_algorithm.sis", "0"); driver.option_num("particle.filter_algorithm.apf", "0"); driver.option_num("particle.filter_algorithm.gf", "1"); driver.option_num("particle.filter_algorithm.gmf", "0"); driver.option_num("particle.filter_algorithm.cpf", "0");}
| FILTER_ALGORITHM EQUAL GMF {driver.option_num("particle.filter_algorithm.sis", "0"); driver.option_num("particle.filter_algorithm.apf", "0"); driver.option_num("particle.filter_algorithm.gf", "0"); driver.option_num("particle.filter_algorithm.gmf", "1"); driver.option_num("particle.filter_algorithm.cpf", "0");}
| FILTER_ALGORITHM EQUAL CPF {driver.option_num("particle.filter_algorithm.sis", "0"); driver.option_num("particle.filter_algorithm.apf", "0"); driver.option_num("particle.filter_algorithm.gf", "0"); driver.option_num("particle.filter_algorithm.gmf", "0"); driver.option_num("particle.filter_algorithm.cpf", "1");} ;
o_filter_algorithm : FILTER_ALGORITHM EQUAL symbol { driver.option_str("particle.filter_algorithm", $3); };
o_proposal_approximation : PROPOSAL_APPROXIMATION EQUAL CUBATURE {driver.option_num("particle.proposal_approximation.cubature", "1"); driver.option_num("particle.proposal_approximation.unscented", "0"); driver.option_num("particle.proposal_approximation.montecarlo", "0");}
| PROPOSAL_APPROXIMATION EQUAL UNSCENTED {driver.option_num("particle.proposal_approximation.cubature", "0"); driver.option_num("particle.proposal_approximation.unscented", "1"); driver.option_num("particle.proposal_approximation.montecarlo", "0");}
| PROPOSAL_APPROXIMATION EQUAL MONTECARLO {driver.option_num("particle.proposal_approximation.cubature", "0"); driver.option_num("particle.proposal_approximation.unscented", "0"); driver.option_num("particle.proposal_approximation.montecarlo", "1");} ;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2003-2014 Dynare Team
* Copyright (C) 2003-2015 Dynare Team
*
* This file is part of Dynare.
*
@ -363,11 +363,6 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2
<DYNARE_STATEMENT>smooth {return token::SMOOTH;}
<DYNARE_STATEMENT>stratified {return token::STRATIFIED;}
<DYNARE_STATEMENT>filter_algorithm {return token::FILTER_ALGORITHM;}
<DYNARE_STATEMENT>sis {return token::SIS;}
<DYNARE_STATEMENT>apf {return token::APF;}
<DYNARE_STATEMENT>gf {return token::GF;}
<DYNARE_STATEMENT>gmf {return token::GMF;}
<DYNARE_STATEMENT>cpf {return token::CPF;}
<DYNARE_STATEMENT>proposal_approximation {return token::PROPOSAL_APPROXIMATION;}
<DYNARE_STATEMENT>cubature {return token::CUBATURE;}
<DYNARE_STATEMENT>unscented {return token::UNSCENTED;}

View File

@ -96,12 +96,6 @@ options_.mode_check.number_of_points = 250;
//set_dynare_threads('local_state_space_iteration_2',3);
options_.particle.algorithm = 'sequential_importance_particle_filter';
//options_.particle.algorithm = 'auxiliary_particle_filter';
//options_.particle.algorithm = 'gaussian_mixture_filter';
//options_.particle.algorithm = 'conditional_particle_filter';
//options_.particle.algorithm = 'gaussian_filter';
//options_.particle.IS_approximation_method = 'quadrature' ;
options_.particle.IS_approximation_method = 'cubature' ;
//options_.particle.IS_approximation_method = 'unscented' ;
@ -117,4 +111,4 @@ options_.mh_posterior_mode_estimation=0 ;
options_.particle.liu_west_delta = 0.99 ;
options_.mode_check_node_number = 250 ;
estimation(datafile=data_risky_perturb3,order=1,nograph,nobs=100,mh_replic=0,mode_compute=11);
estimation(datafile=data_risky_perturb3,order=1,nograph,nobs=100,mh_replic=0,mode_compute=11,filter_algorithm=sis);

View File

@ -44,7 +44,6 @@ varobs x, y;
//estimation(datafile=mydata,order=1,first_obs=5001,nobs=100,mh_replic=0);
options_.particle.status = 1;
options_.particle.algorithm = 'sequential_importance_particle_filter';
options_.particle.initialization = 1;
options_.particle.number_of_particles = 1000;
@ -58,4 +57,4 @@ d, 0.7912;
g, 0.2448;
end;
estimation(datafile=mydata,order=2,first_obs=5001,nobs=100,mh_replic=0,mode_compute=8);
estimation(datafile=mydata,order=2,first_obs=5001,nobs=100,mh_replic=0,mode_compute=8,filter_algorithm=sis);

View File

@ -56,7 +56,6 @@ varobs y, z;
options_.particle.status = 1;
options_.particle.algorithm = 'sequential_importance_particle_filter';
options_.particle.initialization = 1;
options_.particle.pruning = 0;
options_.particle.number_of_particles = 20000;
@ -71,4 +70,4 @@ options_.mode_check_neighbourhood_size = 0.05;
set_dynare_threads('local_state_space_iteration_2',3);
estimation(order=2,nobs=100,datafile=linear_model_data,mh_replic=0);
estimation(order=2,nobs=100,datafile=linear_model_data,mh_replic=0,filter_algorithm=sis);

View File

@ -38,7 +38,6 @@ particle = 1;
if particle;
options_.particle.status = 1;
options_.particle.algorithm = 'sequential_importance_particle_filter';
options_.particle.initialization = 1;
options_.particle.pruning = 0;
options_.particle.number_of_particles = 20000;
@ -52,7 +51,7 @@ options_.mode_check_neighbourhood_size = 0.05;
set_dynare_threads('local_state_space_iteration_2',3);
estimation(order=2,nobs=100,datafile=linear_model_data,mh_replic=0);
estimation(order=2,nobs=100,datafile=linear_model_data,mh_replic=0,filter_algorithm=sis);
else;