Merge branch 'master' into new_ep

time-shift
Michel Juillard 2015-05-23 18:26:07 +02:00
commit b3047c9742
266 changed files with 9536 additions and 7696 deletions

3
.gitignore vendored
View File

@ -113,8 +113,7 @@ mex/build/matlab/run_m2html.m
/preprocessor/doc/
# MATLAB dir
/matlab/dynare_m
/matlab/dynare_m.exe
/matlab/preprocessor*
/matlab/dynare_version.m
# DLL rules

3
.gitmodules vendored
View File

@ -21,3 +21,6 @@
path = matlab/modules/dseries
url = https://github.com/DynareTeam/dseries.git
branch = old-oop-style
[submodule "matlab/modules/reporting"]
path = matlab/modules/reporting
url = https://github.com/DynareTeam/reporting.git

View File

@ -35,17 +35,25 @@ EXTRA_DIST = \
dist-hook:
rm -rf `find $(distdir)/matlab $(distdir)/examples -name *~`
rm -f $(distdir)/matlab/dynare_m$(EXEEXT) $(distdir)/matlab/dynare_version.m
rm -rf $(distdir)/matlab/preprocessor* $(distdir)/matlab/dynare_version.m
$(MKDIR_P) $(distdir)/mex/matlab $(distdir)/mex/octave
rm -rf `find $(distdir)/contrib -name '.git*'`
install-exec-local:
$(MKDIR_P) $(DESTDIR)$(pkglibdir)/contrib/ms-sbvar/TZcode
cp -r contrib/ms-sbvar/TZcode/MatlabFiles $(DESTDIR)$(pkglibdir)/contrib/ms-sbvar/TZcode
cp -r examples $(DESTDIR)$(pkglibdir)
cp -r matlab $(DESTDIR)$(pkglibdir)
rm -f $(DESTDIR)$(pkglibdir)/matlab/dynare_m
cp preprocessor/dynare_m $(DESTDIR)$(pkglibdir)/matlab
cp -r contrib/ms-sbvar/TZcode/MatlabFiles $(DESTDIR)$(pkglibdir)/contrib/ms-sbvar/TZcode
rm -rf $(DESTDIR)$(pkglibdir)/matlab/preprocessor*
{ \
if [ -z "`file preprocessor/dynare_m | grep x86.64`" ]; then \
ARCH="32"; \
else \
ARCH="64"; \
fi; \
mkdir -p $(DESTDIR)$(pkglibdir)/matlab/preprocessor$$ARCH; \
cp preprocessor/dynare_m $(DESTDIR)$(pkglibdir)/matlab/preprocessor$$ARCH; \
}
uninstall-local:
rm -f $(DESTDIR)$(bindir)/dynare++

File diff suppressed because it is too large Load Diff

View File

@ -101,7 +101,7 @@ void SystemResources::getRUS(double& load_avg, long int& pg_avail,
majflt = -1;
#endif
#if !defined(__MINGW32__) && !defined(__CYGWIN32__)
#if !defined(__MINGW32__) && !defined(__CYGWIN32__) && !defined(__CYGWIN__) && !defined(__MINGW64__) && !defined(__CYGWIN64__)
getloadavg(&load_avg, 1);
#else
load_avg = -1.0;

View File

@ -341,6 +341,12 @@ int DynamicAtoms::index(const char* name, int ll) const
return -1;
}
bool DynamicAtoms::is_referenced(const char* name) const
{
Tvarmap::const_iterator it = vars.find(name);
return it != vars.end();
}
const DynamicAtoms::Tlagmap& DynamicAtoms::lagmap(const char* name) const
{
Tvarmap::const_iterator it = vars.find(name);

View File

@ -182,6 +182,9 @@ namespace ogp {
/** Return index of the variable described by the variable
* name and lag/lead. If it doesn't exist, return -1. */
int index(const char* name, int ll) const;
/** Return true if a variable is referenced, i.e. it has lag
* map. */
bool is_referenced(const char* name) const;
/** Return the lag map for the variable name. */
const Tlagmap& lagmap(const char* name) const;
/** Return the variable name for the tree index. It throws an

View File

@ -41,15 +41,14 @@ void StaticAtoms::import_atoms(const DynamicAtoms& da, OperationTree& otree, Tin
register_name(name);
int tnew = otree.add_nulary();
assign(name, tnew);
try {
const DynamicAtoms::Tlagmap& lmap = da.lagmap(name);
if (da.is_referenced(name)) {
const DynamicAtoms::Tlagmap& lmap = da.lagmap(name);
for (DynamicAtoms::Tlagmap::const_iterator it = lmap.begin();
it != lmap.end(); ++it) {
int told = (*it).second;
tmap.insert(Tintintmap::value_type(told, tnew));
}
} catch (const ogu::Exception& e) {
}
}
}
}

View File

@ -1,5 +1,6 @@
// Copyright (C) 2005-2011, Ondra Kamenik
#include "utils/cc/exception.h"
#include "tree.h"
@ -55,7 +56,7 @@ int OperationTree::add_unary(code_t code, int op)
code == SQRT ||
code == ERF))
return zero;
if (op == zero && code == LOG || op == nan)
if ((op == zero && code == LOG) || op == nan)
return nan;
if (op == zero && (code == EXP ||
code == COS ||
@ -86,39 +87,43 @@ int OperationTree::add_binary(code_t code, int op1, int op2)
if (op1 == nan || op2 == nan)
return nan;
// for plus
if (code == PLUS)
if (code == PLUS) {
if (op1 == zero && op2 == zero)
return zero;
else if (op1 == zero)
return op2;
else if (op2 == zero)
return op1;
}
// for minus
if (code == MINUS)
if (code == MINUS) {
if (op1 == zero && op2 == zero)
return zero;
else if (op1 == zero)
return add_unary(UMINUS, op2);
else if (op2 == zero)
return op1;
}
// for times
if (code == TIMES)
if (code == TIMES) {
if (op1 == zero || op2 == zero)
return zero;
else if (op1 == one)
return op2;
else if (op2 == one)
return op1;
}
// for divide
if (code == DIVIDE)
if (code == DIVIDE) {
if (op1 == op2)
return one;
else if (op1 == zero)
return zero;
else if (op2 == zero)
return nan;
}
// for power
if (code == POWER)
if (code == POWER) {
if (op1 == zero && op2 == zero)
return nan;
else if (op1 == zero)
@ -129,6 +134,7 @@ int OperationTree::add_binary(code_t code, int op1, int op2)
return one;
else if (op2 == one)
return op1;
}
// order operands of commutative operations
if (code == TIMES || code == PLUS)

View File

@ -135,22 +135,19 @@ void DynareAtomValues::setValues(ogp::EvalTree& et) const
// set parameteres
for (unsigned int i = 0; i < atoms.get_params().size(); i++) {
try {
if (atoms.is_referenced(atoms.get_params()[i])) {
const ogp::DynamicAtoms::Tlagmap& lmap = atoms.lagmap(atoms.get_params()[i]);
for (ogp::DynamicAtoms::Tlagmap::const_iterator it = lmap.begin();
it != lmap.end(); ++it) {
int t = (*it).second;
et.set_nulary(t, paramvals[i]);
}
} catch (const ogu::Exception& e) {
// ignore non-referenced parameters; there is no
// lagmap for them
}
}
// set endogenous
for (unsigned int outer_i = 0; outer_i < atoms.get_endovars().size(); outer_i++) {
try {
if (atoms.is_referenced(atoms.get_endovars()[outer_i])) {
const ogp::DynamicAtoms::Tlagmap& lmap = atoms.lagmap(atoms.get_endovars()[outer_i]);
for (ogp::DynamicAtoms::Tlagmap::const_iterator it = lmap.begin();
it != lmap.end(); ++it) {
@ -165,15 +162,12 @@ void DynareAtomValues::setValues(ogp::EvalTree& et) const
else
et.set_nulary(t, yyp[i-atoms.nstat()-atoms.npred()]);
}
} catch (const ogu::Exception& e) {
// ignore non-referenced endogenous variables; there is no
// lagmap for them
}
}
// set exogenous
for (unsigned int outer_i = 0; outer_i < atoms.get_exovars().size(); outer_i++) {
try {
if (atoms.is_referenced(atoms.get_exovars()[outer_i])) {
const ogp::DynamicAtoms::Tlagmap& lmap = atoms.lagmap(atoms.get_exovars()[outer_i]);
for (ogp::DynamicAtoms::Tlagmap::const_iterator it = lmap.begin();
it != lmap.end(); ++it) {
@ -184,8 +178,6 @@ void DynareAtomValues::setValues(ogp::EvalTree& et) const
et.set_nulary(t, xx[i]);
}
}
} catch (const ogu::Exception& e) {
// ignore non-referenced variables
}
}
}

View File

@ -1,5 +1,6 @@
// Copyright (C) 2006-2011, Ondra Kamenik
#include "forw_subst_builder.h"
using namespace ogdyn;
@ -47,18 +48,20 @@ void ForwSubstBuilder::substitute_for_term(int t, int i, int j)
// first make lagsubst be substitution setting f(x(+4)) to f(x(+1))
// this is lag = -3 (1-mlead)
map<int,int> lagsubst;
model.variable_shift_map(model.eqs.nulary_of_term(t), 1-mlead, lagsubst);
unordered_set<int> nult = model.eqs.nulary_of_term(t);// make copy of nult!
model.variable_shift_map(nult, 1-mlead, lagsubst);
int lagt = model.eqs.add_substitution(t, lagsubst);
// now maxlead of lagt is +1
// add AUXLD_*_*_1 = f(x(+1)) to the model
char name[100];
sprintf(name, "AUXLD_%d_%d_%d", i, j, 1);
model.atoms.register_uniq_endo(name);
info.num_aux_variables++;
const char* ss = model.atoms.get_name_storage().query(name);
int auxt = model.eqs.add_nulary(name);
model.eqs.add_formula(model.eqs.add_binary(ogp::MINUS, auxt, lagt));
aux_map.insert(Tsubstmap::value_type(ss, lagt));
// now maxlead of lagt is +1
// add AUXLD_*_*_1 = f(x(+1)) to the model
char name[100];
sprintf(name, "AUXLD_%d_%d_%d", i, j, 1);
model.atoms.register_uniq_endo(name);
info.num_aux_variables++;
const char* ss = model.atoms.get_name_storage().query(name);
int auxt = model.eqs.add_nulary(name);
model.eqs.add_formula(model.eqs.add_binary(ogp::MINUS, auxt, lagt));
aux_map.insert(Tsubstmap::value_type(ss, lagt));
// now add variables and equations
// AUXLD_*_*_2 = AUXLD_*_*_1(+1) through
// AUXLD_*_*_{mlead-1} = AUXLD_*_*_{mlead-2}(+1)
@ -82,7 +85,9 @@ void ForwSubstBuilder::substitute_for_term(int t, int i, int j)
aux_map.insert(Tsubstmap::value_type(ss, lagt));
}
// now we have to substitute AUXLEAD_*_*{mlead-1}(+1) for t
// now we have to substitute AUXLD_*_*{mlead-1}(+1) for t
sprintf(name, "AUXLD_%d_%d_%d", i, j, mlead-1);
ss = model.atoms.get_name_storage().query(name);
model.substitute_atom_for_term(ss, +1, t);
}
}

View File

@ -327,11 +327,11 @@ MultInitSS::MultInitSS(const PlannerBuilder& pb, const Vector& pvals, Vector& yy
ogp::FormulaCustomEvaluator fe(builder.static_tree, terms);
fe.eval(dssav, *this);
// solve overdetermined system b+F*lambda=0 => lambda=-(F^T*F)^{-1}*F^T*b
GeneralMatrix FtF(F, "transpose", F);
Vector lambda(builder.diff_f_static.dim2());
F.multVecTrans(0.0, lambda, -1.0, b);
ConstGeneralMatrix(FtF).multInvLeft(lambda);
// solve overdetermined system b+F*lambda=0 using SVD decomposition
SVDDecomp decomp(F);
Vector lambda(builder.diff_f_static.dim2());
decomp.solve(b, lambda);
lambda.mult(-1);
// take values of lambda and put it to yy
for (int fi = 0; fi < builder.diff_f_static.dim2(); fi++) {

View File

@ -481,3 +481,76 @@ void ConstGeneralMatrix::print() const
printf("\n");
}
}
void SVDDecomp::construct(const GeneralMatrix& A)
{
// quick exit if empty matrix
if (minmn == 0) {
U.unit();
VT.unit();
conv = true;
return;
}
// make copy of the matrix
GeneralMatrix AA(A);
lapack_int m = AA.numRows();
lapack_int n = AA.numCols();
double* a = AA.base();
lapack_int lda = AA.getLD();
double* s = sigma.base();
double* u = U.base();
lapack_int ldu = U.getLD();
double* vt = VT.base();
lapack_int ldvt = VT.getLD();
double tmpwork;
lapack_int lwork = -1;
lapack_int info;
lapack_int* iwork = new lapack_int[8*minmn];
// query for optimal lwork
dgesdd("A", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, &tmpwork,
&lwork, iwork, &info);
lwork = (lapack_int)tmpwork;
Vector work(lwork);
// do the decomposition
dgesdd("A", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work.base(),
&lwork, iwork, &info);
delete [] iwork;
if (info < 0)
throw SYLV_MES_EXCEPTION("Internal error in SVDDecomp constructor");
if (info == 0)
conv = true;
}
void SVDDecomp::solve(const GeneralMatrix& B, GeneralMatrix& X) const
{
if (B.numRows() != U.numRows())
throw SYLV_MES_EXCEPTION("Incompatible number of rows ");
// reciprocal condition number for determination of zeros in the
// end of sigma
double rcond = 1e-13;
// solve U: B = U^T*B
GeneralMatrix UTB(U, "trans", B);
// determine nz=number of zeros in the end of sigma
int nz = 0;
while (nz < minmn && sigma[minmn-1-nz] < rcond*sigma[0])
nz++;
// take relevant B for sigma inversion
int m = U.numRows();
int n = VT.numCols();
GeneralMatrix Bprime(UTB, m-minmn, 0, minmn-nz, B.numCols());
// solve sigma
for (int i = 0; i < minmn-nz; i++)
Vector(i, Bprime).mult(1.0/sigma[i]);
// solve VT
X.zeros();
//- copy Bprime to right place of X
for (int i = 0; i < minmn-nz; i++)
Vector(n-minmn+i, X) = ConstVector(i, Bprime);
//- multiply with VT
X.multLeftTrans(VT);
}

View File

@ -7,6 +7,8 @@
#include "Vector.h"
#include <algorithm>
class GeneralMatrix;
class ConstGeneralMatrix {
@ -272,6 +274,40 @@ private:
static int md_length;
};
class SVDDecomp {
protected:
/** Minimum of number of rows and columns of the decomposed
* matrix. */
const int minmn;
/** Singular values. */
Vector sigma;
/** Orthogonal matrix U. */
GeneralMatrix U;
/** Orthogonal matrix V^T. */
GeneralMatrix VT;
/** Convered flag. */
bool conv;
public:
SVDDecomp(const GeneralMatrix& A)
: minmn(std::min<int>(A.numRows(), A.numCols())),
sigma(minmn),
U(A.numRows(), A.numRows()),
VT(A.numCols(), A.numCols()),
conv(false)
{construct(A);}
const GeneralMatrix& getU() const
{return U;}
const GeneralMatrix& getVT() const
{return VT;}
void solve(const GeneralMatrix& B, GeneralMatrix& X) const;
void solve(const Vector& b, Vector& x) const
{
GeneralMatrix xmat(x.base(), x.length(), 1);
solve(GeneralMatrix(b.base(), b.length(), 1), xmat);
}
private:
void construct(const GeneralMatrix& A);
};

View File

@ -39,20 +39,33 @@ License: public-domain
Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
pages 472-489
Files: matlab/bfgsi1.m matlab/csolve.m matlab/csminit1.m matlab/numgrad2.m
matlab/numgrad3.m matlab/numgrad3_.m matlab/numgrad5.m
matlab/numgrad5_.m matlab/csminwel1.m matlab/bvar_density.m
Files: matlab/bfgsi1.m matlab/csolve.m matlab/optimization/csminit1.m matlab/optimization/numgrad2.m
matlab/optimization/numgrad3.m matlab/optimization/numgrad3_.m matlab/optimization/numgrad5.m
matlab/optimization/numgrad5_.m matlab/optimization/csminwel1.m matlab/bvar_density.m
matlab/bvar_toolbox.m matlab/partial_information/PI_gensys.m matlab/qzswitch.m
matlab/qzdiv.m
Copyright: 1993-2009 Christopher Sims
2006-2013 Dynare Team
License: GPL-3+
Files: matlab/cmaes.m
Files: matlab/optimization/cmaes.m
Copyright: 2001-2012 Nikolaus Hansen
2012 Dynare Team
License: GPL-3+
Files: matlab/optimization/solvopt.m
Copyright: 1997-2008 Alexei Kuntsevich and Franz Kappel
2008-2015 Giovanni Lombardo
2015 Dynare Team
License: GPL-3+
Files: matlab/optimization/simulated_annealing.m
Copyright: 1995 E.G.Tsionas
1995-2002 Thomas Werner
2002-2015 Giovanni Lombardo
2015 Dynare Team
License: GPL-3+
Files: matlab/endogenous_prior.m
Copyright: 2011 Lawrence J. Christiano, Mathias Trabandt and Karl Walentin
2013 Dynare Team
@ -63,7 +76,7 @@ Copyright: 2008-2012 VZLU Prague, a.s.
2014 Dynare Team
License: GPL-3+
Files: matlab/simpsa.m matlab/simpsaget.m matlab/simpsaset.m
Files: matlab/optimization/simpsa.m matlab/optimization/simpsaget.m matlab/optimization/simpsaset.m
Copyright: 2005 Henning Schmidt, FCC, henning@fcc.chalmers.se
2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be
2013 Dynare Team

View File

@ -1,4 +1,4 @@
dnl Copyright (C) 2009-2014 Dynare Team
dnl Copyright (C) 2009-2015 Dynare Team
dnl
dnl This file is part of Dynare.
dnl
@ -22,6 +22,9 @@ AC_REQUIRE([AX_MATLAB])
AC_MSG_CHECKING([for MATLAB version])
if test "x$MATLAB_VERSION" != "x"; then
case $MATLAB_VERSION in
*2015a | *2015A)
MATLAB_VERSION="8.5"
;;
*2014b | *2014B)
MATLAB_VERSION="8.4"
;;

View File

@ -69,9 +69,16 @@ M_ = set_all_parameters(xparam1,estim_params_,M_);
%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------
oldoo.restrict_var_list = oo_.dr.restrict_var_list;
oldoo.restrict_columns = oo_.dr.restrict_columns;
oo_.dr.restrict_var_list = bayestopt_.smoother_var_list;
oo_.dr.restrict_columns = bayestopt_.smoother_restrict_columns;
[T,R,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
oo_.dr.restrict_var_list = oldoo.restrict_var_list;
oo_.dr.restrict_columns = oldoo.restrict_columns;
bayestopt_.mf = bayestopt_.smoother_mf;
if options_.noconstant
constant = zeros(vobs,1);
@ -174,6 +181,7 @@ elseif options_.lik_init == 5 % Old diffuse Kalman filter only for th
Pinf = [];
end
kalman_tol = options_.kalman_tol;
diffuse_kalman_tol = options_.diffuse_kalman_tol;
riccati_tol = options_.riccati_tol;
data1 = Y-trend;
% -----------------------------------------------------------------------------
@ -199,7 +207,7 @@ if kalman_algo == 1 || kalman_algo == 3
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH1_Z(ST, ...
Z,R1,Q,H,Pinf,Pstar, ...
data1,vobs,np,smpl,data_index, ...
options_.nk,kalman_tol,options_.filter_decomposition);
options_.nk,kalman_tol,diffuse_kalman_tol,options_.filter_decomposition);
if isinf(alphahat)
if kalman_algo == 1
kalman_algo = 2;
@ -226,7 +234,7 @@ if kalman_algo == 2 || kalman_algo == 4
[alphahat,epsilonhat,etahat,ahat,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH3_Z(ST, ...
Z,R1,Q,diag(H), ...
Pinf,Pstar,data1,vobs,np,smpl,data_index, ...
options_.nk,kalman_tol,...
options_.nk,kalman_tol,diffuse_kalman_tol, ...
options_.filter_decomposition);
end

View File

@ -86,14 +86,14 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
fprintf('\nCONVERGENCE DIAGNOSTICS: Invalid option for geweke_interval. Using the default of [0.2 0.5].\n')
options_.convergence.geweke.geweke_interval=[0.2 0.5];
end
first_obs_begin_sample = max(1,ceil(options_.mh_drop*options_.mh_replic));
last_obs_begin_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(1)*options_.mh_replic*(1-options_.mh_drop));
first_obs_end_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(2)*options_.mh_replic*(1-options_.mh_drop));
first_obs_begin_sample = max(1,ceil(options_.mh_drop*NumberOfDraws));
last_obs_begin_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(1)*NumberOfDraws*(1-options_.mh_drop));
first_obs_end_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(2)*NumberOfDraws*(1-options_.mh_drop));
param_name=[];
for jj=1:npar
param_name = strvcat(param_name,get_the_name(jj,options_.TeX,M_,estim_params_,options_));
end
fprintf('\nGeweke (1992) Convergence Tests, based on means of draws %d to %d vs %d to %d.\n',first_obs_begin_sample,last_obs_begin_sample,first_obs_end_sample,options_.mh_replic);
fprintf('\nGeweke (1992) Convergence Tests, based on means of draws %d to %d vs %d to %d.\n',first_obs_begin_sample,last_obs_begin_sample,first_obs_end_sample,NumberOfDraws);
fprintf('p-values are for Chi2-test for equality of means.\n');
Geweke_header={'Parameter', 'Post. Mean', 'Post. Std', 'p-val No Taper'};
print_string=['%',num2str(size(param_name,2)+3),'s \t %12.3f \t %12.3f \t %12.3f'];

View File

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

View File

@ -16,7 +16,7 @@ function PosteriorIRF(type)
% functions associated with it(the _core1 and _core2).
% See also the comments random_walk_metropolis_hastings.m funtion.
% Copyright (C) 2006-2013 Dynare Team
% Copyright (C) 2006-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -93,8 +93,15 @@ elseif strcmpi(type,'gsa')
else
MhDirectoryName = CheckPath('prior',M_.dname);
end
delete([MhDirectoryName filesep M_.fname '_IRF_DSGEs*.mat']);
delete([MhDirectoryName filesep M_.fname '_IRF_BVARDSGEs*.mat']);
%delete old stale files before creating new ones
delete_stale_file([MhDirectoryName filesep M_.fname '_IRF_DSGEs*.mat']);
delete_stale_file([MhDirectoryName filesep M_.fname '_IRF_BVARDSGEs*.mat']);
delete_stale_file([MhDirectoryName filesep M_.fname '_irf_dsge*.mat']);
delete_stale_file([MhDirectoryName filesep M_.fname '_irf_bvardsge*.mat']);
delete_stale_file([MhDirectoryName filesep M_.fname '_param_irf*.mat']);
if strcmpi(type,'posterior')
B = options_.sub_draws;
options_.B = B;
@ -112,16 +119,7 @@ else% type = 'prior'
B = options_.prior_draws;
options_.B = B;
end
try
delete([MhDirectoryName filesep M_.fname '_irf_dsge*.mat'])
catch
disp('No _IRFs (dsge) files to be deleted!')
end
try
delete([MhDirectoryName filesep M_.fname '_irf_bvardsge*.mat'])
catch
disp('No _IRFs (bvar-dsge) files to be deleted!')
end
irun = 0;
IRUN = 0;
irun2 = 0;

View File

@ -1,17 +1,28 @@
function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam, ThisMatlab)
function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam,ThisMatlab)
% function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam, ThisMatlab)
% Generates the Posterior IRFs plot from the IRFs generated in
% PosteriorIRF_core1
%
% PARALLEL CONTEXT
% Perform in parallel execution a portion of the PosteriorIRF.m code.
% See also the comment in random_walk_metropolis_hastings_core.m funtion.
% Performs in parallel execution a portion of the PosteriorIRF.m code.
% For more information, see the comment in random_walk_metropolis_hastings_core.m
% function.
%
% INPUTS
% See the comment in random_walk_metropolis_hastings_core.m funtion.
% o myimput [struc] The mandatory variables for local/remote
% parallel computing obtained from random_walk_metropolis_hastings.m
% function.
% o fblck and nblck [integer] The Metropolis-Hastings chains.
% o whoiam [integer] In concurrent programming a modality to refer to the differents thread running in parallel is needed.
% The integer whoaim is the integer that
% allows us to distinguish between them. Then it is the index number of this CPU among all CPUs in the
% cluster.
% o ThisMatlab [integer] Allows us to distinguish between the
% 'main' matlab, the slave matlab worker, local matlab, remote matlab,
% ... Then it is the index number of this slave machine in the cluster.
%
% OUTPUTS
% o myoutput [struc]
% Contained:
% OutputFileName (i.e. the figures without the file .txt).
% o myoutput [struc] Contained: OutputFileName (i.e. the figures without the file .txt).
%
% ALGORITHM
% Portion of PosteriorIRF.m function code. Specifically the last 'for' cycle.
@ -19,7 +30,7 @@ function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam, ThisMatlab)
% SPECIAL REQUIREMENTS.
% None.
%
% Copyright (C) 2006-2013 Dynare Team
% Copyright (C) 2006-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -100,13 +111,9 @@ for i=fpar:npar,
set(0,'CurrentFigure',hh)
subplot(nn,nn,subplotnum);
if ~MAX_nirfs_dsgevar
h1 = area(1:options_.irf,HPDIRF(:,2,j,i));
set(h1,'FaceColor',[.9 .9 .9]);
set(h1,'BaseValue',min(HPDIRF(:,1,j,i)));
h1 = area(1:options_.irf,HPDIRF(:,2,j,i),'FaceColor',[.9 .9 .9],'BaseValue',min(HPDIRF(:,1,j,i))); %grey below HPDIsup and minimum of HPDIinf
hold on
h2 = area(1:options_.irf,HPDIRF(:,1,j,i),'FaceColor',[1 1 1],'BaseValue',min(HPDIRF(:,1,j,i)));
set(h2,'FaceColor',[1 1 1]);
set(h2,'BaseValue',min(HPDIRF(:,1,j,i)));
h2 = area(1:options_.irf,HPDIRF(:,1,j,i),'FaceColor',[1 1 1],'BaseValue',min(HPDIRF(:,1,j,i))); %white below HPDIinf and minimum of HPDIinf
plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3)
% plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
box on
@ -114,18 +121,14 @@ for i=fpar:npar,
xlim([1 options_.irf]);
hold off
else
h1 = area(1:options_.irf,HPDIRF(:,2,j,i));
set(h1,'FaceColor',[.9 .9 .9]);
set(h1,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))]));
hold on;
h2 = area(1:options_.irf,HPDIRF(:,1,j,i));
set(h2,'FaceColor',[1 1 1]);
set(h2,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))]));
h1 = area(1:options_.irf,HPDIRF(:,2,j,i),'FaceColor',[.9 .9 .9],'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))])); %grey below HPDIsup and minimum of HPDIinf and HPDIRFdsgevar
hold on
h2 = area(1:options_.irf,HPDIRF(:,1,j,i),'FaceColor',[1 1 1],'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))])); %white below HPDIinf and minimum of HPDIinf and HPDIRFdsgevar
plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3)
% plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
plot(1:options_.irf,MeanIRFdsgevar(:,j,i),'--k','linewidth',2)
plot(1:options_.irf,HPDIRFdsgevar(:,1,j,i),'--k','linewidth',1)
plot(1:options_.irf,HPDIRFdsgevar(:,2,j,i),'--k','linewidth',1)
% plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
box on
axis tight
xlim([1 options_.irf]);
@ -156,6 +159,4 @@ for i=fpar:npar,
end
end% loop over exo_var
myoutput.OutputFileName = OutputFileName;

View File

@ -0,0 +1,89 @@
function mexpath = add_path_to_mex_files(dynareroot, modifypath)
% Copyright (C) 2015 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if nargin<2
modifypath = true;
end
if isoctave
mexpath = {[dynareroot '../mex/octave/']};
if modifypath
addpath(mexpath{1});
end
else
% Add win32 specific paths for Dynare Windows package
if strcmp(computer, 'PCWIN')
tmp = [dynareroot '../mex/matlab/win32-7.5-8.5/'];
if exist(tmp, 'dir')
mexpath = tmp;
if modifypath
addpath(mexpath);
end
end
end
% Add win64 specific paths for Dynare Windows package
if strcmp(computer, 'PCWIN64')
if matlab_ver_less_than('7.8')
tmp = [dynareroot '../mex/matlab/win64-7.5-7.7/'];
if exist(tmp, 'dir')
mexpath = tmp;
if modifypath
addpath(mexpath);
end
end
else
tmp = [dynareroot '../mex/matlab/win64-7.8-8.5/'];
if exist(tmp, 'dir')
mexpath = tmp;
if modifypath
addpath(mexpath);
end
end
end
end
% Add OS X 32bits specific paths for Dynare Mac package
if strcmp(computer, 'MACI')
tmp = [dynareroot '../mex/matlab/osx32-7.5-7.11/'];
if exist(tmp, 'dir')
mexpath = tmp;
if modifypath && exist(mexpath, 'dir')
addpath(mexpath);
end
end
end
% Add OS X 64bits specific paths for Dynare Mac package
if strcmp(computer, 'MACI64')
tmp = [dynareroot '../mex/matlab/osx64/'];
if exist(tmp, 'dir')
mexpath = tmp;
if modifypath && exist(mexpath, 'dir')
addpath(mexpath);
end
end
end
% Add generic MATLAB path (with higher priority than the previous ones)
if exist('mexpath')
mexpath = { mexpath, [dynareroot '../mex/matlab/'] };
else
mexpath = { [dynareroot '../mex/matlab/'] };
end
if modifypath
addpath([dynareroot '../mex/matlab/']);
end
end

View File

@ -1,13 +1,20 @@
function H = bfgsi1(H0,dg,dx)
% H = bfgsi1(H0,dg,dx)
% dg is previous change in gradient; dx is previous change in x;
% Update Inverse Hessian matrix
%
% Inputs:
% H0 [npar by npar] initial inverse Hessian matrix
% dg [npar by 1] previous change in gradient
% dx [npar by 1] previous change in x;
%
% 6/8/93 version that updates inverse hessian instead of hessian
% itself.
%
% Original file downloaded from:
% http://sims.princeton.edu/yftp/optimize/mfiles/bfgsi.m
%
% Copyright (C) 1993-2009 Christopher Sims
% Copyright (C) 2009-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -41,4 +48,4 @@ else
disp(['|H*dg| = ' num2str(Hdg'*Hdg)])
H=H0;
end
save H.dat H
save('H.dat','H')

150
matlab/check_matlab_path.m Normal file
View File

@ -0,0 +1,150 @@
function check_matlab_path(change_path_flag)
% Copyright (C) 2015 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if ~nargin || isempty(change_path_flag)
change_path_flag = true;
end
% Get path to dynare/matlab folder.
DYNARE_PATH = strrep(which('dynare'),'dynare.m','');
if isempty(DYNARE_PATH)
% Nothing to do here (this case should not happen)
disp('dynare.m is not in the Matlab''s path.')
return
else
% Removes trailing slash.
DYNARE_PATH = DYNARE_PATH(1:end-1);
end
% Get matlab path
MATLAB_PATH = path();
% Position of DYNARE_PATH in MATLAB_PATH
idDYNARE = strfind(MATLAB_PATH,DYNARE_PATH);
if isempty(idDYNARE)
disp('dynare.m is not in the Matlab''s path.')
return
else
if isequal(length(idDYNARE),1)
if isequal(idDYNARE, 1)
% Dynare is on top of matlab's path! Nothing to do here...
return
else
str0 = sprintf('Dynare is not on top of matlab''s path!');
% Check that this will not create a problem
MATLAB_PATH_ = path2cell(MATLAB_PATH);
DYNARE_ROUTINES = getallroutinenames(DYNARE_PATH, getalldirectories(DYNARE_PATH));
MATLAB_ROUTINES = {};
for i=1:position(idDYNARE, MATLAB_PATH)
TMP_MATLAB_ROUTINES = getallroutinenames(MATLAB_PATH_{i});
MATLAB_ROUTINES = { MATLAB_ROUTINES{:} TMP_MATLAB_ROUTINES{:} };
end
COMMON_ROUTINES = intersect(MATLAB_ROUTINES, DYNARE_ROUTINES);
if ~isempty(COMMON_ROUTINES)
warning off backtrace
skipline()
if length(COMMON_ROUTINES)==1
warning(sprintf('%s This can cause problems because the Dynare version of %s will be overriden.', str0, COMMON_ROUTINES{1}));
else
str1 = repmat('%s, ', 1, length(COMMON_ROUTINES)-1);
str2 = 'and %s ';
str3 = sprintf(['%s This can cause problems because the Dynare versions of ' str1, str2, 'will be overriden.'], str0, COMMON_ROUTINES{:});
warning(str3);
end
if change_path_flag
skipline()
msg = sprintf('I put %s on top of your matlab''s path. Note that this is a', DYNARE_PATH);
msg = sprintf(' %s a temporary change (ie will not affect future matlab''s session).', msg);
msg = sprintf(' %s If the ordering was intentional, ie if you really want to override the routines distributed with Dynare,', msg);
msg = sprintf(' %s you can change this behaviour using option nopathchange (see the reference manual).', msg);
warning(msg);
skipline()
rmpath(DYNARE_PATH)
addpath(DYNARE_PATH)
end
warning on backtrace
end
end
else
% Check that the user did not put all the subfolders in the path.
% => If DYNARE_PATH/qz is in the path while mjdgges dll is available
% it most likely means that user wrongly put all subfolders in the
% matlab's path!
mexpath = add_path_to_mex_files([DYNARE_PATH filesep], false);
MATLAB_PATH = path2cell(MATLAB_PATH);
for i=1:length(mexpath)
if exist([mexpath{i} filesep 'mjdgges.' mexext],'file') && ismember([DYNARE_PATH filesep 'qz'],MATLAB_PATH)
msg = sprintf(['You put all the dynare/matlab subfolders in matlab''s path! Only ' ...
'the dynare/matlab folder (without subfolders)\nshould be in the ' ...
'path, Dynare will automatically add any required subfolders in the ' ...
'path.']);
error(msg)
end
end
end
end
function q = path2cell(p)
% Converts the output of path() to a cell
s = strfind(p,pathsep);
n = length(s)+1;
q = cell(n,1);
q(1) = {p(1:s(1)-1)};
q(n) = {p(s(end)+1:end)};
for i=2:n-1
q(i) = {p(s(i-1)+1:s(i)-1)};
end
function flist = getallroutinenames(p, excludedsubfolders)
if nargin<2
excludedsubfolders = {};
end
dd = dir(p);
flist = {};
for f=1:length(dd)
if ~(isequal(dd(f).name,'.') || isequal(dd(f).name,'..'))
if dd(f).isdir
if ~ismember(dd(f).name, excludedsubfolders)
r = getallroutinenames([ p filesep dd(f).name]);
flist = { flist{:} r{:} };
end
else
% Filter out files without m extension.
if isequal(dd(f).name(end-1:end),'.m')
flist{length(flist)+1} = [dd(f).name];
end
end
end
end
function dlist = getalldirectories(p)
dd = dir(p);
dlist = {};
for f = 1:length(dd)
if ~(isequal(dd(f).name,'.') || isequal(dd(f).name,'..'))
if dd(f).isdir
dlist{length(dlist)+1} = [dd(f).name];
end
end
end
function n = position(i, currentpath)
n = length(strfind(currentpath(1:i), pathsep));

View File

@ -1,18 +1,17 @@
function o = write(o, fid)
%function o = write(o, fid)
% Write a Vspace object
function check_valid_ver(ver)
%function check_valid_ver(ver)
% Checks that ver is valid
%
% INPUTS
% o [vspace] vspace object
% fid [integer] file id
% ver [string] dynare version number
%
% OUTPUTS
% o [vspace] vspace object
% none
%
% SPECIAL REQUIREMENTS
% none
% none
% Copyright (C) 2013-2014 Dynare Team
% Copyright (C) 2015 Dynare Team
%
% This file is part of Dynare.
%
@ -29,16 +28,12 @@ function o = write(o, fid)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
assert(fid ~= -1);
for i=1:o.number
fprintf(fid, ' \\par \\medskip ');
end
if o.hline > 0
fprintf(fid, '\\\\\n');
for i=1:o.hline
fprintf(fid, '\\midrule');
end
test_ver = strsplit(ver, {'.', '-'});
errmsg = 'check_valid_ver: the desired version must be in the proper format';
assert (length(test_ver) == 3 && ...
~isempty(str2double(test_ver{1})) && ...
~isempty(str2double(test_ver{2})), errmsg);
if isnan(str2double(test_ver{3}))
assert(strcmp(test_ver{3}, 'unstable'), errmsg);
end
end

141
matlab/cli/prior.m Normal file
View File

@ -0,0 +1,141 @@
function varargout = prior(varargin)
% Computes various prior statistics and display them in the command window.
%
% INPUTS
% 'table', 'moments', 'optimize', 'simulate', 'plot'
%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2015 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 isempty(varargin) || ( isequal(length(varargin), 1) && isequal(varargin{1},'help'))
skipline()
disp('Possible options are:')
disp(' + table Prints a table describing the priors.')
disp(' + moments Computes and displays moments of the endogenous variables at the prior mode.')
disp(' + optimize Optimizes the prior density (starting from a random initial guess).')
disp(' + simulate Computes the effective prior mass (using a Monte-Carlo).')
disp(' + plot Plots the marginal prior densities.')
skipline()
return
end
global options_ M_ estim_params_ bayestopt_ oo_ objective_function_penalty_base
donesomething = false;
% Temporarly change qz_criterium option value
changed_qz_criterium_flag = 0;
if isempty(options_.qz_criterium)
options_.qz_criterium = 1+1e-9;
changed_qz_criterium_flag = 1;
end
M_.dname = M_.fname;
% Temporarly set options_.order equal to one
order = options_.order;
options_.order = 1;
[xparam1,estim_params_,bayestopt_,lb,ub,M_] = set_prior(estim_params_,M_,options_);
if ismember('plot', varargin)
plot_priors(bayestopt_,M_,estim_params_,options_)
donesomething = true;
end
if ismember('table', varargin)
print_table_prior(lb, ub, options_, M_, bayestopt_, estim_params_);
donesomething = true;
end
if ismember('simulate', varargin) % Prior simulations (BK).
results = prior_sampler(0,M_,bayestopt_,options_,oo_,estim_params_);
% Display prior mass info
skipline(2)
disp(['Prior mass = ' num2str(results.prior.mass)])
disp(['BK indeterminacy share = ' num2str(results.bk.indeterminacy_share)])
disp(['BK unstability share = ' num2str(results.bk.unstability_share)])
disp(['BK singularity share = ' num2str(results.bk.singularity_share)])
disp(['Complex jacobian share = ' num2str(results.jacobian.problem_share)])
disp(['mjdgges crash share = ' num2str(results.dll.problem_share)])
disp(['Steady state problem share = ' num2str(results.ss.problem_share)])
disp(['Complex steady state share = ' num2str(results.ss.complex_share)])
disp(['Analytical steady state problem share = ' num2str(results.ass.problem_share)])
skipline(2)
donesomething = true;
end
if ismember('optimize', varargin) % Prior optimization.
optimize_prior(options_, M_, oo_, bayestopt_, estim_params_);
donesomething = true;
end
if ismember('moments', varargin) % Prior simulations (2nd order moments).
% Set estimated parameters to the prior mode...
xparam1 = bayestopt_.p5;
% ... Except for uniform priors!
k = find(isnan(xparam1));
xparam1(k) = bayestopt_.p5(k);
% Update vector of parameters and covariance matrices
M_ = set_all_parameters(xparam1,estim_params_,M_);
% Check model.
check_model(M_);
% Compute state space representation of the model.
oo_.dr=set_state_space(oo_.dr, M_, options_);
% Solve model
[dr,info, M_ ,options_ , oo_] = resol(0, M_ , options_ ,oo_);
% Compute and display second order moments
disp_th_moments(oo_.dr,[]);
skipline(2)
donesomething = true;
end
if changed_qz_criterium_flag
options_.qz_criterium = [];
end
options_.order = order;
if ~donesomething
error('prior: Unexpected arguments!')
end
function format_string = build_format_string(PriorStandardDeviation,LowerBound,UpperBound)
format_string = ['%s & %s & %6.4f &'];
if ~isnumeric(PriorStandardDeviation)
format_string = [ format_string , ' %s &'];
else
format_string = [ format_string , ' %6.4f &'];
end
if ~isnumeric(LowerBound)
format_string = [ format_string , ' %s &'];
else
format_string = [ format_string , ' %6.4f &'];
end
if ~isnumeric(UpperBound)
format_string = [ format_string , ' %s &'];
else
format_string = [ format_string , ' %6.4f &'];
end
format_string = [ format_string , ' %6.4f & %6.4f \\\\ \n'];

View File

@ -1,7 +1,27 @@
function oo_ = ...
conditional_variance_decomposition_mc_analysis(NumberOfSimulations, type, dname, fname, Steps, exonames, exo, var_list, endogenous_variable_index, mh_conf_sig, oo_)
% This function analyses the (posterior or prior) distribution of the
% endogenous conditional variance decomposition.
% endogenous variables' conditional variance decomposition.
%
% INPUTS
% NumberOfSimulations [integer] scalar, number of simulations.
% type [string] 'prior' or 'posterior'
% dname [string] directory name where to save
% fname [string] name of the mod-file
% Steps [integers] horizons at which to conduct decomposition
% exonames [string] (n_exo*char_length) character array with names of exogenous variables
% exo [string] name of current exogenous
% variable
% var_list [string] (n_endo*char_length) character array with name
% of endogenous variables
% endogenous_variable_index [integer] index of the current
% endogenous variable
% mh_conf_sig [double] 2 by 1 vector with upper
% and lower bound of HPD intervals
% oo_ [structure] Dynare structure where the results are saved.
%
% OUTPUTS
% oo_ [structure] Dynare structure where the results are saved.
% Copyright (C) 2009-2013 Dynare Team
%

View File

@ -1,19 +1,18 @@
function o = addTable(o, varargin)
%function o = addTable(o, varargin)
% Add a report_table to the Cell Array of report_tables in the report
function oo_ = convert_oo_(oo_, ver)
%function oo_ = convert_oo_(oo_, ver)
% Converts oo_ from oo_.dynare_version to ver
%
% INPUTS
% 1 args => add empty report_table
% 2 args => add given report_table
% 3 args => add report_table at index
% oo_ [struct] dynare output struct
% ver [string] desired oo_ output version
%
% OUTPUTS
% updated section object
% oo_ [struct] dynare output struct
%
% SPECIAL REQUIREMENTS
% none
% none
% Copyright (C) 2013-2014 Dynare Team
% Copyright (C) 2015 Dynare Team
%
% This file is part of Dynare.
%
@ -30,9 +29,19 @@ function o = addTable(o, varargin)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
for i=1:length(o.elements)
assert(~isa(o.elements{i}, 'paragraph'), ...
'@addTable: A Section that contains a Paratable cannot contain a Table');
check_valid_ver(ver);
if isfield(oo_, 'dynare_version')
ver_orig = oo_.dynare_version;
else
ver_orig = '4.4.3';
end
if strcmp(ver_orig, ver)
return;
end
if ver_less_than(ver_orig, '4.5.0') && ver_greater_than_equal(ver, '4.5.0')
oo_.exo_simul = oo_.exo_simul';
end
o.elements{end+1} = report_table(varargin{:});
end

View File

@ -1,8 +1,24 @@
function oo_ = covariance_mc_analysis(NumberOfSimulations,type,dname,fname,vartan,nvar,var1,var2,mh_conf_sig,oo_)
% This function analyses the (posterior or prior) distribution of the
% endogenous variables covariance matrix.
% endogenous variables' covariance matrix.
%
% INPUTS
% NumberOfSimulations [integer] scalar, number of simulations.
% type [string] 'prior' or 'posterior'
% dname [string] directory name where to save
% fname [string] name of the mod-file
% vartan [char] array of characters (with nvar rows).
% nvar [integer] nvar is the number of stationary variables.
% var1 [string] name of the first variable
% var2 [string] name of the second variable
% mh_conf_sig [double] 2 by 1 vector with upper
% and lower bound of HPD intervals
% oo_ [structure] Dynare structure where the results are saved.
%
% OUTPUTS
% oo_ [structure] Dynare structure where the results are saved.
% Copyright (C) 2008-2013 Dynare Team
% Copyright (C) 2008-2015 Dynare Team
%
% This file is part of Dynare.
%

View File

@ -1,5 +1,5 @@
function disp_dr(dr,order,var_list)
% function disp_dr(dr,order,var_list)
% Display the decision rules
%
% INPUTS
@ -7,8 +7,8 @@ function disp_dr(dr,order,var_list)
% order [int]: order of approximation
% var_list [char array]: list of endogenous variables for which the
% decision rules should be printed
% Copyright (C) 2001-2012 Dynare Team
%
% Copyright (C) 2001-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -55,44 +55,67 @@ for i=1:nvar
end
end
% get length of display strings
header_label_length=16; %default
for ii=1:length(ivar)
header_label_length=max(header_label_length,length(deblank(M_.endo_names(k1(ivar(ii)),:)))+2);
end
header_label_format = sprintf('%%%ds',header_label_length);
value_format_float = sprintf('%%%d.6f',header_label_length);
value_format_zero = sprintf('%%%dd',header_label_length);
% account for additional characters introduced by auxiliary variables
if ~isempty(M_.aux_vars)
aux_vars_type = [M_.aux_vars.type];
if any(aux_vars_type==4)
aux_var_additional_characters=14;
else
aux_var_additional_characters=3;
end
else
aux_var_additional_characters=0;
end
var_name_width=max([max(size(deblank(M_.endo_names(k1(ivar),:)),2)),max(size(deblank(M_.exo_names),2))]);
%deal with covariances
if order > 1
var_name_width=max(2*(var_name_width+aux_var_additional_characters)+2,20); %account for covariances, separated by comma
else
var_name_width=max(var_name_width+aux_var_additional_characters,20);
end
label_format = sprintf('%%-%ds',var_name_width);
%% start displayimg
disp('POLICY AND TRANSITION FUNCTIONS')
% variable names
str = ' ';
str = char(32*ones(1,var_name_width));
for i=1:nvar
str = [str sprintf('%16s',M_.endo_names(k1(ivar(i)),:))];
str = [str sprintf(header_label_format,deblank(M_.endo_names(k1(ivar(i)),:)))];
end
disp(str);
%
% constant
%
str = 'Constant ';
str=sprintf(label_format,'Constant');
flag = 0;
for i=1:nvar
x = dr.ys(k1(ivar(i)));
if order > 1
x = x + dr.ghs2(ivar(i))/2;
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
[str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
end
if flag
disp(str)
end
if order > 1
str = '(correction) ';
str = sprintf(label_format,'(correction)');
flag = 0;
for i=1:nvar
x = dr.ghs2(ivar(i))/2;
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
[str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
end
if flag
disp(str)
@ -108,15 +131,10 @@ for k=1:nx
else
str1 = subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2);
end
str = sprintf('%-20s',str1);
str = sprintf(label_format,str1);
for i=1:nvar
x = dr.ghx(ivar(i),k);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
[str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
end
if flag
disp(str)
@ -127,15 +145,10 @@ end
%
for k=1:nu
flag = 0;
str = sprintf('%-20s',M_.exo_names(k,:));
str = sprintf(label_format,M_.exo_names(k,:));
for i=1:nvar
x = dr.ghu(ivar(i),k);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
[str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
end
if flag
disp(str)
@ -149,19 +162,14 @@ if order > 1
flag = 0;
str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
subst_auxvar(k1(klag(j,1)),klag(j,2)-M_.maximum_lag-2));
str = sprintf('%-20s',str1);
str = sprintf(label_format,str1);
for i=1:nvar
if k == j
x = dr.ghxx(ivar(i),(k-1)*nx+j)/2;
else
x = dr.ghxx(ivar(i),(k-1)*nx+j);
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
[str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
end
if flag
disp(str)
@ -174,19 +182,14 @@ if order > 1
for k = 1:nu
for j = 1:k
flag = 0;
str = sprintf('%-20s',[M_.exo_names(k,:) ',' M_.exo_names(j,:)] );
str = sprintf(label_format,[deblank(M_.exo_names(k,:)) ',' deblank(M_.exo_names(j,:))] );
for i=1:nvar
if k == j
x = dr.ghuu(ivar(i),(k-1)*nu+j)/2;
else
x = dr.ghuu(ivar(i),(k-1)*nu+j);
end
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
[str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
end
if flag
disp(str)
@ -200,16 +203,11 @@ if order > 1
for j = 1:nu
flag = 0;
str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
M_.exo_names(j,:));
str = sprintf('%-20s',str1);
deblank(M_.exo_names(j,:)));
str = sprintf(label_format,str1);
for i=1:nvar
x = dr.ghxu(ivar(i),(k-1)*nu+j);
if abs(x) > 1e-6
flag = 1;
str = [str sprintf('%16.6f',x)];
else
str = [str ' 0'];
end
[str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
end
if flag
disp(str)
@ -253,3 +251,12 @@ for i = 1:length(M_.aux_vars)
end
error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :)))
end
function [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_)
if abs(x) > options_.dr_display_tol
flag = 1;
str = [str sprintf(value_format_float,x)];
else
str = [str sprintf(value_format_zero,0)];
end
end

View File

@ -1,4 +1,5 @@
function draw = rand_multivariate_student(Mean,Sigma_upper_chol,df)
% function draw = rand_multivariate_student(Mean,Sigma_upper_chol,df)
% Pseudo random draws from a multivariate student distribution,
% with expectation Mean, variance Sigma*df/(df-2) and degrees of freedom df>0.
%
@ -13,10 +14,14 @@ function draw = rand_multivariate_student(Mean,Sigma_upper_chol,df)
% draw [double] 1*n vector drawn from a multivariate normal distribution with expectation Mean and
% covariance Sigma.
%
% REMARK This is certainly not the most efficient way...
%
% NOTE See Zellner (appendix B.2, 1971) for a definition.
%
% Computes the t-distributed random numbers from
% X = \mu + Y\sqrt{\frac{\nu}{U}}
% where
% Y~N(0,Sigma) with Sigma=Sigma_upper_chol'*Sigma_upper_chol
% U~\Chi^2_{\nu}
% The latter is constructed as the sum of \nu standard normals.
% Copyright (C) 2003-2009 Dynare Team
%

View File

@ -315,13 +315,17 @@ for i = 1:Size;
dr.eigval = [dr.eigval ; data(i).eigval];
case 6
%% ------------------------------------------------------------------
%Solve Forward complete
%Solve Forward complete
if (maximum_lag > 0)
ghx = - jacob(: , n_pred + 1 : n_pred + n_static ...
+ n_pred + n_both) \ jacob(: , 1 : n_pred);
else
ghx = 0;
end;
if maximum_lag > 0 && n_pred > 0
data(i).eigval = eig(- jacob(: , 1 : n_pred) / ...
jacob(: , (n_pred + n_static + 1 : n_pred + n_static + n_pred )));
data(i).eigval = -eig(ghx(n_static+1:end,:));
data(i).rank = 0;
full_rank = (rcond(jacob(: , (n_pred + n_static + 1 : n_pred ...
+ n_static + n_pred ))) > 1e-9);
full_rank = (rcond(ghx(n_static+1:end,:)) > 1e-9);
else
data(i).eigval = [];
data(i).rank = 0;
@ -330,11 +334,6 @@ for i = 1:Size;
dr.eigval = [dr.eigval ; data(i).eigval];
dr.full_rank = dr.full_rank && full_rank;
if task ~= 1
if (maximum_lag > 0)
ghx = - jacob(: , 1 : n_pred) / jacob(: , n_pred + n_static + 1 : n_pred + n_static + n_pred + n_both);
else
ghx = 0;
end;
if other_endo_nbr
fx = data(i).g1_o;
% retrieves the derivatives with respect to endogenous

View File

@ -70,6 +70,8 @@ function [fval,DLIK,Hess,exit_flag,SteadyState,trend_coeff,info,Model,DynareOpti
%! M_.params has been updated in the steadystate routine and has complex valued scalars.
%! @item info==24
%! M_.params has been updated in the steadystate routine and has some NaNs.
%! @item info==26
%! M_.params has been updated in the steadystate routine and has negative/0 values in loglinear model.
%! @item info==30
%! Ergodic variance can't be computed.
%! @item info==41
@ -266,7 +268,7 @@ if info(1) == 1 || info(1) == 2 || info(1) == 5 || info(1) == 7 || info(1) == 8
DLIK=ones(length(xparam1),1);
end
return
elseif info(1) == 3 || info(1) == 4 || info(1)==6 || info(1) == 20 || info(1) == 21 || info(1) == 23
elseif info(1) == 3 || info(1) == 4 || info(1)==6 || info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1)==26
fval = objective_function_penalty_base+info(2);
info = info(1);
exit_flag = 0;
@ -326,6 +328,7 @@ mm = length(T);
pp = DynareDataset.vobs;
rr = length(Q);
kalman_tol = DynareOptions.kalman_tol;
diffuse_kalman_tol = DynareOptions.diffuse_kalman_tol;
riccati_tol = DynareOptions.riccati_tol;
Y = transpose(DynareDataset.data)-trend;
@ -403,13 +406,13 @@ switch DynareOptions.lik_init
if no_missing_data_flag
[dLIK,dlik,a,Pstar] = kalman_filter_d(Y, 1, size(Y,2), ...
zeros(mm,1), Pinf, Pstar, ...
kalman_tol, riccati_tol, DynareOptions.presample, ...
kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ...
T,R,Q,H,Z,mm,pp,rr);
else
[dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations, ...
Y, 1, size(Y,2), ...
zeros(mm,1), Pinf, Pstar, ...
kalman_tol, riccati_tol, DynareOptions.presample, ...
kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ...
T,R,Q,H,Z,mm,pp,rr);
end
diffuse_periods = length(dlik);
@ -446,7 +449,7 @@ switch DynareOptions.lik_init
DatasetInfo.missing.no_more_missing_observations, ...
Y, 1, size(Y,2), ...
zeros(mmm,1), Pinf, Pstar, ...
kalman_tol, riccati_tol, DynareOptions.presample, ...
kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ...
T,R,Q,H1,Z,mmm,pp,rr);
diffuse_periods = size(dlik,1);
end
@ -629,7 +632,7 @@ if analytic_derivation,
analytic_deriv_info={analytic_derivation,DT,DYss,DOm,DH,DP,asy_Hess};
else
analytic_deriv_info={analytic_derivation,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D2P};
clear DT DYss DOm DH DP D2T D2Yss D2Om D2H D2P,
clear DT DYss DOm DP D2T D2Yss D2Om D2H D2P,
end
else
analytic_deriv_info={0};

View File

@ -1,10 +1,13 @@
function [nvar,vartan,NumberOfConditionalDecompFiles] = ...
dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,Steps,M_,options_,oo_,type)
% function [nvar,vartan,NumberOfConditionalDecompFiles] = ...
% dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,Steps,M_,options_,oo_,type)
% This function computes the posterior or prior distribution of the conditional variance
% decomposition of the endogenous variables (or a subset of the endogenous variables).
%
% INPUTS
% SampleSize [integer] scalar, number of simulations.
% Steps [integers] horizons at which to conduct decomposition
% M_ [structure] Dynare structure describing the model.
% options_ [structure] Dynare structure defining global options.
% oo_ [structure] Dynare structure where the results are saved.
@ -16,7 +19,7 @@ function [nvar,vartan,NumberOfConditionalDecompFiles] = ...
% vartan [char] array of characters (with nvar rows).
% NumberOfConditionalDecompFiles [integer] scalar, number of prior or posterior data files (for covariance).
% Copyright (C) 2009-2012 Dynare Team
% Copyright (C) 2009-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -47,6 +50,13 @@ else
error()
end
%delete old stale files before creating new ones
if posterior
delete_stale_file([M_.dname '/metropolis/' M_.fname '_PosteriorConditionalVarianceDecomposition*'])
else
delete_stale_file([M_.dname '/prior/moments/' M_.fname '_PriorConditionalVarianceDecomposition*'])
end
% Set varlist (vartan)
if ~posterior
if isfield(options_,'varlist')

View File

@ -1,21 +1,23 @@
function [nvar,vartan,CorrFileNumber] = dsge_simulated_theoretical_correlation(SampleSize,nar,M_,options_,oo_,type)
% function [nvar,vartan,CorrFileNumber] = dsge_simulated_theoretical_correlation(SampleSize,nar,M_,options_,oo_,type)
% This function computes the posterior or prior distribution of the endogenous
% variables second order moments.
% variables' second order moments.
%
% INPUTS
% SampleSize [integer]
% nar [integer]
% M_ [structure]
% options_ [structure]
% oo_ [structure]
% type [string]
% SampleSize [integer] scalar, number of simulations.
% nar [integer] maximum number of autocorrelations to
% consider
% M_ [structure] Dynare structure describing the model.
% options_ [structure] Dynare structure defining global options
% oo_ [structure] Dynare structure where the results are saved.
% type [string] 'prior' or 'posterior'
%
% OUTPUTS
% nvar [integer]
% vartan [char]
% CorrFileNumber [integer]
% Copyright (C) 2007-2012 Dynare Team
% nvar [integer] nvar is the number of stationary variables.
% vartan [char] array of characters (with nvar rows).
% CorrFileNumber [integer] scalar, number of prior or posterior data files (for correlation).
% Copyright (C) 2007-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -48,6 +50,13 @@ else
end
NumberOfDrawsFiles = length(DrawsFiles);
%delete old stale files before creating new ones
if posterior
delete_stale_file([M_.dname '/metropolis/' M_.fname '_PosteriorCorrelations*']);
else
delete_stale_file([M_.dname '/prior/moments/' M_.fname '_PriorCorrelations*']);
end
% Set varlist (vartan)
if ~posterior
if isfield(options_,'varlist')

View File

@ -1,4 +1,5 @@
function [nvar,vartan,CovarFileNumber] = dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,type)
% function [nvar,vartan,CovarFileNumber] = dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,type)
% This function computes the posterior or prior distribution of the endogenous
% variables second order moments.
%
@ -15,7 +16,7 @@ function [nvar,vartan,CovarFileNumber] = dsge_simulated_theoretical_covariance(S
% vartan [char] array of characters (with nvar rows).
% CovarFileNumber [integer] scalar, number of prior or posterior data files (for covariance).
% Copyright (C) 2007-2012 Dynare Team
% Copyright (C) 2007-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -48,6 +49,13 @@ else
end
NumberOfDrawsFiles = length(DrawsFiles);
%delete old stale files before creating new ones
if posterior
delete_stale_file([M_.dname '/metropolis/' M_.fname '_Posterior2ndOrderMoments*'])
else
delete_stale_file([M_.dname '/prior/moments/' M_.fname '_Prior2ndOrderMoments*'])
end
% Set varlist (vartan)
if ~posterior
if isfield(options_,'varlist')

View File

@ -1,5 +1,7 @@
function [nvar,vartan,NumberOfDecompFiles] = ...
dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,type)
% function [nvar,vartan,NumberOfDecompFiles] = ...
% dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,type)
% This function computes the posterior or prior distribution of the variance
% decomposition of the observed endogenous variables.
%
@ -16,7 +18,7 @@ function [nvar,vartan,NumberOfDecompFiles] = ...
% vartan [char] array of characters (with nvar rows).
% CovarFileNumber [integer] scalar, number of prior or posterior data files (for covariance).
% Copyright (C) 2007-2012 Dynare Team
% Copyright (C) 2007-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -47,7 +49,13 @@ else
disp('dsge_simulated_theoretical_variance_decomposition:: Unknown type!')
error()
end
NumberOfDrawsFiles = length(DrawsFiles);
%delete old stale files before creating new ones
if posterior
delete_stale_file([M_.dname '/metropolis/' M_.fname '_PosteriorVarianceDecomposition*']);
else
delete_stale_file([M_.dname '/prior/moments/' M_.fname '_PosteriorVarianceDecomposition*']);
end
% Set varlist (vartan)
if ~posterior

View File

@ -239,10 +239,38 @@ else% Evaluation of the likelihood of the dsge-var model when the dsge prior wei
lik = .5*lik;% Minus likelihood
end
if isnan(lik)
info = 45;
fval = objective_function_penalty_base + 100;
exit_flag = 0;
return
end
if imag(lik)~=0
info = 46;
fval = objective_function_penalty_base + 100;
exit_flag = 0;
return
end
% Add the (logged) prior density for the dsge-parameters.
lnprior = priordens(xparam1,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
fval = (lik-lnprior);
if isnan(fval)
info = 47;
fval = objective_function_penalty_base + 100;
exit_flag = 0;
return
end
if imag(fval)~=0
info = 48;
fval = objective_function_penalty_base + 100;
exit_flag = 0;
return
end
if (nargout == 8)
if isinf(dsge_prior_weight)
iXX = iGXX;

View File

@ -1,7 +1,7 @@
function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_BC)
function dr = dyn_second_order_solver(jacobia,hessian_mat,dr,M_,threads_ABC,threads_BC)
%@info:
%! @deftypefn {Function File} {@var{dr} =} dyn_second_order_solver (@var{jacobia},@var{hessian},@var{dr},@var{M_},@var{threads_ABC},@var{threads_BC})
%! @deftypefn {Function File} {@var{dr} =} dyn_second_order_solver (@var{jacobia},@var{hessian_mat},@var{dr},@var{M_},@var{threads_ABC},@var{threads_BC})
%! @anchor{dyn_second_order_solver}
%! @sp 1
%! Computes the second order reduced form of the DSGE model
@ -11,7 +11,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
%! @table @ @var
%! @item jacobia
%! Matrix containing the Jacobian of the model
%! @item hessian
%! @item hessian_mat
%! Matrix containing the second order derivatives of the model
%! @item dr
%! Matlab's structure describing the reduced form solution of the model.
@ -73,7 +73,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
kk1 = reshape([1:nk^2],nk,nk);
kk1 = kk1(kk,kk);
% reordering second order derivatives
hessian = hessian(:,kk1(:));
hessian_mat = hessian_mat(:,kk1(:));
zx = zeros(np,np);
zu=zeros(np,M_.exo_nbr);
@ -91,7 +91,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
zu=[zu; eye(M_.exo_nbr);zeros(M_.exo_det_nbr,M_.exo_nbr)];
[nrzx,nczx] = size(zx);
[rhs, err] = sparse_hessian_times_B_kronecker_C(hessian,zx,threads_BC);
[rhs, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zx,threads_BC);
mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
rhs = -rhs;
@ -118,7 +118,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
%ghxu
%rhs
hu = dr.ghu(nstatic+1:nstatic+nspred,:);
[rhs, err] = sparse_hessian_times_B_kronecker_C(hessian,zx,zu,threads_BC);
[rhs, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zx,zu,threads_BC);
mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
hu1 = [hu;zeros(np-nspred,M_.exo_nbr)];
@ -136,7 +136,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
%ghuu
%rhs
[rhs, err] = sparse_hessian_times_B_kronecker_C(hessian,zu,threads_BC);
[rhs, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zu,threads_BC);
mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
[B1, err] = A_times_B_kronecker_C(B*dr.ghxx,hu1,threads_ABC);
@ -164,7 +164,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
hxx = dr.ghxx(nstatic+[1:nspred],:);
[junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+2,order_var));
k3 = nnz(M_.lead_lag_incidence(1:M_.maximum_endo_lag+1,:))+(1:M_.nsfwrd)';
[B1, err] = sparse_hessian_times_B_kronecker_C(hessian(:,kh(k3,k3)),gu(k2a,:),threads_BC);
[B1, err] = sparse_hessian_times_B_kronecker_C(hessian_mat(:,kh(k3,k3)),gu(k2a,:),threads_BC);
mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
RHS = RHS + jacobia(:,k2)*guu(k2a,:)+B1;

View File

@ -16,7 +16,7 @@ function dynare(fname, varargin)
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2001-2014 Dynare Team
% Copyright (C) 2001-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -44,7 +44,22 @@ if strcmpi(fname,'help')
return
end
% detect if MEX files are present; if not, use alternative M-files
% Set default local options
change_path_flag = true;
% Filter out some options.
if nargin>1
id = strfind(varargin,'nopathchange');
if ~isempty(id)
change_path_flag = false;
varargin(id{1}) = [];
end
end
% Check matlab path
check_matlab_path(change_path_flag);
% Detect if MEX files are present; if not, use alternative M-files
dynareroot = dynare_config;
warning_config()
@ -81,6 +96,10 @@ end
% Testing if file have extension
% If no extension default .mod is added
dot_location=(strfind(fname,'.'));
if length(dot_location)>1
error('DYNARE: Periods in filenames are only allowed for .mod or .dyn extensions')
end
if isempty(strfind(fname,'.'))
fnamelength = length(fname);
fname1 = [fname '.dyn'];
@ -91,9 +110,10 @@ if isempty(strfind(fname,'.'))
fname = fname1;
% Checking file extension
else
if ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.MOD') ...
if dot_location~=length(fname)-3 ... %if the file name has fewer than 4 characters and there is a period
|| ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.MOD') ...
&& ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.DYN')
error('DYNARE: argument must be a filename with .mod or .dyn extension')
error('DYNARE: argument must be a filename with .mod or .dyn extension and must not include any other periods')
end;
fnamelength = length(fname) - 4;
end;
@ -140,14 +160,32 @@ if ~exist(fname,'file') || isequal(fname,'dir')
error(['dynare:: can''t open ' fname])
end
if ~isvarname(fname(1:end-4))
error('DYNARE: argument of dynare must conform to Matlab''s convention for naming functions, i.e. start with a letter and not contain special characters. Please rename your MOD-file.')
end
% pre-dynare-preprocessor-hook
if exist(fname(1:end-4),'dir') && exist([fname(1:end-4) filesep 'hooks'],'dir') && exist([fname(1:end-4) filesep 'hooks/priorprocessing.m'],'file')
run([fname(1:end-4) filesep 'hooks/priorprocessing'])
end
command = ['"' dynareroot 'dynare_m" ' fname] ;
for i=2:nargin
command = [command ' ' varargin{i-1}];
if ispc
arch = getenv('PROCESSOR_ARCHITECTURE');
else
[junk, arch] = system('uname -m');
end
if isempty(strfind(arch, '64'))
arch_ext = '32';
disp('Using 32-bit preprocessor');
else
arch_ext = '64';
disp('Using 64-bit preprocessor');
end
command = ['"' dynareroot 'preprocessor' arch_ext filesep 'dynare_m" ' fname] ;
for i=1:length(varargin)
command = [command ' ' varargin{i}];
end
[status, result] = system(command);
@ -164,8 +202,8 @@ end
% Save preprocessor result in logfile (if `no_log' option not present)
no_log = 0;
for i=2:nargin
no_log = no_log || strcmp(varargin{i-1}, 'nolog');
for i=1:length(varargin)
no_log = no_log || strcmp(varargin{i}, 'nolog');
end
if ~no_log
logname = [fname(1:end-4) '.log'];

View File

@ -35,6 +35,7 @@ function dynareroot = dynare_config(path_to_dynare,verbose)
if nargin && ~isempty(path_to_dynare)
addpath(path_to_dynare);
end
dynareroot = strrep(which('dynare'),'dynare.m','');
origin = pwd();
@ -44,7 +45,6 @@ if ~nargin || nargin==1
verbose = 1;
end
addpath([dynareroot '/distributions/'])
addpath([dynareroot '/kalman/'])
addpath([dynareroot '/kalman/likelihood'])
@ -58,7 +58,9 @@ addpath([dynareroot '/parallel/'])
addpath([dynareroot '/particle/'])
addpath([dynareroot '/gsa/'])
addpath([dynareroot '/ep/'])
addpath([dynareroot '/cli/'])
addpath([dynareroot '/lmmcp/'])
addpath([dynareroot '/optimization/'])
addpath([dynareroot '/modules/dates/src/'])
addpath([dynareroot '/modules/dseries/src/'])
addpath([dynareroot '/modules/dseries/src/read'])
@ -66,7 +68,7 @@ addpath([dynareroot '/utilities/doc/'])
addpath([dynareroot '/utilities/tests/src/'])
addpath([dynareroot '/utilities/dataset/'])
addpath([dynareroot '/utilities/general/'])
addpath([dynareroot '/reports/'])
addpath([dynareroot '/modules/reporting/src/'])
% For functions that exist only under some Octave versions
% or some MATLAB versions, and for which we provide some replacement functions
@ -88,8 +90,8 @@ if isoctave
addpath([dynareroot '/missing/ordeig'])
end
% ilu is missing in Octave
if isoctave
% ilu is missing in Octave < 4.0
if isoctave && octave_ver_less_than('4.0')
addpath([dynareroot '/missing/ilu'])
end
@ -112,49 +114,7 @@ if (isoctave && ~user_has_octave_forge_package('statistics')) ...
end
% Add path to MEX files
if isoctave
addpath([dynareroot '../mex/octave/']);
else
% Add win32 specific paths for Dynare Windows package
if strcmp(computer, 'PCWIN')
mexpath = [dynareroot '../mex/matlab/win32-7.5-8.4'];
if exist(mexpath, 'dir')
addpath(mexpath)
end
end
% Add win64 specific paths for Dynare Windows package
if strcmp(computer, 'PCWIN64')
if matlab_ver_less_than('7.8')
mexpath = [dynareroot '../mex/matlab/win64-7.5-7.7'];
if exist(mexpath, 'dir')
addpath(mexpath)
end
else
mexpath = [dynareroot '../mex/matlab/win64-7.8-8.4'];
if exist(mexpath, 'dir')
addpath(mexpath)
end
end
end
if strcmp(computer, 'MACI')
mexpath = [dynareroot '../mex/matlab/osx32-7.5-7.11'];
if exist(mexpath, 'dir')
addpath(mexpath)
end
end
if strcmp(computer, 'MACI64')
mexpath = [dynareroot '../mex/matlab/osx64'];
if exist(mexpath, 'dir')
addpath(mexpath)
end
end
% Add generic MATLAB path (with higher priority than the previous ones)
addpath([dynareroot '../mex/matlab/']);
end
add_path_to_mex_files(dynareroot);
%% Set mex routine names
mex_status = cell(1,3);

View File

@ -1,9 +1,10 @@
function oo_recursive_=dynare_estimation(var_list,dname)
% function dynare_estimation(var_list)
% function dynare_estimation(var_list, dname)
% runs the estimation of the model
%
% INPUTS
% var_list: selected endogenous variables vector
% dname: alternative directory name
%
% OUTPUTS
% oo_recursive_: cell array containing the results structures from recursive estimation
@ -11,7 +12,7 @@ function oo_recursive_=dynare_estimation(var_list,dname)
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2014 Dynare Team
% Copyright (C) 2003-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -28,7 +29,7 @@ function oo_recursive_=dynare_estimation(var_list,dname)
% 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_
global options_ oo_ M_ dataset_
oo_recursive_={};
@ -55,7 +56,7 @@ nnobs = length(nobs);
horizon = options_.forecast;
if nargin<2 || ~exist(dname) || isempty(dname)
dname = M_.fname;
dname = options_.dirname;
end
M_.dname = dname;
@ -91,20 +92,12 @@ else
dynare_estimation_1(var_list,dname);
end
if options_.mode_compute && options_.analytic_derivation,
if isnumeric(options_.mode_compute) && options_.mode_compute && options_.analytic_derivation,
options_.analytic_derivation=analytic_derivation0;
end
if nnobs > 1 && horizon > 0
mh_replic = options_.mh_replic;
rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range);
gend = options_.nobs;
data_plot_end_point=min(options_.first_obs+gend-1+horizon,size(rawdata,1)); %compute last observation that can be plotted
rawdata = rawdata(options_.first_obs:data_plot_end_point,:);
% Take the log of the variables if needed
if options_.loglinear && ~options_.logdata % and if the data are not in logs, then...
rawdata = log(rawdata);
end
endo_names = M_.endo_names;
n_varobs = length(options_.varobs);
@ -132,11 +125,12 @@ if nnobs > 1 && horizon > 0
IdObs(j,1) = iobs;
end
end
gend = dataset_.nobs;
time_offset=min(3,gend-1); %for observables, plot 3 previous periods unless data is shorter
k = time_offset+min(nobs(end)-nobs(1)+horizon, ...
size(rawdata,1)-nobs(1));
data2 = rawdata(end-k+1:end,:);
size(dataset_.data,1)-nobs(1));
data2 = dataset_.data(end-k+1:end,:);
[nbplt,nr,nc,lr,lc,nstar] = pltorg(nvar);
m = 1;
plot_index=0;

View File

@ -231,433 +231,95 @@ end
% Estimation of the posterior mode or likelihood mode
if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation
switch options_.mode_compute
case 1
if isoctave
error('Option mode_compute=1 is not available under Octave')
elseif ~user_has_matlab_license('optimization_toolbox')
error('Option mode_compute=1 requires the Optimization Toolbox')
end
% Set default optimization options for fmincon.
optim_options = optimset('display','iter', 'LargeScale','off', 'MaxFunEvals',100000, 'TolFun',1e-8, 'TolX',1e-6);
if isfield(options_,'optim_opt')
eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
end
if options_.analytic_derivation,
optim_options = optimset(optim_options,'GradObj','on','TolX',1e-7);
end
[xparam1,fval,exitflag,output,lamdba,grad,hessian_fmincon] = ...
fmincon(objective_function,xparam1,[],[],[],[],bounds.lb,bounds.ub,[],optim_options,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
case 2
error('ESTIMATION: mode_compute=2 option (Lester Ingber''s Adaptive Simulated Annealing) is no longer available')
case 3
if isoctave && ~user_has_octave_forge_package('optim')
error('Option mode_compute=3 requires the optim package')
elseif ~isoctave && ~user_has_matlab_license('optimization_toolbox')
error('Option mode_compute=3 requires the Optimization Toolbox')
end
% Set default optimization options for fminunc.
optim_options = optimset('display','iter','MaxFunEvals',100000,'TolFun',1e-8,'TolX',1e-6);
if isfield(options_,'optim_opt')
eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
end
if options_.analytic_derivation,
optim_options = optimset(optim_options,'GradObj','on');
end
if ~isoctave
[xparam1,fval,exitflag] = fminunc(objective_function,xparam1,optim_options,dataset_,dataset_info_,options_,M_,estim_params_,bayestopt_,bounds,oo_);
else
% Under Octave, use a wrapper, since fminunc() does not have a 4th arg
func = @(x) objective_function(x, dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
[xparam1,fval,exitflag] = fminunc(func,xparam1,optim_options);
end
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
case 4
% Set default options.
H0 = 1e-4*eye(nx);
crit = 1e-7;
nit = 1000;
numgrad = options_.gradient_method;
epsilon = options_.gradient_epsilon;
% Change some options.
if isfield(options_,'optim_opt')
%prepare settings for newrat
if options_.mode_compute==5
%get whether outer product Hessian is requested
newratflag=[];
if ~isempty(options_.optim_opt)
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'MaxIter'
nit = options_list{i,2};
case 'InitialInverseHessian'
H0 = eval(options_list{i,2});
case 'TolFun'
crit = options_list{i,2};
case 'NumgradAlgorithm'
numgrad = options_list{i,2};
case 'NumgradEpsilon'
epsilon = options_list{i,2};
otherwise
warning(['csminwel: Unknown option (' options_list{i,1} ')!'])
if strcmp(options_list{i,1},'Hessian')
newratflag=options_list{i,2};
end
end
end
% Set flag for analytical gradient.
if options_.analytic_derivation
analytic_grad=1;
else
analytic_grad=[];
end
% Call csminwell.
[fval,xparam1,grad,hessian_csminwel,itct,fcount,retcodehat] = ...
csminwel1(objective_function, xparam1, H0, analytic_grad, crit, nit, numgrad, epsilon, dataset_, dataset_info, options_, M_, estim_params_, bayestopt_,bounds, oo_);
% Disp value at the mode.
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
case 5
if isfield(options_,'hess')
flag = options_.hess;
else
flag = 1;
end
if isfield(options_,'ftol')
crit = options_.ftol;
else
crit = 1.e-5;
end
if options_.analytic_derivation,
analytic_grad=1;
ana_deriv = options_.analytic_derivation;
options_analytic_derivation_old = options_.analytic_derivation;
options_.analytic_derivation = -1;
crit = 1.e-7;
flag = 0;
else
analytic_grad=0;
if ~isempty(newratflag) && newratflag~=0 %numerical hessian explicitly specified
error('newrat: analytic_derivation is incompatible with numerical Hessian.')
else %use default
newratflag=0; %exclude DYNARE numerical hessian
end
elseif ~options_.analytic_derivation
if isempty(newratflag)
newratflag=options_.newrat.hess; %use default numerical dynare hessian
end
end
if isfield(options_,'nit')
nit = options_.nit;
else
nit=1000;
end
[xparam1,hh,gg,fval,invhess] = newrat(objective_function,xparam1,analytic_grad,crit,nit,0,dataset_, dataset_info, options_,M_,estim_params_,bayestopt_,bounds,oo_);
if options_.analytic_derivation,
options_.analytic_derivation = ana_deriv;
else
if flag ==0,
options_.cova_compute = 1;
end
[xparam1, fval, exitflag, hh, options_, Scale] = dynare_minimize_objective(objective_function,xparam1,options_.mode_compute,options_,[bounds.lb bounds.ub],bayestopt_.name,bayestopt_,hh,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
if isnumeric(options_.mode_compute) && options_.mode_compute==5 && options_.analytic_derivation==-1 %reset options changed by newrat
options_.analytic_derivation = options_analytic_derivation_old; %reset
elseif isnumeric(options_.mode_compute) && options_.mode_compute==6 %save scaling factor
save([M_.fname '_optimal_mh_scale_parameter.mat'],'Scale');
options_.mh_jscale = Scale;
bayestopt_.jscale = ones(length(xparam1),1)*Scale;
end
if ~isnumeric(options_.mode_compute) || ~isequal(options_.mode_compute,6) %always already computes covariance matrix
if options_.cova_compute == 1 %user did not request covariance not to be computed
if options_.analytic_derivation && strcmp(func2str(objective_function),'dsge_likelihood'),
ana_deriv_old = options_.analytic_derivation;
options_.analytic_derivation = 2;
[junk1, junk2, hh] = feval(objective_function,xparam1, ...
dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
options_.analytic_derivation = ana_deriv_old;
elseif ~isnumeric(options_.mode_compute) || ~(isequal(options_.mode_compute,5) && newratflag~=1),
% with flag==0, we force to use the hessian from outer
% product gradient of optimizer 5
hh = reshape(hessian(objective_function,xparam1, ...
options_.gstep,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_),nx,nx);
elseif isnumeric(options_.mode_compute) && isequal(options_.mode_compute,5)
% other numerical hessian options available with optimizer 5
%
% if newratflag == 0
% compute outer product gradient of optimizer 5
%
% if newratflag == 2
% compute 'mixed' outer product gradient of optimizer 5
% with diagonal elements computed with numerical second order derivatives
%
% uses univariate filters, so to get max # of available
% densitities for outer product gradient
kalman_algo0 = options_.kalman_algo;
compute_hessian = 1;
if ~((options_.kalman_algo == 2) || (options_.kalman_algo == 4)),
options_.kalman_algo=2;
if options_.lik_init == 3,
options_.kalman_algo=4;
end
elseif newratflag==0, % hh already contains outer product gradient with univariate filter
compute_hessian = 0;
end
if compute_hessian,
crit = options_.newrat.tolerance.f;
newratflag = newratflag>0;
hh = reshape(mr_hessian(0,xparam1,objective_function,newratflag,crit,dataset_, dataset_info, options_,M_,estim_params_,bayestopt_,bounds,oo_), nx, nx);
end
hh = reshape(mr_hessian(0,xparam1,objective_function,1,crit,dataset_, dataset_info, options_,M_,estim_params_,bayestopt_,bounds,oo_), nx, nx);
options_.kalman_algo = kalman_algo0;
end
end
parameter_names = bayestopt_.name;
save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names');
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
case 6
% Set default options
gmhmaxlikOptions = options_.gmhmaxlik;
if ~isempty(hh);
gmhmaxlikOptions.varinit = 'previous';
else
gmhmaxlikOptions.varinit = 'prior';
end
if isfield(options_,'optim_opt')
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'NumberOfMh'
gmhmaxlikOptions.iterations = options_list{i,2};
case 'ncov-mh'
gmhmaxlikOptions.number = options_list{i,2};
case 'nscale'
gmhmaxlikOptions.nscale = options_list{i,2};
case 'nclimb'
gmhmaxlikOptions.nclimb = options_list{i,2};
case 'InitialCovarianceMatrix'
switch options_list{i,2}
case 'previous'
if isempty(hh)
error('gmhmaxlik: No previous estimate of the Hessian matrix available!')
else
gmhmaxlikOptions.varinit = 'previous'
end
case {'prior', 'identity'}
gmhmaxlikOptions.varinit = options_list{i,2};
otherwise
error('gmhmaxlik: Unknown value for option ''InitialCovarianceMatrix''!')
end
case 'AcceptanceRateTarget'
gmhmaxlikOptions.target = options_list{i,2};
if gmhmaxlikOptions.target>1 || gmhmaxlikOptions.target<eps
error('gmhmaxlik: The value of option AcceptanceRateTarget should be a double between 0 and 1!')
end
otherwise
warning(['gmhmaxlik: Unknown option (' options_list{i,1} ')!'])
end
end
end
% Evaluate the objective function.
fval = feval(objective_function,xparam1,dataset_, dataset_info, options_,M_,estim_params_,bayestopt_,bounds,oo_);
OldMode = fval;
if ~exist('MeanPar','var')
MeanPar = xparam1;
end
switch gmhmaxlikOptions.varinit
case 'previous'
CovJump = inv(hh);
case 'prior'
% The covariance matrix is initialized with the prior
% covariance (a diagonal matrix) %%Except for infinite variances ;-)
stdev = bayestopt_.p2;
indx = find(isinf(stdev));
stdev(indx) = ones(length(indx),1)*sqrt(10);
vars = stdev.^2;
CovJump = diag(vars);
case 'identity'
vars = ones(length(bayestopt_.p2),1)*0.1;
CovJump = diag(vars);
otherwise
error('gmhmaxlik: This is a bug! Please contact the developers.')
end
OldPostVar = CovJump;
Scale = options_.mh_jscale;
for i=1:gmhmaxlikOptions.iterations
if i == 1
if gmhmaxlikOptions.iterations>1
flag = '';
else
flag = 'LastCall';
end
[xparam1,PostVar,Scale,PostMean] = ...
gmhmaxlik(objective_function,xparam1,[bounds.lb bounds.ub],gmhmaxlikOptions,Scale,flag,MeanPar,CovJump,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
fval = feval(objective_function,xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
options_.mh_jscale = Scale;
mouvement = max(max(abs(PostVar-OldPostVar)));
skipline()
disp('========================================================== ')
disp([' Change in the covariance matrix = ' num2str(mouvement) '.'])
disp([' Mode improvement = ' num2str(abs(OldMode-fval))])
disp([' New value of jscale = ' num2str(Scale)])
disp('========================================================== ')
OldMode = fval;
else
OldPostVar = PostVar;
if i<gmhmaxlikOptions.iterations
flag = '';
else
flag = 'LastCall';
end
[xparam1,PostVar,Scale,PostMean] = ...
gmhmaxlik(objective_function,xparam1,[bounds.lb bounds.ub],...
gmhmaxlikOptions,Scale,flag,PostMean,PostVar,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
fval = feval(objective_function,xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
options_.mh_jscale = Scale;
mouvement = max(max(abs(PostVar-OldPostVar)));
fval = feval(objective_function,xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
skipline()
disp('========================================================== ')
disp([' Change in the covariance matrix = ' num2str(mouvement) '.'])
disp([' Mode improvement = ' num2str(abs(OldMode-fval))])
disp([' New value of jscale = ' num2str(Scale)])
disp('========================================================== ')
OldMode = fval;
end
hh = inv(PostVar);
parameter_names = bayestopt_.name;
save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names');
save([M_.fname '_optimal_mh_scale_parameter.mat'],'Scale');
bayestopt_.jscale = ones(length(xparam1),1)*Scale;
end
skipline()
disp(['Optimal value of the scale parameter = ' num2str(Scale)])
skipline()
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
skipline()
parameter_names = bayestopt_.name;
save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names');
case 7
% Matlab's simplex (Optimization toolbox needed).
if isoctave && ~user_has_octave_forge_package('optim')
error('Option mode_compute=7 requires the optim package')
elseif ~isoctave && ~user_has_matlab_license('optimization_toolbox')
error('Option mode_compute=7 requires the Optimization Toolbox')
end
optim_options = optimset('display','iter','MaxFunEvals',1000000,'MaxIter',6000,'TolFun',1e-8,'TolX',1e-6);
if isfield(options_,'optim_opt')
eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
end
[xparam1,fval,exitflag] = fminsearch(objective_function,xparam1,optim_options,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
case 8
% Dynare implementation of the simplex algorithm.
simplexOptions = options_.simplex;
if isfield(options_,'optim_opt')
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'MaxIter'
simplexOptions.maxiter = options_list{i,2};
case 'TolFun'
simplexOptions.tolerance.f = options_list{i,2};
case 'TolX'
simplexOptions.tolerance.x = options_list{i,2};
case 'MaxFunEvals'
simplexOptions.maxfcall = options_list{i,2};
case 'MaxFunEvalFactor'
simplexOptions.maxfcallfactor = options_list{i,2};
case 'InitialSimplexSize'
simplexOptions.delta_factor = options_list{i,2};
otherwise
warning(['simplex: Unknown option (' options_list{i,1} ')!'])
end
end
end
[xparam1,fval,exitflag] = simplex_optimization_routine(objective_function,xparam1,simplexOptions,bayestopt_.name,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
case 9
% Set defaults
H0 = 1e-4*ones(nx,1);
cmaesOptions = options_.cmaes;
% Modify defaults
if isfield(options_,'optim_opt')
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'MaxIter'
cmaesOptions.MaxIter = options_list{i,2};
case 'TolFun'
cmaesOptions.TolFun = options_list{i,2};
case 'TolX'
cmaesOptions.TolX = options_list{i,2};
case 'MaxFunEvals'
cmaesOptions.MaxFunEvals = options_list{i,2};
otherwise
warning(['cmaes: Unknown option (' options_list{i,1} ')!'])
end
end
end
warning('off','CMAES:NonfinitenessRange');
warning('off','CMAES:InitialSigma');
[x, fval, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = cmaes(func2str(objective_function),xparam1,H0,cmaesOptions,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
xparam1=BESTEVER.x;
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', BESTEVER.f);
case 10
simpsaOptions = options_.simpsa;
if isfield(options_,'optim_opt')
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'MaxIter'
simpsaOptions.MAX_ITER_TOTAL = options_list{i,2};
case 'TolFun'
simpsaOptions.TOLFUN = options_list{i,2};
case 'TolX'
tolx = options_list{i,2};
if tolx<0
simpsaOptions = rmfield(simpsaOptions,'TOLX'); % Let simpsa choose the default.
else
simpsaOptions.TOLX = tolx;
end
case 'EndTemparature'
simpsaOptions.TEMP_END = options_list{i,2};
case 'MaxFunEvals'
simpsaOptions.MAX_FUN_EVALS = options_list{i,2};
otherwise
warning(['simpsa: Unknown option (' options_list{i,1} ')!'])
end
end
end
simpsaOptionsList = options2cell(simpsaOptions);
simpsaOptions = simpsaset(simpsaOptionsList{:});
[xparam1, fval, exitflag] = simpsa(func2str(objective_function),xparam1,bounds.lb,bounds.ub,simpsaOptions,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
case 11
options_.cova_compute = 0 ;
[xparam1,stdh,lb_95,ub_95,med_param] = online_auxiliary_filter(xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_) ;
case 101
myoptions=soptions;
myoptions(2)=1e-6; %accuracy of argument
myoptions(3)=1e-6; %accuracy of function (see Solvopt p.29)
myoptions(5)= 1.0;
[xparam1,fval]=solvopt(xparam1,objective_function,[],myoptions,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
case 102
%simulating annealing
% LB=zeros(size(xparam1))-20;
% UB=zeros(size(xparam1))+20;
LB = xparam1 - 1;
UB = xparam1 + 1;
neps=10;
% Set input parameters.
maxy=0;
epsilon=1.0e-9;
rt_=.10;
t=15.0;
ns=10;
nt=10;
maxevl=100000000;
idisp =1;
npar=length(xparam1);
disp(['size of param',num2str(length(xparam1))])
c=.1*ones(npar,1);
%* Set input values of the input/output parameters.*
vm=1*ones(npar,1);
disp(['number of parameters= ' num2str(npar) 'max= ' num2str(maxy) 't= ' num2str(t)]);
disp(['rt_= ' num2str(rt_) 'eps= ' num2str(epsilon) 'ns= ' num2str(ns)]);
disp(['nt= ' num2str(nt) 'neps= ' num2str(neps) 'maxevl= ' num2str(maxevl)]);
% disp(['iprint= ' num2str(iprint) 'seed= ' num2str(seed)]);
disp ' ';
disp ' ';
disp(['starting values(x) ' num2str(xparam1')]);
disp(['initial step length(vm) ' num2str(vm')]);
disp(['lower bound(lb)', 'initial conditions', 'upper bound(ub)' ]);
disp([LB xparam1 UB]);
disp(['c vector ' num2str(c')]);
[xparam1, fval, nacc, nfcnev, nobds, ier, t, vm] = sa(objective_function,xparam1,maxy,rt_,epsilon,ns,nt ...
,neps,maxevl,LB,UB,c,idisp ,t,vm,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
otherwise
if ischar(options_.mode_compute)
[xparam1, fval, retcode ] = feval(options_.mode_compute,objective_function,xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
else
error(['dynare_estimation:: mode_compute = ' int2str(options_.mode_compute) ' option is unknown!'])
end
end
if ~isequal(options_.mode_compute,6) %always already computes covariance matrix
if options_.cova_compute == 1 %user did not request covariance not to be computed
if options_.analytic_derivation && strcmp(func2str(objective_function),'dsge_likelihood'),
ana_deriv = options_.analytic_derivation;
options_.analytic_derivation = 2;
[junk1, junk2, hh] = feval(objective_function,xparam1, ...
dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
options_.analytic_derivation = ana_deriv;
elseif ~(isequal(options_.mode_compute,5) && flag==0),
% with flag==0, we force to use the hessian from outer
% product gradient of optimizer 5
hh = reshape(hessian(objective_function,xparam1, ...
options_.gstep,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_),nx,nx);
end
end
end
parameter_names = bayestopt_.name;
if options_.cova_compute
if options_.cova_compute || options_.mode_compute==5 || options_.mode_compute==6
save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names');
else
save([M_.fname '_mode.mat'],'xparam1','parameter_names');
end
end
if options_.cova_compute == 0
hh = [];%NaN(length(xparam1),length(xparam1));
end
switch options_.MCMC_jumping_covariance
case 'hessian' %Baseline
%do nothing and use hessian from mode_compute
@ -721,10 +383,10 @@ if ~options_.mh_posterior_mode_estimation && options_.cova_compute
end
if options_.mode_check.status == 1 && ~options_.mh_posterior_mode_estimation
ana_deriv = options_.analytic_derivation;
ana_deriv_old = options_.analytic_derivation;
options_.analytic_derivation = 0;
mode_check(objective_function,xparam1,hh,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
options_.analytic_derivation = ana_deriv;
options_.analytic_derivation = ana_deriv_old;
end
oo_.posterior.optimization.mode = xparam1;
@ -767,8 +429,6 @@ elseif ~any(bayestopt_.pshape > 0) && ~options_.mh_posterior_mode_estimation
oo_=display_estimation_results_table(xparam1,stdh,M_,options_,estim_params_,bayestopt_,oo_,pnames,'Maximum Likelihood','mle');
end
OutputDirectoryName = CheckPath('Output',M_.dname);
if np > 0
pindx = estim_params_.param_vals(:,1);
save([M_.fname '_params.mat'],'pindx');
@ -797,14 +457,14 @@ if (any(bayestopt_.pshape >0 ) && options_.mh_replic) || ...
if options_.load_mh_file && options_.use_mh_covariance_matrix
invhess = compute_mh_covariance_matrix;
end
ana_deriv = options_.analytic_derivation;
ana_deriv_old = options_.analytic_derivation;
options_.analytic_derivation = 0;
if options_.cova_compute
feval(options_.posterior_sampling_method,objective_function,options_.proposal_distribution,xparam1,invhess,bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_);
else
error('I Cannot start the MCMC because the Hessian of the posterior kernel at the mode was not computed.')
end
options_.analytic_derivation = ana_deriv;
options_.analytic_derivation = ana_deriv_old;
end
if options_.mh_posterior_mode_estimation
CutSample(M_, options_, estim_params_);

View File

@ -442,6 +442,9 @@ else
end;
if options_.analytic_derivation,
if options_.lik_init == 3,
error('analytic derivation is incompatible with diffuse filter')
end
options_.analytic_derivation = 1;
if ~(exist('sylvester3','file')==2),
dynareroot = strrep(which('dynare'),'dynare.m','');

View File

@ -163,6 +163,11 @@ options_gsa = set_default_option(options_gsa,'istart_rmse',options_.presample+1)
options_gsa = set_default_option(options_gsa,'alpha_rmse',0.001);
options_gsa = set_default_option(options_gsa,'alpha2_rmse',1.e-5);
if options_gsa.neighborhood_width,
options_gsa.pprior=0;
options_gsa.ppost=0;
end
if options_gsa.redform && options_gsa.neighborhood_width==0 && isempty(options_gsa.threshold_redform),
options_gsa.pprior=1;
options_gsa.ppost=0;

View File

@ -35,6 +35,10 @@ if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
if ~isfield(oo_,'endo_simul') || isempty(oo_.endo_simul)
error('dynasave:: The results structure does not contain simulated series. Maybe the periods option has not been set.')
end
n = size(var_list,1);
ivar=zeros(n,1);
for i=1:n

View File

@ -1,7 +1,16 @@
function dyntable(title,headers,labels,values,label_width,val_width, ...
val_precis)
% Copyright (C) 2002-2013 Dynare Team
function dyntable(title,headers,labels,values,label_width,val_width,val_precis)
% function dyntable(title,headers,labels,values,label_width,val_width,val_precis)
% Inputs:
% title [string] Table title
% headers [n by nchar] character array of labels for header row
% labels [n by nchar] character array of labels for label column
% values [matrix] matrix of values to display
% label_width [scalar] Width of the label
% val_width [scalar] Width of value column
% val_precis [integer] precision of displayed values
%
%
% Copyright (C) 2002-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -24,48 +33,46 @@ if options_.noprint
return
end
%label_width = max(size(deblank(char(headers(1,:),labels)),2)+2, ...
% label_width);
label_width = max(size(deblank(char(headers(1,:),labels)),2))+2;
label_fmt = sprintf('%%-%ds',label_width);
%% get width of label column
if ~isempty(label_width)
label_width = max(size(deblank(char(headers(1,:),labels)),2)+2, ...
label_width);
else %use default length
label_width = max(size(deblank(char(headers(1,:),labels)),2))+2;
end
label_format_leftbound = sprintf('%%-%ds',label_width);
%% get width of label column
if all(~isfinite(values))
values_length = 4;
else
values_length = max(ceil(max(max(log10(abs(values(isfinite(values))))))),1)+val_precis+1;
end
if any(values) < 0
if any(values) < 0 %add one character for minus sign
values_length = values_length+1;
end
headers_length = max(size(deblank(headers(2:end,:)),2));
%val_width = max(values_length,val_width);
val_width = max(headers_length,values_length)+2;
%header_fmt = sprintf('%%-%ds',val_width);
val_fmt = sprintf('%%%d.%df',val_width,val_precis);
headers_offset = 0;
values_offset = 0;
if headers_length > values_length
% values_offset = ceil((val_width-values_length)/2);
%% get width of header strings
headers_length = max(size(deblank(headers(2:end,:)),2));
if ~isempty(val_width)
val_width = max(max(headers_length,values_length)+2,val_width);
else
val_width = max(headers_length,values_length)+2;
end
value_format = sprintf('%%%d.%df',val_width,val_precis);
header_string_format = sprintf('%%%ds',val_width);
if length(title) > 0
disp(sprintf('\n\n%s\n',title));
fprintf('\n\n%s\n',title);
end
%Create and print header string
if length(headers) > 0
hh = sprintf(label_fmt,headers(1,:));
hh = sprintf(label_format_leftbound ,deblank(headers(1,:)));
for i=2:size(headers,1)
hla = size(deblank(headers(i,:)),2);
hlb = ceil((val_width - hla)/2);
hla = val_width - hla - hlb;
hh = [hh char(32*ones(1,hlb)) deblank(headers(i,:)) ...
char(32*ones(1,hla))];
hh = [hh sprintf(header_string_format,deblank(headers(i,:)))];
end
disp(hh);
end
for i=1:size(values,1)
disp([sprintf(label_fmt,deblank(labels(i,:))) char(32*ones(1,values_offset)) sprintf(val_fmt,values(i,:))]);
end
% 10/30/02 MJ
disp([sprintf(label_format_leftbound ,deblank(labels(i,:))) sprintf(value_format ,values(i,:))]);
end

View File

@ -1,152 +0,0 @@
function forcst_unc(y0,var_list)
% function [mean,intval1,intval2]=forcst_unc(y0,var_list)
% computes forecasts with parameter uncertainty
%
% INPUTS
% y0: matrix of initial values
% var_list: list of variables to be forecasted
%
% OUTPUTS
% none
%
% ALGORITHM
% uses antithetic draws for the shocks
%
% SPECIAL REQUIREMENTS
% None.
% Copyright (C) 2006-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 M_ options_ oo_ estim_params_ bayestopt_
% setting up estim_params_
[xparam1,estim_params_,bayestopt_,lb,ub] = set_prior(estim_params_,M_);
options_.TeX = 0;
options_.nograph = 0;
plot_priors(bayestopt_,M_,options_);
% workspace initialization
if isempty(var_list)
var_list = M_.endo_names(1:M_.orig_endo_nbr,:);
end
n = size(var_list,1);
periods = options_.forecast;
exo_nbr = M_.exo_nbr;
replic = options_.replic;
order = options_.order;
maximum_lag = M_.maximum_lag;
% params = prior_draw(1);
params = rndprior(bayestopt_);
set_parameters(params);
% eliminate shocks with 0 variance
i_exo_var = setdiff([1:exo_nbr],find(diag(M_.Sigma_e) == 0));
nx = length(i_exo_var);
ex0 = zeros(periods,exo_nbr);
yf1 = zeros(periods+M_.maximum_lag,n,replic);
% loops on parameter values
m1 = 0;
m2 = 0;
for i=1:replic
% draw parameter values from the prior
% params = prior_draw(0);
params = rndprior(bayestopt_);
set_parameters(params);
% solve the model
[dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
% discard problematic cases
if info
continue
end
% compute forecast with zero shocks
m1 = m1+1;
yf1(:,:,m1) = simult_(y0,dr,ex0,order)';
% compute forecast with antithetic shocks
chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var));
ex(:,i_exo_var) = randn(periods,nx)*chol_S;
m2 = m2+1;
yf2(:,:,m2) = simult_(y0,dr,ex,order)';
m2 = m2+1;
yf2(:,:,m2) = simult_(y0,dr,-ex,order)';
end
oo_.forecast.accept_rate = (replic-m1)/replic;
if options_.noprint == 0 && m1 < replic
skipline(2)
disp('FORECASTING WITH PARAMETER UNCERTAINTY:')
disp(sprintf(['The model couldn''t be solved for %f%% of the parameter' ...
' values'],100*oo_.forecast.accept_rate))
skipline(2)
end
% compute moments
yf1 = yf1(:,:,1:m1);
yf2 = yf2(:,:,1:m2);
yf_mean = mean(yf1,3);
yf1 = sort(yf1,3);
yf2 = sort(yf2,3);
sig_lev = options_.conf_sig;
k1 = round((0.5+[-sig_lev, sig_lev]/2)*replic);
% make sure that lower bound is at least the first element
if k1(2) == 0
k1(2) = 1;
end
k2 = round((1+[-sig_lev, sig_lev])*replic);
% make sure that lower bound is at least the first element
if k2(2) == 0
k2(2) = 1;
end
% compute shock uncertainty around forecast with mean prior
set_parameters(bayestopt_.p1);
[dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
[yf3,yf3_intv] = forcst(dr,y0,periods,var_list);
yf3_1 = yf3'-[zeros(maximum_lag,n); yf3_intv];
yf3_2 = yf3'+[zeros(maximum_lag,n); yf3_intv];
% graphs
OutputDirectoryName = CheckPath('graphs',M_.fname);
dyn_graph=dynare_graph_init('Forecasts type I',n,{'b-' 'g-' 'g-' 'r-' 'r-'});
for i=1:n
dynare_graph(dyn_graph,[yf_mean(:,i) squeeze(yf1(:,i,k1)) squeeze(yf2(:,i,k2))],...
var_list(i,:));
end
dyn_saveas(dyn_graph.fh,[OutputDirectoryName '/' M_.fname '_forecast_param_uncert_',num2str(nlags)],options_)
dyn_graph=dynare_graph_init('Forecasts type II',n,{'b-' 'k-' 'k-' 'r-' 'r-'});
for i=1:n
dynare_graph(dyn_graph,[yf_mean(:,i) yf3_1(:,i) yf3_2(:,i) squeeze(yf2(:,i,k2))],...
var_list(i,:));
end
dyn_saveas(dyn_graph.fh,[OutputDirectoryName '/' M_.fname '_forecast_param_shock_uncert_',num2str(nlags)],options_)
% saving results
save_results(yf_mean,'oo_.forecast.Mean.',var_list);
save_results(yf1(:,:,k1(1)),'oo_.forecast.HPDinf.',var_list);
save_results(yf1(:,:,k1(2)),'oo_.forecast.HPDsup.',var_list);
save_results(yf2(:,:,k2(1)),'oo_.forecast.HPDTotalinf.',var_list);
save_results(yf2(:,:,k2(2)),'oo_.forecast.HPDTotalsup.',var_list);

View File

@ -1,252 +0,0 @@
function results = get_prior_info(info,plt_flag)
% Computes various prior statistics.
%
% INPUTS
% info [integer] scalar specifying what has to be done.
%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2009-2012 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_ M_ estim_params_ oo_ objective_function_penalty_base
if ~nargin
info = 0;
plt_flag = 0;
end
if nargin==1
plt_flag = 1;
end
% Initialize returned variable.
results = [];
changed_qz_criterium_flag = 0;
if isempty(options_.qz_criterium)
options_.qz_criterium = 1+1e-9;
changed_qz_criterium_flag = 1;
end
M_.dname = M_.fname;
% Temporarly set options_.order equal to one
order = options_.order;
options_.order = 1;
[xparam1,estim_params_,bayestopt_,lb,ub,M_] = set_prior(estim_params_,M_,options_);
if plt_flag
plot_priors(bayestopt_,M_,estim_params_,options_)
end
PriorNames = { 'Beta' , 'Gamma' , 'Gaussian' , 'Inverted Gamma' , 'Uniform' , 'Inverted Gamma -- 2' };
if size(M_.param_names,1)==size(M_.param_names_tex,1)% All the parameters have a TeX name.
fidTeX = fopen('priors_data.tex','w+');
fprintf(fidTeX,'%% TeX-table generated by get_prior_info (Dynare).\n');
fprintf(fidTeX,'%% Prior Information\n');
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|ccccccc} \n');
fprintf(fidTeX,'\\caption{Prior information (parameters)}\\\\\n ');
fprintf(fidTeX,'\\label{Table:Prior}\\\\\n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Lower Bound & Upper Bound & LB Untrunc. 80\\%% HPDI & UB Untrunc. 80\\%% HPDI \\\\ \n');
fprintf(fidTeX,'\\hline \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Lower Bound & Upper Bound & LB Untrunc. 80\\%% HPDI & UB Untrunc. 80\\%% HPDI \\\\ \n');
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{8}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
% Column 1: a string for the name of the prior distribution.
% Column 2: the prior mean.
% Column 3: the prior standard deviation.
% Column 4: the lower bound of the prior density support.
% Column 5: the upper bound of the prior density support.
% Column 6: the lower bound of the interval containing 80% of the prior mass.
% Column 7: the upper bound of the interval containing 80% of the prior mass.
prior_trunc_backup = options_.prior_trunc ;
options_.prior_trunc = (1-options_.prior_interval)/2 ;
PriorIntervals = prior_bounds(bayestopt_,options_) ;
options_.prior_trunc = prior_trunc_backup ;
for i=1:size(bayestopt_.name,1)
[tmp,TexName] = get_the_name(i,1,M_,estim_params_,options_);
PriorShape = PriorNames{ bayestopt_.pshape(i) };
PriorMean = bayestopt_.p1(i);
PriorStandardDeviation = bayestopt_.p2(i);
switch bayestopt_.pshape(i)
case { 1 , 5 }
LowerBound = bayestopt_.p3(i);
UpperBound = bayestopt_.p4(i);
if ~isinf(bayestopt_.lb(i))
LowerBound=max(LowerBound,bayestopt_.lb(i));
end
if ~isinf(bayestopt_.ub(i))
UpperBound=min(UpperBound,bayestopt_.ub(i));
end
case { 2 , 4 , 6 }
LowerBound = bayestopt_.p3(i);
if ~isinf(bayestopt_.lb(i))
LowerBound=max(LowerBound,bayestopt_.lb(i));
end
if ~isinf(bayestopt_.ub(i))
UpperBound=bayestopt_.ub(i);
else
UpperBound = '$\infty$';
end
case 3
if isinf(bayestopt_.p3(i)) && isinf(bayestopt_.lb(i))
LowerBound = '$-\infty$';
else
LowerBound = bayestopt_.p3(i);
if ~isinf(bayestopt_.lb(i))
LowerBound=max(LowerBound,bayestopt_.lb(i));
end
end
if isinf(bayestopt_.p4(i)) && isinf(bayestopt_.ub(i))
UpperBound = '$\infty$';
else
UpperBound = bayestopt_.p4(i);
if ~isinf(bayestopt_.ub(i))
UpperBound=min(UpperBound,bayestopt_.ub(i));
end
end
otherwise
error('get_prior_info:: Dynare bug!')
end
format_string = build_format_string(PriorStandardDeviation,LowerBound,UpperBound);
fprintf(fidTeX,format_string, ...
TexName, ...
PriorShape, ...
PriorMean, ...
PriorStandardDeviation, ...
LowerBound, ...
UpperBound, ...
PriorIntervals.lb(i), ...
PriorIntervals.ub(i) );
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end
M_.dname = M_.fname;
if info==1% Prior simulations (BK).
results = prior_sampler(0,M_,bayestopt_,options_,oo_,estim_params_);
% Display prior mass info
disp(['Prior mass = ' num2str(results.prior.mass)])
disp(['BK indeterminacy share = ' num2str(results.bk.indeterminacy_share)])
disp(['BK unstability share = ' num2str(results.bk.unstability_share)])
disp(['BK singularity share = ' num2str(results.bk.singularity_share)])
disp(['Complex jacobian share = ' num2str(results.jacobian.problem_share)])
disp(['mjdgges crash share = ' num2str(results.dll.problem_share)])
disp(['Steady state problem share = ' num2str(results.ss.problem_share)])
disp(['Complex steady state share = ' num2str(results.ss.complex_share)])
disp(['Analytical steady state problem share = ' num2str(results.ass.problem_share)])
end
if info==2% Prior optimization.
% Initialize to the prior mode if possible
oo_.dr=set_state_space(oo_.dr,M_,options_);
k = find(~isnan(bayestopt_.p5));
xparam1(k) = bayestopt_.p5(k);
% 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(:)>bayestopt_.p3) && all(xinit(:)<bayestopt_.p4)
M_ = set_all_parameters(xinit,estim_params_,M_);
[dr,INFO,M_,options_,oo_] = resol(0,M_,options_,oo_);
if ~INFO(1)
look_for_admissible_initial_condition = 0;
end
else
if iter == 2000;
scale = scale/1.1;
iter = 0;
else
iter = iter+1;
end
end
end
objective_function_penalty_base = minus_logged_prior_density(xinit, bayestopt_.pshape, ...
bayestopt_.p6, ...
bayestopt_.p7, ...
bayestopt_.p3, ...
bayestopt_.p4,options_,M_,estim_params_,oo_);
% Maximization
[xparams,lpd,hessian] = ...
maximize_prior_density(xinit, bayestopt_.pshape, ...
bayestopt_.p6, ...
bayestopt_.p7, ...
bayestopt_.p3, ...
bayestopt_.p4,options_,M_,estim_params_,oo_);
% Display the results.
skipline(2)
disp('------------------')
disp('PRIOR OPTIMIZATION')
disp('------------------')
skipline()
for i = 1:length(xparams)
disp(['deep parameter ' int2str(i) ': ' get_the_name(i,0,M_,estim_params_,options_) '.'])
disp([' Initial condition ....... ' num2str(xinit(i)) '.'])
disp([' Prior mode .............. ' num2str(bayestopt_.p5(i)) '.'])
disp([' Optimized prior mode .... ' num2str(xparams(i)) '.'])
skipline()
end
end
if info==3% Prior simulations (2nd order moments).
oo_ = compute_moments_varendo('prior',options_,M_,oo_);
end
if changed_qz_criterium_flag
options_.qz_criterium = [];
end
options_.order = order;
function format_string = build_format_string(PriorStandardDeviation,LowerBound,UpperBound)
format_string = ['%s & %s & %6.4f &'];
if ~isnumeric(PriorStandardDeviation)
format_string = [ format_string , ' %s &'];
else
format_string = [ format_string , ' %6.4f &'];
end
if ~isnumeric(LowerBound)
format_string = [ format_string , ' %s &'];
else
format_string = [ format_string , ' %6.4f &'];
end
if ~isnumeric(UpperBound)
format_string = [ format_string , ' %s &'];
else
format_string = [ format_string , ' %6.4f &'];
end
format_string = [ format_string , ' %6.4f & %6.4f \\\\ \n'];

View File

@ -33,6 +33,7 @@ global oo_ M_ options_ estim_params_ bayestopt_ estimation_info ex0_ ys0_
estim_params_ = [];
bayestopt_ = [];
options_.datafile = '';
options_.dirname = M_.fname;
options_.dataset = [];
options_.verbosity = 1;
options_.terminal_condition = 0;
@ -55,6 +56,7 @@ options_.qz_zero_threshold = 1e-6;
options_.lyapunov_complex_threshold = 1e-15;
options_.solve_tolf = eps^(1/3);
options_.solve_tolx = eps^(2/3);
options_.dr_display_tol=1e-6;
options_.dp.maxit = 3000;
options_.steady.maxit = 50;
@ -66,6 +68,8 @@ options_.mode_check.symmetric_plots = 1;
options_.mode_check.number_of_points = 20;
options_.mode_check.nolik = 0;
options_.huge_number = 1e7;
% Default number of threads for parallelized mex files.
options_.threads.kronecker.A_times_B_kronecker_C = 1;
options_.threads.kronecker.sparse_hessian_times_B_kronecker_C = 1;
@ -103,6 +107,10 @@ options_.bvar_prior_omega = 1;
options_.bvar_prior_flat = 0;
options_.bvar_prior_train = 0;
% Initialize the field that will contain the optimization algorigthm's options declared in the
% estimation command (if anny).
options_.optim_opt = [];
% Optimization algorithm [6] gmhmaxlik
gmhmaxlik.iterations = 3;
gmhmaxlik.number = 20000;
@ -362,6 +370,8 @@ estimation_info.measurement_error_corr.range_index = {};
estimation_info.structural_innovation_corr_prior_index = {};
estimation_info.structural_innovation_corr_options_index = {};
estimation_info.structural_innovation_corr.range_index = {};
estimation_info.joint_parameter_prior_index = {};
estimation_info.joint_parameter = {'index','domain','interval','mean','median','mode','shape','shift','stdev','truncate','variance'};
options_.initial_period = NaN; %dates(1,1);
options_.dataset.file = [];
options_.dataset.series = [];
@ -385,6 +395,7 @@ options_.nobs = NaN;
options_.kalman_algo = 0;
options_.fast_kalman = 0;
options_.kalman_tol = 1e-10;
options_.diffuse_kalman_tol = 1e-6;
options_.use_univariate_filters_if_singularity_is_detected = 1;
options_.riccati_tol = 1e-6;
options_.lik_algo = 1;
@ -406,6 +417,7 @@ options_.recursive_estimation_restart = 0;
options_.MCMC_jumping_covariance='hessian';
options_.use_calibration_initialization = 0;
options_.endo_vars_for_moment_computations_in_estimation=[];
options_.TaRB.use_TaRB = 0;
% Prior restrictions
options_.prior_restrictions.status = 0;
@ -426,8 +438,8 @@ options_.student_degrees_of_freedom = 3;
options_.posterior_max_subsample_draws = 1200;
options_.sub_draws = [];
options_.use_mh_covariance_matrix = 0;
options_.gradient_method = 2;
options_.gradient_epsilon = 1e-6;
options_.gradient_method = 2; %used by csminwel and newrat
options_.gradient_epsilon = 1e-6; %used by csminwel and newrat
options_.posterior_sampling_method = 'random_walk_metropolis_hastings';
options_.proposal_distribution = 'rand_multivariate_normal';
options_.student_degrees_of_freedom = 3;
@ -473,6 +485,18 @@ options_.homotopy_mode = 0;
options_.homotopy_steps = 1;
options_.homotopy_force_continue = 0;
%csminwel optimization routine
csminwel.tolerance.f=1e-7;
csminwel.maxiter=1000;
options_.csminwel=csminwel;
%newrat optimization routine
newrat.hess=1; % dynare numerical hessian
newrat.tolerance.f=1e-5;
newrat.tolerance.f_analytic=1e-7;
newrat.maxiter=1000;
options_.newrat=newrat;
% Simplex optimization routine (variation on Nelder Mead algorithm).
simplex.tolerance.x = 1e-4;
simplex.tolerance.f = 1e-4;
@ -510,6 +534,30 @@ simpsa.MAX_FUN_EVALS = 20000;
simpsa.DISPLAY = 'iter';
options_.simpsa = simpsa;
%solveopt optimizer
solveopt.minimizer_indicator=-1; %use minimizer
solveopt.TolX=1e-6; %accuracy of argument
solveopt.TolFun=1e-6; %accuracy of function
solveopt.MaxIter=15000;
solveopt.verbosity=1;
solveopt.TolXConstraint=1.e-8;
solveopt.SpaceDilation=2.5;
solveopt.LBGradientStep=1.e-11;
options_.solveopt=solveopt;
%simulated annealing
options_.saopt.neps=10;
options_.saopt.maximizer_indicator=0;
options_.saopt.rt=0.10;
options_.saopt.MaxIter=100000;
options_.saopt.verbosity=1;
options_.saopt.TolFun=1.0e-8;
options_.saopt.initial_temperature=15;
options_.saopt.ns=10;
options_.saopt.nt=10;
options_.saopt.step_length_c=0.1;
options_.saopt.initial_step_length=1;
% prior analysis
options_.prior_mc = 20000;
options_.prior_analysis_endo_var_list = [];
@ -627,8 +675,7 @@ options_.endogenous_prior_restrictions.irf={};
options_.endogenous_prior_restrictions.moment={};
% OSR Optimal Simple Rules
options_.osr.tolf=1e-7;
options_.osr.maxit=1000;
options_.osr.opt_algo=4;
% use GPU
options_.gpu = 0;

View File

@ -43,7 +43,7 @@ alpha = options_gsa_.alpha_rmse;
% alpha2 = options_gsa_.alpha2_rmse;
alpha2 = 0;
pvalue = options_gsa_.alpha2_rmse;
istart = options_gsa_.istart_rmse;
istart = max(2,options_gsa_.istart_rmse);
alphaPC = 0.5;
fname_ = M_.fname;
@ -242,41 +242,66 @@ end
if ~options_.opt_gsa.ppost && options_.opt_gsa.lik_only
if options_.opt_gsa.pprior
anam='rmse_prior_post';
atitle='RMSE prior: Log Posterior Kernel';
else
anam='rmse_mc_post';
atitle='RMSE MC: Log Posterior Kernel';
end
stab_map_1(x, ipost(1:nfilt), ipost(nfilt+1:end), anam, 1,[],OutDir);
stab_map_2(x(ipost(1:nfilt),:),alpha2,pvalue,anam, OutDir);
options_mcf.pvalue_ks = alpha;
options_mcf.pvalue_corr = pvalue;
options_mcf.alpha2 = alpha2;
options_mcf.param_names = char(bayestopt_.name);
options_mcf.fname_ = fname_;
options_mcf.OutputDirectoryName = OutDir;
options_mcf.amcf_name = anam;
options_mcf.amcf_title = atitle;
options_mcf.title = atitle;
options_mcf.beha_title = 'better posterior kernel';
options_mcf.nobeha_title = 'worse posterior kernel';
mcf_analysis(x, ipost(1:nfilt), ipost(nfilt+1:end), options_mcf, options_);
if options_.opt_gsa.pprior
anam='rmse_prior_lik';
anam = 'rmse_prior_lik';
atitle = 'RMSE prior: Log Likelihood Kernel';
else
anam='rmse_mc_lik';
atitle = 'RMSE MC: Log Likelihood Kernel';
end
stab_map_1(x, ilik(1:nfilt), ilik(nfilt+1:end), anam, 1,[],OutDir);
stab_map_2(x(ilik(1:nfilt),:),alpha2,pvalue,anam, OutDir);
options_mcf.amcf_name = anam;
options_mcf.amcf_title = atitle;
options_mcf.title = atitle;
options_mcf.beha_title = 'better likelihood';
options_mcf.nobeha_title = 'worse likelihood';
mcf_analysis(x, ilik(1:nfilt), ilik(nfilt+1:end), options_mcf, options_);
else
for i=1:size(vvarvecm,1),
[dum, ixx(:,i)]=sort(rmse_MC(:,i));
if options_.opt_gsa.ppost,
if options_.opt_gsa.ppost,
rmse_txt=rmse_pmean;
r2_txt=r2_pmean;
else
if options_.opt_gsa.pprior || ~exist('rmse_pmean'),
if exist('rmse_mode'),
rmse_txt=rmse_mode;
r2_txt=r2_mode;
else
rmse_txt=NaN(1,size(rmse_MC,2));
r2_txt=NaN(1,size(r2_MC,2));
end
else
%nfilt0(i)=length(find(rmse_MC(:,i)<rmse_pmean(i)));
rmse_txt=rmse_pmean;
r2_txt=r2_pmean;
else
if options_.opt_gsa.pprior || ~exist('rmse_pmean'),
if exist('rmse_mode'),
rmse_txt=rmse_mode;
r2_txt=r2_mode;
else
rmse_txt=NaN(1,size(rmse_MC,2));
r2_txt=NaN(1,size(r2_MC,2));
end
else
%nfilt0(i)=length(find(rmse_MC(:,i)<rmse_pmean(i)));
rmse_txt=rmse_pmean;
r2_txt=r2_pmean;
end
end
for j=1:npar+nshock,
end
for i=1:size(vvarvecm,1),
[dum, ixx(:,i)]=sort(rmse_MC(:,i));
end
PP=ones(npar+nshock,size(vvarvecm,1));
PPV=ones(size(vvarvecm,1),size(vvarvecm,1),npar+nshock);
SS=zeros(npar+nshock,size(vvarvecm,1));
for j=1:npar+nshock,
for i=1:size(vvarvecm,1),
[H,P,KSSTAT] = smirnov(x(ixx(nfilt0(i)+1:end,i),j),x(ixx(1:nfilt0(i),i),j), alpha);
[H1,P1,KSSTAT1] = smirnov(x(ixx(nfilt0(i)+1:end,i),j),x(ixx(1:nfilt0(i),i),j),alpha,1);
[H2,P2,KSSTAT2] = smirnov(x(ixx(nfilt0(i)+1:end,i),j),x(ixx(1:nfilt0(i),i),j),alpha,-1);
@ -289,6 +314,22 @@ else
end
PP(j,i)=P;
end
for i=1:size(vvarvecm,1),
for l=1:size(vvarvecm,1),
if l~=i && PP(j,i)<alpha && PP(j,l)<alpha
[H,P,KSSTAT] = smirnov(x(ixx(1:nfilt0(i),i),j),x(ixx(1:nfilt0(l),l),j), alpha);
%[H1,P1,KSSTAT1] = smirnov(x(ixx(1:nfilt0(i),i),j),x(:,j), alpha);
% PP(j,i)=min(P,PP(j,i));
% PP(j,l)=min(P,PP(j,l));
%if P<P1
% if SS(j,i)*SS(j,l)
PPV(i,l,j) = P;
% end
elseif l==i
PPV(i,l,j) = PP(j,i);
end
end
end
end
if ~options_.nograph,
ifig=0;
@ -308,12 +349,17 @@ else
end
subplot(3,3,i-9*(ifig-1))
h=cumplot(lnprior(ixx(1:nfilt0(i),i)));
set(h,'color','red')
hold on, cumplot(lnprior)
set(h,'color','blue','linewidth',2)
hold on, h=cumplot(lnprior);
set(h,'color','k','linewidth',1)
h=cumplot(lnprior(ixx(nfilt0(i)+1:end,i)));
set(h,'color','green')
set(h,'color','red','linewidth',2)
title(vvarvecm(i,:),'interpreter','none')
if mod(i,9)==0 || i==size(vvarvecm,1)
if ~isoctave
annotation('textbox', [0.1,0,0.35,0.05],'String', 'Log-prior for BETTER R2','Color','Blue','horizontalalignment','center');
annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-prior for WORSE R2', 'Color','Red','horizontalalignment','center');
end
if options_.opt_gsa.ppost
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],options_);
else
@ -342,15 +388,20 @@ else
end
subplot(3,3,i-9*(ifig-1))
h=cumplot(likelihood(ixx(1:nfilt0(i),i)));
set(h,'color','red')
set(h,'color','blue','linewidth',2)
hold on, h=cumplot(likelihood);
set(h,'color','k','linewidth',1)
h=cumplot(likelihood(ixx(nfilt0(i)+1:end,i)));
set(h,'color','green')
set(h,'color','red','linewidth',2)
title(vvarvecm(i,:),'interpreter','none')
if options_.opt_gsa.ppost==0,
set(gca,'xlim',[min( likelihood(ixx(1:nfilt0(i),i)) ) max( likelihood(ixx(1:nfilt0(i),i)) )])
end
if mod(i,9)==0 || i==size(vvarvecm,1)
if ~isoctave
annotation('textbox', [0.1,0,0.35,0.05],'String', 'Log-likelihood for BETTER R2','Color','Blue','horizontalalignment','center');
annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-likelihood for WORSE R2', 'Color','Red','horizontalalignment','center');
end
if options_.opt_gsa.ppost
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnlik',int2str(ifig) ],options_);
else
@ -379,15 +430,20 @@ else
end
subplot(3,3,i-9*(ifig-1))
h=cumplot(logpo2(ixx(1:nfilt0(i),i)));
set(h,'color','red')
set(h,'color','blue','linewidth',2)
hold on, h=cumplot(logpo2);
set(h,'color','k','linewidth',1)
h=cumplot(logpo2(ixx(nfilt0(i)+1:end,i)));
set(h,'color','green')
set(h,'color','red','linewidth',2)
title(vvarvecm(i,:),'interpreter','none')
if options_.opt_gsa.ppost==0,
set(gca,'xlim',[min( logpo2(ixx(1:nfilt0(i),i)) ) max( logpo2(ixx(1:nfilt0(i),i)) )])
end
if mod(i,9)==0 || i==size(vvarvecm,1)
if ~isoctave
annotation('textbox', [0.1,0,0.35,0.05],'String', 'Log-posterior for BETTER R2','Color','Blue','horizontalalignment','center');
annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-posterior for WORSE R2', 'Color','Red','horizontalalignment','center');
end
if options_.opt_gsa.ppost
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],options_);
else
@ -401,11 +457,12 @@ else
end
end
param_names='';
for j=1:npar+nshock,
param_names=char(param_names, bayestopt_.name{j});
end
param_names=param_names(2:end,:);
param_names=char(bayestopt_.name);
% param_names='';
% for j=1:npar+nshock,
% param_names=char(param_names, bayestopt_.name{j});
% end
% param_names=param_names(2:end,:);
skipline()
disp('RMSE over the MC sample:')
@ -526,15 +583,94 @@ else
a00=jet(size(vvarvecm,1));
if options_.opt_gsa.ppost
temp_name='RMSE Posterior Tradeoffs:';
atitle='RMSE Posterior Map:';
asname='rmse_post';
else
if options_.opt_gsa.pprior
temp_name='RMSE Prior Tradeoffs:';
atitle='RMSE Prior Map:';
asname='rmse_prior';
else
temp_name='RMSE MC Tradeoffs;';
temp_name='RMSE MC Tradeoffs:';
atitle='RMSE MC Map:';
asname='rmse_mc';
end
end
% now I plot by observed variables
options_mcf.pvalue_ks = alpha;
options_mcf.pvalue_corr = pvalue;
options_mcf.alpha2 = alpha2;
options_mcf.param_names = char(bayestopt_.name);
options_mcf.fname_ = fname_;
options_mcf.OutputDirectoryName = OutDir;
for iy=1:size(vvarvecm,1),
options_mcf.amcf_name = [asname '_' deblank(vvarvecm(iy,:)) '_map' ];
options_mcf.amcf_title = [atitle ' ' deblank(vvarvecm(iy,:))];
options_mcf.beha_title = ['better fit of ' deblank(vvarvecm(iy,:))];
options_mcf.nobeha_title = ['worse fit of ' deblank(vvarvecm(iy,:))];
options_mcf.title = ['the fit of ' deblank(vvarvecm(iy,:))];
mcf_analysis(x, ixx(1:nfilt0(iy),iy), ixx(nfilt0(iy)+1:end,iy), options_mcf, options_);
end
for iy=1:size(vvarvecm,1),
ipar = find(any(squeeze(PPV(iy,:,:))<alpha));
for ix=1:ceil(length(ipar)/5),
hh = dyn_figure(options_,'name',[temp_name,' observed variable ',deblank(vvarvecm(iy,:))]);
for j=1+5*(ix-1):min(length(ipar),5*ix),
subplot(2,3,j-5*(ix-1))
%h0=cumplot(x(:,nsnam(j)+nshock));
h0=cumplot(x(:,ipar(j)));
set(h0,'color',[0 0 0])
hold on,
iobs=find(squeeze(PPV(iy,:,ipar(j)))<alpha);
for i=1:size(vvarvecm,1),
%h0=cumplot(x(ixx(1:nfilt,np(i)),nsnam(j)+nshock));
% h0=cumplot(x(ixx(1:nfilt0(np(i)),np(i)),nsnam(j)));
if any(iobs==i) || i==iy,
h0=cumplot(x(ixx(1:nfilt0(i),i),ipar(j)));
if ~isoctave
hcmenu = uicontextmenu;
uimenu(hcmenu,'Label',deblank(vvarvecm(i,:)));
set(h0,'uicontextmenu',hcmenu)
end
else
h0=cumplot(x(ixx(1:nfilt0(i),i),ipar(j))*NaN);
end
set(h0,'color',a00(i,:),'linewidth',2)
end
ydum=get(gca,'ylim');
%xdum=xparam1(nshock+nsnam(j));
if exist('xparam1')
xdum=xparam1(ipar(j));
h1=plot([xdum xdum],ydum);
set(h1,'color',[0.85 0.85 0.85],'linewidth',2)
end
xlabel('')
title([pnam{ipar(j)}],'interpreter','none')
end
%subplot(3,2,6)
if isoctave
legend(char('base',vvarvecm),'location','eastoutside');
else
h0=legend(char('base',vvarvecm),0);
set(h0,'fontsize',6,'position',[0.7 0.1 0.2 0.3],'interpreter','none');
end
%h0=legend({'base',vnam{np}}',0);
%set(findobj(get(h0,'children'),'type','text'),'interpreter','none')
if options_.opt_gsa.ppost
dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_);
else
if options_.opt_gsa.pprior
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_' deblank(vvarvecm(iy,:)) '_' int2str(ix) ],options_);
else
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_);
end
end
end
end
% now I plot by individual parameters
for ix=1:ceil(length(nsnam)/5),
hh = dyn_figure(options_,'name',[temp_name,' observed variables ',int2str(ix)]);
hh = dyn_figure(options_,'name',[temp_name,' estimated params and shocks ',int2str(ix)]);
for j=1+5*(ix-1):min(size(snam2,1),5*ix),
subplot(2,3,j-5*(ix-1))
%h0=cumplot(x(:,nsnam(j)+nshock));
@ -551,8 +687,13 @@ else
h0=cumplot(x(ixx(1:nfilt0(i),i),nsnam(j))*NaN);
else
h0=cumplot(x(ixx(1:nfilt0(i),i),nsnam(j)));
end
set(h0,'color',a00(i,:))
if ~isoctave
hcmenu = uicontextmenu;
uimenu(hcmenu,'Label',deblank(vvarvecm(i,:)));
set(h0,'uicontextmenu',hcmenu)
end
end
set(h0,'color',a00(i,:),'linewidth',2)
end
ydum=get(gca,'ylim');
%xdum=xparam1(nshock+nsnam(j));
@ -574,74 +715,74 @@ else
%h0=legend({'base',vnam{np}}',0);
%set(findobj(get(h0,'children'),'type','text'),'interpreter','none')
if options_.opt_gsa.ppost
dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_' int2str(ix)],options_);
dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_params_' int2str(ix)],options_);
else
if options_.opt_gsa.pprior
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_' int2str(ix) ],options_);
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],options_);
else
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_' int2str(ix)],options_);
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],options_);
end
end
end
end
for j=1:size(SP,2),
nsx(j)=length(find(SP(:,j)));
end
% for j=1:size(SP,2),
% nsx(j)=length(find(SP(:,j)));
% end
skipline(2)
disp('Sensitivity table (significance and direction):')
vav=char(zeros(1, size(param_names,2)+3 ));
ibl = 12-size(vvarvecm,2);
for j=1:size(vvarvecm,1),
vav = [vav, char(zeros(1,ibl)),vvarvecm(j,:)];
end
disp(vav)
for j=1:npar+nshock, %estim_params_.np,
%disp([param_names(j,:), sprintf('%8.5g',SP(j,:))])
disp([param_names(j,:),' ', sprintf('%12.3g',PP(j,:))])
disp([char(zeros(1, size(param_names,2)+3 )),sprintf(' (%6g)',SS(j,:))])
end
% skipline(2)
% disp('Sensitivity table (significance and direction):')
% vav=char(zeros(1, size(param_names,2)+3 ));
% ibl = 12-size(vvarvecm,2);
% for j=1:size(vvarvecm,1),
% vav = [vav, char(zeros(1,ibl)),vvarvecm(j,:)];
% end
% disp(vav)
% for j=1:npar+nshock, %estim_params_.np,
% %disp([param_names(j,:), sprintf('%8.5g',SP(j,:))])
% disp([param_names(j,:),' ', sprintf('%12.3g',PP(j,:))])
% disp([char(zeros(1, size(param_names,2)+3 )),sprintf(' (%6g)',SS(j,:))])
% end
skipline()
disp('Starting bivariate analysis:')
for i=1:size(vvarvecm,1)
if options_.opt_gsa.ppost
fnam = ['rmse_post_',deblank(vvarvecm(i,:))];
else
if options_.opt_gsa.pprior
fnam = ['rmse_prior_',deblank(vvarvecm(i,:))];
else
fnam = ['rmse_mc_',deblank(vvarvecm(i,:))];
end
end
stab_map_2(x(ixx(1:nfilt0(i),i),:),alpha2,pvalue,fnam, OutDir,[],[temp_name ' observed variable ' deblank(vvarvecm(i,:))]);
% [pc,latent,explained] = pcacov(c0);
% %figure, bar([explained cumsum(explained)])
% ifig=0;
% j2=0;
% for j=1:npar+nshock,
% i2=find(abs(pc(:,j))>alphaPC);
% if ~isempty(i2),
% j2=j2+1;
% if mod(j2,12)==1,
% ifig=ifig+1;
% figure('name',['PCA of the filtered sample ',deblank(vvarvecm(i,:)),' ',num2str(ifig)]),
% end
% subplot(3,4,j2-(ifig-1)*12)
% bar(pc(i2,j)),
% set(gca,'xticklabel',bayestopt_.name(i2)),
% set(gca,'xtick',[1:length(i2)])
% title(['PC ',num2str(j),'. Explained ',num2str(explained(j)),'%'])
% end
% if (mod(j2,12)==0 | j==(npar+nshock)) & j2,
% saveas(gcf,[fname_,'_SA_PCA_',deblank(vvarvecm(i,:)),'_',int2str(ifig)])
% end
% end
% close all
end
% skipline()
% disp('Starting bivariate analysis:')
%
% for i=1:size(vvarvecm,1)
% if options_.opt_gsa.ppost
% fnam = ['rmse_post_',deblank(vvarvecm(i,:))];
% else
% if options_.opt_gsa.pprior
% fnam = ['rmse_prior_',deblank(vvarvecm(i,:))];
% else
% fnam = ['rmse_mc_',deblank(vvarvecm(i,:))];
% end
% end
% stab_map_2(x(ixx(1:nfilt0(i),i),:),alpha2,pvalue,fnam, OutDir,[],[temp_name ' observed variable ' deblank(vvarvecm(i,:))]);
%
% % [pc,latent,explained] = pcacov(c0);
% % %figure, bar([explained cumsum(explained)])
% % ifig=0;
% % j2=0;
% % for j=1:npar+nshock,
% % i2=find(abs(pc(:,j))>alphaPC);
% % if ~isempty(i2),
% % j2=j2+1;
% % if mod(j2,12)==1,
% % ifig=ifig+1;
% % figure('name',['PCA of the filtered sample ',deblank(vvarvecm(i,:)),' ',num2str(ifig)]),
% % end
% % subplot(3,4,j2-(ifig-1)*12)
% % bar(pc(i2,j)),
% % set(gca,'xticklabel',bayestopt_.name(i2)),
% % set(gca,'xtick',[1:length(i2)])
% % title(['PC ',num2str(j),'. Explained ',num2str(explained(j)),'%'])
% % end
% % if (mod(j2,12)==0 | j==(npar+nshock)) & j2,
% % saveas(gcf,[fname_,'_SA_PCA_',deblank(vvarvecm(i,:)),'_',int2str(ifig)])
% % end
% % end
% % close all
% end
end

View File

@ -1,4 +1,4 @@
function [yy, xdir, isig, lam]=log_trans_(y0,xdir0)
function [yy, xdir, isig, lam]=log_trans_(y0,xdir0,isig,lam)
% Copyright (C) 2012 Dynare Team
%
@ -17,6 +17,12 @@ function [yy, xdir, isig, lam]=log_trans_(y0,xdir0)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if nargin==4,
% inverse transformation
yy = (exp(y0)-lam)*isig;
return
end
if nargin==1,
xdir0='';
end
@ -67,5 +73,6 @@ else
lam = -min(y0)+abs(median(y0)); %abs(100*(1+min(y0)));
end
end
lam = max(lam,0);
yy = log(y0+lam);
end

View File

@ -55,7 +55,7 @@ else
load(filetoload,'lpmat','lpmat0','istable','iunstable','iindeterm','iwrong' ,'infox')
lpmat = [lpmat0 lpmat];
type = 'mc';
end
end
end
[Nsam, np] = size(lpmat);
npar = size(pnames,1);
@ -65,58 +65,91 @@ nbr_irf_restrictions = size(DynareOptions.endogenous_prior_restrictions.irf,1);
nbr_moment_restrictions = size(DynareOptions.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}));
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}));
end
irestrictions = [1:Nsam];
h = dyn_waitbar(0,'Please wait...');
for j=1:Nsam,
Model = set_all_parameters(lpmat(j,:)',EstimatedParameters,Model);
[Tt,Rr,SteadyState,info] = dynare_resolve(Model,DynareOptions,DynareResults,'restrict');
if info(1)==0,
[info, info_irf, info_moment, data_irf, data_moment]=endogenous_prior_restrictions(Tt,Rr,Model,DynareOptions,DynareResults);
if ~isempty(info_irf)
for ij=1:nbr_irf_restrictions,
mat_irf{ij}(j,:)=data_irf{ij}(:,2)';
end
indx_irf(j,:)=info_irf(:,1);
end
if ~isempty(info_moment)
for ij=1:nbr_moment_restrictions,
mat_moment{ij}(j,:)=data_moment{ij}(:,2)';
end
indx_moment(j,:)=info_moment(:,1);
end
else
irestrictions(j)=0;
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}));
end
dyn_waitbar(j/Nsam,h,['MC iteration ',int2str(j),'/',int2str(Nsam)])
end
dyn_waitbar_close(h);
irestrictions=irestrictions(find(irestrictions));
xmat=lpmat(irestrictions,:);
skipline()
endo_prior_restrictions=DynareOptions.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');
end
if ~isempty(indx_irf),
% For single legend search which has maximum nbr of restrictions
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}));
end
irestrictions = [1:Nsam];
h = dyn_waitbar(0,'Please wait...');
for j=1:Nsam,
Model = set_all_parameters(lpmat(j,:)',EstimatedParameters,Model);
if nbr_moment_restrictions,
[Tt,Rr,SteadyState,info,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults);
else
[Tt,Rr,SteadyState,info,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults,'restrict');
end
if info(1)==0,
[info, info_irf, info_moment, data_irf, data_moment]=endogenous_prior_restrictions(Tt,Rr,Model,DynareOptions,DynareResults);
if ~isempty(info_irf)
for ij=1:nbr_irf_restrictions,
mat_irf{ij}(j,:)=data_irf{ij}(:,2)';
end
indx_irf(j,:)=info_irf(:,1);
end
if ~isempty(info_moment)
for ij=1:nbr_moment_restrictions,
mat_moment{ij}(j,:)=data_moment{ij}(:,2)';
end
indx_moment(j,:)=info_moment(:,1);
end
else
irestrictions(j)=0;
end
dyn_waitbar(j/Nsam,h,['MC iteration ',int2str(j),'/',int2str(Nsam)])
end
dyn_waitbar_close(h);
irestrictions=irestrictions(find(irestrictions));
xmat=lpmat(irestrictions,:);
skipline()
endo_prior_restrictions=DynareOptions.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');
end
if ~isempty(indx_irf),
skipline()
disp('Deleting old IRF calibration plots ...')
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_calib*.eps']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_calib*.fig']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_calib*.pdf']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions.eps']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions.fig']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions.pdf']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
disp('done !')
skipline()
% For single legend search which has maximum nbr of restrictions
all_irf_couples = cellstr([char(endo_prior_restrictions.irf(:,1)) char(endo_prior_restrictions.irf(:,2))]);
irf_couples = unique(all_irf_couples);
nbr_irf_couples = size(irf_couples,1);
plot_indx = NaN(nbr_irf_couples,1);
time_matrix=cell(nbr_irf_couples,1);
indx_irf_matrix=zeros(length(irestrictions),nbr_irf_couples);
irf_matrix=cell(nbr_irf_couples,1);
irf_mean=cell(nbr_irf_couples,1);
irf_median=cell(nbr_irf_couples,1);
@ -131,17 +164,21 @@ if ~isempty(indx_irf),
plot_indx(ij) = find(strcmp(irf_couples,all_irf_couples(ij,:)));
time_matrix{plot_indx(ij)} = [time_matrix{plot_indx(ij)} endo_prior_restrictions.irf{ij,3}];
end
iplot_indx = ones(size(plot_indx));
indx_irf = indx_irf(irestrictions,:);
h1=dyn_figure(DynareOptions,'name',[type ' evaluation of irf restrictions']);
nrow=ceil(sqrt(nbr_irf_couples));
ncol=nrow;
if nrow*(nrow-1)>nbr_irf_couples,
ncol=nrow-1;
if ~DynareOptions.nograph,
h1=dyn_figure(DynareOptions,'name',[type ' evaluation of irf restrictions']);
nrow=ceil(sqrt(nbr_irf_couples));
ncol=nrow;
if nrow*(nrow-1)>nbr_irf_couples,
ncol=nrow-1;
end
end
for ij=1:nbr_irf_restrictions,
mat_irf{ij}=mat_irf{ij}(irestrictions,:);
irf_matrix{plot_indx(ij)} = [irf_matrix{plot_indx(ij)} mat_irf{ij}];
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);
@ -156,18 +193,21 @@ if ~isempty(indx_irf),
if size(mat_irf{ij},2)>1,
leg = [leg,':' ,num2str(endo_prior_restrictions.irf{ij,3}(end))];
aleg = [aleg,'-' ,num2str(endo_prior_restrictions.irf{ij,3}(end))];
end
if length(time_matrix{plot_indx(ij)})==1,
figure(h1),
iplot_indx(ij)=0;
end
if ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1,
set(0,'currentfigure',h1),
subplot(nrow,ncol, plot_indx(ij)),
hc = cumplot(mat_irf{ij}(:,ik));
set(hc,'color','k','linewidth',2)
hold all,
a=axis;
delete(hc);
x1val=max(endo_prior_restrictions.irf{ij,4}(1),a(1));
x2val=min(endo_prior_restrictions.irf{ij,4}(2),a(2));
hp = patch([x1val x2val x2val x1val],a([3 3 4 4]),'b');
set(hp,'FaceAlpha', 0.5)
hold all,
set(hp,'FaceColor', [0.7 0.8 1])
hc = cumplot(mat_irf{ij}(:,ik));
set(hc,'color','k','linewidth',2)
hold off,
% hold off,
title([endo_prior_restrictions.irf{ij,1},' vs ',endo_prior_restrictions.irf{ij,2}, '(', leg,')'],'interpreter','none'),
@ -185,75 +225,133 @@ if ~isempty(indx_irf),
indx1 = find(indx_irf(:,ij)==0);
indx2 = find(indx_irf(:,ij)~=0);
atitle0=[endo_prior_restrictions.irf{ij,1},' vs ',endo_prior_restrictions.irf{ij,2}, '(', leg,')'];
fprintf(['%4.1f%% of the prior support matches IRF ',atitle0,' inside [%4.1f, %4.1f]\n'],length(indx1)/length(irestrictions)*100,endo_prior_restrictions.irf{ij,4})
fprintf(['%4.1f%% of the ',type,' support matches IRF ',atitle0,' inside [%4.1f, %4.1f]\n'],length(indx1)/length(irestrictions)*100,endo_prior_restrictions.irf{ij,4})
% aname=[type '_irf_calib_',int2str(ij)];
aname=[type '_irf_calib_',endo_prior_restrictions.irf{ij,1},'_vs_',endo_prior_restrictions.irf{ij,2},'_',aleg];
atitle=[type ' IRF Calib: Parameter(s) driving ',endo_prior_restrictions.irf{ij,1},' vs ',endo_prior_restrictions.irf{ij,2}, '(', leg,')'];
options_mcf.amcf_name = aname;
options_mcf.amcf_title = atitle;
options_mcf.beha_title = 'IRF prior restriction';
options_mcf.nobeha_title = 'NO IRF prior restriction';
options_mcf.beha_title = 'IRF restriction';
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);
end
% [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0);
% indplot=find(proba<pvalue_ks);
% if ~isempty(indplot)
% stab_map_1(xmat, indx1, indx2, aname, 1, indplot, OutputDirectoryName,[],atitle);
% end
% [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0);
% indplot=find(proba<pvalue_ks);
% if ~isempty(indplot)
% stab_map_1(xmat, indx1, indx2, aname, 1, indplot, OutputDirectoryName,[],atitle);
% end
end
figure(h1);
for ij=1:nbr_irf_couples,
if length(time_matrix{ij})>1,
subplot(nrow,ncol, ij)
itmp = (find(plot_indx==ij));
plot(time_matrix{ij},[max(irf_matrix{ij})' min(irf_matrix{ij})'],'k--','linewidth',2)
hold on,
plot(time_matrix{ij},irf_median{ij},'k','linewidth',2)
plot(time_matrix{ij},[irf_distrib{ij}],'k-')
a=axis;
tmp=[];
for ir=1:length(itmp),
for it=1:length(endo_prior_restrictions.irf{itmp(ir),3})
temp_index = find(time_matrix{ij}==endo_prior_restrictions.irf{itmp(ir),3}(it));
tmp(temp_index,:) = endo_prior_restrictions.irf{itmp(ir),4};
if ~DynareOptions.nograph,
set(0,'currentfigure',h1);
subplot(nrow,ncol, ij)
itmp = (find(plot_indx==ij));
htmp = plot(time_matrix{ij},[max(irf_matrix{ij})' min(irf_matrix{ij})'],'k--','linewidth',2);
a=axis;
delete(htmp);
tmp=[];
for ir=1:length(itmp),
for it=1:length(endo_prior_restrictions.irf{itmp(ir),3})
temp_index = find(time_matrix{ij}==endo_prior_restrictions.irf{itmp(ir),3}(it));
tmp(temp_index,:) = endo_prior_restrictions.irf{itmp(ir),4};
end
end
% tmp = cell2mat(endo_prior_restrictions.irf(itmp,4));
tmp(isinf(tmp(:,1)),1)=a(3);
tmp(isinf(tmp(:,2)),2)=a(4);
hp = patch([time_matrix{ij} time_matrix{ij}(end:-1:1)],[tmp(:,1); tmp(end:-1:1,2)],'c');
set(hp,'FaceColor',[0.7 0.8 1])
hold on,
plot(time_matrix{ij},[max(irf_matrix{ij})' min(irf_matrix{ij})'],'k--','linewidth',2)
plot(time_matrix{ij},irf_median{ij},'k','linewidth',2)
plot(time_matrix{ij},[irf_distrib{ij}],'k-')
plot(a(1:2),[0 0],'r')
hold off,
axis([max(1,a(1)) a(2:4)])
box on,
set(gca,'xtick',sort(time_matrix{ij}))
itmp = min(itmp);
title([endo_prior_restrictions.irf{itmp,1},' vs ',endo_prior_restrictions.irf{itmp,2}],'interpreter','none'),
end
if any(iplot_indx.*plot_indx==ij),
% MCF of the couples with logical AND
itmp = min(find(plot_indx==ij));
indx1 = find(indx_irf_matrix(:,ij)==0);
indx2 = find(indx_irf_matrix(:,ij)~=0);
leg = num2str(time_matrix{ij}(1));
leg = [leg '...' num2str(time_matrix{ij}(end))];
aleg = 'ALL';
atitle0=[endo_prior_restrictions.irf{itmp,1},' vs ',endo_prior_restrictions.irf{itmp,2}, '(', leg,')'];
fprintf(['%4.1f%% of the ',type,' support matches IRF restrictions ',atitle0,'\n'],length(indx1)/length(irestrictions)*100)
% aname=[type '_irf_calib_',int2str(ij)];
aname=[type '_irf_calib_',endo_prior_restrictions.irf{itmp,1},'_vs_',endo_prior_restrictions.irf{itmp,2},'_',aleg];
atitle=[type ' IRF Calib: Parameter(s) driving ',endo_prior_restrictions.irf{itmp,1},' vs ',endo_prior_restrictions.irf{itmp,2}, '(', leg,')'];
options_mcf.amcf_name = aname;
options_mcf.amcf_title = atitle;
options_mcf.beha_title = 'IRF restriction';
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);
end
end
% tmp = cell2mat(endo_prior_restrictions.irf(itmp,4));
tmp(isinf(tmp(:,1)),1)=a(3);
tmp(isinf(tmp(:,2)),2)=a(4);
hp = patch([time_matrix{ij} time_matrix{ij}(end:-1:1)],tmp(:),'b');
set(hp,'FaceAlpha',[0.5])
plot(a(1:2),[0 0],'r')
hold off,
axis([max(1,a(1)) a(2:4)])
box on,
set(gca,'xtick',sort(time_matrix{ij}))
itmp = min(itmp);
title([endo_prior_restrictions.irf{itmp,1},' vs ',endo_prior_restrictions.irf{itmp,2}],'interpreter','none'),
end
end
dyn_saveas(h1,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],DynareOptions);
if ~DynareOptions.nograph,
dyn_saveas(h1,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],DynareOptions);
end
skipline()
end
if ~isempty(indx_moment)
skipline()
disp('Deleting old MOMENT calibration plots ...')
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_calib*.eps']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_calib*.fig']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_calib*.pdf']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions.eps']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions.fig']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions.pdf']);
for j=1:length(a),
delete([OutputDirectoryName,filesep,a(j).name]);
end
disp('done !')
skipline()
options_mcf.param_names = char(BayesInfo.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);
plot_indx = NaN(nbr_moment_couples,1);
time_matrix=cell(nbr_moment_couples,1);
indx_moment_matrix=zeros(length(irestrictions),nbr_moment_couples);
moment_matrix=cell(nbr_moment_couples,1);
moment_mean=cell(nbr_moment_couples,1);
moment_median=cell(nbr_moment_couples,1);
moment_var=cell(nbr_moment_couples,1);
moment_HPD=cell(nbr_moment_couples,1);
moment_distrib=cell(nbr_moment_couples,1);
% For single legend search which has maximum nbr of restrictions
% For single legend search which has maximum nbr of restrictions
maxijv=0;
for ij=1:nbr_moment_restrictions
if length(endo_prior_restrictions.moment{ij,3})>maxijv
@ -262,18 +360,22 @@ if ~isempty(indx_moment)
plot_indx(ij) = find(strcmp(moment_couples,all_moment_couples(ij,:)));
time_matrix{plot_indx(ij)} = [time_matrix{plot_indx(ij)} endo_prior_restrictions.moment{ij,3}];
end
iplot_indx = ones(size(plot_indx));
indx_moment = indx_moment(irestrictions,:);
h2=dyn_figure(DynareOptions,'name',[type ' evaluation of moment restrictions']);
nrow=ceil(sqrt(nbr_moment_couples));
ncol=nrow;
if nrow*(nrow-1)>nbr_moment_couples,
ncol=nrow-1;
if ~DynareOptions.nograph,
h2=dyn_figure(DynareOptions,'name',[type ' evaluation of moment restrictions']);
nrow=ceil(sqrt(nbr_moment_couples));
ncol=nrow;
if nrow*(nrow-1)>nbr_moment_couples,
ncol=nrow-1;
end
end
for ij=1:nbr_moment_restrictions,
mat_moment{ij}=mat_moment{ij}(irestrictions,:);
moment_matrix{plot_indx(ij)} = [moment_matrix{plot_indx(ij)} mat_moment{ij}];
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);
@ -288,82 +390,113 @@ if ~isempty(indx_moment)
if size(mat_moment{ij},2)>1,
leg = [leg,':' ,num2str(endo_prior_restrictions.moment{ij,3}(end))];
aleg = [aleg,'_' ,num2str(endo_prior_restrictions.moment{ij,3}(end))];
iplot_indx(ij)=0;
end
if length(time_matrix{plot_indx(ij)})==1,
figure(h2),
if ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1,
set(0,'currentfigure',h2);
subplot(nrow,ncol,plot_indx(ij)),
hc = cumplot(mat_moment{ij}(:,ik));
set(hc,'color','k','linewidth',2)
hold all,
a=axis; delete(hc),
% hist(mat_moment{ij}),
a=axis;
x1val=max(endo_prior_restrictions.moment{ij,4}(1),a(1));
x2val=min(endo_prior_restrictions.moment{ij,4}(2),a(2));
hp = patch([x1val x2val x2val x1val],a([3 3 4 4]),'b');
set(hp,'FaceAlpha', 0.5)
set(hp,'FaceColor', [0.7 0.8 1])
hold all,
hc = cumplot(mat_moment{ij}(:,ik));
set(hc,'color','k','linewidth',2)
hold off,
title([endo_prior_restrictions.moment{ij,1},' vs ',endo_prior_restrictions.moment{ij,2},'(',leg,')'],'interpreter','none'),
% if ij==maxij
% leg1 = num2str(endo_prior_restrictions.moment{ij,3}(:));
% [legend_h,object_h,plot_h,text_strings]=legend(leg1);
% Position=get(legend_h,'Position');Position(1:2)=[-0.055 0.95-Position(4)];
% set(legend_h,'Position',Position);
% end
% if ij==maxij
% leg1 = num2str(endo_prior_restrictions.moment{ij,3}(:));
% [legend_h,object_h,plot_h,text_strings]=legend(leg1);
% Position=get(legend_h,'Position');Position(1:2)=[-0.055 0.95-Position(4)];
% set(legend_h,'Position',Position);
% end
end
indx1 = find(indx_moment(:,ij)==0);
indx2 = find(indx_moment(:,ij)~=0);
atitle0=[endo_prior_restrictions.moment{ij,1},' vs ',endo_prior_restrictions.moment{ij,2}, '(', leg,')'];
fprintf(['%4.1f%% of the prior support matches MOMENT ',atitle0,' inside [%4.1f, %4.1f]\n'],length(indx1)/length(irestrictions)*100,endo_prior_restrictions.moment{ij,4})
fprintf(['%4.1f%% of the ',type,' support matches MOMENT ',atitle0,' inside [%4.1f, %4.1f]\n'],length(indx1)/length(irestrictions)*100,endo_prior_restrictions.moment{ij,4})
% aname=[type '_moment_calib_',int2str(ij)];
aname=[type '_moment_calib_',endo_prior_restrictions.moment{ij,1},'_vs_',endo_prior_restrictions.moment{ij,2},'_',aleg];
atitle=[type ' MOMENT Calib: Parameter(s) driving ',endo_prior_restrictions.moment{ij,1},' vs ',endo_prior_restrictions.moment{ij,2}, '(', leg,')'];
options_mcf.amcf_name = aname;
options_mcf.amcf_title = atitle;
options_mcf.beha_title = 'moment prior restriction';
options_mcf.nobeha_title = 'NO moment prior restriction';
options_mcf.beha_title = 'moment restriction';
options_mcf.nobeha_title = 'NO moment restriction';
options_mcf.title = atitle0;
if ~isempty(indx1) && ~isempty(indx2)
mcf_analysis(xmat, indx1, indx2, options_mcf, DynareOptions);
end
% [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0);
% indplot=find(proba<pvalue_ks);
% if ~isempty(indplot)
% stab_map_1(xmat, indx1, indx2, aname, 1, indplot, OutputDirectoryName,[],atitle);
% end
% [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0);
% indplot=find(proba<pvalue_ks);
% if ~isempty(indplot)
% stab_map_1(xmat, indx1, indx2, aname, 1, indplot, OutputDirectoryName,[],atitle);
% end
end
figure(h2);
for ij=1:nbr_moment_couples,
if length(time_matrix{ij})>1,
subplot(nrow,ncol, ij)
itmp = (find(plot_indx==ij));
plot(time_matrix{ij},[max(moment_matrix{ij})' min(moment_matrix{ij})'],'k--','linewidth',2)
hold on,
plot(time_matrix{ij},moment_median{ij},'k','linewidth',2)
plot(time_matrix{ij},[moment_distrib{ij}],'k-')
a=axis;
tmp=[];
for ir=1:length(itmp),
for it=1:length(endo_prior_restrictions.moment{itmp(ir),3})
temp_index = find(time_matrix{ij}==endo_prior_restrictions.moment{itmp(ir),3}(it));
tmp(temp_index,:) = endo_prior_restrictions.moment{itmp(ir),4};
if ~DynareOptions.nograph
itmp = (find(plot_indx==ij));
set(0,'currentfigure',h2);
subplot(nrow,ncol, ij)
htmp = plot(time_matrix{ij},[max(moment_matrix{ij})' min(moment_matrix{ij})'],'k--','linewidth',2);
a=axis;
delete(htmp);
tmp=[];
for ir=1:length(itmp),
for it=1:length(endo_prior_restrictions.moment{itmp(ir),3})
temp_index = find(time_matrix{ij}==endo_prior_restrictions.moment{itmp(ir),3}(it));
tmp(temp_index,:) = endo_prior_restrictions.moment{itmp(ir),4};
end
end
% tmp = cell2mat(endo_prior_restrictions.moment(itmp,4));
tmp(isinf(tmp(:,1)),1)=a(3);
tmp(isinf(tmp(:,2)),2)=a(4);
hp = patch([time_matrix{ij} time_matrix{ij}(end:-1:1)],[tmp(:,1); tmp(end:-1:1,2)],'b');
set(hp,'FaceColor',[0.7 0.8 1])
hold on,
plot(time_matrix{ij},[max(moment_matrix{ij})' min(moment_matrix{ij})'],'k--','linewidth',2)
plot(time_matrix{ij},moment_median{ij},'k','linewidth',2)
plot(time_matrix{ij},[moment_distrib{ij}],'k-')
plot(a(1:2),[0 0],'r')
hold off,
axis(a)
box on,
set(gca,'xtick',sort(time_matrix{ij}))
itmp = min(itmp);
title([endo_prior_restrictions.moment{itmp,1},' vs ',endo_prior_restrictions.moment{itmp,2}],'interpreter','none'),
end
if any(iplot_indx.*plot_indx==ij),
% MCF of the couples with logical AND
itmp = min(find(plot_indx==ij));
indx1 = find(indx_moment_matrix(:,ij)==0);
indx2 = find(indx_moment_matrix(:,ij)~=0);
leg = num2str(time_matrix{ij}(1));
leg = [leg '...' num2str(time_matrix{ij}(end))];
aleg = 'ALL';
atitle0=[endo_prior_restrictions.moment{itmp,1},' vs ',endo_prior_restrictions.moment{itmp,2}, '(', leg,')'];
fprintf(['%4.1f%% of the ',type,' support matches MOMENT restrictions ',atitle0,'\n'],length(indx1)/length(irestrictions)*100)
% aname=[type '_moment_calib_',int2str(ij)];
aname=[type '_moment_calib_',endo_prior_restrictions.moment{itmp,1},'_vs_',endo_prior_restrictions.moment{itmp,2},'_',aleg];
atitle=[type ' MOMENT Calib: Parameter(s) driving ',endo_prior_restrictions.moment{itmp,1},' vs ',endo_prior_restrictions.moment{itmp,2}, '(', leg,')'];
options_mcf.amcf_name = aname;
options_mcf.amcf_title = atitle;
options_mcf.beha_title = 'moment restriction';
options_mcf.nobeha_title = 'NO moment restriction';
options_mcf.title = atitle0;
if ~isempty(indx1) && ~isempty(indx2)
mcf_analysis(xmat, indx1, indx2, options_mcf, DynareOptions);
end
end
% tmp = cell2mat(endo_prior_restrictions.moment(itmp,4));
tmp(isinf(tmp(:,1)),1)=a(3);
tmp(isinf(tmp(:,2)),2)=a(4);
hp = patch([time_matrix{ij} time_matrix{ij}(end:-1:1)],tmp(:),'b');
set(hp,'FaceAlpha',[0.5])
plot(a(1:2),[0 0],'r')
hold off,
axis(a)
box on,
set(gca,'xtick',sort(time_matrix{ij}))
itmp = min(itmp);
title([endo_prior_restrictions.moment{itmp,1},' vs ',endo_prior_restrictions.moment{itmp,2}],'interpreter','none'),
end
end
dyn_saveas(h2,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],DynareOptions);
if ~DynareOptions.nograph,
dyn_saveas(h2,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],DynareOptions);
end
skipline()
end
return

View File

@ -1,4 +1,4 @@
function mcf_analysis(lpmat, ibeha, inobeha, options_mcf, DynareOptions)
function indmcf = mcf_analysis(lpmat, ibeha, inobeha, options_mcf, DynareOptions)
%
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
@ -53,7 +53,7 @@ if length(ibeha)>10 && length(inobeha)>10,
indcorr = indcorr(~ismember(indcorr(:),indmcf));
indmcf = [indmcf(:); indcorr(:)];
end
if ~isempty(indmcf)
if ~isempty(indmcf) && ~DynareOptions.nograph,
skipline()
scatter_mcf(lpmat(ibeha,indmcf),lpmat(inobeha,indmcf), param_names(indmcf,:), ...
'.', [fname_,'_',amcf_name], OutputDirectoryName, amcf_title,[], DynareOptions, ...

View File

@ -53,21 +53,31 @@ alpha2 = options_gsa_.alpha2_redform;
alpha2=0;
pvalue_ks = options_gsa_.ksstat_redform;
pvalue_corr = options_gsa_.alpha2_redform;
pnames = M_.param_names(estim_params_.param_vals(:,1),:);
fname_ = M_.fname;
bounds = prior_bounds(bayestopt_,options_);
pnames = M_.param_names(estim_params_.param_vals(:,1),:);
if nargin==0,
dirname='';
end
if pprior
load([dirname,filesep,M_.fname,'_prior'],'lpmat', 'lpmat0', 'istable','T');
adir=[dirname filesep 'redform_stab'];
adir=[dirname filesep 'redform_prior'];
type = 'prior';
else
load([dirname,filesep,M_.fname,'_mc'],'lpmat', 'lpmat0', 'istable','T');
adir=[dirname filesep 'redform_mc'];
type = 'mc';
end
options_mcf.pvalue_ks = options_gsa_.ksstat_redform;
options_mcf.pvalue_corr = options_gsa_.alpha2_redform;
options_mcf.alpha2 = options_gsa_.alpha2_redform;
options_mcf.param_names = pnames;
options_mcf.fname_ = M_.fname;
options_mcf.OutputDirectoryName = adir;
if ~exist('T')
stab_map_(dirname,options_gsa_);
if pprior
@ -106,6 +116,15 @@ else
pd = [bayestopt_.p6(offset+1:end) bayestopt_.p7(offset+1:end) bayestopt_.p3(offset+1:end) bayestopt_.p4(offset+1:end)];
end
options_map.param_names = pnames;
options_map.fname_ = M_.fname;
options_map.OutputDirectoryName = adir;
options_map.iload = iload;
options_map.log_trans = ilog;
options_map.prior_range = options_gsa_.prior_range;
options_map.pshape = pshape;
options_map.pd = pd;
nsok = length(find(M_.lead_lag_incidence(M_.maximum_lag,:)));
lpmat=[];
lpmat0=[];
@ -119,7 +138,7 @@ for j=1:size(anamendo,1)
namexo=deblank(anamexo(jx,:));
iexo=strmatch(namexo,M_.exo_names,'exact');
skipline()
disp(['[', namendo,' vs. ',namexo,']'])
disp(['[', namendo,' vs ',namexo,']'])
if ~isempty(iexo),
@ -128,7 +147,7 @@ for j=1:size(anamendo,1)
if (max(y0)-min(y0))>1.e-10,
if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph,
ifig=ifig+1;
hfig = dyn_figure(options_,'name',['Reduced Form Mapping: ', namendo,' vs. shocks ',int2str(ifig)]);
hfig = dyn_figure(options_,'name',['Reduced Form Mapping: ', namendo,' vs shocks ',int2str(ifig)]);
iplo=0;
end
iplo=iplo+1;
@ -139,7 +158,15 @@ for j=1:size(anamendo,1)
if isempty(dir(xdir0))
mkdir(xdir0)
end
si(:,js) = redform_private(x0, y0, pshape, pd, iload, pnames, namendo, namexo, xdir0, options_gsa_);
atitle0=['Reduced Form Mapping (ANOVA) for ',namendo,' vs ', namexo];
aname=[type '_' namendo '_vs_' namexo];
atitle=[type ' Reduced Form Mapping (ANOVA): Parameter(s) driving ',namendo,' vs ',namexo];
options_map.amap_name = aname;
options_map.amap_title = atitle;
options_map.figtitle = atitle0;
options_map.title = [namendo,' vs ', namexo];
options_map.OutputDirectoryName = xdir0;
si(:,js) = redform_private(x0, y0, options_map, options_);
else
iy=find( (y0>threshold(1)) & (y0<threshold(2)));
iyc=find( (y0<=threshold(1)) | (y0>=threshold(2)));
@ -148,41 +175,65 @@ for j=1:size(anamendo,1)
mkdir(xdir)
end
if ~options_.nograph,
hf=dyn_figure(options_,'name',['Reduced Form Mapping: ',namendo,' vs. ', namexo]); hist(y0,30), title([namendo,' vs. ', namexo],'interpreter','none')
dyn_saveas(hf,[xdir,filesep, namendo,'_vs_', namexo],options_);
hf=dyn_figure(options_,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs ', namexo]);
hc = cumplot(y0);
a=axis; delete(hc);
% hist(mat_moment{ij}),
x1val=max(threshold(1),a(1));
x2val=min(threshold(2),a(2));
hp = patch([x1val x2val x2val x1val],a([3 3 4 4]),'b');
set(hp,'FaceColor', [0.7 0.8 1])
hold all,
hc = cumplot(y0);
set(hc,'color','k','linewidth',2)
hold off,
title([namendo,' vs ', namexo ' - threshold [' num2str(threshold(1)) ' ' num2str(threshold(2)) ']'],'interpreter','none')
dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namexo],options_);
end
% if ~isempty(iy),
% si(:,js) = redform_private(x0(iy,:), y0(iy), pshape, pd, iload, pnames, namendo, namexo, xdir, options_gsa_);
% else
si(:,js) = NaN(np,1);
% end
if length(iy)>size(x0,2) && length(iyc)>size(x0,2)
delete([xdir, '/*threshold*.*'])
[proba, dproba] = stab_map_1(x0, iy, iyc, 'threshold',0);
% indsmirnov = find(dproba>ksstat);
indsmirnov = find(proba<pvalue_ks);
for jp=1:length(indsmirnov),
disp([M_.param_names(estim_params_.param_vals(indsmirnov(jp),1),:),' d-stat = ', num2str(dproba(indsmirnov(jp)),'%1.3f'),' p-value = ', num2str(proba(indsmirnov(jp)),'%1.3f')])
end
skipline()
stab_map_1(x0, iy, iyc, 'threshold',pvalue_ks,indsmirnov,xdir,[],['Reduced Form Mapping (Threshold) for ', namendo,' vs. lagged ', namexo]);
stab_map_2(x0(iy,:),alpha2,pvalue_corr,'inside_threshold',xdir,[],['Reduced Form Mapping (Inside Threshold)for ', namendo,' vs. lagged ', namexo])
stab_map_2(x0(iyc,:),alpha2,pvalue_corr,'outside_threshold',xdir,[],['Reduced Form Mapping (Outside Threshold) for ', namendo,' vs. lagged ', namexo])
delete([xdir, '/*threshold*.*'])
atitle0=['Reduced Form Mapping (Monte Carlo Filtering) for ',namendo,' vs ', namexo];
aname=[type '_' namendo '_vs_' namexo '_threshold'];
atitle=[type ' Reduced Form Mapping (Monte Carlo Filtering): Parameter(s) driving ',namendo,' vs ',namexo];
options_mcf.amcf_name = aname;
options_mcf.amcf_title = atitle;
options_mcf.beha_title = 'inside threshold';
options_mcf.nobeha_title = 'outside threshold';
options_mcf.title = atitle0;
options_mcf.OutputDirectoryName = xdir;
if ~isempty(iy) && ~isempty(iyc)
fprintf(['%4.1f%% of the ',type,' support matches ',atitle0,'\n'],length(iy)/length(y0)*100)
icheck = mcf_analysis(x0, iy, iyc, options_mcf, options_);
lpmat=x0(iy,:);
if nshocks,
lpmat0=xx0(iy,:);
end
istable=[1:length(iy)];
save([xdir,filesep,'threshold.mat'],'lpmat','lpmat0','istable','y0','x0','xx0','iy','iyc')
save([xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namexo '_threshold' ],'lpmat','lpmat0','istable','y0','x0','xx0','iy','iyc')
lpmat=[]; lpmat0=[]; istable=[];
else
icheck=[];
end
if isempty(icheck),
atitle0=['Monte Carlo Filtering for ',namendo,' vs ', namexo];
options_mcf.title = atitle0;
indmcf = redform_mcf(y0, x0, options_mcf, options_);
end
end
else
[yy, xdir] = log_trans_(y0,xdir0);
if isempty(dir(xdir))
mkdir(xdir)
end
silog(:,js) = redform_private(x0, yy, pshape, pd, iload, pnames, namendo, namexo, xdir, options_gsa_);
atitle0=['Reduced Form Mapping (ANOVA) for log-transformed ',namendo,' vs ', namexo];
aname=[type '_' namendo '_vs_' namexo];
atitle=[type ' Reduced Form Mapping (ANOVA): Parameter(s) driving ',namendo,' vs ',namexo];
options_map.amap_name = aname;
options_map.amap_title = atitle;
options_map.figtitle = atitle0;
options_map.title = ['log(' namendo ' vs ' namexo ')'];
options_map.OutputDirectoryName = xdir0;
silog(:,js) = redform_private(x0, y0, options_map, options_);
end
if isempty(threshold) && ~options_.nograph,
@ -203,7 +254,7 @@ for j=1:size(anamendo,1)
for ip=1:min(np,10),
text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
title([logflag,' ',namendo,' vs. ',namexo],'interpreter','none')
title([logflag,' ',namendo,' vs ',namexo],'interpreter','none')
if iplo==9,
dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_);
end
@ -221,7 +272,7 @@ for j=1:size(anamendo,1)
namlagendo=deblank(anamlagendo(je,:));
ilagendo=strmatch(namlagendo,M_.endo_names(oo_.dr.order_var(M_.nstatic+1:M_.nstatic+nsok),:),'exact');
skipline()
disp(['[', namendo,' vs. lagged ',namlagendo,']'])
disp(['[', namendo,' vs lagged ',namlagendo,']'])
if ~isempty(ilagendo),
%y0=squeeze(T(iendo,ilagendo,istable));
@ -229,7 +280,7 @@ for j=1:size(anamendo,1)
if (max(y0)-min(y0))>1.e-10,
if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph,
ifig=ifig+1;
hfig = dyn_figure(options_,'name',['Reduced Form Mapping: ' namendo,' vs. lags ',int2str(ifig)]);
hfig = dyn_figure(options_,'name',['Reduced Form Mapping: ' namendo,' vs lags ',int2str(ifig)]);
iplo=0;
end
iplo=iplo+1;
@ -240,7 +291,15 @@ for j=1:size(anamendo,1)
if isempty(dir(xdir0))
mkdir(xdir0)
end
si(:,js) = redform_private(x0, y0, pshape, pd, iload, pnames, namendo, namlagendo, xdir0, options_gsa_);
atitle0=['Reduced Form Mapping (ANOVA) for ',namendo,' vs ', namlagendo];
aname=[type '_' namendo '_vs_' namlagendo];
atitle=[type ' Reduced Form Mapping (ANOVA): Parameter(s) driving ',namendo,' vs ',namlagendo];
options_map.amap_name = aname;
options_map.amap_title = atitle;
options_map.figtitle = atitle0;
options_map.title = [namendo,' vs ', namlagendo];
options_map.OutputDirectoryName = xdir0;
si(:,js) = redform_private(x0, y0, options_map, options_);
else
iy=find( (y0>threshold(1)) & (y0<threshold(2)));
iyc=find( (y0<=threshold(1)) | (y0>=threshold(2)));
@ -248,41 +307,67 @@ for j=1:size(anamendo,1)
if isempty(dir(xdir))
mkdir(xdir)
end
% if ~isempty(iy)
% si(:,js) = redform_private(x0(iy,:), y0(iy), pshape, pd, iload, pnames, namendo, namlagendo, xdir, options_gsa_);
% end
if ~options_.nograph,
hf=dyn_figure(options_,'name',['Reduced Form Mapping: ',namendo,' vs. lagged ', namlagendo]); hist(y0,30), title([namendo,' vs. lagged ', namlagendo],'interpreter','none')
dyn_saveas(hf,[xdir,filesep, namendo,'_vs_', namlagendo],options_);
hf=dyn_figure(options_,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs lagged ', namlagendo]);
hc = cumplot(y0);
a=axis; delete(hc);
% hist(mat_moment{ij}),
x1val=max(threshold(1),a(1));
x2val=min(threshold(2),a(2));
hp = patch([x1val x2val x2val x1val],a([3 3 4 4]),'b');
set(hp,'FaceColor', [0.7 0.8 1])
hold all,
hc = cumplot(y0);
set(hc,'color','k','linewidth',2)
hold off,
title([namendo,' vs lagged ', namlagendo ' - threshold [' num2str(threshold(1)) ' ' num2str(threshold(2)) ']'],'interpreter','none')
dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo],options_);
end
if length(iy)>size(x0,2) && length(iyc)>size(x0,2),
delete([xdir, '/*threshold*.*'])
[proba, dproba] = stab_map_1(x0, iy, iyc, 'threshold',0);
% indsmirnov = find(dproba>ksstat);
indsmirnov = find(proba<pvalue_ks);
for jp=1:length(indsmirnov),
disp([M_.param_names(estim_params_.param_vals(indsmirnov(jp),1),:),' d-stat = ', num2str(dproba(indsmirnov(jp)),'%1.3f'),' p-value = ', num2str(proba(indsmirnov(jp)),'%1.3f')])
end
skipline()
stab_map_1(x0, iy, iyc, 'threshold',pvalue_ks,indsmirnov,xdir,[],['Reduced Form Mapping (Threshold) for ', namendo,' vs. lagged ', namlagendo]);
stab_map_2(x0(iy,:),alpha2,pvalue_corr,'inside_threshold',xdir,[],['Reduced Form Mapping (Inside Threshold) for ', namendo,' vs. lagged ', namlagendo])
stab_map_2(x0(iyc,:),alpha2,pvalue_corr,'outside_threshold',xdir,[],['Reduced Form Mapping (Outside Threshold) for ', namendo,' vs. lagged ', namlagendo])
delete([xdir, '/*threshold*.*'])
atitle0=['Reduced Form Mapping (Monte Carlo Filtering) for ',namendo,' vs ', namlagendo];
aname=[type '_' namendo '_vs_' namlagendo '_threshold'];
atitle=[type ' Reduced Form Mapping (Monte Carlo Filtering): Parameter(s) driving ',namendo,' vs ',namlagendo];
options_mcf.amcf_name = aname;
options_mcf.amcf_title = atitle;
options_mcf.beha_title = 'inside threshold';
options_mcf.nobeha_title = 'outside threshold';
options_mcf.title = atitle0;
options_mcf.OutputDirectoryName = xdir;
if ~isempty(iy) && ~isempty(iyc)
fprintf(['%4.1f%% of the ',type,' support matches ',atitle0,'\n'],length(iy)/length(y0)*100)
icheck = mcf_analysis(x0, iy, iyc, options_mcf, options_);
lpmat=x0(iy,:);
if nshocks,
lpmat0=xx0(iy,:);
end
istable=[1:length(iy)];
save([xdir,filesep,'threshold.mat'],'lpmat','lpmat0','istable','y0','x0','xx0','iy','iyc')
save([xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo '_threshold' ],'lpmat','lpmat0','istable','y0','x0','xx0','iy','iyc')
lpmat=[]; lpmat0=[]; istable=[];
else
icheck = [];
end
if isempty(icheck),
atitle0=['Monte Carlo Filtering for ',namendo,' vs ', namlagendo];
options_mcf.title = atitle0;
indmcf = redform_mcf(y0, x0, options_mcf, options_);
end
end
else
[yy, xdir] = log_trans_(y0,xdir0);
if isempty(dir(xdir))
mkdir(xdir)
end
silog(:,js) = redform_private(x0, yy, pshape, pd, iload, pnames, namendo, namlagendo, xdir, options_gsa_);
atitle0=['Reduced Form Mapping (ANOVA) for log-transformed ',namendo,' vs ', namlagendo];
aname=[type '_' namendo '_vs_' namlagendo];
atitle=[type ' Reduced Form Mapping (ANOVA): Parameter(s) driving ',namendo,' vs ',namlagendo];
options_map.amap_name = aname;
options_map.amap_title = atitle;
options_map.figtitle = atitle0;
options_map.title = ['log(' namendo ' vs ' namlagendo ')'];
options_map.OutputDirectoryName = xdir0;
silog(:,js) = redform_private(x0, y0, options_map, options_);
end
if isempty(threshold) && ~options_.nograph
@ -303,7 +388,7 @@ for j=1:size(anamendo,1)
for ip=1:min(np,10),
text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
title([logflag,' ',namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none')
title([logflag,' ',namendo,' vs ',namlagendo,'(-1)'],'interpreter','none')
if iplo==9,
dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_);
end
@ -351,13 +436,17 @@ if isempty(threshold) && ~options_.nograph,
end
end
function si = redform_private(x0, y0, pshape, pd, iload, pnames, namy, namx, xdir, opt_gsa)
global bayestopt_ options_
function si = redform_private(x0, y0, options_map, options_)
% opt_gsa=options_.opt_gsa;
np=size(x0,2);
x00=x0;
if opt_gsa.prior_range,
ilog = options_map.log_trans;
iload = options_map.iload;
pnames = options_map.param_names;
pd = options_map.pd;
pshape = options_map.pshape;
xdir = options_map.OutputDirectoryName;
if options_map.prior_range,
for j=1:np,
x0(:,j)=(x0(:,j)-pd(j,3))./(pd(j,4)-pd(j,3));
end
@ -365,61 +454,286 @@ else
x0=priorcdf(x0,pshape, pd(:,1), pd(:,2), pd(:,3), pd(:,4));
end
fname=[xdir,'/map'];
if ilog,
fname=[xdir filesep options_map.fname_ '_' options_map.amap_name '_log'];
else
fname=[xdir filesep options_map.fname_ '_' options_map.amap_name];
end
if iload==0,
if isempty(dir(xdir))
mkdir(xdir)
end
if ~options_.nograph,
hfig=dyn_figure(options_,'name',['Reduced Form Mapping: ', namy,' vs. ', namx]); hist(y0,30), title([namy,' vs. ', namx],'interpreter','none')
dyn_saveas(hfig,[xdir,filesep, namy,'_vs_', namx],options_);
end
% gsa_ = gsa_sdp_dyn(y0, x0, -2, [],[],[],1,fname, pnames);
nrun=length(y0);
nest=min(250,nrun);
nfit=min(1000,nrun);
% dotheplots = (nfit<=nest);
gsa_ = gsa_sdp(y0(1:nest), x0(1:nest,:), 2, [],[-1 -1 -1 -1 -1 0],[],0,[fname,'_est'], pnames);
if nfit>nest,
gsa_ = gsa_sdp(y0(1:nfit), x0(1:nfit,:), -2, gsa_.nvr*nest^3/nfit^3,[-1 -1 -1 -1 -1 0],[],0,fname, pnames);
% gsa_ = gsa_sdp(y0(1:nest), x0(1:nest,:), 2, [],[-1 -1 -1 -1 -1 0],[],0,[fname,'_est'], pnames);
[ys,is] = sort(y0);
istep = ceil(nrun/nest);
iest = is(floor(istep/2):istep:end);
nest = length(iest);
irest = is(setdiff([1:nrun],[floor(istep/2):istep:nrun]));
istep = ceil(length(irest)/(nfit-nest));
ifit = union(iest, irest(1:istep:end));
if ~ismember(irest(end),ifit),
ifit = union(ifit, irest(end));
end
nfit=length(ifit);
% ifit = union(iest, irest(randperm(nrun-nest,nfit-nest)));
% ifit = iest;
% nfit=nest;
ipred = setdiff([1:nrun],ifit);
if ilog,
[y1, tmp, isig, lam] = log_trans_(y0(iest));
y1 = log(y0*isig+lam);
end
save([fname,'.mat'],'gsa_')
[sidum, iii]=sort(-gsa_.si);
gsa_.x0=x00(1:nfit,:);
if ~options_.nograph,
hfig=gsa_sdp_plot(gsa_,fname,pnames,iii(1:min(12,np)));
if options_.nodisplay
close(hfig);
hfig=dyn_figure(options_,'name',options_map.figtitle);
subplot(221)
if ilog,
hist(y1,30),
else
hist(y0,30),
end
title(options_map.title,'interpreter','none')
subplot(222)
if ilog,
hc = cumplot(y1);
else
hc = cumplot(y0);
end
set(hc,'color','k','linewidth',2)
title([options_map.title ' CDF'],'interpreter','none')
end
gsa_.x0=x0(1:nfit,:);
gsa0 = ss_anova(y0(iest), x0(iest,:), 1);
if ilog,
[gsa22, gsa1, gsax] = ss_anova_log(y1(iest), x0(iest,:), isig, lam, gsa0);
end
% if (gsa1.out.bic-gsa0.out.bic) < 10,
% y00=y0;
% gsa00=gsa0;
% gsa0=gsa1;
% y0=y1;
% ilog=1;
% end
if nfit>nest,
% gsa_ = gsa_sdp(y0(1:nfit), x0(1:nfit,:), -2, gsa_.nvr*nest^3/nfit^3,[-1 -1 -1 -1 -1 0],[],0,fname, pnames);
nvr = gsa0.nvr*nest^3/nfit^3;
nvr(gsa0.stat<2) = gsa0.nvr(gsa0.stat<2)*nest^5/nfit^5;
gsa_ = ss_anova(y0(ifit), x0(ifit,:), 1, 0, 2, nvr);
if ilog
gsa0 = gsa_;
nvr1 = gsa1.nvr*nest^3/nfit^3;
nvr1(gsa1.stat<2) = gsa1.nvr(gsa1.stat<2)*nest^5/nfit^5;
nvrx = gsax.nvr*nest^3/nfit^3;
nvrx(gsax.stat<2) = gsax.nvr(gsax.stat<2)*nest^5/nfit^5;
[gsa22, gsa1, gsax] = ss_anova_log(y1(ifit), x0(ifit,:), isig, lam, gsa0, [nvr1' nvrx']);
% gsa1 = ss_anova(y1(ifit), x0(ifit,:), 1, 0, 2, nvr);
% gsa2=gsa1;
% gsa2.y = gsa0.y;
% gsa2.fit = (exp(gsa1.fit)-lam)*isig;
% gsa2.f0 = mean(gsa2.fit);
% gsa2.out.SSE = sum((gsa2.fit-gsa2.y).^2);
% gsa2.out.bic = gsa2.out.bic-nest*log(gsa1.out.SSE)+nest*log(gsa2.out.SSE);
% gsa2.r2 = 1-cov(gsa2.fit-gsa2.y)/cov(gsa2.y);
% for j=1:np,
% gsa2.fs(:,j) = exp(gsa1.fs(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0;
% gsa2.f(:,j) = exp(gsa1.f(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0;
% gsa2.si(j) = var(gsa2.f(:,j))/var(gsa2.y);
% end
% nvr = gsax.nvr*nest^3/nfit^3;
% nvr(gsax.stat<2) = gsax.nvr(gsax.stat<2)*nest^5/nfit^5;
% gsax = ss_anova([gsa2.y-gsa2.fit], x0(ifit,:), 1, 0, 2, nvr);
% gsa22=gsa2;
% gsa22.fit = gsa2.fit+gsax.fit;
% gsa22.f0 = mean(gsa22.fit);
% gsa22.out.SSE = sum((gsa22.fit-gsa22.y).^2);
% gsa22.out.bic = nest*log(gsa22.out.SSE/nest) + (gsax.out.df+gsa2.out.df-1)*log(nest);
% gsa22.r2 = 1-sum((gsa22.fit-gsa22.y).^2)/sum((gsa22.y-mean(gsa22.y)).^2);
% for j=1:np,
% gsa22.fs(:,j) = gsa2.fs(:,j)+gsax.fs(:,j);
% gsa22.f(:,j) = gsa2.f(:,j)+gsax.f(:,j);
% gsa22.si(j) = var(gsa22.f(:,j))/var(gsa22.y);
% end
gsa_ = gsa22;
end
else
if ilog
gsa_ = gsa22;
else
gsa_ = gsa0;
end
end
save([fname,'_map.mat'],'gsa_')
[sidum, iii]=sort(-gsa_.si);
gsa_.x0=x00(ifit,:);
if ~options_.nograph,
hmap=gsa_sdp_plot(gsa_,[fname '_map'],pnames,iii(1:min(12,np)));
set(hmap,'name',options_map.amap_title);
end
gsa_.x0=x0(ifit,:);
% copyfile([fname,'_est.mat'],[fname,'.mat'])
if ~options_.nograph,
hfig=dyn_figure(options_,'name',['Reduced Form Mapping: ' namy,'_vs_', namx,'_fit']);
plot(y0(1:nfit),[gsa_.fit y0(1:nfit)],'.'),
title([namy,' vs. ', namx,' fit'],'interpreter','none')
dyn_saveas(hfig,[xdir,filesep, namy,'_vs_', namx,'_fit'],options_);
figure(hfig);
subplot(223),
plot(y0(ifit),[gsa_.fit y0(ifit)],'.'),
r2 = gsa_.r2;
% if ilog,
% plot(y00(ifit),[log_trans_(gsa_.fit,'',isig,lam) y00(ifit)],'.'),
% r2 = 1 - cov(log_trans_(gsa_.fit,'',isig,lam)-y00(ifit))/cov(y00(ifit));
% else
% plot(y0(ifit),[gsa_.fit y0(ifit)],'.'),
% r2 = gsa_.r2;
% end
title(['Learning sample fit - R2=' num2str(r2,2)],'interpreter','none')
if nfit<nrun,
npred=[nfit+1:nrun];
yf = ss_anova_fcast(x0(npred,:), gsa_);
hfig=dyn_figure(options_,'name',['Reduced Form Mapping: ' namy,'_vs_', namx,'_pred']);
plot(y0(npred),[yf y0(npred)],'.'),
title([namy,' vs. ', namx,' pred'],'interpreter','none')
dyn_saveas(hfig,[xdir,filesep, namy,'_vs_', namx,'_pred'],options_);
if ilog,
yf = ss_anova_fcast(x0(ipred,:), gsa1);
yf = log_trans_(yf,'',isig,lam)+ss_anova_fcast(x0(ipred,:), gsax);
else
yf = ss_anova_fcast(x0(ipred,:), gsa_);
end
yn = y0(ipred);
r2 = 1-cov(yf-yn)/cov(yn);
subplot(224),
plot(yn,[yf yn],'.'),
title(['Out-of-sample prediction - R2=' num2str(r2,2)],'interpreter','none')
end
dyn_saveas(hfig,fname,options_);
if options_.nodisplay
close(hmap);
end
end
else
% gsa_ = gsa_sdp_dyn(y0, x0, 0, [],[],[],0,fname, pnames);
gsa_ = gsa_sdp(y0, x0, 0, [],[],[],0,fname, pnames);
% gsa_ = gsa_sdp(y0, x0, 0, [],[],[],0,fname, pnames);
load([fname,'_map.mat'],'gsa_')
if ~options_.nograph,
yf = ss_anova_fcast(x0, gsa_);
hfig=dyn_figure(options_,['Reduced Form Mapping: ' namy,'_vs_', namx,'_pred']);
hfig=dyn_figure(options_,'name',options_map.title);
plot(y0,[yf y0],'.'),
title([namy,' vs. ', namx,' pred'],'interpreter','none')
dyn_saveas(hfig,[xdir,filesep, namy,'_vs_', namx,'_pred'],options_);
title([namy,' vs ', namx,' pred'],'interpreter','none')
dyn_saveas(hfig,[fname '_pred'],options_);
end
end
% si = gsa_.multivariate.si;
si = gsa_.si;
return
function gsa2 = log2level_map(gsa1, isig, lam)
nest=length(gsa1.y);
np = size(gsa1.x0,2);
gsa2=gsa1;
gsa2.y = log_trans_(gsa1.y,'',isig,lam);
gsa2.fit = (exp(gsa1.fit)-lam)*isig;
gsa2.f0 = mean(gsa2.fit);
gsa2.out.SSE = sum((gsa2.fit-gsa2.y).^2);
gsa2.out.bic = gsa2.out.bic-nest*log(gsa1.out.SSE)+nest*log(gsa2.out.SSE);
gsa2.r2 = 1-cov(gsa2.fit-gsa2.y)/cov(gsa2.y);
for j=1:np,
gsa2.fs(:,j) = exp(gsa1.fs(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0;
gsa2.fses(:,j) = exp(gsa1.fs(:,j)+gsa1.fses(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0-gsa2.fs(:,j);
gsa2.f(:,j) = exp(gsa1.f(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0;
gsa2.si(j) = var(gsa2.f(:,j))/var(gsa2.y);
end
return
function [gsa22, gsa1, gsax] = ss_anova_log(y,x,isig,lam,gsa0,nvrs)
[nest, np]=size(x);
if nargin==6,
gsa1 = ss_anova(y, x, 1, 0, 2, nvrs(:,1));
else
gsa1 = ss_anova(y, x, 1);
end
gsa2 = log2level_map(gsa1, isig, lam);
if nargin >=5 && ~isempty(gsa0),
for j=1:np,
nvr2(j) = var(diff(gsa2.fs(:,j),2));
nvr0(j) = var(diff(gsa0.fs(:,j),2));
end
inda = find((gsa0.stat<2)&(gsa1.stat>2));
inda = inda(log10(nvr0(inda)./nvr2(inda))/2<0);
gsa1.nvr(inda)=gsa1.nvr(inda).*10.^(log10(nvr0(inda)./nvr2(inda)));
gsa1 = ss_anova(y, x, 1, 0, 2, gsa1.nvr);
gsa2 = log2level_map(gsa1, isig, lam);
end
if nargin==6,
gsax = ss_anova(gsa2.y-gsa2.fit, x, 1, 0, 2, nvrs(:,2));
else
gsax = ss_anova(gsa2.y-gsa2.fit, x, 1);
end
gsa22=gsa2;
gsa22.fit = gsa2.fit+gsax.fit;
gsa22.f0 = mean(gsa22.fit);
gsa22.out.SSE = sum((gsa22.fit-gsa22.y).^2);
gsa22.out.bic = nest*log(gsa22.out.SSE/nest) + (gsax.out.df+gsa2.out.df-1)*log(nest);
gsa22.r2 = 1-sum((gsa22.fit-gsa22.y).^2)/sum((gsa22.y-mean(gsa22.y)).^2);
for j=1:np,
gsa22.fs(:,j) = gsa2.fs(:,j)+gsax.fs(:,j);
gsa22.fses(:,j) = gsax.fses(:,j);
gsa22.f(:,j) = gsa2.f(:,j)+gsax.f(:,j);
gsa22.si(j) = var(gsa22.f(:,j))/var(gsa22.y);
end
return
function indmcf = redform_mcf(y0, x0, options_mcf, options_)
hfig=dyn_figure(options_,'name',options_mcf.amcf_title);
[post_mean, post_median, post_var, hpd_interval, post_deciles, ...
density] = posterior_moments(y0,1,0.9);
post_deciles = [-inf; post_deciles; inf];
for jt=1:10,
indy{jt}=find( (y0>post_deciles(jt)) & (y0<=post_deciles(jt+1)));
leg{jt}=[int2str(jt) '-dec'];
end
[proba, dproba] = stab_map_1(x0, indy{1}, indy{end}, [],0);
indmcf=find(proba<options_mcf.pvalue_ks);
[tmp,jtmp] = sort(proba(indmcf),2,'ascend');
indmcf = indmcf(jtmp);
nbr_par = length(indmcf);
nrow=ceil(sqrt(nbr_par+1));
ncol=nrow;
if nrow*(nrow-1)>nbr_par,
ncol=nrow-1;
end
cmap = colormap(jet(10));
for jx=1:nbr_par,
subplot(nrow,ncol,jx)
hold off
for jt=1:10,
h=cumplot(x0(indy{jt},indmcf(jx)));
set(h,'color', cmap(jt,:), 'linewidth', 2)
hold all,
end
title(options_mcf.param_names(indmcf(jx),:),'interpreter','none')
end
hleg = legend(leg);
aa=get(hleg,'Position');
aa(1)=1-aa(3)-0.02;
aa(2)=0.02;
set(hleg,'Position',aa);
if ~isoctave
annotation('textbox', [0.25,0.01,0.5,0.05], ...
'String', options_mcf.title, ...
'Color','black',...
'FontWeight','bold',...
'interpreter','none',...
'horizontalalignment','center');
end
dyn_saveas(hfig,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],options_);
return

View File

@ -158,8 +158,8 @@ for i = 1:p
end
end
if ~isoctave
annotation('textbox', [0.1,0,0.35,0.05],'String', beha_name,'Color','Blue','horizontalalignment','center');
annotation('textbox', [0.55,0,0.35,0.05],'String', non_beha_name,'Color','Red','horizontalalignment','center');
annotation('textbox', [0.1,0,0.35,0.05],'String', beha_name,'Color','Blue','horizontalalignment','center','interpreter','none');
annotation('textbox', [0.55,0,0.35,0.05],'String', non_beha_name,'Color','Red','horizontalalignment','center','interpreter','none');
end
if ~nograph,

View File

@ -267,7 +267,11 @@ if fload==0,
M_ = set_all_parameters([lpmat0(j,:) lpmat(j,:)]',estim_params_,M_);
%try stoch_simul([]);
try
[Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_,'restrict');
if ~ isempty(options_.endogenous_prior_restrictions.moment)
[Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
else
[Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_,'restrict');
end
infox(j,1)=info(1);
if infox(j,1)==0 && ~exist('T'),
dr_=oo_.dr;
@ -557,7 +561,7 @@ if length(iunstable)>0 || length(iwrong)>0,
options_mcf.beha_title = 'unique Stable Saddle-Path';
options_mcf.nobeha_title = 'NO unique Stable Saddle-Path';
options_mcf.title = 'unique solution';
mcf_analysis(lpmat, istable, itmp, options_mcf, options_)
mcf_analysis(lpmat, istable, itmp, options_mcf, options_);
if ~isempty(iindeterm),
itmp = itot(find(~ismember(itot,iindeterm)));
@ -566,7 +570,7 @@ if length(iunstable)>0 || length(iwrong)>0,
options_mcf.beha_title = 'NO indeterminacy';
options_mcf.nobeha_title = 'indeterminacy';
options_mcf.title = 'indeterminacy';
mcf_analysis(lpmat, itmp, iindeterm, options_mcf, options_)
mcf_analysis(lpmat, itmp, iindeterm, options_mcf, options_);
end
if ~isempty(ixun),
@ -576,7 +580,7 @@ if length(iunstable)>0 || length(iwrong)>0,
options_mcf.beha_title = 'NO explosive solution';
options_mcf.nobeha_title = 'explosive solution';
options_mcf.title = 'instability';
mcf_analysis(lpmat, itmp, ixun, options_mcf, options_)
mcf_analysis(lpmat, itmp, ixun, options_mcf, options_);
end
inorestriction = istable(find(~ismember(istable,irestriction))); % what went wrong beyong prior restrictions
@ -588,7 +592,7 @@ if length(iunstable)>0 || length(iwrong)>0,
options_mcf.beha_title = 'NO inability to find a solution';
options_mcf.nobeha_title = 'inability to find a solution';
options_mcf.title = 'inability to find a solution';
mcf_analysis(lpmat, itmp, iwrong, options_mcf, options_)
mcf_analysis(lpmat, itmp, iwrong, options_mcf, options_);
end
if ~isempty(irestriction),
@ -598,7 +602,7 @@ if length(iunstable)>0 || length(iwrong)>0,
options_mcf.beha_title = 'prior IRF/moment calibration';
options_mcf.nobeha_title = 'NO prior IRF/moment calibration';
options_mcf.title = 'prior restrictions';
mcf_analysis([lpmat0 lpmat], irestriction, inorestriction, options_mcf, options_)
mcf_analysis([lpmat0 lpmat], irestriction, inorestriction, options_mcf, options_);
iok = irestriction(1);
x0 = [lpmat0(iok,:)'; lpmat(iok,:)'];
else

View File

@ -85,6 +85,9 @@ if info(1)==0,
derivatives_info.DYss=dYss;
if init,
indJJ = (find(max(abs(JJ'),[],1)>1.e-8));
if isempty(indJJ) && any(any(isnan(JJ)))
error('There are NaN in the JJ matrix. Please check whether your model has units roots and you forgot to set lik_init~=1.' )
end
while length(indJJ)<nparam && nlags<10,
disp('The number of moments with non-zero derivative is smaller than the number of parameters')
disp(['Try increasing ar = ', int2str(nlags+1)])

View File

@ -49,20 +49,22 @@ old_steady_params=Model.params; %save initial parameters for check if steady sta
% % 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);
if isfield(EstimatedParameters,'param_vals') && ~isempty(EstimatedParameters.param_vals)
%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))));
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.')
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
end
if any(BayesInfo.pshape) % if Bayesian estimation
@ -87,8 +89,14 @@ if any(BayesInfo.pshape) % if Bayesian estimation
end
end
%% display warning if some parameters are still NaN
% display warning if some parameters are still NaN
test_for_deep_parameters_calibration(Model);
[lnprior, junk1,junk2,info]= priordens(xparam1,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
if info
fprintf('The prior density evaluated at the initial values is Inf for the following parameters: %s\n',BayesInfo.name{info,1})
error('The initial value of the prior is -Inf')
end
% Evaluate the likelihood.
ana_deriv = DynareOptions.analytic_derivation;

View File

@ -64,6 +64,7 @@ switch (extension)
load(basename);
case { '.xls', '.xlsx' }
[data_,names_v_]=xlsread(fullname); % Octave needs the extension explicitly
series_=0;
otherwise
error(['Unsupported extension for datafile: ' extension])
end
@ -75,27 +76,35 @@ oo_.exo_simul = [];
for i_=1:size(M_.endo_names,1)
if series_ == 1
x_ = eval(M_.endo_names(i_,:));
oo_.endo_simul = [oo_.endo_simul; x_'];
if size(x_,2)>size(x_,1) %oo_.endo_simul must be collection of row vectors
oo_.endo_simul = [oo_.endo_simul; x_];
else %transpose if column vector
oo_.endo_simul = [oo_.endo_simul; x_'];
end
else
k_ = strmatch(upper(M_.endo_names(i_,:)),names_v_,'exact');
k_ = strmatch(deblank(M_.endo_names(i_,:)),names_v_,'exact');
if isempty(k_)
error(['INITVAL_FILE: ' M_.endo_names(i_,:) ' not found'])
error(['INITVAL_FILE: ' deblank(M_.endo_names(i_,:)) ' not found'])
end
x_ = data_(:,k_);
oo_.endo_simul = [oo_.endo_simul; x_'];
oo_.endo_simul = [oo_.endo_simul; x_'];
end
end
for i_=1:size(M_.exo_names,1)
if series_ == 1
x_ = eval(M_.exo_names(i_,:) );
oo_.exo_simul = [oo_.exo_simul x_];
if size(x_,2)>size(x_,1) %oo_.endo_simul must be collection of row vectors
oo_.exo_simul = [oo_.exo_simul x_'];
else %if column vector
oo_.exo_simul = [oo_.exo_simul x_];
end
else
k_ = strmatch(upper(M_.exo_names(i_,:)),names_v_,'exact');
k_ = strmatch(deblank(M_.exo_names(i_,:)),names_v_,'exact');
if isempty(k_)
error(['INITVAL_FILE: ' M_.exo_names(i_,:) ' not found'])
error(['INITVAL_FILE: ' deblank(M_.exo_names(i_,:)) ' not found'])
end
x_ = data_(:,k_);
oo_.exo_simul = [oo_.exo_simul x_];
oo_.exo_simul = [oo_.exo_simul x_];
end
end
end

View File

@ -1,4 +1,4 @@
function [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, start, last, a, Pinf, Pstar, kalman_tol, riccati_tol, presample, T, R, Q, H, Z, mm, pp, rr)
function [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, start, last, a, Pinf, Pstar, kalman_tol, diffuse_kalman_tol, riccati_tol, presample, T, R, Q, H, Z, mm, pp, rr)
% Computes the diffuse likelihood of a state space model.
%
% INPUTS
@ -60,12 +60,12 @@ dLIK = Inf; % Default value of the log likelihood.
oldK = Inf;
s = 0;
while rank(Pinf,kalman_tol) && (t<=last)
while rank(Pinf,diffuse_kalman_tol) && (t<=last)
s = t-start+1;
v = Y(:,t)-Z*a;
Finf = Z*Pinf*Z';
if rcond(Finf) < kalman_tol
if ~all(abs(Finf(:)) < kalman_tol)
if rcond(Finf) < diffuse_kalman_tol
if ~all(abs(Finf(:)) < diffuse_kalman_tol)
% The univariate diffuse kalman filter should be used instead.
return
else

View File

@ -1,7 +1,7 @@
function [dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(data_index,number_of_observations,no_more_missing_observations, ...
Y, start, last, ...
a, Pinf, Pstar, ...
kalman_tol, riccati_tol, presample, ...
kalman_tol, diffuse_kalman_tol, riccati_tol, presample, ...
T, R, Q, H, Z, mm, pp, rr)
% Computes the diffuse likelihood of a state space model when some observations are missing.
%
@ -72,7 +72,7 @@ if isequal(H,0)
end
s = 0;
while rank(Pinf,kalman_tol) && (t<=last)
while rank(Pinf,diffuse_kalman_tol) && (t<=last)
s = t-start+1;
d_index = data_index{t};
if isempty(d_index)
@ -83,8 +83,8 @@ while rank(Pinf,kalman_tol) && (t<=last)
ZZ = Z(d_index,:);
v = Y(d_index,t)-ZZ*a;
Finf = ZZ*Pinf*ZZ';
if rcond(Finf) < kalman_tol
if ~all(abs(Finf(:)) < kalman_tol)
if rcond(Finf) < diffuse_kalman_tol
if ~all(abs(Finf(:)) < diffuse_kalman_tol)
% The univariate diffuse kalman filter should be used.
return
else

View File

@ -1,4 +1,4 @@
function [dLIK, dlikk, a, Pstar, llik] = univariate_kalman_filter_d(data_index, number_of_observations, no_more_missing_observations, Y, start, last, a, Pinf, Pstar, kalman_tol, riccati_tol, presample, T, R, Q, H, Z, mm, pp, rr)
function [dLIK, dlikk, a, Pstar, llik] = univariate_kalman_filter_d(data_index, number_of_observations, no_more_missing_observations, Y, start, last, a, Pinf, Pstar, kalman_tol, diffuse_kalman_tol, riccati_tol, presample, T, R, Q, H, Z, mm, pp, rr)
% Computes the likelihood of a state space model (initialization with diffuse steps, univariate approach).
%@info:
@ -110,7 +110,7 @@ dLIK = Inf; % Default value of the log likelihood.
oldK = Inf;
llik = zeros(smpl,pp);
newRank = rank(Pinf,kalman_tol);
newRank = rank(Pinf,diffuse_kalman_tol);
l2pi = log(2*pi);
while newRank && (t<=last)
@ -138,7 +138,7 @@ while newRank && (t<=last)
end
end
if newRank
oldRank = rank(Pinf,kalman_tol);
oldRank = rank(Pinf,diffuse_kalman_tol);
else
oldRank = 0;
end
@ -146,7 +146,7 @@ while newRank && (t<=last)
Pstar = T*Pstar*T'+QQ;
Pinf = T*Pinf*T';
if newRank
newRank = rank(Pinf,kalman_tol);
newRank = rank(Pinf,diffuse_kalman_tol);
end
if oldRank ~= newRank
disp('univariate_diffuse_kalman_filter:: T does influence the rank of Pinf!')

View File

@ -392,7 +392,7 @@ while (k < kmax) && (Psix > eps2)
Fx = Fxnew;
Phix = Phixnew;
Psix = Psixnew;
[~,DFx] = feval(FUN,x,varargin{:});
[junk,DFx] = feval(FUN,x,varargin{:});
DPhix = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset);
DPsix = DPhix'*Phix;
normDPsix = norm(DPsix);

View File

@ -1,5 +1,5 @@
function [xparams,lpd,hessian] = ...
maximize_prior_density(iparams, prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound,DynareOptions,DynareModel,EstimatedParams,DynareResults)
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)
% Maximizes the logged prior density using Chris Sims' optimization routine.
%
% INPUTS
@ -13,9 +13,9 @@ function [xparams,lpd,hessian] = ...
% OUTPUTS
% xparams [double] vector, prior mode.
% lpd [double] scalar, value of the logged prior density at the mode.
% hessian [double] matrix, Hessian matrix at the prior mode.
% hessian_mat [double] matrix, Hessian matrix at the prior mode.
% Copyright (C) 2009-2012 Dynare Team
% Copyright (C) 2009-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -32,15 +32,10 @@ function [xparams,lpd,hessian] = ...
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
number_of_estimated_parameters = length(iparams);
H0 = 1e-4*eye(number_of_estimated_parameters);
crit = 1e-7;
nit = 1000;
gradient_method = 2;
gradient_epsilon = 1e-6;
[lpd,xparams,grad,hessian,itct,fcount,retcodehat] = ...
csminwel1('minus_logged_prior_density',iparams,H0,[],crit,nit,gradient_method, gradient_epsilon, ...
prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound,DynareOptions,DynareModel,EstimatedParams,DynareResults);
[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, [], ...
prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound, ...
DynareOptions,DynareModel,EstimatedParams,DynareResults);
lpd = -lpd;

View File

@ -1,7 +1,7 @@
function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck, nruns, NewFile, MAX_nruns, d ] = ...
metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
%function [ ix2, ilogpo2, ModelName, MhDirectoryName, fblck, fline, npar, nblck, nruns, NewFile, MAX_nruns, d ] =
% metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds, dataset_,dataset_info,,options_,M_,estim_params_,bayestopt_,oo_)
%function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck, nruns, NewFile, MAX_nruns, d ] = ...
% metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
% Metropolis-Hastings initialization.
%
% INPUTS
@ -11,6 +11,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck,
% o vv [double] (p*p) matrix, posterior covariance matrix (at the mode).
% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters.
% o dataset_ data structure
% o dataset_info dataset info structure
% o options_ options structure
% o M_ model structure
% o estim_params_ estimated parameters structure
@ -18,12 +19,25 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck,
% o oo_ outputs structure
%
% OUTPUTS
% None
% o ix2 [double] (nblck*npar) vector of starting points for different chains
% o ilogpo2 [double] (nblck*1) vector of initial posterior values for different chains
% o ModelName [string] name of the mod-file
% o MetropolisFolder [string] path to the Metropolis subfolder
% o fblck [scalar] number of the first MH chain to be run (not equal to 1 in case of recovery)
% o fline [double] (nblck*1) vector of first draw in each chain (not equal to 1 in case of recovery)
% o npar [scalar] number of parameters estimated
% o nblck [scalar] Number of MCM chains requested
% o nruns [double] (nblck*1) number of draws in each chain
% o NewFile [scalar] (nblck*1) vector storing the number
% of the first MH-file to created for each chain when saving additional
% draws
% o MAX_nruns [scalar] maximum number of draws in each MH-file on the harddisk
% o d [double] (p*p) matrix, Cholesky decomposition of the posterior covariance matrix (at the mode).
%
% SPECIAL REQUIREMENTS
% None.
% Copyright (C) 2006-2013 Dynare Team
% Copyright (C) 2006-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -40,6 +54,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck,
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
%Initialize outputs
ix2 = [];
ilogpo2 = [];
ModelName = [];
@ -68,7 +83,7 @@ MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8);
d = chol(vv);
if ~options_.load_mh_file && ~options_.mh_recover
% Here we start a new metropolis-hastings, previous draws are discarded.
% Here we start a new Metropolis-Hastings, previous draws are discarded.
if nblck > 1
disp('Estimation::mcmc: Multiple chains mode.')
else
@ -80,7 +95,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
delete([BaseName '_mh*_blck*.mat']);
disp('Estimation::mcmc: Old mh-files successfully erased!')
end
% Delete old metropolis log file.
% Delete old Metropolis log file.
file = dir([ MetropolisFolder '/metropolis.log']);
if length(file)
delete([ MetropolisFolder '/metropolis.log']);
@ -128,11 +143,11 @@ if ~options_.load_mh_file && ~options_.mh_recover
if init_iter > 100 && validate == 0
disp(['Estimation::mcmc: I couldn''t get a valid initial value in 100 trials.'])
if options_.nointeractive
disp(['Estimation::mcmc: I reduce mh_init_scale by ten percent:'])
disp(['Estimation::mcmc: I reduce mh_init_scale by 10 percent:'])
options_.mh_init_scale = .9*options_.mh_init_scale;
disp(sprintf('Estimation::mcmc: Parameter mh_init_scale is now equal to %f.',options_.mh_init_scale))
else
disp(['Estimation::mcmc: You should Reduce mh_init_scale...'])
disp(['Estimation::mcmc: You should reduce mh_init_scale...'])
disp(sprintf('Estimation::mcmc: Parameter mh_init_scale is equal to %f.',options_.mh_init_scale))
options_.mh_init_scale = input('Estimation::mcmc: Enter a new value... ');
end
@ -217,7 +232,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
fclose(fidlog);
elseif options_.load_mh_file && ~options_.mh_recover
% Here we consider previous mh files (previous mh did not crash).
disp('Estimation::mcmc: I am loading past metropolis-hastings simulations...')
disp('Estimation::mcmc: I am loading past Metropolis-Hastings simulations...')
load_last_mh_history_file(MetropolisFolder, ModelName);
mh_files = dir([ MetropolisFolder filesep ModelName '_mh*.mat']);
if ~length(mh_files)
@ -238,7 +253,7 @@ elseif options_.load_mh_file && ~options_.mh_recover
nblck = past_number_of_blocks;
options_.mh_nblck = nblck;
end
% I read the last line of the last mh-file for initialization of the new metropolis-hastings simulations:
% I read the last line of the last mh-file for initialization of the new Metropolis-Hastings simulations:
LastFileNumber = record.LastFileNumber;
LastLineNumber = record.LastLineNumber;
if LastLineNumber < MAX_nruns
@ -252,7 +267,7 @@ elseif options_.load_mh_file && ~options_.mh_recover
ix2 = record.LastParameters;
fblck = 1;
NumberOfPreviousSimulations = sum(record.MhDraws(:,1),1);
fprintf('Estimation::mcmc: I am writting a new mh-history file... ');
fprintf('Estimation::mcmc: I am writing a new mh-history file... ');
record.MhDraws = [record.MhDraws;zeros(1,3)];
NumberOfDrawsWrittenInThePastLastFile = MAX_nruns - LastLineNumber;
NumberOfDrawsToBeSaved = nruns(1) - NumberOfDrawsWrittenInThePastLastFile;
@ -318,7 +333,7 @@ elseif options_.mh_recover
disp('Estimation::mcmc: It appears that you don''t need to use the mh_recover option!')
disp(' You have to edit the mod file and remove the mh_recover option')
disp(' in the estimation command')
error()
error('Estimation::mcmc: mh_recover option not required!')
end
% I count the number of saved mh files per block.
NumberOfMhFilesPerBlock = zeros(nblck,1);
@ -339,7 +354,7 @@ elseif options_.mh_recover
end
% How many mh-files are saved in this block?
NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(fblck);
% Correct the number of saved mh files if the crashed metropolis was not the first session (so
% Correct the number of saved mh files if the crashed Metropolis was not the first session (so
% that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain
% of the current session).
if OldMh

View File

@ -1,6 +1,6 @@
function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,decomp_flag)
function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,diffuse_kalman_tol,decomp_flag)
% function [alphahat,epsilonhat,etahat,a,aK,PK,decomp] = DiffuseKalmanSmoother1(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,decomp_flag)
% function [alphahat,epsilonhat,etahat,a,aK,PK,decomp] = DiffuseKalmanSmoother1(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,diffuse_kalman_tol,decomp_flag)
% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix
%
% INPUTS
@ -18,6 +18,7 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp] = missing_DiffuseKal
% data_index [cell] 1*smpl cell of column vectors of indices.
% nk number of forecasting periods
% kalman_tol tolerance for reciprocal condition number
% diffuse_kalman_tol tolerance for reciprocal condition number (for Finf) and the rank of Pinf
% decomp_flag if true, compute filter decomposition
%
% OUTPUTS
@ -38,7 +39,7 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp] = missing_DiffuseKal
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2011 Dynare Team
% Copyright (C) 2004-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -80,7 +81,6 @@ Kstar = zeros(mm,pp,smpl);
P = zeros(mm,mm,smpl+1);
Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
crit1 = 1.e-8;
steady = smpl;
rr = size(Q,1);
QQ = R*Q*transpose(R);
@ -91,7 +91,7 @@ epsilonhat = zeros(rr,smpl);
r = zeros(mm,smpl+1);
t = 0;
while rank(Pinf(:,:,t+1),crit1) && t<smpl
while rank(Pinf(:,:,t+1),diffuse_kalman_tol) && t<smpl
t = t+1;
di = data_index{t};
if isempty(di)
@ -103,8 +103,8 @@ while rank(Pinf(:,:,t+1),crit1) && t<smpl
ZZ = Z(di,:);
v(di,t)= Y(di,t) - ZZ*a(:,t);
Finf = ZZ*Pinf(:,:,t)*ZZ';
if rcond(Finf) < kalman_tol
if ~all(abs(Finf(:)) < kalman_tol)
if rcond(Finf) < diffuse_kalman_tol
if ~all(abs(Finf(:)) < diffuse_kalman_tol)
% The univariate diffuse kalman filter should be used.
alphahat = Inf;
return
@ -170,7 +170,7 @@ while notsteady && t<smpl
F = ZZ*P(:,:,t)*ZZ' + H(di,di);
if rcond(F) < kalman_tol
alphahat = Inf;
return
return
end
iF(di,di,t) = inv(F);
PZI = P(:,:,t)*ZZ'*iF(di,di,t);

View File

@ -1,4 +1,4 @@
function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH3_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,decomp_flag)
function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH3_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,diffuse_kalman_tol,decomp_flag)
% function [alphahat,epsilonhat,etahat,a1,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmootherH3_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,decomp_flag)
% Computes the diffuse kalman smoother without measurement error, in the case of a singular var-cov matrix.
% Univariate treatment of multivariate time series.
@ -17,7 +17,8 @@ function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp] = missing_DiffuseKalmanSm
% smpl: sample size
% data_index [cell] 1*smpl cell of column vectors of indices.
% nk number of forecasting periods
% kalman_tol tolerance for zero divider
% kalman_tol tolerance for zero divider
% diffuse_kalman_tol tolerance for zero divider
% decomp_flag if true, compute filter decomposition
%
% OUTPUTS
@ -38,7 +39,7 @@ function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp] = missing_DiffuseKalmanSm
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2011 Dynare Team
% Copyright (C) 2004-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -80,7 +81,6 @@ Pstar = zeros(spstar(1),spstar(2),smpl); Pstar(:,:,1) = Pstar1;
Pinf = zeros(spinf(1),spinf(2),smpl); Pinf(:,:,1) = Pinf1;
Pstar1 = Pstar;
Pinf1 = Pinf;
crit1 = 1.e-6;
steady = smpl;
rr = size(Q,1); % number of structural shocks
QQ = R*Q*transpose(R);
@ -92,7 +92,7 @@ r = zeros(mm,smpl);
t = 0;
icc=0;
newRank = rank(Pinf(:,:,1),crit1);
newRank = rank(Pinf(:,:,1),diffuse_kalman_tol);
while newRank && t < smpl
t = t+1;
a(:,t) = a1(:,t);
@ -121,7 +121,7 @@ while newRank && t < smpl
end
end
if newRank
oldRank = rank(Pinf(:,:,t),crit1);
oldRank = rank(Pinf(:,:,t),diffuse_kalman_tol);
else
oldRank = 0;
end
@ -134,7 +134,7 @@ while newRank && t < smpl
Pinf(:,:,t+1) = T*Pinf(:,:,t)*T';
P0=Pinf(:,:,t+1);
if newRank,
newRank = rank(Pinf(:,:,t+1),crit1);
newRank = rank(Pinf(:,:,t+1),diffuse_kalman_tol);
end
if oldRank ~= newRank
disp('univariate_diffuse_kalman_filter:: T does influence the rank of Pinf!')

View File

@ -1,8 +1,8 @@
function mode_check(fun,x,hessian,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults)
function mode_check(fun,x,hessian_mat,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults)
% Checks the estimated ML mode or Posterior mode.
%@info:
%! @deftypefn {Function File} mode_check (@var{fun}, @var{x}, @var{hessian}, @var{DynareDataset}, @var{DynareOptions}, @var{Model}, @var{EstimatedParameters}, @var{BayesInfo}, @var{DynareResults})
%! @deftypefn {Function File} mode_check (@var{fun}, @var{x}, @var{hessian_mat}, @var{DynareDataset}, @var{DynareOptions}, @var{Model}, @var{EstimatedParameters}, @var{BayesInfo}, @var{DynareResults})
%! @anchor{mode_check}
%! @sp 1
%! Checks the estimated ML mode or Posterior mode by plotting sections of the likelihood/posterior kernel.
@ -58,17 +58,17 @@ function mode_check(fun,x,hessian,DynareDataset,DatasetInfo,DynareOptions,Model,
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
TeX = DynareOptions.TeX;
if ~isempty(hessian);
[ s_min, k ] = min(diag(hessian));
if ~isempty(hessian_mat);
[ s_min, k ] = min(diag(hessian_mat));
end
fval = feval(fun,x,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults);
if ~isempty(hessian);
if ~isempty(hessian_mat);
skipline()
disp('MODE CHECK')
skipline()
disp(sprintf('Fval obtained by the minimization routine: %f', fval))
fprintf('Fval obtained by the minimization routine (minus the posterior/likelihood)): %f', fval);
skipline()
if s_min<eps
disp(sprintf('Most negative variance %f for parameter %d (%s = %f)', s_min, k , BayesInfo.name{k}, x(k)))
@ -149,7 +149,7 @@ for plt = 1:nbplt,
y(i,2) = (y(i,1)+lnprior-dy);
end
end
plot(z,-y);
fighandle=plot(z,-y);
hold on
yl=get(gca,'ylim');
plot( [x(kk) x(kk)], yl, 'c', 'LineWidth', 1)
@ -173,8 +173,9 @@ for plt = 1:nbplt,
else
axes('position',[0.3 0.01 0.42 0.05],'box','on'),
end
plot([0.48 0.68],[0.5 0.5],'color',[0 0.5 0])
hold on, plot([0.04 0.24],[0.5 0.5],'b')
line_color=get(fighandle,'color');
plot([0.48 0.68],[0.5 0.5],'color',line_color{2})
hold on, plot([0.04 0.24],[0.5 0.5],'color',line_color{1})
set(gca,'xlim',[0 1],'ylim',[0 1],'xtick',[],'ytick',[])
text(0.25,0.5,'log-post')
text(0.69,0.5,'log-lik kernel')

View File

@ -173,7 +173,7 @@ if singularity_problem
options_check=options;
options_check.noprint=1;
[eigenvalues_] = check(M, options_check, oo);
if any((abs(eigenvalues_)-1)<1e-6)
if any(abs(abs(eigenvalues_)-1)<1e-6)
fprintf('MODEL_DIAGNOSTICS: The singularity seems to be (partly) caused by the presence of a unit root\n')
fprintf('MODEL_DIAGNOSTICS: as the absolute value of one eigenvalue is in the range of +-1e-6 to 1.\n')
fprintf('MODEL_DIAGNOSTICS: If the model is actually supposed to feature unit root behavior, such a warning is expected,\n')

@ -1 +1 @@
Subproject commit d7d49e38b62c6ef20fa8455d6987737d2e88081d
Subproject commit 55686d7f06673bde2ab52e75833a1bbdba16b2a1

@ -0,0 +1 @@
Subproject commit b7d5391051635207f088a493c92d7357f3bdd4e9

View File

@ -319,9 +319,11 @@ DynareOptions.warning_for_steadystate = 0;
LIK = feval(DynareOptions.particle.algorithm,ReducedForm,Y,start,DynareOptions);
set_dynare_random_generator_state(s1,s2);
if imag(LIK)
info = 46;
likelihood = objective_function_penalty_base;
exit_flag = 0;
elseif isnan(LIK)
info = 45;
likelihood = objective_function_penalty_base;
exit_flag = 0;
else
@ -332,4 +334,18 @@ DynareOptions.warning_for_steadystate = 1;
% Adds prior if necessary
% ------------------------------------------------------------------------------
lnprior = priordens(xparam1(:),BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
fval = (likelihood-lnprior);
fval = (likelihood-lnprior);
if isnan(fval)
info = 47;
fval = objective_function_penalty_base + 100;
exit_flag = 0;
return
end
if imag(fval)~=0
info = 48;
fval = objective_function_penalty_base + 100;
exit_flag = 0;
return
end

View File

@ -0,0 +1,73 @@
function g = apprgrdn(x,f,fun,deltax,obj,varargin)
% g = apprgrdn(x,f,fun,deltax,obj,varargin)
% Performs the finite difference approximation of the gradient <g> at a
% point <x> used in solveopt
%
% Inputs:
% x: point at which to evaluate gradient
% f: calculated function value at a point x;
% fun: Name of the Matlab function calculating the function values
% deltax: vector of the relative stepsizes,
% obj flag indicating whether the gradient of the objective
% function (1) or the constraint function (0) is to be calculated.
%
% Modified by Giovanni Lombardo and Johannes Pfeifer to accomodate Dynare
% structure
%
%
% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel
% Copyright (C) 2008-2015 Giovanni Lombardo
% Copyright (C) 2015 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/>.
n=max(size(x)); ee=ones(size(x));
di=abs(x); idx=find(di<5e-15); di(idx)=5e-15*ee(idx);
di=deltax.*di;
if obj
idx=find(abs(di)<2e-10);
di(idx)=2e-10*sign(di(idx));
else
idx=find(abs(di)<5e-15);
di(idx)=5e-15*sign(di(idx));
end
y=x;
g=NaN(n,1);
for i=1:n
y(i)=x(i)+di(i);
fi=feval(fun,y,varargin{:});
if obj
if fi==f,
for j=1:3
di(i)=di(i)*10; y(i)=x(i)+di(i);
fi=feval(fun,y,varargin{:});
if fi~=f
break
end
end
end
end
g(i)=(fi-f)/di(i);
if obj
if ~isempty(idx) && any(idx==i)
y(i)=x(i)-di(i);
fi=feval(fun,y,varargin{:});
g(i)=.5*(g(i)+(f-fi)/di(i));
end
end
y(i)=x(i);
end

View File

@ -1,10 +1,24 @@
function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,f0,g0,badg,H0,varargin)
% [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,f0,g0,badg,H0,...
% P1,P2,P3,P4,P5,P6,P7,P8)
% retcodes: 0, normal step. 5, largest step still improves too fast.
% 4,2 back and forth adjustment of stepsize didn't finish. 3, smallest
% stepsize still improves too slow. 6, no improvement found. 1, zero
% gradient.
% [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,f0,g0,badg,H0,varargin)
%
% Inputs:
% fcn: [string] string naming the objective function to be minimized
% x0: [npar by 1] initial value of the parameter vector
% g0: [npar by 1] initial value of the gradient vector
% H0: [npar by npar] initial value for the inverse Hessian. Must be positive definite.
% varargin: Optional additional inputs that get handed off to fcn each
% time it is called.
% Outputs:
% fhat: [scalar] function value at minimum
% xhat: [npar by 1] parameter vector at minimum
% fcount [scalar] function iteration count upon termination
% retcode [scalar] 0: normal step
% 1: zero gradient.
% 5: largest step still improves too fast.
% 2,4: back and forth adjustment of stepsize didn't finish.
% 3: smallest stepsize still improves too slow
% 6: no improvement found
%---------------------
% Modified 7/22/96 to omit variable-length P list, for efficiency and compilation.
% Places where the number of P's need to be altered or the code could be returned to
@ -15,12 +29,12 @@ function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,f0,g0,badg,H0,varargin)
%
% Fixed 7/19/93 to flip eigenvalues of H to get better performance when
% it's not psd.
%
% Original file downloaded from:
% http://sims.princeton.edu/yftp/optimize/mfiles/csminit.m
%
% Copyright (C) 1993-2007 Christopher Sims
% Copyright (C) 2008-2011 Dynare Team
% Copyright (C) 2008-2015 Dynare Team
%
% This file is part of Dynare.
%

View File

@ -1,29 +1,48 @@
function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,method,epsilon,varargin)
%[fhat,xhat,ghat,Hhat,itct,fcount,retcodehat] = csminwel1(fcn,x0,H0,grad,crit,nit,method,epsilon,varargin)
% fcn: string naming the objective function to be minimized
% x0: initial value of the parameter vector
% H0: initial value for the inverse Hessian. Must be positive definite.
% grad: Either a string naming a function that calculates the gradient, or the null matrix.
% If it's null, the program calculates a numerical gradient. In this case fcn must
% be written so that it can take a matrix argument and produce a row vector of values.
% crit: Convergence criterion. Iteration will cease when it proves impossible to improve the
% function value by more than crit.
% nit: Maximum number of iterations.
% method: integer scalar, 2, 3 or 5 points formula.
% epsilon: scalar double, numerical differentiation increment
% varargin: A list of optional length of additional parameters that get handed off to fcn each
% time it is called.
%[fhat,xhat,ghat,Hhat,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,method,epsilon,varargin)
% Inputs:
% fcn: [string] string naming the objective function to be minimized
% x0: [npar by 1] initial value of the parameter vector
% H0: [npar by npar] initial value for the inverse Hessian. Must be positive definite.
% grad: [string or empty matrix] Either a string naming a function that calculates the gradient, or the null matrix.
% If it's null, the program calculates a numerical gradient. In this case fcn must
% be written so that it can take a matrix argument and produce a row vector of values.
% crit: [scalar] Convergence criterion. Iteration will cease when it proves impossible to improve the
% function value by more than crit.
% nit: [scalar] Maximum number of iterations.
% method: [scalar] integer scalar for selecting gradient method: 2, 3 or 5 points formula.
% epsilon: [scalar] scalar double, numerical differentiation increment
% varargin: Optional additional inputs that get handed off to fcn each
% time it is called.
%
% Note that if the program ends abnormally, it is possible to retrieve the current x,
% f, and H from the files g1.mat and H.mat that are written at each iteration and at each
% hessian update, respectively. (When the routine hits certain kinds of difficulty, it
% write g2.mat and g3.mat as well. If all were written at about the same time, any of them
% may be a decent starting point. One can also start from the one with best function value.)
% writes g2.mat and g3.mat as well. If all were written at about the same time, any of them
% may be a decent starting point. One can also start from the one with best function value.)
%
% Outputs:
% fh: [scalar] function value at minimum
% xh: [npar by 1] parameter vector at minimum
% gh [npar by 1] gradient vector
% H [npar by npar] inverse of the Hessian matrix
% itct [scalar] iteration count upon termination
% fcount [scalar] function iteration count upon termination
% retcodeh [scalar] return code:
% 0: normal step
% 1: zero gradient
% 2: back and forth on step length never finished
% 3: smallest step still improving too slow
% 4: back and forth on step length never finished
% 5: largest step still improving too fast
% 6: smallest step still improving too slow, reversed gradient
% 7: warning: possible inaccuracy in H matrix
%
% Original file downloaded from:
% http://sims.princeton.edu/yftp/optimize/mfiles/csminwel.m
%
% Copyright (C) 1993-2007 Christopher Sims
% Copyright (C) 2006-2012 Dynare Team
% Copyright (C) 2006-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -51,7 +70,6 @@ NumGrad= isempty(grad);
done=0;
itct=0;
fcount=0;
snit=100;
gh = [];
H = [];
retcodeh = [];
@ -74,20 +92,7 @@ if ~cost_flag
end
if NumGrad
switch method
case 2
[g,badg] = numgrad2(fcn, f0, x0, epsilon, varargin{:});
case 3
[g,badg] = numgrad3(fcn, f0, x0, epsilon, varargin{:});
case 5
[g,badg] = numgrad5(fcn, f0, x0, epsilon, varargin{:});
case 13
[g,badg] = numgrad3_(fcn, f0, x0, epsilon, varargin{:});
case 15
[g,badg] = numgrad5_(fcn, f0, x0, epsilon, varargin{:});
otherwise
error('csminwel1: Unknown method for gradient evaluation!')
end
[g, badg]=get_num_grad(method,fcn,f0,x0,epsilon,varargin{:});
elseif ischar(grad)
[g,badg] = feval(grad,x0,varargin{:});
else
@ -105,19 +110,15 @@ while ~done
g1=[]; g2=[]; g3=[];
%addition fj. 7/6/94 for control
disp('-----------------')
disp('-----------------')
%disp('f and x at the beginning of new iteration')
disp(sprintf('f at the beginning of new iteration, %20.10f',f))
if Verbose
disp('-----------------')
disp(sprintf('f at the beginning of new iteration, %20.10f',f))
end
%-----------Comment out this line if the x vector is long----------------
% disp([sprintf('x = ') sprintf('%15.8g %15.8g %15.8g %15.8g\n',x)]);
%-------------------------
itct=itct+1;
[f1 x1 fc retcode1] = csminit1(fcn,x,f,g,badg,H,varargin{:});
%ARGLIST
%[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,P1,P2,P3,P4,P5,P6,P7,...
% P8,P9,P10,P11,P12,P13);
% itct=itct+1;
[f1, x1, fc, retcode1] = csminit1(fcn,x,f,g,badg,H,varargin{:});
fcount = fcount+fc;
% erased on 8/4/94
% if (retcode == 1) || (abs(f1-f) < crit)
@ -132,22 +133,9 @@ while ~done
wall1=1; badg1=1;
else
if NumGrad
switch method
case 2
[g1 badg1] = numgrad2(fcn, f1, x1, epsilon, varargin{:});
case 3
[g1 badg1] = numgrad3(fcn, f1, x1, epsilon, varargin{:});
case 5
[g1,badg1] = numgrad5(fcn, f1, x1, epsilon, varargin{:});
case 13
[g1,badg1] = numgrad3_(fcn, f1, x1, epsilon, varargin{:});
case 15
[g1,badg1] = numgrad5_(fcn, f1, x1, epsilon, varargin{:});
otherwise
error('csminwel1: Unknown method for gradient evaluation!')
end
[g1, badg1]=get_num_grad(method,fcn,f1,x1,epsilon,varargin{:});
elseif ischar(grad),
[g1 badg1] = feval(grad,x1,varargin{:});
[g1, badg1] = feval(grad,x1,varargin{:});
else
[junk1,g1,junk2, cost_flag] = feval(fcn,x1,varargin{:});
badg1 = ~cost_flag;
@ -155,8 +143,6 @@ while ~done
wall1=badg1;
% g1
save g1.mat g1 x1 f1 varargin;
%ARGLIST
%save g1 g1 x1 f1 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end
if wall1 % && (~done) by Jinill
% Bad gradient or back and forth on step length. Possibly at
@ -164,33 +150,19 @@ while ~done
%
%fcliff=fh;xcliff=xh;
Hcliff=H+diag(diag(H).*rand(nx,1));
disp('Cliff. Perturbing search direction.')
[f2 x2 fc retcode2] = csminit1(fcn,x,f,g,badg,Hcliff,varargin{:});
%ARGLIST
%[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,P1,P2,P3,P4,...
% P5,P6,P7,P8,P9,P10,P11,P12,P13);
if Verbose
disp('Cliff. Perturbing search direction.')
end
[f2, x2, fc, retcode2] = csminit1(fcn,x,f,g,badg,Hcliff,varargin{:});
fcount = fcount+fc; % put by Jinill
if f2 < f
if retcode2==2 || retcode2==4
wall2=1; badg2=1;
else
if NumGrad
switch method
case 2
[g2 badg2] = numgrad2(fcn, f2, x2, epsilon, varargin{:});
case 3
[g2 badg2] = numgrad3(fcn, f2, x2, epsilon, varargin{:});
case 5
[g2,badg2] = numgrad5(fcn, f2, x2, epsilon, varargin{:});
case 13
[g2,badg2] = numgrad3_(fcn, f2, x2, epsilon, varargin{:});
case 15
[g2,badg2] = numgrad5_(fcn, f2, x2, epsilon, varargin{:});
otherwise
error('csminwel1: Unknown method for gradient evaluation!')
end
[g2, badg2]=get_num_grad(method,fcn,f2,x2,epsilon,varargin{:});
elseif ischar(grad),
[g2 badg2] = feval(grad,x2,varargin{:});
[g2, badg2] = feval(grad,x2,varargin{:});
else
[junk1,g2,junk2, cost_flag] = feval(fcn,x1,varargin{:});
badg2 = ~cost_flag;
@ -199,8 +171,6 @@ while ~done
% g2
badg2
save g2.mat g2 x2 f2 varargin
%ARGLIST
%save g2 g2 x2 f2 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end
if wall2
disp('Cliff again. Try traversing')
@ -208,33 +178,19 @@ while ~done
f3=f; x3=x; badg3=1;retcode3=101;
else
gcliff=((f2-f1)/((norm(x2-x1))^2))*(x2-x1);
if(size(x0,2)>1), gcliff=gcliff', end
[f3 x3 fc retcode3] = csminit1(fcn,x,f,gcliff,0,eye(nx),varargin{:});
%ARGLIST
%[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),P1,P2,P3,...
% P4,P5,P6,P7,P8,...
% P9,P10,P11,P12,P13);
if(size(x0,2)>1)
gcliff=gcliff';
end
[f3, x3, fc, retcode3] = csminit1(fcn,x,f,gcliff,0,eye(nx),varargin{:});
fcount = fcount+fc; % put by Jinill
if retcode3==2 || retcode3==4
wall3=1; badg3=1;
wall3=1;
badg3=1;
else
if NumGrad
switch method
case 2
[g3 badg3] = numgrad2(fcn, f3, x3, epsilon, varargin{:});
case 3
[g3 badg3] = numgrad3(fcn, f3, x3, epsilon, varargin{:});
case 5
[g3,badg3] = numgrad5(fcn, f3, x3, epsilon, varargin{:});
case 13
[g3,badg3] = numgrad3_(fcn, f3, x3, epsilon, varargin{:});
case 15
[g3,badg3] = numgrad5_(fcn, f3, x3, epsilon, varargin{:});
otherwise
error('csminwel1: Unknown method for gradient evaluation!')
end
[g3, badg3]=get_num_grad(method,fcn,f3,x3,epsilon,varargin{:});
elseif ischar(grad),
[g3 badg3] = feval(grad,x3,varargin{:});
[g3, badg3] = feval(grad,x3,varargin{:});
else
[junk1,g3,junk2, cost_flag] = feval(fcn,x1,varargin{:});
badg3 = ~cost_flag;
@ -242,8 +198,6 @@ while ~done
wall3=badg3;
% g3
save g3.mat g3 x3 f3 varargin;
%ARGLIST
%save g3 g3 x3 f3 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
end
end
else
@ -292,22 +246,9 @@ while ~done
end
if nogh
if NumGrad
switch method
case 2
[gh,badgh] = numgrad2(fcn, fh, xh, epsilon, varargin{:});
case 3
[gh,badgh] = numgrad3(fcn, fh, xh, epsilon, varargin{:});
case 5
[gh,badgh] = numgrad5(fcn, fh, xh, epsilon, varargin{:});
case 13
[gh,badgh] = numgrad3_(fcn, fh, xh, epsilon, varargin{:});
case 15
[gh,badgh] = numgrad5_(fcn, fh, xh, epsilon, varargin{:});
otherwise
error('csminwel1: Unknown method for gradient evaluation!')
end
[gh, badgh]=get_num_grad(method,fcn,fh,xh,epsilon,varargin{:});
elseif ischar(grad),
[gh badgh] = feval(grad, xh,varargin{:});
[gh, badgh] = feval(grad, xh,varargin{:});
else
[junk1,gh,junk2, cost_flag] = feval(fcn,x1,varargin{:});
badgh = ~cost_flag;
@ -316,11 +257,6 @@ while ~done
badgh=1;
end
%end of picking
%ih
%fh
%xh
%gh
%badgh
stuck = (abs(fh-f) < crit);
if (~badg) && (~badgh) && (~stuck)
H = bfgsi1(H,gh-g,xh-x);
@ -338,24 +274,47 @@ while ~done
done = 1;
end
rc=retcodeh;
if rc == 1
disp('zero gradient')
elseif rc == 6
disp('smallest step still improving too slow, reversed gradient')
elseif rc == 5
disp('largest step still improving too fast')
elseif (rc == 4) || (rc==2)
disp('back and forth on step length never finished')
elseif rc == 3
disp('smallest step still improving too slow')
elseif rc == 7
disp('warning: possible inaccuracy in H matrix')
if Verbose || done
if rc ==0
%do nothing, just a normal step
elseif rc == 1
disp('zero gradient')
elseif rc == 6
disp('smallest step still improving too slow, reversed gradient')
elseif rc == 5
disp('largest step still improving too fast')
elseif (rc == 4) || (rc==2)
disp('back and forth on step length never finished')
elseif rc == 3
disp('smallest step still improving too slow')
elseif rc == 7
disp('warning: possible inaccuracy in H matrix')
else
error('Unaccounted Case, please contact the developers')
end
end
% end
f=fh;
x=xh;
g=gh;
badg=badgh;
end
% what about making an m-file of 10 lines including numgrad.m
% since it appears three times in csminwel.m
end
function [g, badg]=get_num_grad(method,fcn,f0,x0,epsilon,varargin)
switch method
case 2
[g,badg] = numgrad2(fcn, f0, x0, epsilon, varargin{:});
case 3
[g,badg] = numgrad3(fcn, f0, x0, epsilon, varargin{:});
case 5
[g,badg] = numgrad5(fcn, f0, x0, epsilon, varargin{:});
case 13
[g,badg] = numgrad3_(fcn, f0, x0, epsilon, varargin{:});
case 15
[g,badg] = numgrad5_(fcn, f0, x0, epsilon, varargin{:});
otherwise
error('csminwel1: Unknown method for gradient evaluation!')
end
end

View File

@ -0,0 +1,384 @@
function [opt_par_values,fval,exitflag,hessian_mat,options_,Scale]=dynare_minimize_objective(objective_function,start_par_value,minimizer_algorithm,options_,bounds,parameter_names,prior_information,Initial_Hessian,varargin)
% Calls a minimizer
%
% INPUTS
% objective_function [function handle] handle to the objective function
% start_par_value [n_params by 1] vector of doubles starting values for the parameters
% minimizer_algorithm [scalar double] code of the optimizer algorithm
% options_ [matlab structure] Dynare options structure
% bounds [n_params by 2] vector of doubles 2 row vectors containing lower and upper bound for parameters
% parameter_names [n_params by 1] cell array strings containing the parameters names
% prior_information [matlab structure] Dynare prior information structure (bayestopt_) provided for algorithm 6
% Initial_Hessian [n_params by n_params] matrix initial hessian matrix provided for algorithm 6
% varargin [cell array] Input arguments for objective function
%
% OUTPUTS
% opt_par_values [n_params by 1] vector of doubles optimal parameter values minimizing the objective
% fval [scalar double] value of the objective function at the minimum
% exitflag [scalar double] return code of the respective optimizer
% hessian_mat [n_params by n_params] matrix hessian matrix at the mode returned by optimizer
% options_ [matlab structure] Dynare options structure (to return options set by algorithms 5)
% Scale [scalar double] scaling parameter returned by algorith 6
%
% SPECIAL REQUIREMENTS
% none.
%
%
% Copyright (C) 2014-2015 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 bounds and parameter names if not already set
n_params=size(start_par_value,1);
if isempty(bounds)
if isnumeric(minimizer_algorithm) && minimizer_algorithm==10
error('Algorithm 10 (simpsa) requires upper and lower bounds')
else
bounds=[-Inf(n_params,1) Inf(n_params,1)];
end
end
if isempty(parameter_names)
parameter_names=[repmat('parameter ',n_params,1),num2str((1:n_params)')];
end
%% initialize function outputs
hessian_mat=[];
Scale=[];
exitflag=1;
fval=NaN;
opt_par_values=NaN(size(start_par_value));
switch minimizer_algorithm
case 1
if isoctave
error('Optimization algorithm 1 is not available under Octave')
elseif ~user_has_matlab_license('optimization_toolbox')
error('Optimization algorithm 1 requires the Optimization Toolbox')
end
% Set default optimization options for fmincon.
optim_options = optimset('display','iter', 'LargeScale','off', 'MaxFunEvals',100000, 'TolFun',1e-8, 'TolX',1e-6);
if ~isempty(options_.optim_opt)
eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
end
if options_.analytic_derivation,
optim_options = optimset(optim_options,'GradObj','on','TolX',1e-7);
end
[opt_par_values,fval,exitflag,output,lamdba,grad,hessian_mat] = ...
fmincon(objective_function,start_par_value,[],[],[],[],bounds(:,1),bounds(:,2),[],optim_options,varargin{:});
case 2
%simulating annealing
sa_options = options_.saopt;
if ~isempty(options_.optim_opt)
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'neps'
sa_options.neps = options_list{i,2};
case 'rt'
sa_options.rt = options_list{i,2};
case 'MaxIter'
sa_options.MaxIter = options_list{i,2};
case 'TolFun'
sa_options.TolFun = options_list{i,2};
case 'verbosity'
sa_options.verbosity = options_list{i,2};
case 'initial_temperature'
sa_options.initial_temperature = options_list{i,2};
case 'ns'
sa_options.ns = options_list{i,2};
case 'nt'
sa_options.nt = options_list{i,2};
case 'step_length_c'
sa_options.step_length_c = options_list{i,2};
case 'initial_step_length'
sa_options.initial_step_length = options_list{i,2};
otherwise
warning(['solveopt: Unknown option (' options_list{i,1} ')!'])
end
end
end
npar=length(start_par_value);
[LB, UB]=set_bounds_to_finite_values(bounds, options_.huge_number);
fprintf('\nNumber of parameters= %d, initial temperatur= %4.3f \n', npar,sa_options.initial_temperature);
fprintf('rt= %4.3f; TolFun= %4.3f; ns= %4.3f;\n',sa_options.rt,sa_options.TolFun,sa_options.ns);
fprintf('nt= %4.3f; neps= %4.3f; MaxIter= %d\n',sa_options.nt,sa_options.neps,sa_options.MaxIter);
fprintf('Initial step length(vm): %4.3f; step_length_c: %4.3f\n', sa_options.initial_step_length,sa_options.step_length_c);
fprintf('%-20s %-6s %-6s %-6s\n','Name:', 'LB;','Start;','UB;');
for pariter=1:npar
fprintf('%-20s %6.4f; %6.4f; %6.4f;\n',parameter_names{pariter}, LB(pariter),start_par_value(pariter),UB(pariter));
end
sa_options.initial_step_length= sa_options.initial_step_length*ones(npar,1); %bring step length to correct vector size
sa_options.step_length_c= sa_options.step_length_c*ones(npar,1); %bring step_length_c to correct vector size
[opt_par_values, fval,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_draws, t, vm] =...
simulated_annealing(objective_function,start_par_value,sa_options,LB,UB,varargin{:});
case 3
if isoctave && ~user_has_octave_forge_package('optim')
error('Optimization algorithm 3 requires the optim package')
elseif ~isoctave && ~user_has_matlab_license('optimization_toolbox')
error('Optimization algorithm 3 requires the Optimization Toolbox')
end
% Set default optimization options for fminunc.
optim_options = optimset('display','iter','MaxFunEvals',100000,'TolFun',1e-8,'TolX',1e-6);
if ~isempty(options_.optim_opt)
eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
end
if options_.analytic_derivation,
optim_options = optimset(optim_options,'GradObj','on');
end
if ~isoctave
[opt_par_values,fval,exitflag] = fminunc(objective_function,start_par_value,optim_options,varargin{:});
else
% Under Octave, use a wrapper, since fminunc() does not have a 4th arg
func = @(x) objective_function(x,varargin{:});
[opt_par_values,fval,exitflag] = fminunc(func,start_par_value,optim_options);
end
case 4
% Set default options.
H0 = 1e-4*eye(n_params);
crit = options_.csminwel.tolerance.f;
nit = options_.csminwel.maxiter;
numgrad = options_.gradient_method;
epsilon = options_.gradient_epsilon;
% Change some options.
if ~isempty(options_.optim_opt)
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'MaxIter'
nit = options_list{i,2};
case 'InitialInverseHessian'
H0 = eval(options_list{i,2});
case 'TolFun'
crit = options_list{i,2};
case 'NumgradAlgorithm'
numgrad = options_list{i,2};
case 'NumgradEpsilon'
epsilon = options_list{i,2};
otherwise
warning(['csminwel: Unknown option (' options_list{i,1} ')!'])
end
end
end
% Set flag for analytical gradient.
if options_.analytic_derivation
analytic_grad=1;
else
analytic_grad=[];
end
% Call csminwell.
[fval,opt_par_values,grad,inverse_hessian_mat,itct,fcount,exitflag] = ...
csminwel1(objective_function, start_par_value, H0, analytic_grad, crit, nit, numgrad, epsilon, varargin{:});
hessian_mat=inv(inverse_hessian_mat);
case 5
if options_.analytic_derivation==-1 %set outside as code for use of analytic derivation
analytic_grad=1;
crit = options_.newrat.tolerance.f_analytic;
newratflag = 0; %analytical Hessian
else
analytic_grad=0;
crit=options_.newrat.tolerance.f;
newratflag = options_.newrat.hess; %default
end
nit=options_.newrat.maxiter;
if ~isempty(options_.optim_opt)
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'MaxIter'
nit = options_list{i,2};
case 'Hessian'
flag=options_list{i,2};
if options_.analytic_derivation && flag~=0
error('newrat: analytic_derivation is incompatible with numerical Hessian. Using analytic Hessian')
else
newratflag=flag;
end
case 'TolFun'
crit = options_list{i,2};
otherwise
warning(['newrat: Unknown option (' options_list{i,1} ')!'])
end
end
end
[opt_par_values,hessian_mat,gg,fval,invhess] = newrat(objective_function,start_par_value,analytic_grad,crit,nit,0,varargin{:});
%hessian_mat is the plain outer product gradient Hessian
case 6
[opt_par_values, hessian_mat, Scale, fval] = gmhmaxlik(objective_function, start_par_value, ...
Initial_Hessian, options_.mh_jscale, bounds, prior_information.p2, options_.gmhmaxlik, options_.optim_opt, varargin{:});
case 7
% Matlab's simplex (Optimization toolbox needed).
if isoctave && ~user_has_octave_forge_package('optim')
error('Option mode_compute=7 requires the optim package')
elseif ~isoctave && ~user_has_matlab_license('optimization_toolbox')
error('Option mode_compute=7 requires the Optimization Toolbox')
end
optim_options = optimset('display','iter','MaxFunEvals',1000000,'MaxIter',6000,'TolFun',1e-8,'TolX',1e-6);
if ~isempty(options_.optim_opt)
eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
end
if ~isoctave
[opt_par_values,fval,exitflag] = fminsearch(objective_function,start_par_value,optim_options,varargin{:});
else
% Under Octave, use a wrapper, since fminsearch() does not have a 4th arg
func = @(x) objective_function(x,varargin{:});
[opt_par_values,fval,exitflag] = fminsearch(func,start_par_value,optim_options);
end
case 8
% Dynare implementation of the simplex algorithm.
simplexOptions = options_.simplex;
if ~isempty(options_.optim_opt)
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'MaxIter'
simplexOptions.maxiter = options_list{i,2};
case 'TolFun'
simplexOptions.tolerance.f = options_list{i,2};
case 'TolX'
simplexOptions.tolerance.x = options_list{i,2};
case 'MaxFunEvals'
simplexOptions.maxfcall = options_list{i,2};
case 'MaxFunEvalFactor'
simplexOptions.maxfcallfactor = options_list{i,2};
case 'InitialSimplexSize'
simplexOptions.delta_factor = options_list{i,2};
otherwise
warning(['simplex: Unknown option (' options_list{i,1} ')!'])
end
end
end
[opt_par_values,fval,exitflag] = simplex_optimization_routine(objective_function,start_par_value,simplexOptions,parameter_names,varargin{:});
case 9
% Set defaults
H0 = 1e-4*ones(n_params,1);
cmaesOptions = options_.cmaes;
% Modify defaults
if ~isempty(options_.optim_opt)
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'MaxIter'
cmaesOptions.MaxIter = options_list{i,2};
case 'TolFun'
cmaesOptions.TolFun = options_list{i,2};
case 'TolX'
cmaesOptions.TolX = options_list{i,2};
case 'MaxFunEvals'
cmaesOptions.MaxFunEvals = options_list{i,2};
otherwise
warning(['cmaes: Unknown option (' options_list{i,1} ')!'])
end
end
end
warning('off','CMAES:NonfinitenessRange');
warning('off','CMAES:InitialSigma');
[x, fval, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = cmaes(func2str(objective_function),start_par_value,H0,cmaesOptions,varargin{:});
opt_par_values=BESTEVER.x;
fval=BESTEVER.f;
case 10
simpsaOptions = options_.simpsa;
if ~isempty(options_.optim_opt)
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'MaxIter'
simpsaOptions.MAX_ITER_TOTAL = options_list{i,2};
case 'TolFun'
simpsaOptions.TOLFUN = options_list{i,2};
case 'TolX'
tolx = options_list{i,2};
if tolx<0
simpsaOptions = rmfield(simpsaOptions,'TOLX'); % Let simpsa choose the default.
else
simpsaOptions.TOLX = tolx;
end
case 'EndTemparature'
simpsaOptions.TEMP_END = options_list{i,2};
case 'MaxFunEvals'
simpsaOptions.MAX_FUN_EVALS = options_list{i,2};
otherwise
warning(['simpsa: Unknown option (' options_list{i,1} ')!'])
end
end
end
simpsaOptionsList = options2cell(simpsaOptions);
simpsaOptions = simpsaset(simpsaOptionsList{:});
[LB, UB]=set_bounds_to_finite_values(bounds, options_.huge_number);
[opt_par_values, fval, exitflag] = simpsa(func2str(objective_function),start_par_value,LB,UB,simpsaOptions,varargin{:});
case 11
options_.cova_compute = 0 ;
[opt_par_values,stdh,lb_95,ub_95,med_param] = online_auxiliary_filter(start_par_value,varargin{:}) ;
case 101
solveoptoptions = options_.solveopt;
if ~isempty(options_.optim_opt)
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
switch options_list{i,1}
case 'TolX'
solveoptoptions.TolX = options_list{i,2};
case 'TolFun'
solveoptoptions.TolFun = options_list{i,2};
case 'MaxIter'
solveoptoptions.MaxIter = options_list{i,2};
case 'verbosity'
solveoptoptions.verbosity = options_list{i,2};
case 'SpaceDilation'
solveoptoptions.SpaceDilation = options_list{i,2};
case 'LBGradientStep'
solveoptoptions.LBGradientStep = options_list{i,2};
otherwise
warning(['solveopt: Unknown option (' options_list{i,1} ')!'])
end
end
end
[opt_par_values,fval]=solvopt(start_par_value,objective_function,[],[],[],solveoptoptions,varargin{:});
case 102
if isoctave
error('Optimization algorithm 2 is not available under Octave')
elseif ~user_has_matlab_license('GADS_Toolbox')
error('Optimization algorithm 2 requires the Global Optimization Toolbox')
end
% Set default optimization options for fmincon.
optim_options = saoptimset('display','iter','TolFun',1e-8);
if ~isempty(options_.optim_opt)
eval(['optim_options = saoptimset(optim_options,' options_.optim_opt ');']);
end
func = @(x)objective_function(x,varargin{:});
[opt_par_values,fval,exitflag,output] = simulannealbnd(func,start_par_value,bounds(:,1),bounds(:,2),optim_options);
otherwise
if ischar(minimizer_algorithm)
if exist(options_.mode_compute)
[opt_par_values, fval, exitflag] = feval(options_.mode_compute,objective_function,start_par_value,varargin{:});
else
error('No minimizer with the provided name detected.')
end
else
error(['Optimization algorithm ' int2str(minimizer_algorithm) ' is unknown!'])
end
end
end
function [LB, UB]=set_bounds_to_finite_values(bounds, huge_number)
LB=bounds(:,1);
LB(isinf(LB))=-huge_number;
UB=bounds(:,2);
UB(isinf(UB))=huge_number;
end

View File

@ -0,0 +1,120 @@
function [PostMode, HessianMatrix, Scale, ModeValue] = gmhmaxlik(fun, xinit, Hinit, iscale, bounds, priorstd, gmhmaxlikOptions, OptimizationOptions, varargin)
% Copyright (C) 2006-2015 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 default options
if ~isempty(Hinit);
gmhmaxlikOptions.varinit = 'previous';
else
gmhmaxlikOptions.varinit = 'prior';
end
if ~isempty(OptimizationOptions)
DynareOptionslist = read_key_value_string(OptimizationOptions);
for i=1:rows(DynareOptionslist)
switch DynareOptionslist{i,1}
case 'NumberOfMh'
gmhmaxlikOptions.iterations = DynareOptionslist{i,2};
case 'ncov-mh'
gmhmaxlikOptions.number = DynareOptionslist{i,2};
case 'nscale'
gmhmaxlikOptions.nscale = DynareOptionslist{i,2};
case 'nclimb'
gmhmaxlikOptions.nclimb = DynareOptionslist{i,2};
case 'InitialCovarianceMatrix'
switch DynareOptionslist{i,2}
case 'previous'
if isempty(Hinit)
error('gmhmaxlik: No previous estimate of the Hessian matrix available! You cannot use the InitialCovarianceMatrix option!')
else
gmhmaxlikOptions.varinit = 'previous';
end
case {'prior', 'identity'}
gmhmaxlikOptions.varinit = DynareOptionslist{i,2};
otherwise
error('gmhmaxlik: Unknown value for option ''InitialCovarianceMatrix''!')
end
case 'AcceptanceRateTarget'
gmhmaxlikOptions.target = DynareOptionslist{i,2};
if gmhmaxlikOptions.target>1 || gmhmaxlikOptions.target<eps
error('gmhmaxlik: The value of option AcceptanceRateTarget should be a double between 0 and 1!')
end
otherwise
warning(['gmhmaxlik: Unknown option (' DynareOptionslist{i,1} ')!'])
end
end
end
% Evaluate the objective function.
OldModeValue = feval(fun,xinit,varargin{:});
if ~exist('MeanPar','var')
MeanPar = xinit;
end
switch gmhmaxlikOptions.varinit
case 'previous'
CovJump = inv(Hinit);
case 'prior'
% The covariance matrix is initialized with the prior
% covariance (a diagonal matrix) %%Except for infinite variances ;-)
stdev = priorstd;
indx = find(isinf(stdev));
stdev(indx) = ones(length(indx),1)*sqrt(10);
vars = stdev.^2;
CovJump = diag(vars);
case 'identity'
vars = ones(length(priorstd),1)*0.1;
CovJump = diag(vars);
otherwise
error('gmhmaxlik: This is a bug! Please contact the developers.')
end
OldPostVariance = CovJump;
OldPostMean = xinit;
OldPostMode = xinit;
Scale = iscale;
for i=1:gmhmaxlikOptions.iterations
if i<gmhmaxlikOptions.iterations
flag = '';
else
flag = 'LastCall';
end
[PostMode, PostVariance, Scale, PostMean] = gmhmaxlik_core(fun, OldPostMode, bounds, gmhmaxlikOptions, Scale, flag, MeanPar, OldPostVariance, varargin{:});
ModeValue = feval(fun, PostMode, varargin{:});
dVariance = max(max(abs(PostVariance-OldPostVariance)));
dMean = max(abs(PostMean-OldPostMean));
skipline()
printline(58,'=')
disp([' Change in the posterior covariance matrix = ' num2str(dVariance) '.'])
disp([' Change in the posterior mean = ' num2str(dMean) '.'])
disp([' Mode improvement = ' num2str(abs(OldModeValue-ModeValue))])
disp([' New value of jscale = ' num2str(Scale)])
printline(58,'=')
OldModeValue = ModeValue;
OldPostMean = PostMean;
OldPostVariance = PostVariance;
end
HessianMatrix = inv(PostVariance);
skipline()
disp(['Optimal value of the scale parameter = ' num2str(Scale)])
skipline()

View File

@ -1,8 +1,5 @@
function [PostMod,PostVar,Scale,PostMean] = ...
gmhmaxlik(ObjFun,xparam1,mh_bounds,options,iScale,info,MeanPar,VarCov,varargin)
function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bounds,options,iScale,info,MeanPar,VarCov,varargin)
%function [PostMod,PostVar,Scale,PostMean] = ...
%gmhmaxlik(ObjFun,xparam1,mh_bounds,num,iScale,info,MeanPar,VarCov,varargin)
% (Dirty) Global minimization routine of (minus) a likelihood (or posterior density) function.
%
% INPUTS
@ -59,7 +56,7 @@ function [PostMod,PostVar,Scale,PostMean] = ...
% SPECIAL REQUIREMENTS
% None.
% Copyright (C) 2006-2012 Dynare Team
% Copyright (C) 2006-2015 Dynare Team
%
% This file is part of Dynare.
%

View File

@ -0,0 +1,459 @@
function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_draws, t, vm] = ...
simulated_annealing(fcn,x,optim,lb,ub,varargin)
% function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_draws, t, vm] = ...
% simulated_annealing(fcn,x,optim,lb,ub,varargin)
%
% Implements the continuous simulated annealing global optimization
% algorithm described in Corana et al. (1987)
%
% A very quick (perhaps too quick) overview of SA:
% SA tries to find the global optimum of an N dimensional function.
% It moves both up and downhill and as the optimization process
% proceeds, it focuses on the most promising area.
% To start, it randomly chooses a trial point within the step length
% VM (a vector of length N) of the user selected starting point. The
% function is evaluated at this trial point and its value is compared
% to its value at the initial point.
% In a maximization problem, all uphill moves are accepted and the
% algorithm continues from that trial point. Downhill moves may be
% accepted the decision is made by the Metropolis criteria. It uses T
% (temperature) and the size of the downhill move in a probabilistic
% manner. The smaller T and the size of the downhill move are, the more
% likely that move will be accepted. If the trial is accepted, the
% algorithm moves on from that point. If it is rejected, another point
% is chosen instead for a trial evaluation.
% Each element of VM periodically adjusted so that half of all
% function evaluations in that direction are accepted.
% A fall in T is imposed upon the system with the RT option by
% T(i+1) = RT*T(i) where i is the ith iteration. Thus, as T declines,
% downhill moves are less likely to be accepted and the percentage of
% rejections rise. Given the scheme for the selection for VM, VM falls.
% Thus, as T declines, VM falls and SA focuses upon the most promising
% area for optimization.
%
% The importance of the parameter T (initial_temperature):
% The parameter T is crucial in using SA successfully. It influences
% VM, the step length over which the algorithm searches for optima. For
% a small intial T, the step length may be too small thus not enough
% of the function might be evaluated to find the global optima. The user
% should carefully examine VM in the intermediate output (set verbosity =
% 1) to make sure that VM is appropriate. The relationship between the
% initial temperature and the resulting step length is function
% dependent.
% To determine the starting temperature that is consistent with
% optimizing a function, it is worthwhile to run a trial run first. Set
% RT = 1.5 and T = 1.0. With RT > 1.0, the temperature increases and VM
% rises as well. Then select the T that produces a large enough VM.
%
% Input Parameters:
% Note: The suggested values generally come from Corana et al. To
% drastically reduce runtime, see Goffe et al., pp. 90-1 for
% suggestions on choosing the appropriate RT and NT.
%
% fcn - function to be optimized.
% x - The starting values for the variables of the function to be
% optimized. (N)
% optim: Options structure with fields
%
% optim.maximizer_indicator - Denotes whether the function should be maximized or
% minimized. A value =1 denotes maximization while a
% value =0 denotes minimization. Intermediate output (see verbosity)
% takes this into account.
% optim.RT - The temperature reduction factor
% optim.TolFun - Error tolerance for termination. If the final function
% values from the last neps temperatures differ from the
% corresponding value at the current temperature by less than
% optim.TolFun and the final function value at the current temperature
% differs from the current optimal function value by less than
% optim.TolFun, execution terminates and exitflag = 0 is returned.
% optim.ns - Number of cycles. After NS*N function evaluations, each
% element of VM is adjusted so that approximately half of
% all function evaluations are accepted. The suggested value
% is 20.
% optim.nt - Number of iterations before temperature reduction. After
% NT*NS*N function evaluations, temperature (T) is changed
% by the factor optim.RT. Value suggested by Corana et al. is
% max(100, 5*n). See Goffe et al. for further advice.
% optim.neps - Number of final function values used to decide upon termi-
% nation. See optim.TolFun. Suggested value is 4.
% optim.MaxIter - Maximum number of function evaluations. If it is
% exceeded, exitflag = 1.
% optim.step_length_c - Vector that controls the step length adjustment. The suggested
% value for all elements is 2.0.
% optim.verbosity - controls printing inside SA.
% Values: 0 - Nothing printed.
% 1 - Function value for the starting value and summary results before each temperature
% reduction. This includes the optimal function value found so far, the total
% number of moves (broken up into uphill, downhill, accepted and rejected), the
% number of out of bounds trials, the number of new optima found at this
% temperature, the current optimal X and the step length VM. Note that there are
% N*NS*NT function evalutations before each temperature reduction. Finally, notice is
% is also given upon achieveing the termination criteria.
% 2 - Each new step length (VM), the current optimal X (XOPT) and the current trial X (X). This
% gives the user some idea about how far X strays from XOPT as well as how VM is adapting
% to the function.
% 3 - Each function evaluation, its acceptance or rejection and new optima. For many problems,
% this option will likely require a small tree if hard copy is used. This option is best
% used to learn about the algorithm. A small value for optim.MaxIter is thus recommended when
% using optim.verbosity = 3.
% optim.initial_temperature initial temperature. See Goffe et al. for advice.
% optim.initial_step_length (VM) step length vector. On input it should encompass the
% region of interest given the starting value X. For point
% X(I), the next trial point is selected is from X(I) - VM(I)
% to X(I) + VM(I). Since VM is adjusted so that about half
% of all points are accepted, the input value is not very
% important (i.e. is the value is off, SA adjusts VM to the
% correct value)
%
% lb - The lower bound for the allowable solution variables.
% ub - The upper bound for the allowable solution variables.
% If the algorithm chooses X(I) < LB(I) or X(I) > UB(I),
% I = 1, N, a point is from inside is randomly selected.
% This focuses the algorithm on the region inside UB and LB.
% Unless the user wishes to concentrate the search to a par-
% ticular region, UB and LB should be set to very large positive
% and negative values, respectively. Note that the starting
% vector X should be inside this region. Also note that LB and
% UB are fixed in position, while VM is centered on the last
% accepted trial set of variables that optimizes the function.
%
%
% Input/Output Parameters:
%
% Output Parameters:
% xopt - The variables that optimize the function. (N)
% fopt - The optimal value of the function.
% exitflag - The error return number.
% Values: 0 - Normal return termination criteria achieved.
% 1 - Number of function evaluations (NFCNEV) is
% greater than the maximum number (optim.MaxIter).
% 2 - The starting value (X) is not inside the
% bounds (LB and UB).
% 3 - The initial temperature is not positive.
% 99 - Should not be seen only used internally.
% n_accepted_draws - The number of accepted function evaluations.
% n_total_draws - The total number of function evaluations. In a minor
% point, note that the first evaluation is not used in the
% core of the algorithm it simply initializes the
% algorithm.
% n_out_of_bounds_draws - The total number of trial function evaluations that
% would have been out of bounds of LB and UB. Note that
% a trial point is randomly selected between LB and UB.
% t: On output, the final temperature.
% vm: Final step length vector
%
% Algorithm:
% This routine implements the continuous simulated annealing global
% optimization algorithm described in Corana et al.'s article
% "Minimizing Multimodal Functions of Continuous Variables with the
% "Simulated Annealing" Algorithm" in the September 1987 (vol. 13,
% no. 3, pp. 262-280) issue of the ACM Transactions on Mathematical
% Software.
%
% For modifications to the algorithm and many details on its use,
% (particularly for econometric applications) see Goffe, Ferrier
% and Rogers, "Global Optimization of Statistical Functions with
% Simulated Annealing," Journal of Econometrics, vol. 60, no. 1/2,
% Jan./Feb. 1994, pp. 65-100.
%
% Based on the Matlab code written by Thomas Werner (Bundesbank December
% 2002), which in turn is based on the GAUSS version of Bill Goffe's simulated annealing
% program for global optimization, written by E.G.Tsionas (9/4/95).
%
% Copyright (C) 1995 E.G.Tsionas
% Copyright (C) 1995-2002 Thomas Werner
% Copyright (C) 2002-2015 Giovanni Lombardo
% Copyright (C) 2015 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/>.
c=optim.step_length_c;
t=optim.initial_temperature;
vm=optim.initial_step_length;
n=size(x,1);
xp=zeros(n,1);
%* Set initial values.*
n_accepted_draws=0;
n_out_of_bounds_draws=0;
n_total_draws=0;
exitflag=99;
xopt=x;
nacp=zeros(n,1);
fstar=1e20*ones(optim.neps,1);
%* If the initial temperature is not positive, notify the user and abort. *
if(t<=0.0);
fprintf('\nThe initial temperature is not positive. Reset the variable t\n');
exitflag=3;
return;
end;
%* If the initial value is out of bounds, notify the user and abort. *
if(sum(x>ub)+sum(x<lb)>0);
fprintf('\nInitial condition out of bounds\n');
exitflag=2;
return;
end;
%* Evaluate the function with input x and return value as f. *
f=feval(fcn,x,varargin{:});
%*
% If the function is to be minimized, switch the sign of the function.
% Note that all intermediate and final output switches the sign back
% to eliminate any possible confusion for the user.
%*
if(optim.maximizer_indicator==0);
f=-f;
end;
n_total_draws=n_total_draws+1;
fopt=f;
fstar(1)=f;
if(optim.verbosity >1);
disp ' ';
disp(['initial x ' num2str(x(:)')]);
if(optim.maximizer_indicator);
disp(['initial f ' num2str(f)]);
else
disp(['initial f ' num2str(-f)]);
end;
end;
% Start the main loop. Note that it terminates if (i) the algorithm
% succesfully optimizes the function or (ii) there are too many
% function evaluations (more than optim.MaxIter).
while (1>0);
nup=0;
nrej=0;
nnew=0;
ndown=0;
lnobds=0;
m=1;
while m<=optim.nt;
j=1;
while j<=optim.ns;
h=1;
while h<=n;
%* Generate xp, the trial value of x. Note use of vm to choose xp. *
i=1;
while i<=n;
if(i==h);
xp(i)=x(i)+(rand(1,1)*2.0-1.0)*vm(i);
else
xp(i)=x(i);
end;
%* If xp is out of bounds, select a point in bounds for the trial. *
if((xp(i)<lb(i) || xp(i)>ub(i)));
xp(i)=lb(i)+(ub(i)-lb(i))*rand(1,1);
lnobds=lnobds+1;
n_out_of_bounds_draws=n_out_of_bounds_draws+1;
if(optim.verbosity >=3);
if exist('fp','var')
print_current_invalid_try(optim.maximizer_indicator,xp,x,fp,f);
end
end;
end;
i=i+1;
end;
%* Evaluate the function with the trial point xp and return as fp. *
% fp=feval(fcn,xp,listarg);
fp=feval(fcn,xp,varargin{:});
if(optim.maximizer_indicator==0);
fp=-fp;
end;
n_total_draws=n_total_draws+1;
if(optim.verbosity >=3);
print_current_valid_try(optim.maximizer_indicator,xp,x,fp,f);
end;
%* If too many function evaluations occur, terminate the algorithm. *
if(n_total_draws>=optim.MaxIter);
fprintf('Too many function evaluations; consider\n');
fprintf('increasing optim.MaxIter or optim.TolFun or decreasing\n');
fprintf('optim.nt or optim.rt. These results are likely to be poor\n');
if(optim.maximizer_indicator==0);
fopt=-fopt;
end;
exitflag=1;
return;
end;
%* Accept the new point if the function value increases. *
if(fp>=f);
if(optim.verbosity >=3);
fprintf('point accepted\n');
end;
x=xp;
f=fp;
n_accepted_draws=n_accepted_draws+1;
nacp(h)=nacp(h)+1;
nup=nup+1;
%* If greater than any other point, record as new optimum. *
if(fp>fopt);
if(optim.verbosity >=3);
fprintf('new optimum\n');
end;
xopt=xp;
fopt=fp;
nnew=nnew+1;
end;
%*
% If the point is lower, use the Metropolis criteria to decide on
% acceptance or rejection.
%*
else
p=exp((fp-f)/t);
pp=rand(1,1);
if(pp<p);
if(optim.verbosity >=3);
if(optim.maximizer_indicator);
fprintf('though lower, point accepted\n');
else
fprintf('though higher, point accepted\n');
end;
end;
x=xp;
f=fp;
n_accepted_draws=n_accepted_draws+1;
nacp(h)=nacp(h)+1;
ndown=ndown+1;
else
nrej=nrej+1;
if(optim.verbosity >=3);
if(optim.maximizer_indicator);
fprintf('lower point rejected\n');
else
fprintf('higher point rejected\n');
end;
end;
end;
end;
h=h+1;
end;
j=j+1;
end;
%* Adjust vm so that approximately half of all evaluations are accepted. *
i=1;
while i<=n;
ratio=nacp(i)/optim.ns;
if(ratio>.6);
vm(i)=vm(i)*(1.+c(i)*(ratio-.6)/.4);
elseif(ratio<.4);
vm(i)=vm(i)/(1.+c(i)*((.4-ratio)/.4));
end;
if(vm(i)>(ub(i)-lb(i)));
vm(i)=ub(i)-lb(i);
end;
i=i+1;
end;
if(optim.verbosity >=2);
fprintf('intermediate results after step length adjustment\n');
fprintf('new step length(vm) %4.3f', vm(:)');
fprintf('current optimal x %4.3f', xopt(:)');
fprintf('current x %4.3f', x(:)');
end;
nacp=zeros(n,1);
m=m+1;
end;
if(optim.verbosity >=1);
print_intermediate_statistics(optim.maximizer_indicator,t,xopt,vm,fopt,nup,ndown,nrej,lnobds,nnew);
end;
%* Check termination criteria. *
quit=0;
fstar(1)=f;
if((fopt-fstar(1))<=optim.TolFun);
quit=1;
end;
if(sum(abs(f-fstar)>optim.TolFun)>0);
quit=0;
end;
%* Terminate SA if appropriate. *
if(quit);
exitflag=0;
if(optim.maximizer_indicator==0);
fopt=-fopt;
end;
if(optim.verbosity >=1);
fprintf('SA achieved termination criteria.exitflag=0\n');
end;
return;
end;
%* If termination criteria are not met, prepare for another loop. *
t=optim.rt*t;
i=optim.neps;
while i>=2;
fstar(i)=fstar(i-1);
i=i-1;
end;
f=fopt;
x=xopt;
%* Loop again. *
end;
end
function print_current_invalid_try(max,xp,x,fp,f)
fprintf('\n');
disp(['Current x ' num2str(x(:)')]);
if(max);
disp(['Current f ' num2str(f)]);
else
disp(['Current f ' num2str(-f)]);
end;
disp(['Trial x ' num2str(xp(:)')]);
disp 'Point rejected since out of bounds';
end
function print_current_valid_try(max,xp,x,fp,f)
disp(['Current x ' num2str(x(:)')]);
if(max);
disp(['Current f ' num2str(f)]);
disp(['Trial x ' num2str(xp(:)')]);
disp(['Resulting f ' num2str(fp)]);
else
disp(['Current f ' num2str(-f)]);
disp(['Trial x ' num2str(xp(:)')]);
disp(['Resulting f ' num2str(-fp)]);
end;
end
function print_intermediate_statistics(max,t,xopt,vm,fopt,nup,ndown,nrej,lnobds,nnew)
totmov=nup+ndown+nrej;
fprintf('\nIntermediate results before next temperature reduction\n');
disp(['current temperature ' num2str(t)]);
if(max)
disp(['Max function value so far ' num2str(fopt)]);
disp(['Total moves ' num2str(totmov)]);
disp(['Uphill ' num2str(nup)]);
disp(['Accepted downhill ' num2str(ndown)]);
disp(['Rejected downhill ' num2str(nrej)]);
disp(['Out of bounds trials ' num2str(lnobds)]);
disp(['New maxima this temperature ' num2str(nnew)]);
else
disp(['Min function value so far ' num2str(-fopt)]);
disp(['Total moves ' num2str(totmov)]);
disp(['Downhill ' num2str(nup)]);
disp(['Accepted uphill ' num2str(ndown)]);
disp(['Rejected uphill ' num2str(nrej)]);
disp(['Trials out of bounds ' num2str(lnobds)]);
disp(['New minima this temperature ' num2str(nnew)]);
end
xopt1=xopt(1:round(length(xopt)/2));
xopt2=xopt(round(length(xopt)/2)+1:end);
disp(['Current optimal x1 ' num2str(xopt1')]);
disp(['Current optimal x2 ' num2str(xopt2')]);
disp(['Strength(vm) ' num2str(vm')]);
fprintf('\n');
end

View File

@ -0,0 +1,991 @@
function [x,f,exitflag,n_f_evals,n_grad_evals,n_constraint_evals,n_constraint_gradient_evals]=solvopt(x,fun,grad,func,gradc,optim,varargin)
% [x,f,options]=solvopt(x,fun,grad,func,gradc,options,varargin)
%
% The function SOLVOPT, developed by Alexei Kuntsevich and Franz Kappe,
% performs a modified version of Shor's r-algorithm in
% order to find a local minimum resp. maximum of a nonlinear function
% defined on the n-dimensional Euclidean space or % a solution of a nonlinear
% constrained problem:
% min { f(x): g(x) (<)= 0, g(x) in R(m), x in R(n) }
%
% Inputs:
% x n-vector (row or column) of the coordinates of the starting
% point,
% fun name of an M-file (M-function) which computes the value
% of the objective function <fun> at a point x,
% synopsis: f=fun(x)
% grad name of an M-file (M-function) which computes the gradient
% vector of the function <fun> at a point x,
% synopsis: g=grad(x)
% func name of an M-file (M-function) which computes the MAXIMAL
% RESIDUAL(!) for a set of constraints at a point x,
% synopsis: fc=func(x)
% gradc name of an M-file (M-function) which computes the gradient
% vector for the maximal residual constraint at a point x,
% synopsis: gc=gradc(x)
% optim Options structure with fields:
% optim.minimizer_indicator= H, where sign(H)=-1 resp. sign(H)=+1 means minimize
% resp. maximize <fun> (valid only for unconstrained problem)
% and H itself is a factor for the initial trial step size
% (optim.minimizer_indicator=-1 by default),
% optim.TolX= relative error for the argument in terms of the
% infinity-norm (1.e-4 by default),
% optim.TolFun= relative error for the function value (1.e-6 by default),
% optim.MaxIter= limit for the number of iterations (15000 by default),
% optim.verbosity= control of the display of intermediate results and error
% resp. warning messages (default value is 0, i.e., no intermediate
% output but error and warning messages, see more in the manual),
% optim.TolXConstraint= admissible maximal residual for a set of constraints
% (optim.TolXConstraint=1e-8 by default, see more in the manual),
% *optim.SpaceDilation= the coefficient of space dilation (2.5 by default),
% *optim.LBGradientStep= lower bound for the stepsize used for the difference
% approximation of gradients (1e-12 by default, see more in the manual).
% (* ... changes should be done with care)
%
% Outputs:
% x optimal parameter vector (row resp. column),
% f optimum function value
% exitflag: the number of iterations, if positive,
% or an abnormal stop code, if negative (see more in the manual),
% n_f_evals: number of objective evaluations
% n_grad_evals: number of gradient evaluations,
% n_constraint_evals: number of constraint function evaluations,
% n_constraint_gradient_evals number of constraint gradient evaluations.
%
%
% Algorithm: Kuntsevich, A.V., Kappel, F., SolvOpt - The solver for local nonlinear optimization problems
% (version 1.1, Matlab, C, FORTRAN). University of Graz, Graz, 1997.
%
%
% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel
% Copyright (C) 2008-2015 Giovanni Lombardo
% Copyright (C) 2015 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/>.
% strings: ----{
errmes='SolvOpt error:';
wrnmes='SolvOpt warning:';
error1='No function name and/or starting point passed to the function.';
error2='Argument X has to be a row or column vector of dimension > 1.';
error30='<fun> returns an empty string.';
error31='Function value does not exist (NaN is returned).';
error32='Function equals infinity at the point.';
error40='<grad> returns an improper matrix. Check the dimension.';
error41='Gradient does not exist (NaN is returned by <grad>).';
error42='Gradient equals infinity at the starting point.';
error43='Gradient equals zero at the starting point.';
error50='<func> returns an empty string.';
error51='<func> returns NaN at the point.';
error52='<func> returns infinite value at the point.';
error60='<gradc> returns an improper vector. Check the dimension';
error61='<gradc> returns NaN at the point.';
error62='<gradc> returns infinite vector at the point.';
error63='<gradc> returns zero vector at an infeasible point.';
error5='Function is unbounded.';
error6='Choose another starting point.';
warn1= 'Gradient is zero at the point, but stopping criteria are not fulfilled.';
warn20='Normal re-setting of a transformation matrix.' ;
warn21='Re-setting due to the use of a new penalty coefficient.' ;
warn4= 'Iterations limit exceeded.';
warn31='The function is flat in certain directions.';
warn32='Trying to recover by shifting insensitive variables.';
warn09='Re-run from recorded point.';
warn08='Ravine with a flat bottom is detected.';
termwarn0='SolvOpt: Normal termination.';
termwarn1='SolvOpt: Termination warning:';
appwarn='The above warning may be reasoned by inaccurate gradient approximation';
endwarn=[...
'Premature stop is possible. Try to re-run the routine from the obtained point. ';...
'Result may not provide the optimum. The function apparently has many extremum points. ';...
'Result may be inaccurate in the coordinates. The function is flat at the optimum. ';...
'Result may be inaccurate in a function value. The function is extremely steep at the optimum.'];
% ----}
% ARGUMENTS PASSED ----{
if nargin<2 % Function and/or starting point are not specified
exitflag=-1;
disp(errmes);
disp(error1);
return
end
if nargin<3
app=1; % No user-supplied gradients
elseif isempty(grad)
app=1;
else
app=0; % Exact gradients are supplied
end
% OPTIONS ----{
doptions.minimizer_indicator=1;
doptions.TolX=1e-6; %accuracy of argument
doptions.TolFun=1e-6; %accuracy of function (see Solvopt p.29)
doptions.MaxIter=15000;
doptions.verbosity=1;
doptions.TolXConstraint=1.e-8;
doptions.SpaceDilation=2.5;
doptions.LBGradientStep=1.e-11;
if nargin<4
optim=doptions;
elseif isempty(optim)
optim=doptions;
end
% Check the values:
optim.TolX=max(optim.TolX,1.e-12);
optim.TolFun=max(optim.TolFun,1.e-12);
optim.TolX=max(optim.LBGradientStep*1.e2,optim.TolX);
optim.TolX=min(optim.TolX,1);
optim.TolFun=min(optim.TolFun,1);
optim.TolXConstraint=max(optim.TolXConstraint,1e-12);
optim.SpaceDilation=max([optim.SpaceDilation,1.5]);
optim.LBGradientStep=max(optim.LBGradientStep,1e-11);
% ----}
if isempty(func)
constr=0;
else
constr=1; % Constrained problem
if isempty(gradc),
appconstr=1;
else
appconstr=0; % Exact gradients of constraints are supplied
end
end
% ----}
% STARTING POINT ----{
if max(size(x))<=1
disp(errmes);
disp(error2);
exitflag=-2;
return
elseif size(x,2)==1
n=size(x,1);
x=x';
trx=1;
elseif size(x,1)==1
n=size(x,2);
trx=0;
else
disp(errmes);
disp(error2);
exitflag=-2;
return
end
% ----}
% WORKING CONSTANTS AND COUNTERS ----{
n_f_evals=0; n_grad_evals=0; % function and gradient calculations
if constr
n_constraint_evals=0;
n_constraint_gradient_evals=0; % same for constraints
end
epsnorm=1.e-15;
epsnorm2=1.e-30; % epsilon & epsilon^2
if constr, h1=-1; % NLP: restricted to minimization
cnteps=optim.TolXConstraint; % Max. admissible residual
else
h1=sign(optim.minimizer_indicator); % Minimize resp. maximize a function
end
k=0; % Iteration counter
wdef=1/optim.SpaceDilation-1; % Default space transf. coeff.
%Gamma control ---{
ajb=1+.1/n^2; % Base I
ajp=20;
ajpp=ajp; % Start value for the power
ajs=1.15; % Base II
knorms=0; gnorms=zeros(1,10); % Gradient norms stored
%---}
%Display control ---{
if optim.verbosity<=0, dispdata=0;
if optim.verbosity==-1
dispwarn=0;
else
dispwarn=1;
end
else
dispdata=round(optim.verbosity);
dispwarn=1;
end
ld=dispdata;
%---}
%Stepsize control ---{
dq=5.1; % Step divider (at f_{i+1}>gamma*f_{i})
du20=2;du10=1.5;du03=1.05; % Step multipliers (at certain steps made)
kstore=3;nsteps=zeros(1,kstore); % Steps made at the last 'kstore' iterations
if app
des=6.3; % Desired number of steps per 1-D search
else
des=3.3;
end
mxtc=3; % Number of trial cycles (steep wall detect)
%---}
termx=0; limxterm=50; % Counter and limit for x-criterion
ddx =max(1e-11,optim.LBGradientStep); % stepsize for gradient approximation
low_bound=-1+1e-4; % Lower bound cosine used to detect a ravine
ZeroGrad=n*1.e-16; % Lower bound for a gradient norm
nzero=0; % Zero-gradient events counter
% Lower bound for values of variables taking into account
lowxbound=max([optim.TolX,1e-3]);
% Lower bound for function values to be considered as making difference
lowfbound=optim.TolFun^2;
krerun=0; % Re-run events counter
detfr=optim.TolFun*100; % relative error for f/f_{record}
detxr=optim.TolX*10; % relative error for norm(x)/norm(x_{record})
warnno=0; % the number of warn.mess. to end with
kflat=0; % counter for points of flatness
stepvanish=0; % counter for vanished steps
stopf=0;
% ----} End of setting constants
% ----} End of the preamble
% COMPUTE THE FUNCTION ( FIRST TIME ) ----{
if trx
f=feval(fun,x',varargin{:});
else
f=feval(fun,x,varargin{:});
end
n_f_evals=n_f_evals+1;
if isempty(f), if dispwarn,disp(errmes);disp(error30);end
exitflag=-3; if trx, x=x';end, return
elseif isnan(f), if dispwarn,disp(errmes);disp(error31);disp(error6);end
exitflag=-3; if trx, x=x';end, return
elseif abs(f)==Inf, if dispwarn,disp(errmes);disp(error32);disp(error6);end
exitflag=-3; if trx, x=x';end, return
end
xrec=x; frec=f; % record point and function value
% Constrained problem
if constr, fp=f; kless=0;
if trx,
fc=feval(func,x');
else
fc=feval(func,x);
end
if isempty(fc),
if dispwarn,disp(errmes);disp(error50);end
exitflag=-5; if trx, x=x';end, return
elseif isnan(fc),
if dispwarn,disp(errmes);disp(error51);disp(error6);end
exitflag=-5; if trx, x=x';end, return
elseif abs(fc)==Inf,
if dispwarn,disp(errmes);disp(error52);disp(error6);end
exitflag=-5; if trx, x=x';end, return
end
n_constraint_evals=n_constraint_evals+1;
PenCoef=1; % first rough approximation
if fc<=cnteps
FP=1; fc=0; % feasible point
else
FP=0; % infeasible point
end
f=f+PenCoef*fc;
end
% ----}
% COMPUTE THE GRADIENT ( FIRST TIME ) ----{
if app
deltax=h1*ddx*ones(size(x));
if constr
if trx
g=apprgrdn(x',fp,fun,deltax',1,varargin{:});
else
g=apprgrdn(x ,fp,fun,deltax,1,varargin{:});
end
else
if trx
g=apprgrdn(x',f,fun,deltax',1,varargin{:});
else
g=apprgrdn(x ,f,fun,deltax,1,varargin{:});
end
end
n_f_evals=n_f_evals+n;
else
if trx
g=feval(grad,x',varargin{:});
else
g=feval(grad,x,varargin{:});
end
n_grad_evals=n_grad_evals+1;
end
if size(g,2)==1, g=g'; end, ng=norm(g);
if size(g,2)~=n, if dispwarn,disp(errmes);disp(error40);end
exitflag=-4; if trx, x=x';end, return
elseif isnan(ng), if dispwarn,disp(errmes);disp(error41);disp(error6);end
exitflag=-4; if trx, x=x';end, return
elseif ng==Inf, if dispwarn,disp(errmes);disp(error42);disp(error6);end
exitflag=-4; if trx, x=x';end, return
elseif ng<ZeroGrad, if dispwarn,disp(errmes);disp(error43);disp(error6);end
exitflag=-4; if trx, x=x';end, return
end
if constr
if ~FP
if appconstr,
deltax=sign(x); idx=find(deltax==0);
deltax(idx)=ones(size(idx));
deltax=ddx*deltax;
if trx
gc=apprgrdn(x',fc,func,deltax',0);
else
gc=apprgrdn(x ,fc,func,deltax ,0);
end
n_constraint_evals=n_constraint_evals+n;
else
if trx
gc=feval(gradc,x');
else
gc=feval(gradc,x);
end
n_constraint_gradient_evals=n_constraint_gradient_evals+1;
end
if size(gc,2)==1
gc=gc';
end
ngc=norm(gc);
if size(gc,2)~=n,
if dispwarn
disp(errmes);
disp(error60);
end
exitflag=-6;
if trx
x=x';
end
return
elseif isnan(ngc),
if dispwarn
disp(errmes);
disp(error61);
disp(error6);
end
exitflag=-6;
if trx
x=x';
end
return
elseif ngc==Inf,
if dispwarn
disp(errmes);
disp(error62);
disp(error6);
end
exitflag=-6;
if trx
x=x';
end
return
elseif ngc<ZeroGrad,
if dispwarn
disp(errmes);
disp(error63);
end
exitflag=-6;
if trx
x=x';
end
return
end
g=g+PenCoef*gc; ng=norm(g);
end, end
grec=g; nng=ng;
% ----}
% INITIAL STEPSIZE
h=h1*sqrt(optim.TolX)*max(abs(x)); % smallest possible stepsize
if abs(optim.minimizer_indicator)~=1,
h=h1*max(abs([optim.minimizer_indicator,h])); % user-supplied stepsize
else
h=h1*max(1/log(ng+1.1),abs(h)); % calculated stepsize
end
% RESETTING LOOP ----{
while 1,
kcheck=0; % Set checkpoint counter.
kg=0; % stepsizes stored
kj=0; % ravine jump counter
B=eye(n); % re-set transf. matrix to identity
fst=f; g1=g; dx=0;
% ----}
% MAIN ITERATIONS ----{
while 1,
k=k+1;kcheck=kcheck+1;
laststep=dx;
% ADJUST GAMMA --{
gamma=1+max([ajb^((ajp-kcheck)*n),2*optim.TolFun]);
gamma=min([gamma,ajs^max([1,log10(nng+1)])]);
% --}
gt=g*B; w=wdef;
% JUMPING OVER A RAVINE ----{
if (gt/norm(gt))*(g1'/norm(g1))<low_bound
if kj==2, xx=x; end, if kj==0, kd=4; end,
kj=kj+1; w=-.9; h=h*2; % use large coef. of space dilation
if kj>2*kd, kd=kd+1; warnno=1;
if any(abs(x-xx)<epsnorm*abs(x)), % flat bottom is detected
if dispwarn,disp(wrnmes);disp(warn08); end
end
end
else
kj=0;
end
% ----}
% DILATION ----{
z=gt-g1;
nrmz=norm(z);
if(nrmz>epsnorm*norm(gt))
z=z/nrmz;
g1=gt+w*(z*gt')*z; B=B+w*(B*z')*z;
else
z=zeros(1,n);
nrmz=0;
g1=gt;
end
d1=norm(g1); g0=(g1/d1)*B';
% ----}
% RESETTING ----{
if kcheck>1
idx=find(abs(g)>ZeroGrad); numelem=size(idx,2);
if numelem>0, grbnd=epsnorm*numelem^2;
if all(abs(g1(idx))<=abs(g(idx))*grbnd) | nrmz==0
if dispwarn, disp(wrnmes); disp(warn20); end
if abs(fst-f)<abs(f)*.01
ajp=ajp-10*n;
else
ajp=ajpp;
end
h=h1*dx/3;
k=k-1;
break
end
end
end
% ----}
% STORE THE CURRENT VALUES AND SET THE COUNTERS FOR 1-D SEARCH
xopt=x;fopt=f; k1=0;k2=0;ksm=0;kc=0;knan=0; hp=h;
if constr, Reset=0; end
% 1-D SEARCH ----{
while 1,
x1=x;f1=f;
if constr, FP1=FP; fp1=fp; end
x=x+hp*g0;
% FUNCTION VALUE
if trx
f=feval(fun,x',varargin{:});
else
f=feval(fun,x,varargin{:});
end
n_f_evals=n_f_evals+1;
if h1*f==Inf
if dispwarn
disp(errmes);
disp(error5);
end
exitflag=-7;
if trx
x=x';
end
return
end
if constr, fp=f;
if trx
fc=feval(func,x');
else
fc=feval(func,x);
end
n_constraint_evals=n_constraint_evals+1;
if isnan(fc),
if dispwarn,disp(errmes);disp(error51);disp(error6);end
exitflag=-5; if trx, x=x';end, return
elseif abs(fc)==Inf,
if dispwarn,disp(errmes);disp(error52);disp(error6);end
exitflag=-5; if trx, x=x';end, return
end
if fc<=cnteps
FP=1;
fc=0;
else
FP=0;
fp_rate=(fp-fp1);
if fp_rate<-epsnorm
if ~FP1
PenCoefNew=-15*fp_rate/norm(x-x1);
if PenCoefNew>1.2*PenCoef,
PenCoef=PenCoefNew; Reset=1; kless=0; f=f+PenCoef*fc; break
end
end
end
end
f=f+PenCoef*fc;
end
if abs(f)==Inf || isnan(f)
if dispwarn, disp(wrnmes);
if isnan(f)
disp(error31);
else
disp(error32);
end
end
if ksm || kc>=mxtc
exitflag=-3;
if trx
x=x';
end
return
else
k2=k2+1;
k1=0;
hp=hp/dq;
x=x1;
f=f1;
knan=1;
if constr
FP=FP1;
fp=fp1;
end
end
% STEP SIZE IS ZERO TO THE EXTENT OF EPSNORM
elseif all(abs(x-x1)<abs(x)*epsnorm),
stepvanish=stepvanish+1;
if stepvanish>=5,
exitflag=-14;
if dispwarn, disp(termwarn1);
disp(endwarn(4,:)); end
if trx,x=x';end, return
else
x=x1;
f=f1;
hp=hp*10;
ksm=1;
if constr
FP=FP1;
fp=fp1;
end
end
% USE SMALLER STEP
elseif h1*f<h1*gamma^sign(f1)*f1
if ksm,break,end, k2=k2+1;k1=0; hp=hp/dq; x=x1;f=f1;
if constr, FP=FP1; fp=fp1; end
if kc>=mxtc, break, end
% 1-D OPTIMIZER IS LEFT BEHIND
else if h1*f<=h1*f1, break, end
% USE LARGER STEP
k1=k1+1; if k2>0, kc=kc+1; end, k2=0;
if k1>=20, hp=du20*hp;
elseif k1>=10, hp=du10*hp;
elseif k1>=3, hp=du03*hp;
end
end
end
% ----} End of 1-D search
% ADJUST THE TRIAL STEP SIZE ----{
dx=norm(xopt-x);
if kg<kstore, kg=kg+1; end
if kg>=2, nsteps(2:kg)=nsteps(1:kg-1); end
nsteps(1)=dx/(abs(h)*norm(g0));
kk=sum(nsteps(1:kg).*[kg:-1:1])/sum([kg:-1:1]);
if kk>des
if kg==1
h=h*(kk-des+1);
else
h=h*sqrt(kk-des+1);
end
elseif kk<des
h=h*sqrt(kk/des);
end
stepvanish=stepvanish+ksm;
% ----}
% COMPUTE THE GRADIENT ----{
if app,
deltax=sign(g0); idx=find(deltax==0);
deltax(idx)=ones(size(idx)); deltax=h1*ddx*deltax;
if constr
if trx
g=apprgrdn(x',fp,fun,deltax',1,varargin{:});
else
g=apprgrdn(x ,fp,fun,deltax,1,varargin{:});
end
else
if trx
g=apprgrdn(x',f,fun,deltax',1,varargin{:});
else
g=apprgrdn(x ,f,fun,deltax ,1,varargin{:});
end
end
n_f_evals=n_f_evals+n;
else
if trx
g=feval(grad,x',varargin{:});
else
g=feval(grad,x,varargin{:});
end
n_grad_evals=n_grad_evals+1;
end
if size(g,2)==1, g=g'; end, ng=norm(g);
if isnan(ng),
if dispwarn, disp(errmes); disp(error41); end
exitflag=-4; if trx, x=x'; end, return
elseif ng==Inf,
if dispwarn,disp(errmes);disp(error42);end
exitflag=-4; if trx, x=x';end, return
elseif ng<ZeroGrad,
if dispwarn,disp(wrnmes);disp(warn1);end
ng=ZeroGrad;
end
% Constraints:
if constr
if ~FP
if ng<.01*PenCoef
kless=kless+1;
if kless>=20, PenCoef=PenCoef/10; Reset=1; kless=0; end
else
kless=0;
end
if appconstr,
deltax=sign(x); idx=find(deltax==0);
deltax(idx)=ones(size(idx)); deltax=ddx*deltax;
if trx
gc=apprgrdn(x',fc,func,deltax',0);
else
gc=apprgrdn(x ,fc,func,deltax ,0);
end
n_constraint_evals=n_constraint_evals+n;
else
if trx
gc=feval(gradc,x');
else
gc=feval(gradc,x );
end
n_constraint_gradient_evals=n_constraint_gradient_evals+1;
end
if size(gc,2)==1, gc=gc'; end, ngc=norm(gc);
if isnan(ngc),
if dispwarn,disp(errmes);disp(error61);end
exitflag=-6; if trx, x=x';end, return
elseif ngc==Inf,
if dispwarn,disp(errmes);disp(error62);end
exitflag=-6; if trx, x=x';end, return
elseif ngc<ZeroGrad && ~appconstr,
if dispwarn,disp(errmes);disp(error63);end
exitflag=-6; if trx, x=x';end, return
end
g=g+PenCoef*gc; ng=norm(g);
if Reset, if dispwarn, disp(wrnmes); disp(warn21); end
h=h1*dx/3; k=k-1; nng=ng; break
end
end, end
if h1*f>h1*frec, frec=f; xrec=x; grec=g; end
% ----}
if ng>ZeroGrad,
if knorms<10, knorms=knorms+1; end
if knorms>=2, gnorms(2:knorms)=gnorms(1:knorms-1); end
gnorms(1)=ng;
nng=(prod(gnorms(1:knorms)))^(1/knorms);
end
% DISPLAY THE CURRENT VALUES ----{
if k==ld
disp('Iter.# ..... Function ... Step Value ... Gradient Norm ');
disp(sprintf('%5i %13.5e %13.5e %13.5e',k,f,dx,ng));
ld=k+dispdata;
end
%----}
% CHECK THE STOPPING CRITERIA ----{
termflag=1;
if constr, if ~FP, termflag=0; end, end
if kcheck<=5, termflag=0; end
if knan, termflag=0; end
if kc>=mxtc, termflag=0; end
% ARGUMENT
if termflag
idx=find(abs(x)>=lowxbound);
if isempty(idx) || all(abs(xopt(idx)-x(idx))<=optim.TolX*abs(x(idx)))
termx=termx+1;
% FUNCTION
if abs(f-frec)> detfr * abs(f) && ...
abs(f-fopt)<=optim.TolFun*abs(f) && ...
krerun<=3 && ...
~constr
if any(abs(xrec(idx)-x(idx))> detxr * abs(x(idx)))
if dispwarn
disp(wrnmes);
disp(warn09);
end
x=xrec;
f=frec;
g=grec;
ng=norm(g);
krerun=krerun+1;
h=h1*max([dx,detxr*norm(x)])/krerun;
warnno=2;
break
else
h=h*10;
end
elseif abs(f-frec)> optim.TolFun*abs(f) && ...
norm(x-xrec)<optim.TolX*norm(x) && constr
elseif abs(f-fopt)<=optim.TolFun*abs(f) || ...
abs(f)<=lowfbound || ...
(abs(f-fopt)<=optim.TolFun && termx>=limxterm )
if stopf
if dx<=laststep
if warnno==1 && ng<sqrt(optim.TolFun), warnno=0; end
if ~app, if any(abs(g)<=epsnorm2), warnno=3; end, end
if warnno~=0
exitflag=-warnno-10;
if dispwarn, disp(termwarn1);
disp(endwarn(warnno,:));
if app, disp(appwarn); end
end
else
exitflag=k;
if dispwarn
disp(termwarn0);
end
end
if trx
x=x';
end
return
end
else
stopf=1;
end
elseif dx<1.e-12*max(norm(x),1) && termx>=limxterm
exitflag=-14;
if dispwarn, disp(termwarn1); disp(endwarn(4,:));
if app, disp(appwarn); end
end
x=xrec; f=frec;
if trx,x=x';end, return
else
stopf=0;
end
end
end
% ITERATIONS LIMIT
if(k==optim.MaxIter)
exitflag=-9;
if trx
x=x';
end,
if dispwarn, disp(wrnmes); disp(warn4); end
return
end
% ----}
% ZERO GRADIENT ----{
if constr
if ng<=ZeroGrad,
if dispwarn, disp(termwarn1); disp(warn1); end
exitflag=-8;
if trx
x=x';
end
return
end
else
if ng<=ZeroGrad, nzero=nzero+1;
if dispwarn, disp(wrnmes); disp(warn1); end
if nzero>=3
exitflag=-8;
if trx
x=x';
end
return
end
g0=-h*g0/2;
for i=1:10,
x=x+g0;
if trx
f=feval(fun,x',varargin{:});
else
f=feval(fun,x,varargin{:});
end
n_f_evals=n_f_evals+1;
if abs(f)==Inf
if dispwarn
disp(errmes);
disp(error32);
end
exitflag=-3;
if trx
x=x';
end
return
elseif isnan(f),
if dispwarn
disp(errmes);
disp(error32);
end
exitflag=-3;
if trx
x=x';
end
return
end
if app,
deltax=sign(g0);
idx=find(deltax==0);
deltax(idx)=ones(size(idx));
deltax=h1*ddx*deltax;
if trx
g=apprgrdn(x',f,fun,deltax',1,varargin{:});
else
g=apprgrdn(x,f,fun,deltax,1,varargin{:});
end
n_f_evals=n_f_evals+n;
else
if trx
g=feval(grad,x',varargin{:});
else
g=feval(grad,x,varargin{:});
end
n_grad_evals=n_grad_evals+1;
end
if size(g,2)==1
g=g';
end
ng=norm(g);
if ng==Inf
if dispwarn
disp(errmes);
disp(error42);
end
exitflag=-4;
if trx
x=x';
end
return
elseif isnan(ng)
if dispwarn
disp(errmes);
disp(error41);
end
exitflag=-4;
if trx
x=x';
end
return
end
if ng>ZeroGrad
break
end
end
if ng<=ZeroGrad,
if dispwarn
disp(termwarn1);
disp(warn1);
end
exitflag=-8;
if trx
x=x';
end
return
end
h=h1*dx;
break
end
end
% ----}
% FUNCTION IS FLAT AT THE POINT ----{
if ~constr && abs(f-fopt)<abs(fopt)*optim.TolFun && kcheck>5 && ng<1
idx=find(abs(g)<=epsnorm2);
ni=size(idx,2);
if ni>=1 && ni<=n/2 && kflat<=3, kflat=kflat+1;
if dispwarn, disp(wrnmes); disp(warn31); end, warnno=1;
x1=x; fm=f;
for j=idx, y=x(j); f2=fm;
if y==0, x1(j)=1; elseif abs(y)<1, x1(j)=sign(y); else, x1(j)=y; end
for i=1:20, x1(j)=x1(j)/1.15;
if trx
f1=feval(fun,x1',varargin{:});
else
f1=feval(fun,x1,varargin{:});
end
n_f_evals=n_f_evals+1;
if abs(f1)~=Inf && ~isnan(f1),
if h1*f1>h1*fm
y=x1(j);
fm=f1;
elseif h1*f2>h1*f1
break
elseif f2==f1
x1(j)=x1(j)/1.5;
end
f2=f1;
end
end
x1(j)=y;
end
if h1*fm>h1*f
if app,
deltax=h1*ddx*ones(size(deltax));
if trx
gt=apprgrdn(x1',fm,fun,deltax',1,varargin{:});
else
gt=apprgrdn(x1 ,fm,fun,deltax ,1,varargin{:});
end
n_f_evals=n_f_evals+n;
else
if trx
gt=feval(grad,x1',varargin{:});
else
gt=feval(grad,x1,varargin{:});
end
n_grad_evals=n_grad_evals+1;
end
if size(gt,2)==1
gt=gt';
end
ngt=norm(gt);
if ~isnan(ngt) && ngt>epsnorm2,
if dispwarn
disp(warn32);
end
optim.TolFun=optim.TolFun/5;
x=x1;
g=gt;
ng=ngt;
f=fm;
h=h1*dx/3;
break
end
end
end
end
% ----}
end % iterations
end % restart
% end of the function
%
end

74
matlab/optimize_prior.m Normal file
View File

@ -0,0 +1,74 @@
function optimize_prior(DynareOptions, ModelInfo, DynareResults, BayesInfo, EstimationInfo)
% This routine computes the mode of the prior density using an optimization algorithm.
% Copyright (C) 2015 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/>.
% Initialize to the prior mean
DynareResults.dr = set_state_space(DynareResults.dr,ModelInfo,DynareOptions);
xparam1 = BayesInfo.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);
[dr,INFO,ModelInfo,DynareOptions,DynareResults] = resol(0,ModelInfo,DynareOptions,DynareResults);
if ~INFO(1)
look_for_admissible_initial_condition = 0;
end
else
if iter == 2000;
scale = scale/1.1;
iter = 0;
else
iter = iter+1;
end
end
end
% Evaluate the prior density at the initial condition.
objective_function_penalty_base = minus_logged_prior_density(xinit, BayesInfo.pshape, ...
BayesInfo.p6, ...
BayesInfo.p7, ...
BayesInfo.p3, ...
BayesInfo.p4,DynareOptions,ModelInfo,EstimationInfo,DynareResults);
% 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);
% Display the results.
skipline(2)
disp('------------------')
disp('PRIOR OPTIMIZATION')
disp('------------------')
skipline()
for i = 1:length(xparams)
disp(['deep parameter ' int2str(i) ': ' get_the_name(i,0,ModelInfo,EstimationInfo,DynareOptions) '.'])
disp([' Initial condition ....... ' num2str(xinit(i)) '.'])
disp([' Prior mode .............. ' num2str(BayesInfo.p5(i)) '.'])
disp([' Optimized prior mode .... ' num2str(xparams(i)) '.'])
skipline()
end
skipline()

View File

@ -73,9 +73,6 @@ t0 = M_.params(i_params);
inv_order_var = oo_.dr.inv_order_var;
H0 = 1e-4*eye(np);
crit=options_.osr.tolf;
nit=options_.osr.maxit;
%extract unique entries of covariance
i_var=unique(i_var);
@ -93,20 +90,25 @@ if isinf(loss)
error('OSR: Initial likelihood is infinite')
end
if isequal(options_.osr.opt_algo,5)
error('OSR: OSR does not support opt_algo=5.')
elseif isequal(options_.osr.opt_algo,6)
error('OSR: OSR does not support opt_algo=6.')
elseif isequal(options_.osr.opt_algo,10)
error('OSR: OSR does not support opt_algo=10.')
else
%%do actual optimization
[f,p]=csminwel1('osr_obj',t0,H0,[],crit,nit,options_.gradient_method,options_.gradient_epsilon,i_params,...
[p, f, exitflag] = dynare_minimize_objective(str2func('osr_obj'),t0,options_.osr.opt_algo,options_,[],cellstr(M_.param_names(i_params,:)),[],[], i_params,...
inv_order_var(i_var),weights(i_var,i_var));
end
osr_res.objective_function = f;
M_.params(i_params)=p; %make sure optimal parameters are set (and not the last draw used in csminwel)
for i=1:length(i_params)
osr_res.optim_params.(deblank(M_.param_names(i_params(i),:))) = p(i);
end
% options = optimset('fminunc');
% options = optimset('display','iter');
% [p,f]=fminunc(@osr_obj,t0,options,i_params,...
% inv_order_var(i_var),weights(i_var,i_var));
skipline()
disp('OPTIMAL VALUE OF THE PARAMETERS:')
skipline()

View File

@ -3,28 +3,38 @@ function [fOutVar,nBlockPerCPU, totCPU] = masterParallel(Parallel,fBlock,nBlock,
% This is the most important function for the management of DYNARE parallel
% computing.
% It is the top-level function called on the master computer when parallelizing a task.
% This function has two main computational strategies for managing the matlab worker (slave process).
%
% This function has two main computational strategies for managing the
% matlab worker (slave process):
%
% 0 Simple Close/Open Stategy:
% In this case the new Matlab instances (slave process) are open when
% necessary and then closed. This can happen many times during the
% simulation of a model.
% In this case the new Matlab instances (slave process) are open when
% necessary and then closed. This can happen many times during the
% simulation of a model.
%
% 1 Always Open Strategy:
% In this case we have a more sophisticated management of slave processes,
% which are no longer closed at the end of each job. The slave processes
% wait for a new job (if it exists). If a slave does not receive a new job after a
% fixed time it is destroyed. This solution removes the computational
% time necessary to Open/Close new Matlab instances.
% In this case we have a more sophisticated management of slave processes,
% which are no longer closed at the end of each job. The slave processes
% wait for a new job (if it exists). If a slave does not receive a new job after a
% fixed time it is destroyed. This solution removes the computational
% time necessary to Open/Close new Matlab instances.
%
% The first (point 0) is the default Strategy
% i.e.(Parallel_info.leaveSlaveOpen=0). This value can be changed by the
% user in xxx.mod file or it is changed by the programmer if it is necessary to
% reduce the overall computational time. See for example the
% prior_posterior_statistics.m.
%
% The number of parallelized threads will be equal to (nBlock-fBlock+1).
%
% Treatment of global variables:
% Global variables used within the called function (e.g.
% objective_function_penalty_base) are wrapped and passed by storing their
% values at the start of the parallel computation in a file via
% storeGlobalVars.m. This file is then loaded in the separate,
% independent slave Matlab sessions. By keeping them separate, no
% interaction via global variables can take place.
%
% INPUTS
% o Parallel [struct vector] copy of options_.parallel
% o fBlock [int] index number of the first thread
@ -53,7 +63,7 @@ function [fOutVar,nBlockPerCPU, totCPU] = masterParallel(Parallel,fBlock,nBlock,
% the number of CPUs declared in "Parallel", if
% the number of required threads is lower)
% Copyright (C) 2009-2013 Dynare Team
% Copyright (C) 2009-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -126,7 +136,7 @@ if isHybridMatlabOctave || isoctave
end
end
if exist('fGlobalVar') && ~isempty(fGlobalVar),
if exist('fGlobalVar','var') && ~isempty(fGlobalVar),
fInputNames = fieldnames(fGlobalVar);
for j=1:length(fInputNames),
TargetVar = fGlobalVar.(fInputNames{j});
@ -161,7 +171,7 @@ switch Strategy
save([fname,'_input.mat'],'fInputVar','Parallel','-append')
case 1
if exist('fGlobalVar'),
if exist('fGlobalVar','var'),
save(['temp_input.mat'],'fInputVar','fGlobalVar')
else
save(['temp_input.mat'],'fInputVar')
@ -540,7 +550,6 @@ else
'Renderer','Painters', ...
'Resize','off');
vspace = 0.1;
ncol = ceil(totCPU/10);
hspace = 0.9/ncol;
hstatus(1) = axes('position',[0.05/ncol 0.92 0.9/ncol 0.03], ...
@ -882,8 +891,4 @@ switch Strategy
end
end
end
end
end

View File

@ -34,8 +34,16 @@ global M_ options_ oo_
test_for_deep_parameters_calibration(M_);
if size(M_.lead_lag_incidence,2)-nnz(M_.lead_lag_incidence(M_.maximum_endo_lag+1,:)) > 0
mess = ['PERFECT_FORESIGHT_SETUP: error in model specification : variable ' M_.endo_names(find(M_.lead_lag_incidence(M_.maximum_lag+1,:)==0),:)];
mess = [mess ' doesn''t appear as current variable.'];
mess = ['PERFECT_FORESIGHT_SETUP: error in model specification : the variable(s) '];
var_list=M_.endo_names(find(M_.lead_lag_incidence(M_.maximum_lag+1,:)==0),:);
for i=1:size(var_list,1)
if i<size(var_list,1)
mess = [mess, deblank(var_list(i,:)) ', '];
else
mess = [mess, deblank(var_list(i,:)) ];
end
end
mess = [mess ' don''t appear as current period variables.'];
error(mess)
end

View File

@ -65,9 +65,11 @@ lastperiods = (M_.maximum_endo_lag+options_.periods+1):(M_.maximum_endo_lag+opti
if ~oo_.deterministic_simulation.status && ~options_.no_homotopy
skipline()
disp('Simulation of the perfect foresight model failed!')
disp('Switching to a homotopy method...')
skipline()
% Disable warnings if homotopy
warning_old_state = warning;
warning off all
% Do not print anything
oldverbositylevel = options_.verbosity;
@ -147,7 +149,7 @@ if ~oo_.deterministic_simulation.status && ~options_.no_homotopy
fprintf('++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n')
skipline()
options_.verbosity = oldverbositylevel;
warning on all
warning(warning_old_state);
end
if oo_.deterministic_simulation.status == 1

View File

@ -1,5 +1,7 @@
function check_input_arguments(DynareOptions, DynareModel, DynareResults)
%function check_input_arguments(DynareOptions, DynareModel, DynareResults)
%Conducts checks for inconsistent/missing inputs to deterministic
%simulations
% Copyright (C) 2015 Dynare Team
%
@ -41,10 +43,21 @@ 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'' ?')
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)
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 ]))
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.exo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')
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)
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'' ?')
end
end

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