Merge branch 'master' into lik_init_5_fixes

Conflicts:
	doc/dynare.texi
	tests/Makefile.am
time-shift
Stéphane Adjemian (Lupi) 2016-03-24 17:40:27 +01:00
commit fd850ca5bd
201 changed files with 7868 additions and 1995 deletions

93
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,93 @@
# Instructions for Contributing to Dynare
## Introduction
Hello from the Dynare Team! We're happy you're on this page because hopefully that means you're thinking of getting directly involved with the Dynare project. Herein, we outline how you can contribute to Dynare. Please read this document all the way through before contributing.
Please follow the steps in the sections below in order. Note that, though we'd love for you to contribute code, you don't need to be a programmer to contribute to Dynare. You can report bugs, ask for enhancements, fix typos in the manual, contribute tests to the test suite, or do something we haven't thought of yet!
If something is not clear, don't hesitate to ask if you can't find the answer online. You can contact us directly at [dev@dynare.org](mailto:dev@dynare.org).
Please note that the repositories under the purview of this page are:
* [Dynare](https://github.com/DynareTeam/dynare)
* [Particles](https://github.com/DynareTeam/particles)
* [Dates](https://github.com/DynareTeam/dates)
* [Dseries](https://github.com/DynareTeam/dseries)
* [Reporting](https://github.com/DynareTeam/reporting)
* [Testsuite](https://github.com/DynareTeam/testsuite)
* [M-unit-tests](https://github.com/DynareTeam/m-unit-tests)
## Making your Intentions Known
Before making changes to the codebase, it'd be helpful if you communicated your intentions with us. This will avoid double work and ensure that you don't contribute code that won't be included in Dynare for one reason or another. The way to communicate with us is via [GitHub Issues](https://guides.github.com/features/issues/).
### Issues: Reporting Bugs
You can report bugs in both the stable and unstable versions of Dynare. Before reporting a bug in the stable version of Dynare, please check the [Known Bugs](http://www.dynare.org/DynareWiki/KnownBugs) page to ensure it has not already been encountered/fixed. If reporting a bug in the unstable version of Dynare, please ensure the bug exists in the latest [unstable Dynare snapshot](http://www.dynare.org/download/dynare-unstable).
To report a bug in Dynare, simply open a GitHub issue in the repository where the bug resides. For example, to report a bug in Dynare itself, go to the [Dynare repository issue page](https://github.com/DynareTeam/dynare/issues) and click on "New Issue."
The minimal information to add is a subject and a description of the steps needed to reproduce the bug. However, the most helpful description would also provide the code to reproduce the bug (often times a `.mod` file). The most helpful `.mod` file is a minimal, quick-running example that reproduces the bug, but we'll take anything that will help us squash a bug.
To include short amounts of code, please paste it into the description box, using the appropriate [GitHub markdown](https://help.github.com/articles/github-flavored-markdown/) code. For larger amounds of code like `.mod` files, please create a new [GitHub Gist](https://gist.github.com) and provide the link in the description box.
### Issues: Enhancements
Issues are not only used to report bugs. They are also used to ask for improvements to the codebase or new features to Dynare in general. Please be descriptive when asking for improvements or new features. Links or references to papers or detailed examples are helpful.
Though our development priorities lay with those who finance Dynare and with what we think may most benefit the Dynare community, this does not mean we are closed to outside ideas for enhancements. On the contrary: we invite them! Moreover, if you are willing to program the enhancement you want, the odds of it being included in Dynare are much higher than if you needed us to do it. That said, it is best to create an issue with an enhancement idea **before** beginning the work. As stated above, this is important to avoid duplication of work and also because we wouldn't want you to take the time to work on something that would not end up being included in Dynare.
## Get to Coding!
So, now you've reported the bug or asked for an enhancemnt by creating a GitHub issue. That's already a great help. Thank you!
Now, if you want to go the extra mile, you'll volunteer to contribute code to fix the GitHub issue you created above. Once we've agreed that you'll do it, please do the following:
1. Clone the Dynare repository:
* `git clone https://github.com/DynareTeam/dynare.git`
1. [Fork the Dynare repository](https://help.github.com/articles/fork-a-repo)
1. Change into the `dynare` folder and add the forked repository as a remote:
* `cd dynare`
* `git remote add personal https://github.com/<<GitHub username>>/dynare.git`
1. Create a branch to work on
* `git checkout -b <<descriptive branch name>>`
1. Do your work, all the while respecting the [Dynare Coding Standards](http://www.dynare.org/DynareWiki/CodingStandards)
As you work, your forked repository will likely fall out of sync with the main Dynare repository as we'll be working in parallel. No matter. Follow these steps to ensure your changes will be merge-able when they're done:
1. Get the changes from the main Dynare repository:
* `git checkout master`
* `git fetch`
* `git rebase origin master`
1. Move your changes on top of the current master branch of Dynare
* `git checkout <<descriptive branch name>>`
* `git rebase origin/master`
* This last command may cause a conflict. It is up to you to resolve this conflict.
Once you've made the changes necessary to fix the bug or add an enhancement, ensure that it has been rebased on the master branch (following the steps above), commit it, push it to your forked Dynare repository, and create a pull request:
1. Get the latest changes from Dynare and rebase your branch on top of them (see above)
1. Commit your changes:
* `git add <<files to commit>>`
* `git commit -m "<<descriptive commit message.>> Closes #<<Ref. to GitHub issue number fixed by this commit>>"`
1. Push to your forked Dynare repository
* `git push personal <<descriptive branch name>>`
1. Create a [Pull Request](https://help.github.com/articles/creating-a-pull-request/) from the branch in your forked Dynare repository
## Tests
The Dynare Test Suite runs nightly. It's how we quickly catch bugs that may have been introduced by changes made during the day. The output from the test suite can be found here: [http://www.dynare.org/testsuite/master/](http://www.dynare.org/testsuite/master/). This is also a good place to start fixing bugs. If you see a `.mod` file that doesn't run in the test suite and think you can fix it, create an issue and once you have the go ahead, go for it!
### Test `.mod` File
It's useful to contribute `.mod` files that test some aspect of Dynare that is not currently tested. A `.mod` file that runs into a bug is perfect. As the test suite currently takes several hours to run, we prefer you modify a current test to also create the bug you've found. If you can't do that, please add a new test that runs as quickly as possible. It will contain only those commands necessary to create the bug, nothing more. To contribute a test, after having made an issue and cloned and forked the repository as described above, do the following:
1. Modify the `MODFILES` variable in `tests/Makefile.am` with a line containing your test file name
1. If any ancillary files are needed to run your test, please include them in the `EXTRA_DIST` variable in `tests/Makefile.am`
1. Add and commit your test file and `tests/Makefile.am` as described above
1. Push and create a pull request as described above
NB: Please do not contribute non-text files (e.g. `.xls`). If you absolutely need such a file for your test to run, please contact us to see how to go about contributing it.
### Unitary Tests

View File

@ -24,6 +24,8 @@ EXTRA_DIST = \
NEWS \ NEWS \
license.txt \ license.txt \
README.md \ README.md \
COPYING \
CONTRIBUTING.md \
windows/dynare.nsi \ windows/dynare.nsi \
windows/mexopts-win32.bat \ windows/mexopts-win32.bat \
windows/mexopts-win64.bat \ windows/mexopts-win64.bat \

View File

@ -14,6 +14,10 @@ Described on the homepage: <http://www.dynare.org/>
Most users should use the precompiled package available for your OS, also Most users should use the precompiled package available for your OS, also
available via the Dynare homepage: <http://www.dynare.org/download/dynare-stable>. available via the Dynare homepage: <http://www.dynare.org/download/dynare-stable>.
# Contributions
To contribute to Dynare and participate in the Dynare community, please see: [CONTRIBUTING.md](https://github.com/DynareTeam/dynare/blob/master/CONTRIBUTING.md)
# License # License
Most of the source files are covered by the GNU General Public Licence version Most of the source files are covered by the GNU General Public Licence version
@ -110,10 +114,15 @@ Alternatively, you can disable the compilation of MEX files for MATLAB with the
You may need to specify additional options to the configure script, see the platform specific instructions below. You may need to specify additional options to the configure script, see the platform specific instructions below.
Note that if you don't want to compile with debugging information, you can specify the `CFLAGS` and `CXXFLAGS` variables to configure, such as: Note that if you don't want to compile the C/C++ programs with debugging information, you can specify the `CFLAGS` and `CXXFLAGS` variables to the configure script, such as:
``` ```
./configure CFLAGS="-O3" CXXFLAGS="-O3" ./configure CFLAGS="-O3" CXXFLAGS="-O3"
``` ```
To remove debugging information for Matlab mex functions, the analagous call would be:
```
./configure MATLAB_MEX_CFLAGS="-O3" MATLAB_MEX_CXXFLAGS="-O3"
```
If you want to give a try to the parallelized versions of some mex files (`A_times_B_kronecker_C` and `sparse_hessian_times_B_kronecker_C` used to get the reduced form of the second order approximation of the model) you can add the `--enable-openmp` flag, for instance: If you want to give a try to the parallelized versions of some mex files (`A_times_B_kronecker_C` and `sparse_hessian_times_B_kronecker_C` used to get the reduced form of the second order approximation of the model) you can add the `--enable-openmp` flag, for instance:
``` ```
./configure --with-matlab=/usr/local/matlab78 MATLAB_VERSION=7.8 --enable-openmp ./configure --with-matlab=/usr/local/matlab78 MATLAB_VERSION=7.8 --enable-openmp
@ -197,6 +206,7 @@ We no longer support compilation on Windows. To use the unstable version of Dyna
- ```brew tap homebrew/science``` - ```brew tap homebrew/science```
- **(Optional)** To compile Dynare mex files for use on Octave: - **(Optional)** To compile Dynare mex files for use on Octave:
- ```brew install octave``` - ```brew install octave```
- ```brew install suite-sparse```
- To see the available options for compiling Dynare, type: - To see the available options for compiling Dynare, type:
- ```brew info dynare``` - ```brew info dynare```
- Install Dynare via a command of the form: - Install Dynare via a command of the form:

View File

@ -64,7 +64,7 @@ AC_PROG_MKDIR_P
AM_PROG_LEX AM_PROG_LEX
# Hack to get lex include dir, ticket #575 # Hack to get lex include dir, ticket #575
AC_PATH_PROG([LEXPATH], [$LEX]) AC_PATH_PROG([LEXPATH], [$LEX])
AC_SUBST([LEXINC], [`eval "echo $LEXPATH | sed 's|$LEX$|../include|'"`]) AC_SUBST([LEXINC], [`eval "echo $LEXPATH | sed 's|\(.*\)$LEX$|\1../include|'"`])
AC_CHECK_PROG([YACC], [bison], [bison]) AC_CHECK_PROG([YACC], [bison], [bison])
if test "x$YACC" = "x"; then if test "x$YACC" = "x"; then

View File

@ -11,7 +11,7 @@
\begin{document} \begin{document}
\title{BVAR models ``\`a la Sims'' in Dynare\thanks{Copyright \copyright~2007--2011 S\'ebastien \title{BVAR models ``\`a la Sims'' in Dynare\thanks{Copyright \copyright~2007--2016 S\'ebastien
Villemot. Permission is granted to copy, distribute and/or modify Villemot. Permission is granted to copy, distribute and/or modify
this document under the terms of the GNU Free Documentation this document under the terms of the GNU Free Documentation
License, Version 1.3 or any later version published by the Free License, Version 1.3 or any later version published by the Free
@ -27,7 +27,7 @@
\author{S\'ebastien Villemot\thanks{Paris School of Economics and \author{S\'ebastien Villemot\thanks{Paris School of Economics and
CEPREMAP. E-mail: CEPREMAP. E-mail:
\href{mailto:sebastien@dynare.org}{\texttt{sebastien@dynare.org}}.}} \href{mailto:sebastien@dynare.org}{\texttt{sebastien@dynare.org}}.}}
\date{First version: September 2007 \hspace{1cm} This version: August 2012} \date{First version: September 2007 \hspace{1cm} This version: March 2016}
\maketitle \maketitle
@ -169,7 +169,7 @@ $$\left[
$$\left[ $$\left[
\begin{array}{cc} \begin{array}{cc}
0 & 0 \\ 0 & 0 \\
0 & 0 0 & 0
\end{array} \end{array}
\right] \right]
= =
@ -499,7 +499,7 @@ The syntax for computing the marginal density is:
The options are those described above. The options are those described above.
The command will actually compute the marginal density for several models: first for the model with one lag, then with two lags, and so on up to \textit{max\_number\_of\_lags} lags. The command will actually compute the marginal density for several models: first for the model with one lag, then with two lags, and so on up to \textit{max\_number\_of\_lags} lags. Results will be stored in a \textit{max\_number\_of\_lags} by 1 vector \texttt{oo\_.bvar.log\_marginal\_data\_density}.
\subsection{Forecasting} \subsection{Forecasting}

View File

@ -879,6 +879,10 @@ Instructs Dynare not to write parameter assignments to parameter names
in the @file{.m} file produced by the preprocessor. This is in the @file{.m} file produced by the preprocessor. This is
potentially useful when running @code{dynare} on a large @file{.mod} potentially useful when running @code{dynare} on a large @file{.mod}
file that runs into workspace size limitations imposed by MATLAB. file that runs into workspace size limitations imposed by MATLAB.
@item compute_xrefs
Tells Dynare to compute the equation cross references, writing them to the
output @file{.m} file.
@end table @end table
@outputhead @outputhead
@ -1096,9 +1100,9 @@ number @var{i} and the index in many loops. Rather, name investment @var{invest}
Declarations of variables and parameters are made with the following commands: Declarations of variables and parameters are made with the following commands:
@deffn Command var @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})]@dots{}; @deffn Command var @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})] [(NAME=@var{QUOTED_STRING})]@dots{};
@deffnx Command var (deflator = @var{MODEL_EXPRESSION}) @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})]@dots{}; @deffnx Command var (deflator = @var{MODEL_EXPRESSION}) @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})] [(NAME=@var{QUOTED_STRING})]@dots{};
@deffnx Command var (log_deflator = @var{MODEL_EXPRESSION}) @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})]@dots{}; @deffnx Command var (log_deflator = @var{MODEL_EXPRESSION}) @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})] [(NAME=@var{QUOTED_STRING})]@dots{};
@descriptionhead @descriptionhead
@ -1139,19 +1143,25 @@ multiplicative trend).
@item long_name = @var{QUOTED_STRING} @item long_name = @var{QUOTED_STRING}
This is the long version of the variable name. Its value is stored in This is the long version of the variable name. Its value is stored in
@code{M_.endo_names_long}. Default: @var{VARIABLE_NAME} @code{M_.endo_names_long}. Default: @var{VARIABLE_NAME}
@anchor{partitioning}
@item NAME = @var{QUOTED_STRING}
This is used to create a partitioning of variables. It results in the direct
output in the @file{.m} file analogous to: @code{M_.endo_}@var{NAME}@code{ =
}@var{QUOTED_STRING}@code{;}.
@end table @end table
@examplehead @examplehead
@example @example
var c gnp q1 q2; var c gnp q1 (country=`US') q2 (country=`FR');
var(deflator=A) i b; var(deflator=A) i b;
var c $C$ (long_name=`Consumption'); var c $C$ (long_name=`Consumption');
@end example @end example
@end deffn @end deffn
@deffn Command varexo @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})]@dots{}; @deffn Command varexo @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})] [(NAME=@var{QUOTED_STRING})]@dots{};
@descriptionhead @descriptionhead
@ -1169,6 +1179,9 @@ will concatenate them.
@table @code @table @code
@item long_name = @var{QUOTED_STRING} @item long_name = @var{QUOTED_STRING}
Like @ref{long_name} but value stored in @code{M_.exo_names_long}. Like @ref{long_name} but value stored in @code{M_.exo_names_long}.
@item NAME = @var{QUOTED_STRING}
Like @ref{partitioning} but @var{QUOTED_STRING} stored in @code{M_.exo_}@var{NAME}.
@end table @end table
@examplehead @examplehead
@ -1179,7 +1192,7 @@ varexo m gov;
@end deffn @end deffn
@deffn Command varexo_det @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})]@dots{}; @deffn Command varexo_det @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})] [(NAME=@var{QUOTED_STRING})]@dots{};
@descriptionhead @descriptionhead
@ -1203,6 +1216,9 @@ Dynare will concatenate them.
@table @code @table @code
@item long_name = @var{QUOTED_STRING} @item long_name = @var{QUOTED_STRING}
Like @ref{long_name} but value stored in @code{M_.exo_det_names_long}. Like @ref{long_name} but value stored in @code{M_.exo_det_names_long}.
@item NAME = @var{QUOTED_STRING}
Like @ref{partitioning} but @var{QUOTED_STRING} stored in @code{M_.exo_det_}@var{NAME}.
@end table @end table
@examplehead @examplehead
@ -1216,7 +1232,7 @@ varexo_det tau;
@end deffn @end deffn
@deffn Command parameters @var{PARAMETER_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})]@dots{}; @deffn Command parameters @var{PARAMETER_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING})] [(NAME=@var{QUOTED_STRING})]@dots{};
@descriptionhead @descriptionhead
@ -1235,6 +1251,9 @@ Dynare will concatenate them.
@table @code @table @code
@item long_name = @var{QUOTED_STRING} @item long_name = @var{QUOTED_STRING}
Like @ref{long_name} but value stored in @code{M_.param_names_long}. Like @ref{long_name} but value stored in @code{M_.param_names_long}.
@item NAME = @var{QUOTED_STRING}
Like @ref{partitioning} but @var{QUOTED_STRING} stored in @code{M_.param_}@var{NAME}.
@end table @end table
@examplehead @examplehead
@ -2672,9 +2691,9 @@ Specifies the correlation of two variables.
@end table @end table
In an estimation context, it is also possible to specify variances and In an estimation context, it is also possible to specify variances and
covariances on endogenous variables: in that case, these values are covariances on endogenous variables: in that case, these values are interpreted
interpreted as the calibration of the measurement errors on these as the calibration of the measurement errors on these variables. This requires
variables. This requires the @code{var_obs}-command to be specified before the @code{shocks}-block. the @code{varobs} command to be specified before the @code{shocks} block.
Here is an example: Here is an example:
@ -3958,6 +3977,12 @@ Default value: @code{1e-6}.
Saves the contemporaneous correlation between the endogenous variables in @code{oo_.contemporaneous_correlation}. Saves the contemporaneous correlation between the endogenous variables in @code{oo_.contemporaneous_correlation}.
Requires the @code{nocorr}-option not to be set. Requires the @code{nocorr}-option not to be set.
@item spectral_density
@anchor{spectral_density}
Triggers the computation and display of the theoretical spectral density of the (filtered) model variables.
Results are stored in @code{oo_.SpectralDensity}, defined below.
Default: do not request spectral density estimates
@end table @end table
@outputhead @outputhead
@ -4093,6 +4118,13 @@ After a run of @code{stoch_simul} with the
and simulated contemporaneous correlations otherwise. The variables are arranged in declaration order. and simulated contemporaneous correlations otherwise. The variables are arranged in declaration order.
@end defvr @end defvr
@anchor{oo_.SpectralDensity}
@defvr {MATLAB/Octave variable} oo_.SpectralDensity
After a run of @code{stoch_simul} with option @code{spectral_density} contains the spectral density
of the model variables. There will be a @code{nvars} by @code{nfrequencies} subfield
@code{freqs} storing the respective frequency grid points ranging from 0 to 2*pi and a
same sized subfield @code{density} storing the corresponding density.
@end defvr
@defvr {MATLAB/Octave variable} oo_.irfs @defvr {MATLAB/Octave variable} oo_.irfs
After a run of @code{stoch_simul} with option @code{irf} different After a run of @code{stoch_simul} with option @code{irf} different
@ -4537,7 +4569,7 @@ likelihood estimation. In a Bayesian estimation context, sets a lower bound
only effective while maximizing the posterior kernel. This lower bound does not only effective while maximizing the posterior kernel. This lower bound does not
modify the shape of the prior density, and is only aimed at helping the modify the shape of the prior density, and is only aimed at helping the
optimizer in identifying the posterior mode (no consequences for the MCMC). For optimizer in identifying the posterior mode (no consequences for the MCMC). For
some prior densities (namely inverse gamma, gamma, uniform or beta) it is some prior densities (namely inverse gamma, gamma, uniform, beta or weibull) it is
possible to shift the support of the prior distributions to the left or the right using possible to shift the support of the prior distributions to the left or the right using
@ref{prior_3rd_parameter}. In this case the prior density is effectively @ref{prior_3rd_parameter}. In this case the prior density is effectively
modified (note that the truncated Gaussian density is not implemented in modified (note that the truncated Gaussian density is not implemented in
@ -4552,7 +4584,7 @@ A keyword specifying the shape of the prior density.
The possible values are: @code{beta_pdf}, The possible values are: @code{beta_pdf},
@code{gamma_pdf}, @code{normal_pdf}, @code{gamma_pdf}, @code{normal_pdf},
@code{uniform_pdf}, @code{inv_gamma_pdf}, @code{uniform_pdf}, @code{inv_gamma_pdf},
@code{inv_gamma1_pdf}, @code{inv_gamma2_pdf}. Note @code{inv_gamma1_pdf}, @code{inv_gamma2_pdf} and @code{weibull_pdf}. Note
that @code{inv_gamma_pdf} is equivalent to that @code{inv_gamma_pdf} is equivalent to
@code{inv_gamma1_pdf} @code{inv_gamma1_pdf}
@ -4565,7 +4597,7 @@ that @code{inv_gamma_pdf} is equivalent to
@item @var{PRIOR_3RD_PARAMETER} @item @var{PRIOR_3RD_PARAMETER}
@anchor{prior_3rd_parameter} @anchor{prior_3rd_parameter}
A third parameter of the prior used for generalized beta distribution, A third parameter of the prior used for generalized beta distribution,
generalized gamma and for the uniform distribution. Default: @code{0} generalized gamma, generalized weibull and for the uniform distribution. Default: @code{0}
@item @var{PRIOR_4TH_PARAMETER} @item @var{PRIOR_4TH_PARAMETER}
@anchor{prior_4th_parameter} @anchor{prior_4th_parameter}
@ -4838,7 +4870,7 @@ first observation of the rolling window.
@item prefilter = @var{INTEGER} @item prefilter = @var{INTEGER}
@anchor{prefilter} @anchor{prefilter}
A value of @code{1} means that the estimation procedure will demean A value of @code{1} means that the estimation procedure will demean
each data series by its empirical mean. Default: @code{0}, @i{i.e.} no prefiltering each data series by its empirical mean. If the (@ref{loglinear}) option without the (@ref{logdata}) option is requested, the data will first be logged and then demeaned. Default: @code{0}, @i{i.e.} no prefiltering
@item presample = @var{INTEGER} @item presample = @var{INTEGER}
@anchor{presample} @anchor{presample}
@ -4973,8 +5005,12 @@ Metropolis-Hastings chain. Default: 2*@code{mh_scale}
@item mh_recover @item mh_recover
@anchor{mh_recover} Attempts to recover a Metropolis-Hastings @anchor{mh_recover} Attempts to recover a Metropolis-Hastings
simulation that crashed prematurely. Shouldn't be used together with simulation that crashed prematurely, starting with the last available saved
@code{load_mh_file} @code{mh}-file. Shouldn't be used together with
@code{load_mh_file} or a different @code{mh_replic} than in the crashed run.
To assure a neat continuation of the chain with the same proposal density, you should
provide the @code{mode_file} used in the previous
run or the same user-defined @code{mcmc_jumping_covariance} when using this option.
@item mh_mode = @var{INTEGER} @item mh_mode = @var{INTEGER}
@dots{} @dots{}
@ -5533,6 +5569,12 @@ from the likelihood computations (for details see @cite{Durbin and Koopman (2012
singularity is encountered, Dynare by default automatically switches to the univariate Kalman filter for this parameter draw. This behavior can be changed via the singularity is encountered, Dynare by default automatically switches to the univariate Kalman filter for this parameter draw. This behavior can be changed via the
@ref{use_univariate_filters_if_singularity_is_detected} option. @ref{use_univariate_filters_if_singularity_is_detected} option.
@item fast_kalman_filter
@anchor{fast_kalman_filter} Select the fast Kalman filter using Chandrasekhar
recursions as described by @cite{Herbst, 2015}. This setting is only used with
@code{kalman_algo=1} or @code{kalman_algo=3}. It is not yet compatible with
@code{analytical_derivation}.
@item kalman_tol = @var{DOUBLE} @item kalman_tol = @var{DOUBLE}
@anchor{kalman_tol} Numerical tolerance for determining the singularity of the covariance matrix of the prediction errors during the Kalman filter (minimum allowed reciprocal of the matrix condition number). Default value is @code{1e-10} @anchor{kalman_tol} Numerical tolerance for determining the singularity of the covariance matrix of the prediction errors during the Kalman filter (minimum allowed reciprocal of the matrix condition number). Default value is @code{1e-10}
@ -5605,8 +5647,7 @@ using a standard Kalman filter.
@xref{irf}. Only used if @ref{bayesian_irf} is passed. @xref{irf}. Only used if @ref{bayesian_irf} is passed.
@item irf_shocks = ( @var{VARIABLE_NAME} [[,] @var{VARIABLE_NAME} @dots{}] ) @item irf_shocks = ( @var{VARIABLE_NAME} [[,] @var{VARIABLE_NAME} @dots{}] )
@xref{irf_shocks}. Only used if @ref{bayesian_irf} is passed. Cannot be used @xref{irf_shocks}. Only used if @ref{bayesian_irf} is passed.
with @ref{dsge_var}.
@item irf_plot_threshold = @var{DOUBLE} @item irf_plot_threshold = @var{DOUBLE}
@xref{irf_plot_threshold}. Only used if @ref{bayesian_irf} is passed. @xref{irf_plot_threshold}. Only used if @ref{bayesian_irf} is passed.
@ -7065,7 +7106,7 @@ The planner objective must be declared with the @code{planner_objective} command
This command only creates the expanded model, it doesn't perform any This command only creates the expanded model, it doesn't perform any
computations. It needs to be followed by other instructions to actually computations. It needs to be followed by other instructions to actually
perfrom desired computations. Note that it is the only way to perform perform desired computations. Note that it is the only way to perform
perfect foresight simulation of the Ramsey policy problem. perfect foresight simulation of the Ramsey policy problem.
@xref{Auxiliary @xref{Auxiliary
@ -7078,8 +7119,10 @@ This command accepts the following options:
@table @code @table @code
@anchor{planner_discount}
@item planner_discount = @var{EXPRESSION} @item planner_discount = @var{EXPRESSION}
Declares the discount factor of the central planner. Default: @code{1.0} Declares or reassigns the discount factor of the central planner
@code{optimal_policy_discount_factor}. Default: @code{1.0}
@item instruments = (@var{VARIABLE_NAME},@dots{}) @item instruments = (@var{VARIABLE_NAME},@dots{})
Declares instrument variables for the computation of the steady state Declares instrument variables for the computation of the steady state
@ -7172,7 +7215,7 @@ This command accepts all options of @code{stoch_simul}, plus:
@table @code @table @code
@item planner_discount = @var{EXPRESSION} @item planner_discount = @var{EXPRESSION}
Declares the discount factor of the central planner. Default: @code{1.0} @xref{planner_discount}
@item instruments = (@var{VARIABLE_NAME},@dots{}) @item instruments = (@var{VARIABLE_NAME},@dots{})
Declares instrument variables for the computation of the steady state Declares instrument variables for the computation of the steady state
@ -7206,7 +7249,9 @@ In contrast, the second entry stores the value of the planner objective with
initial Lagrange multipliers of the planner's problem set to 0, i.e. it is assumed initial Lagrange multipliers of the planner's problem set to 0, i.e. it is assumed
that the planner succumbs to the temptation to exploit the preset private expecatations that the planner succumbs to the temptation to exploit the preset private expecatations
in the first period (but not in later periods due to commitment). in the first period (but not in later periods due to commitment).
Because it entails computing at least a second order approximation, this
computation is skipped with a message when the model is too large (more than 180 state
variables, including lagged Lagrange multipliers).
@customhead{Steady state} @customhead{Steady state}
@xref{Ramsey steady state}. @xref{Ramsey steady state}.
@ -9571,8 +9616,9 @@ following @LaTeX{} packages: @code{longtable}
Writes a @LaTeX{} file named @code{<<M_.fname>>_TeX_binder.tex} that collects all @TeX{} output generated by Dynare Writes a @LaTeX{} file named @code{<<M_.fname>>_TeX_binder.tex} that collects all @TeX{} output generated by Dynare
into a file. This file can be compiled using pdflatex and automatically tries to load all required packages. into a file. This file can be compiled using pdflatex and automatically tries to load all required packages.
Requires the following @LaTeX{} packages: @code{longtable}, @code{psfrag}, Requires the following @LaTeX{} packages: @code{breqn}, @code{psfrag},
@code{graphicx}, @code{epstopdf}, @code{longtable}, and @code{float} @code{graphicx}, @code{epstopdf}, @code{longtable}, @code{booktabs}, @code{caption},
@code{float}, and @code{morefloats}
@end deffn @end deffn
@ -11917,6 +11963,28 @@ ts1 is a dseries object:
@sp 1 @sp 1
@deftypefn{dseries} {@var{B} =} rename (@var{A},@var{newname})
Replace the names in @var{A} with those passed in the cell string array
@var{newname}. @var{newname} must have the same number of cells as @var{A} has
@var{dseries}. Returns a @dseries object.
@examplehead
@example
>> ts0 = dseries(ones(2,3));
>> ts1 = ts0.rename(@{'Tree','Worst','President'@})
ts1 is a dseries object:
| Bush | Worst | President
1Y | 1 | 1 | 1
2Y | 1 | 1 | 1
@end example
@end deftypefn
@sp 1
@deftypefn{dseries} save (@var{A}, @var{basename}[, @var{format}]) @deftypefn{dseries} save (@var{A}, @var{basename}[, @var{format}])
Overloads the Matlab/Octave @code{save} function and saves @dseries Overloads the Matlab/Octave @code{save} function and saves @dseries
@ -12023,6 +12091,16 @@ in @dseries object @var{A}. Returns a @dseries object.
@sp 1 @sp 1
@deftypefn{dseries} {@var{B} =} tex_rename (@var{A}, @var{newtexname})
Redefines the tex names of the @var{A} to those contained in
@var{newtexname}. Here, @var{newtexname} is a cell string array with the same
number of entries as variables in @var{A}
@end deftypefn
@sp 1
@deftypefn{dseries} {@var{B} =} uminus (@var{A}) @deftypefn{dseries} {@var{B} =} uminus (@var{A})
Overloads @code{uminus} (@code{-}, unary minus) for @dseries object. Overloads @code{uminus} (@code{-}, unary minus) for @dseries object.
@ -12511,7 +12589,7 @@ with the same base name as specified by @ref{tableName} with the ending
@end defmethod @end defmethod
@anchor{addSeries} @anchor{addSeries}
@defmethod Report addSeries data, graphBar, graphBarColor, graphBarFillColor, graphBarWidth, graphFanShadeColor, graphFanShadeOpacity, graphHline, graphLegendName, graphLineColor, graphLineStyle, graphLineWidth, graphMarker, graphMarkerEdgeColor, graphMarkerFaceColor, graphMarkerSize, graphMiscTikzAddPlotOptions, graphShowInLegend, graphVline, tableDataRhs, tableRowColor, tableRowIndent, tableShowMarkers, tableAlignRight, tableNegColor, tablePosColor, tableSubSectionHeader, zeroTol @defmethod Report addSeries data, graphBar, graphBarColor, graphBarFillColor, graphBarWidth, graphFanShadeColor, graphFanShadeOpacity, graphHline, graphLegendName, graphLineColor, graphLineStyle, graphLineWidth, graphMarker, graphMarkerEdgeColor, graphMarkerFaceColor, graphMarkerSize, graphMiscTikzAddPlotOptions, graphShowInLegend, graphVline, tableDataRhs, tableRowColor, tableRowIndent, tableShowMarkers, tableAlignRight, tableNaNSymb, tableNegColor, tablePosColor, tableSubSectionHeader, zeroTol
Adds a @code{Series} to a @code{Graph} or a @code{Table}. NB: Options specific Adds a @code{Series} to a @code{Graph} or a @code{Table}. NB: Options specific
to graphs begin with `@code{graph}' while options specific to tables begin with to graphs begin with `@code{graph}' while options specific to tables begin with
`@code{table}'. `@code{table}'.
@ -12628,6 +12706,9 @@ with the color denoted by @ref{tableNegColor}. For those greater than
@code{tableMarkerLimit}, mark the cell with the color denoted by @code{tableMarkerLimit}, mark the cell with the color denoted by
@ref{tablePosColor}. Default: @code{1e-4} @ref{tablePosColor}. Default: @code{1e-4}
@item tableNaNSymb, @code{STRING}
Replace @code{NaN} values with the text in this option. Default: @code{NaN}
@anchor{tableNegColor} @anchor{tableNegColor}
@item tableNegColor, @code{LATEX_COLOR} @item tableNegColor, @code{LATEX_COLOR}
The color to use when marking Table data that is less than The color to use when marking Table data that is less than
@ -13076,6 +13157,11 @@ Harvey, Andrew C. and Garry D.A. Phillips (1979): ``Maximum likelihood estimatio
regression models with autoregressive-moving average disturbances,'' regression models with autoregressive-moving average disturbances,''
@i{Biometrika}, 66(1), 49--58 @i{Biometrika}, 66(1), 49--58
@item
Herbst, Edward (2015):
``Using the ``Chandrasekhar Recursions'' for Likelihood Evaluation of DSGE
Models,'' @i{Computational Economics}, 45(4), 693--705.
@item @item
Ireland, Peter (2004): ``A Method for Taking Models to the Data,'' Ireland, Peter (2004): ``A Method for Taking Models to the Data,''
@i{Journal of Economic Dynamics and Control}, 28, 1205--26 @i{Journal of Economic Dynamics and Control}, 28, 1205--26

View File

@ -1,14 +1,31 @@
// Example 1 from Collard's guide to Dynare /*
* Example 1 from F. Collard (2001): "Stochastic simulations with DYNARE:
* A practical guide" (see "guide.pdf" in the documentation directory).
*/
/*
* Copyright (C) 2001-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/>.
*/
var y, c, k, a, h, b; var y, c, k, a, h, b;
varexo e, u; varexo e, u;
verbatim;
% I want these comments included in
% example1.m
%
var = 1;
end;
parameters beta, rho, alpha, delta, theta, psi, tau; parameters beta, rho, alpha, delta, theta, psi, tau;
alpha = 0.36; alpha = 0.36;
@ -79,4 +96,4 @@ r = report();
@#endfor @#endfor
r.write(); r.write();
r.compile(); r.compile();

View File

@ -1,6 +1,6 @@
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Dynare Upstream-Name: Dynare
Upstream-Contact: Dynare Team, whose members in 2015 are: Upstream-Contact: Dynare Team, whose members in 2016 are:
Stéphane Adjemian <stephane.adjemian@univ-lemans.fr> Stéphane Adjemian <stephane.adjemian@univ-lemans.fr>
Houtan Bastani <houtan@dynare.org> Houtan Bastani <houtan@dynare.org>
Michel Juillard <michel.juillard@mjui.fr> Michel Juillard <michel.juillard@mjui.fr>
@ -14,7 +14,7 @@ Upstream-Contact: Dynare Team, whose members in 2015 are:
Source: http://www.dynare.org Source: http://www.dynare.org
Files: * Files: *
Copyright: 1996-2015 Dynare Team Copyright: 1996-2016 Dynare Team
License: GPL-3+ License: GPL-3+
Files: matlab/AIM/SP* Files: matlab/AIM/SP*
@ -98,11 +98,6 @@ Copyright: 1995-2007 Kurt Hornik
2008-2009 Dynare Team 2008-2009 Dynare Team
License: GPL-3+ License: GPL-3+
Files: matlab/missing/strjoin/strjoin.m
Copyright: 2007 Muthiah Annamalai <muthiah.annamalai@uta.edu>
2013 Dynare Team
License: GPL-3+
Files: matlab/missing/corrcoef/corrcoef.m matlab/missing/corrcoef/sumskipnan.m Files: matlab/missing/corrcoef/corrcoef.m matlab/missing/corrcoef/sumskipnan.m
matlab/missing/corrcoef/flag_implicit_skip_nan.m matlab/missing/corrcoef/tcdf.m matlab/missing/corrcoef/flag_implicit_skip_nan.m matlab/missing/corrcoef/tcdf.m
Copyright: 2000-2005,2008,2009,2011 by Alois Schloegl <alois.schloegl@gmail.com> Copyright: 2000-2005,2008,2009,2011 by Alois Schloegl <alois.schloegl@gmail.com>
@ -144,7 +139,7 @@ License: permissive
distribute this software. distribute this software.
Files: doc/dynare.texi doc/*.tex doc/*.svg doc/*.dia doc/*.pdf doc/*.bib Files: doc/dynare.texi doc/*.tex doc/*.svg doc/*.dia doc/*.pdf doc/*.bib
Copyright: 1996-2015 Dynare Team Copyright: 1996-2016 Dynare Team
License: GFDL-NIV-1.3+ License: GFDL-NIV-1.3+
Files: doc/userguide/*.tex doc/userguide/*.bib doc/userguide/*.pdf Files: doc/userguide/*.tex doc/userguide/*.bib doc/userguide/*.pdf

View File

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

View File

@ -1,4 +1,4 @@
dnl Copyright (C) 2009-2014 Dynare Team dnl Copyright (C) 2009-2016 Dynare Team
dnl dnl
dnl This file is part of Dynare. dnl This file is part of Dynare.
dnl dnl
@ -98,6 +98,32 @@ else
AC_MSG_RESULT([unknown]) AC_MSG_RESULT([unknown])
fi fi
# Allow user to override default Matlab compilation flags
# Github ticket #1121
if test "x$MATLAB_MEX_CPPFLAGS" != "x"; then
MATLAB_CPPFLAGS="$MATLAB_CPPFLAGS $MATLAB_MEX_CPPFLAGS"
fi
if test "x$MATLAB_MEX_DEFS" != "x"; then
MATLAB_DEFS="$MATLAB_DEFS $MATLAB_MEX_DEFS"
fi
if test "x$MATLAB_MEX_CFLAGS" != "x"; then
MATLAB_CFLAGS="$MATLAB_CFLAGS $MATLAB_MEX_CFLAGS"
fi
if test "x$MATLAB_MEX_CXXFLAGS" != "x"; then
MATLAB_CXXFLAGS="$MATLAB_CXXFLAGS $MATLAB_MEX_CXXFLAGS"
fi
if test "x$MATLAB_MEX_LDFLAGS" != "x"; then
MATLAB_LDFLAGS="$MATLAB_LDFLAGS $MATLAB_MEX_LDFLAGS"
fi
if test "x$MATLAB_MEX_LIBS" != "x"; then
MATLAB_LIBS="$MATLAB_LIBS $MATLAB_MEX_LIBS"
fi
AC_SUBST([MATLAB_CPPFLAGS]) AC_SUBST([MATLAB_CPPFLAGS])
AC_SUBST([MATLAB_DEFS]) AC_SUBST([MATLAB_DEFS])
AC_SUBST([MATLAB_CFLAGS]) AC_SUBST([MATLAB_CFLAGS])

View File

@ -1,4 +1,4 @@
function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,decomp] = DsgeSmoother(xparam1,gend,Y,data_index,missing_value) function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,decomp,trend_addition] = DsgeSmoother(xparam1,gend,Y,data_index,missing_value)
% Estimation of the smoothed variables and innovations. % Estimation of the smoothed variables and innovations.
% %
% INPUTS % INPUTS
@ -9,10 +9,10 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,de
% o missing_value 1 if missing values, 0 otherwise % o missing_value 1 if missing values, 0 otherwise
% %
% OUTPUTS % OUTPUTS
% o alphahat [double] (m*T) matrix, smoothed endogenous variables. % o alphahat [double] (m*T) matrix, smoothed endogenous variables (a_{t|T})
% o etahat [double] (r*T) matrix, smoothed structural shocks (r>n is the umber of shocks). % o etahat [double] (r*T) matrix, smoothed structural shocks (r>n is the umber of shocks).
% o epsilonhat [double] (n*T) matrix, smoothed measurement errors. % o epsilonhat [double] (n*T) matrix, smoothed measurement errors.
% o ahat [double] (m*T) matrix, one step ahead filtered (endogenous) variables. % o ahat [double] (m*T) matrix, updated (endogenous) variables (a_{t|t})
% o SteadyState [double] (m*1) vector specifying the steady state level of each endogenous variable. % o SteadyState [double] (m*1) vector specifying the steady state level of each endogenous variable.
% o trend_coeff [double] (n*1) vector, parameters specifying the slope of the trend associated to each observed variable. % o trend_coeff [double] (n*1) vector, parameters specifying the slope of the trend associated to each observed variable.
% o aK [double] (K,n,T+K) array, k (k=1,...,K) steps ahead filtered (endogenous) variables. % o aK [double] (K,n,T+K) array, k (k=1,...,K) steps ahead filtered (endogenous) variables.
@ -23,7 +23,8 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,de
% matrices (meaningless for periods 1:d) % matrices (meaningless for periods 1:d)
% o decomp 4D array of shock decomposition of k-step ahead % o decomp 4D array of shock decomposition of k-step ahead
% filtered variables % filtered variables
% % o trend_addition [double] (n_observed_series*T) pure trend component; stored in options_.varobs order
%
% ALGORITHM % ALGORITHM
% Diffuse Kalman filter (Durbin and Koopman) % Diffuse Kalman filter (Durbin and Koopman)
% %
@ -93,15 +94,10 @@ else
end end
trend_coeff = zeros(vobs,1); trend_coeff = zeros(vobs,1);
if bayestopt_.with_trend == 1 if bayestopt_.with_trend == 1
trend_coeff = zeros(vobs,1); [trend_addition, trend_coeff] =compute_trend_coefficients(M_,options_,vobs,gend);
t = options_.trend_coeffs; trend = constant*ones(1,gend)+trend_addition;
for i=1:length(t)
if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i});
end
end
trend = constant*ones(1,gend)+trend_coeff*(1:gend);
else else
trend_addition=zeros(size(constant,1),gend);
trend = constant*ones(1,gend); trend = constant*ones(1,gend);
end end
start = options_.presample+1; start = options_.presample+1;

View File

@ -34,7 +34,7 @@ switch type
case 'posterior' case 'posterior'
[xparams, logpost] = metropolis_draw(0); [xparams, logpost] = metropolis_draw(0);
case 'prior' case 'prior'
xparams = prior_draw(0); xparams = prior_draw();
if nargout>1 if nargout>1
logpost = evaluate_posterior_kernel(xparams'); logpost = evaluate_posterior_kernel(xparams');
end end

View File

@ -1,4 +1,4 @@
function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bayestopt_, oo_) function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bayestopt_, oo_, pnames)
% This function prints and saves posterior estimates after the mcmc % This function prints and saves posterior estimates after the mcmc
% (+updates of oo_ & TeX output). % (+updates of oo_ & TeX output).
% %
@ -8,6 +8,7 @@ function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bay
% options_ [structure] % options_ [structure]
% bayestopt_ [structure] % bayestopt_ [structure]
% oo_ [structure] % oo_ [structure]
% pnames [char] Array of char, names of the prior shapes available
% %
% OUTPUTS % OUTPUTS
% oo_ [structure] % oo_ [structure]
@ -15,7 +16,7 @@ function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bay
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% None. % None.
% Copyright (C) 2006-2013 Dynare Team % Copyright (C) 2006-2015 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -59,7 +60,6 @@ FirstMhFile = record.KeepedDraws.FirstMhFile;
NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws);
clear record; clear record;
pnames=[' ';'beta ';'gamma';'norm ';'invg ';'unif ';'invg2'];
header_width = row_header_width(M_,estim_params_,bayestopt_); header_width = row_header_width(M_,estim_params_,bayestopt_);
hpd_interval=[num2str(options_.mh_conf_sig*100), '% HPD interval']; hpd_interval=[num2str(options_.mh_conf_sig*100), '% HPD interval'];
tit2 = sprintf('%-*s %12s %12s %23s %8s %12s\n',header_width,' ','prior mean','post. mean',hpd_interval,'prior','pstdev'); tit2 = sprintf('%-*s %12s %12s %23s %8s %12s\n',header_width,' ','prior mean','post. mean',hpd_interval,'prior','pstdev');
@ -336,22 +336,23 @@ fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n'); fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n'); fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n'); fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|lcccccc} \n'); fprintf(fidTeX,'\\begin{longtable}{llcccccc} \n');
fprintf(fidTeX,['\\caption{Results from Metropolis-Hastings (' title ')}\n ']); fprintf(fidTeX,['\\caption{Results from Metropolis-Hastings (' title ')}\n ']);
fprintf(fidTeX,['\\label{Table:MHPosterior:' int2str(fnum) '}\\\\\n']); fprintf(fidTeX,['\\label{Table:MHPosterior:' int2str(fnum) '}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n'); fprintf(fidTeX,'\\toprule \n');
fprintf(fidTeX,[' & Prior distribution & Prior mean & Prior ' ... fprintf(fidTeX,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{4}{c}{Posterior} \\\\\n');
's.d. & Posterior mean & Posterior s.d. & HPD inf & HPD sup\\\\ \n']); fprintf(fidTeX,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-8}\n');
fprintf(fidTeX,'\\hline \\endfirsthead \n'); fprintf(fidTeX,' & Dist. & Mean & Stdev. & Mean & Stdev. & HPD inf & HPD sup\\\\\n');
fprintf(fidTeX,['\\caption{(continued)}']); fprintf(fidTeX,'\\midrule \\endfirsthead \n');
fprintf(fidTeX,['\\label{Table:MHPosterior:' int2str(fnum) '}\\\\\n']); fprintf(fidTeX,['\\caption{(continued)}\\\\']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n'); fprintf(fidTeX,'\\toprule \n');
fprintf(fidTeX,[' & Prior distribution & Prior mean & Prior ' ... fprintf(fidTeX,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{4}{c}{Posterior} \\\\\n');
's.d. & Posterior mean & Posterior s.d. & HPD inf & HPD sup\\\\ \n']); fprintf(fidTeX,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-8}\n');
fprintf(fidTeX,'\\hline \\endhead \n'); fprintf(fidTeX,' & Dist. & Mean & Stdev. & Mean & Stdev. & HPD inf & HPD sup\\\\\n');
fprintf(fidTeX,'\\midrule \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{8}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n'); fprintf(fidTeX,'\\bottomrule \\multicolumn{8}{r}{(Continued on next page)} \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n'); fprintf(fidTeX,'\\bottomrule \\endlastfoot \n');
fid = fidTeX; fid = fidTeX;

View File

@ -90,22 +90,26 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
last_obs_begin_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(1)*NumberOfDraws*(1-options_.mh_drop)); 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)); first_obs_end_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(2)*NumberOfDraws*(1-options_.mh_drop));
param_name=[]; param_name=[];
for jj=1:npar if options_.TeX
param_name = strvcat(param_name,get_the_name(jj,options_.TeX,M_,estim_params_,options_)); param_name_tex=[];
end
for jj=1:npar
if options_.TeX
[param_name_temp, param_name_tex_temp]= get_the_name(jj,options_.TeX,M_,estim_params_,options_);
param_name_tex = strvcat(param_name_tex,strrep(param_name_tex_temp,'$',''));
param_name = strvcat(param_name,param_name_temp);
else
param_name_temp = get_the_name(jj,options_.TeX,M_,estim_params_,options_);
param_name = strvcat(param_name,param_name_temp);
end
end 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,NumberOfDraws); 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'); fprintf('p-values are for Chi2-test for equality of means.\n');
Geweke_header={'Parameter', 'Post. Mean', 'Post. Std', 'p-val No Taper'}; Geweke_header=char('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'];
print_string_header=['%',num2str(size(param_name,2)+3),'s \t %12s \t %12s \t %12s'];
for ii=1:length(options_.convergence.geweke.taper_steps) for ii=1:length(options_.convergence.geweke.taper_steps)
Geweke_header=[Geweke_header, ['p-val ' num2str(options_.convergence.geweke.taper_steps(ii)),'% Taper']]; Geweke_header=char(Geweke_header,['p-val ' num2str(options_.convergence.geweke.taper_steps(ii)),'% Taper']);
print_string=[print_string,'\t %12.3f'];
print_string_header=[print_string_header,'\t %12s'];
end end
print_string=[print_string,'\n']; datamat=NaN(npar,3+length(options_.convergence.geweke.taper_steps));
print_string_header=[print_string_header,'\n'];
fprintf(print_string_header,Geweke_header{1,:});
for jj=1:npar for jj=1:npar
startline=0; startline=0;
for n = 1:NumberOfMcFilesPerBlock for n = 1:NumberOfMcFilesPerBlock
@ -124,7 +128,21 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
results_struct = geweke_chi2_test(results_vec1,results_vec2,results_struct,options_); results_struct = geweke_chi2_test(results_vec1,results_vec2,results_struct,options_);
eval(['oo_.convergence.geweke.',param_name(jj,:),'=results_struct;']) eval(['oo_.convergence.geweke.',param_name(jj,:),'=results_struct;'])
fprintf(print_string,param_name(jj,:),results_struct.posteriormean,results_struct.posteriorstd,results_struct.prob_chi2_test) datamat(jj,:)=[results_struct.posteriormean,results_struct.posteriorstd,results_struct.prob_chi2_test];
end
lh = size(param_name,2)+2;
dyntable('',Geweke_header,param_name,datamat,lh,12,3);
if options_.TeX
Geweke_tex_header=char('Parameter', 'Mean', 'Std', 'No\ Taper');
additional_header={[' & \multicolumn{2}{c}{Posterior} & \multicolumn{',num2str(1+length(options_.convergence.geweke.taper_steps)),'}{c}{p-values} \\'],
['\cmidrule(r{.75em}){2-3} \cmidrule(r{.75em}){4-',num2str(4+length(options_.convergence.geweke.taper_steps)),'}']};
for ii=1:length(options_.convergence.geweke.taper_steps)
Geweke_tex_header=char(Geweke_tex_header,[num2str(options_.convergence.geweke.taper_steps(ii)),'\%%\ Taper']);
end
headers = char(Geweke_tex_header);
lh = size(param_name_tex,2)+2;
my_title=sprintf('Geweke (1992) Convergence Tests, based on means of draws %d to %d vs %d to %d. p-values are for $\\\\chi^2$-test for equality of means.',first_obs_begin_sample,last_obs_begin_sample,first_obs_end_sample,NumberOfDraws);
dyn_latex_table(M_,my_title,'geweke',headers,param_name_tex,datamat,lh,12,4,additional_header);
end end
skipline(2); skipline(2);
return; return;

View File

@ -77,7 +77,7 @@ if options_.dsge_var
NumberOfLagsTimesNvobs = myinputs.NumberOfLagsTimesNvobs; NumberOfLagsTimesNvobs = myinputs.NumberOfLagsTimesNvobs;
Companion_matrix = myinputs.Companion_matrix; Companion_matrix = myinputs.Companion_matrix;
stock_irf_bvardsge = zeros(options_.irf,nvobs,M_.exo_nbr,MAX_nirfs_dsgevar); stock_irf_bvardsge = zeros(options_.irf,nvobs,M_.exo_nbr,MAX_nirfs_dsgevar);
bounds = prior_bounds(bayestopt_,options_); bounds = prior_bounds(bayestopt_,options_.prior_trunc);
end end

View File

@ -236,7 +236,8 @@ for curr_chain = fblck:nblck,
dyn_waitbar(prtfrc,hh,[ 'MH (' int2str(curr_chain) '/' int2str(options_.mh_nblck) ') ' sprintf('Current acceptance ratio %4.3f', accepted_draws_this_chain/blocked_draws_counter_this_chain)]); dyn_waitbar(prtfrc,hh,[ 'MH (' int2str(curr_chain) '/' int2str(options_.mh_nblck) ') ' sprintf('Current acceptance ratio %4.3f', accepted_draws_this_chain/blocked_draws_counter_this_chain)]);
end end
if (draw_index_current_file == InitSizeArray(curr_chain)) || (draw_iter == nruns(curr_chain)) % Now I save the simulations, either because the current file is full or the chain is done if (draw_index_current_file == InitSizeArray(curr_chain)) || (draw_iter == nruns(curr_chain)) % Now I save the simulations, either because the current file is full or the chain is done
save([BaseName '_mh' int2str(NewFile(curr_chain)) '_blck' int2str(curr_chain) '.mat'],'x2','logpo2'); [LastSeeds.(['file' int2str(NewFile(curr_chain))]).Unifor, LastSeeds.(['file' int2str(NewFile(curr_chain))]).Normal] = get_dynare_random_generator_state();
save([BaseName '_mh' int2str(NewFile(curr_chain)) '_blck' int2str(curr_chain) '.mat'],'x2','logpo2','LastSeeds');
fidlog = fopen([MetropolisFolder '/metropolis.log'],'a'); fidlog = fopen([MetropolisFolder '/metropolis.log'],'a');
fprintf(fidlog,['\n']); fprintf(fidlog,['\n']);
fprintf(fidlog,['%% Mh' int2str(NewFile(curr_chain)) 'Blck' int2str(curr_chain) ' (' datestr(now,0) ')\n']); fprintf(fidlog,['%% Mh' int2str(NewFile(curr_chain)) 'Blck' int2str(curr_chain) ' (' datestr(now,0) ')\n']);

View File

@ -1,6 +1,6 @@
function mexpath = add_path_to_mex_files(dynareroot, modifypath) function mexpath = add_path_to_mex_files(dynareroot, modifypath)
% Copyright (C) 2015 Dynare Team % Copyright (C) 2015-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -29,7 +29,7 @@ if exist('OCTAVE_VERSION')
else else
% Add win32 specific paths for Dynare Windows package % Add win32 specific paths for Dynare Windows package
if strcmp(computer, 'PCWIN') if strcmp(computer, 'PCWIN')
tmp = [dynareroot '../mex/matlab/win32-7.5-8.5/']; tmp = [dynareroot '../mex/matlab/win32-7.5-8.6/'];
if exist(tmp, 'dir') if exist(tmp, 'dir')
mexpath = tmp; mexpath = tmp;
if modifypath if modifypath
@ -48,7 +48,7 @@ else
end end
end end
else else
tmp = [dynareroot '../mex/matlab/win64-7.8-8.5/']; tmp = [dynareroot '../mex/matlab/win64-7.8-8.6/'];
if exist(tmp, 'dir') if exist(tmp, 'dir')
mexpath = tmp; mexpath = tmp;
if modifypath if modifypath

View File

@ -57,7 +57,7 @@ function plan = basic_plan(plan, exogenous, expectation_type, date, value)
if ~isempty(common_var) if ~isempty(common_var)
common_date = intersect(date, plan.constrained_date_{common_var}); common_date = intersect(date, plan.constrained_date_{common_var});
if ~isempty(common_date) if ~isempty(common_date)
[date, i_date] = setdiff(date, common_date); [date_, i_date] = setdiff(date, common_date);
value = value(i_date); value = value(i_date);
if common_date.length > 1 if common_date.length > 1
the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))]; the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))];

View File

@ -12,7 +12,7 @@ function bvar_density(maxnlags)
% none % none
% Copyright (C) 2003-2007 Christopher Sims % Copyright (C) 2003-2007 Christopher Sims
% Copyright (C) 2007-2009 Dynare Team % Copyright (C) 2007-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -29,6 +29,10 @@ function bvar_density(maxnlags)
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global oo_
oo_.bvar.log_marginal_data_density=NaN(maxnlags,1);
for nlags = 1:maxnlags for nlags = 1:maxnlags
[ny, nx, posterior, prior] = bvar_toolbox(nlags); [ny, nx, posterior, prior] = bvar_toolbox(nlags);
@ -39,6 +43,8 @@ for nlags = 1:maxnlags
log_dnsty = posterior_int - prior_int - 0.5*ny*lik_nobs*log(2*pi); log_dnsty = posterior_int - prior_int - 0.5*ny*lik_nobs*log(2*pi);
oo_.bvar.log_marginal_data_density(nlags)=log_dnsty;
skipline() skipline()
fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ... fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ...
nlags, log_dnsty); nlags, log_dnsty);

63
matlab/cellofchar2mfile.m Normal file
View File

@ -0,0 +1,63 @@
function cellofchar2mfile(fname, c, cname)
% Write a cell of char in a matlab script.
%
% INPUTS
% - fname [string] name of the file where c is to be saved.
% - c [cell] a two dimensional cell of char.
%
% OUTPUTS
% 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/>.
[pathstr,name,ext] = fileparts(fname);
if isempty(ext)
fname = [pathstr, name, '.m']
else
if ~isequal(ext, '.m')
error(['The first argument needs to be the name of a matlab script (with an .m extension)!'])
end
end
if ~iscell(c)
error('The second input argument must be a cell!')
end
if ndims(c)>2
error(['The cell passed has a second argument cannot have more than two dimensions!'])
end
variablename = inputname(2);
if isempty(variablename) && nargin<3
error(['You must pass the name of the cell (second input argument) as a string in the third input argument!'])
end
if nargin>2
if isvarname(cname)
variablename = cname;
else
error('The third input argument must be a valid variable name!')
end
end
fid = fopen(fname,'w');
fprintf(fid, '%s = %s;', variablename, writecellofchar(c));
fclose(fid);

View File

@ -1,4 +1,4 @@
function clear_persistent_variables(folder) function clear_persistent_variables(folder, writelistofroutinestobecleared)
% Clear all the functions with persistent variables in directory folder (and subdirectories). % Clear all the functions with persistent variables in directory folder (and subdirectories).
@ -19,37 +19,44 @@ function clear_persistent_variables(folder)
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
DYNARE_FOLDER = strrep(which('dynare'),'dynare.m','');
if ~nargin || isempty(folder) if nargin<2
writelistofroutinestobecleared = false;
end
if nargin<1 || isempty(folder)
folder = pwd(); folder = pwd();
end end
if ~exist('list_of_functions_to_be_cleared.mat') || isolder(sprintf('%slist_of_functions_to_be_cleared.mat', DYNARE_FOLDER), DYNARE_FOLDER) DYNARE_FOLDER = strrep(which('dynare'),'dynare.m','');
if isunix() || ismac()
[status, output] = system(sprintf('grep -lr ^persistent %s', folder)); if writelistofroutinestobecleared
list_of_files = strsplit(output); if ~exist('list_of_functions_to_be_cleared.m') || isolder(sprintf('%slist_of_functions_to_be_cleared.m', DYNARE_FOLDER), DYNARE_FOLDER)
list_of_files(find(cellfun(@isempty, list_of_files))) = []; if isunix() || ismac()
else [status, output] = system(sprintf('grep -lr ^persistent %s', folder));
[status, output] = system(sprintf('findstr /B/S/M persistent %s\\*', folder)); list_of_files = strsplit(output);
list_of_files = strsplit(output); list_of_files(find(cellfun(@isempty, list_of_files))) = [];
list_of_files(find(cellfun(@isempty, list_of_files))) = []; else
i = 1; mobius = true; [status, output] = system(sprintf('findstr /B/S/M persistent %s\\*', folder));
while mobius list_of_files = strsplit(output);
if i>length(list_of_files) list_of_files(find(cellfun(@isempty, list_of_files))) = [];
break i = 1; mobius = true;
end while mobius
if ismember(list_of_files{i},{'FINDSTR:', 'ignored', '//'}) if i>length(list_of_files)
list_of_files(i) = []; break
else end
i = i + 1; if ismember(list_of_files{i},{'FINDSTR:', 'ignored', '//'})
list_of_files(i) = [];
else
i = i + 1;
end
end end
end end
[paths, list_of_functions, extensions] = cellfun(@fileparts, list_of_files, 'UniformOutput',false);
cellofchar2mfile(sprintf('%slist_of_functions_to_be_cleared.m', DYNARE_FOLDER), list_of_functions)
end end
[paths, list_of_functions, extensions] = cellfun(@fileparts, list_of_files, 'UniformOutput',false); return
save(sprintf('%slist_of_functions_to_be_cleared.mat', DYNARE_FOLDER), 'list_of_functions');
else
load('list_of_functions_to_be_cleared');
end end
clear(list_of_functions{:}); list_of_functions_to_be_cleared;
clear(list_of_functions{:});

View File

@ -30,13 +30,14 @@ function collect_LaTeX_Files(M_)
f_name_binder=[M_.fname,'_TeX_binder.TeX']; f_name_binder=[M_.fname,'_TeX_binder.TeX'];
fid=fopen(f_name_binder,'w+'); fid=fopen(f_name_binder,'w+');
fprintf(fid,'%s \n','\documentclass[12pt]{article}'); fprintf(fid,'%s \n','\documentclass[12pt]{article}');
fprintf(fid,'%s \n','\usepackage[margin=2cm]{geometry}');
fprintf(fid,'%s \n','\usepackage{psfrag}'); fprintf(fid,'%s \n','\usepackage{psfrag}');
fprintf(fid,'%s \n','\usepackage{graphicx}'); fprintf(fid,'%s \n','\usepackage{graphicx}');
fprintf(fid,'%s \n','\usepackage{epstopdf}'); fprintf(fid,'%s \n','\usepackage{epstopdf}');
fprintf(fid,'%s \n','\usepackage{longtable}'); fprintf(fid,'%s \n','\usepackage{longtable,booktabs}');
fprintf(fid,'%s \n','\usepackage{amsfonts}'); fprintf(fid,'%s \n','\usepackage{amsfonts}');
fprintf(fid,'%s \n','\usepackage{breqn}'); fprintf(fid,'%s \n','\usepackage{breqn}');
fprintf(fid,'%s \n','\usepackage{float}'); fprintf(fid,'%s \n','\usepackage{float,morefloats,caption}');
fprintf(fid,'%s \n','\begin{document}'); fprintf(fid,'%s \n','\begin{document}');
%% Root directory %% Root directory
@ -60,7 +61,7 @@ for ii=1:length(TeX_Files)
end end
end end
%5 graphs directory %% graphs directory
TeX_Files=dir([M_.dname filesep 'graphs' filesep M_.fname '*.TeX']); TeX_Files=dir([M_.dname filesep 'graphs' filesep M_.fname '*.TeX']);
for ii=1:length(TeX_Files) for ii=1:length(TeX_Files)
[pathstr,f_name,ext] = fileparts(TeX_Files(ii).name); [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
@ -69,6 +70,24 @@ for ii=1:length(TeX_Files)
end end
end end
%% Identification directory
TeX_Files=dir([M_.dname filesep 'identification' filesep M_.fname '*.TeX']);
for ii=1:length(TeX_Files)
[pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
if ~strcmp(TeX_Files(ii).name,f_name_binder)
fprintf(fid,'%s \n',['\include{', M_.dname '/identification' '/',f_name,'}']);
end
end
%% GSA directory
TeX_Files=dir([M_.dname filesep 'gsa' filesep M_.fname '*.TeX']);
for ii=1:length(TeX_Files)
[pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
if ~strcmp(TeX_Files(ii).name,f_name_binder)
fprintf(fid,'%s \n',['\include{', M_.dname '/gsa' '/',f_name,'}']);
end
end
%% Write footer %% Write footer
fprintf(fid,'%s \n','\end{document}'); fprintf(fid,'%s \n','\end{document}');

View File

@ -0,0 +1,49 @@
function [trend_addition, trend_coeff]=compute_trend_coefficients(M_,DynareOptions,nvarobs,ntobs)
% [trend_addition, trend_coeff]=compute_trend_coefficients(DynareOptions,nvarobs,ntobs)
% Computes the trend coefficiencts and the trend, accounting for
% prefiltering
%
% INPUTS
% M_ [structure] describing the model; called in the eval
% statement
% DynareOptions [structure] describing the options
% nvarobs [scalar] number of observed variables
% ntobs [scalar] length of data sample for estimation
%
% OUTPUTS
% trend_addition [nvarobs by ntobs double] matrix storing deterministic
% trend component
% trend_coeff [nvarobs by 1] vector storing trend slope
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2014 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
trend_coeff = zeros(nvarobs,1);
t = DynareOptions.trend_coeffs;
for i=1:length(t)
if ~isempty(t{i})
trend_coeff(i) = eval(t{i});
end
end
trend_addition=trend_coeff*[DynareOptions.first_obs:DynareOptions.first_obs+ntobs-1];
if DynareOptions.prefilter
trend_addition = bsxfun(@minus,trend_addition,mean(trend_addition,2));
end

View File

@ -23,7 +23,7 @@ function oo_ = ...
% OUTPUTS % OUTPUTS
% oo_ [structure] Dynare structure where the results are saved. % oo_ [structure] Dynare structure where the results are saved.
% Copyright (C) 2009-2013 Dynare Team % Copyright (C) 2009-2015 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -60,7 +60,10 @@ if isempty(exogenous_variable_index)
return return
end end
name = [ var_list(endogenous_variable_index,:) '.' exo ]; name_1 = var_list(endogenous_variable_index,:);
name_2 = exo;
name = [ name_1 '.' name_2 ];
if isfield(oo_, [ TYPE 'TheoreticalMoments' ]) if isfield(oo_, [ TYPE 'TheoreticalMoments' ])
temporary_structure = oo_.([TYPE 'TheoreticalMoments']); temporary_structure = oo_.([TYPE 'TheoreticalMoments']);
if isfield(temporary_structure,'dsge') if isfield(temporary_structure,'dsge')
@ -112,13 +115,16 @@ for i=1:length(Steps)
p_hpdinf(i) = hpd_interval(1); p_hpdinf(i) = hpd_interval(1);
p_hpdsup(i) = hpd_interval(2); p_hpdsup(i) = hpd_interval(2);
end end
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.Steps = Steps;
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.Mean.(name) = p_mean; FirstField = sprintf('%sTheoreticalMoments', TYPE);
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.Median.(name) = p_median;
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.Variance.(name) = p_variance; oo_.(FirstField).dsge.ConditionalVarianceDecomposition.Steps = Steps;
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.HPDinf.(name) = p_hpdinf; oo_.(FirstField).dsge.ConditionalVarianceDecomposition.Mean.(name_1).(name_2) = p_mean;
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.HPDsup.(name) = p_hpdsup; oo_.(FirstField).dsge.ConditionalVarianceDecomposition.Median.(name_1).(name_2) = p_median;
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.deciles.(name) = p_deciles; oo_.(FirstField).dsge.ConditionalVarianceDecomposition.Variance.(name_1).(name_2) = p_variance;
oo_.(FirstField).dsge.ConditionalVarianceDecomposition.HPDinf.(name_1).(name_2) = p_hpdinf;
oo_.(FirstField).dsge.ConditionalVarianceDecomposition.HPDsup.(name_1).(name_2) = p_hpdsup;
oo_.(FirstField).dsge.ConditionalVarianceDecomposition.deciles.(name_1).(name_2) = p_deciles;
if options_.estimation.moments_posterior_density.indicator if options_.estimation.moments_posterior_density.indicator
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.density.(name) = p_density; oo_.(FirstField).dsge.ConditionalVarianceDecomposition.density.(name_1).(name_2) = p_density;
end end

View File

@ -52,7 +52,7 @@ if isfield(oo_,'PointForecast')
end end
%% change HPD-fields back to row vectors %% change HPD-fields back to row vectors
if isfield(oo_.PointForecast,'HPDinf') if isfield(oo_,'PointForecast') && isfield(oo_.PointForecast,'HPDinf')
names=fieldnames(oo_.PointForecast.HPDinf); names=fieldnames(oo_.PointForecast.HPDinf);
for ii=1:length(names) for ii=1:length(names)
oo_.PointForecast.HPDinf.(names{ii})=oo_.PointForecast.HPDinf.(names{ii})'; oo_.PointForecast.HPDinf.(names{ii})=oo_.PointForecast.HPDinf.(names{ii})';
@ -60,7 +60,7 @@ if isfield(oo_.PointForecast,'HPDinf')
end end
end end
if isfield(oo_.MeanForecast,'HPDinf') if isfield(oo_,'MeanForecast') && isfield(oo_.MeanForecast,'HPDinf')
names=fieldnames(oo_.MeanForecast.HPDinf); names=fieldnames(oo_.MeanForecast.HPDinf);
for ii=1:length(names) for ii=1:length(names)
oo_.MeanForecast.HPDinf.(names{ii})=oo_.MeanForecast.HPDinf.(names{ii})'; oo_.MeanForecast.HPDinf.(names{ii})=oo_.MeanForecast.HPDinf.(names{ii})';
@ -68,7 +68,7 @@ if isfield(oo_.MeanForecast,'HPDinf')
end end
end end
if isfield(oo_.UpdatedVariables,'HPDinf') if isfield(oo_,'UpdatedVariables') && isfield(oo_.UpdatedVariables,'HPDinf')
names=fieldnames(oo_.UpdatedVariables.HPDinf); names=fieldnames(oo_.UpdatedVariables.HPDinf);
for ii=1:length(names) for ii=1:length(names)
oo_.UpdatedVariables.HPDinf.(names{ii})=oo_.UpdatedVariables.HPDinf.(names{ii})'; oo_.UpdatedVariables.HPDinf.(names{ii})=oo_.UpdatedVariables.HPDinf.(names{ii})';
@ -76,7 +76,7 @@ if isfield(oo_.UpdatedVariables,'HPDinf')
end end
end end
if isfield(oo_.SmoothedVariables,'HPDinf') if isfield(oo_,'SmoothedVariables') && isfield(oo_.SmoothedVariables,'HPDinf')
names=fieldnames(oo_.SmoothedVariables.HPDinf); names=fieldnames(oo_.SmoothedVariables.HPDinf);
for ii=1:length(names) for ii=1:length(names)
oo_.SmoothedVariables.HPDinf.(names{ii})=oo_.SmoothedVariables.HPDinf.(names{ii})'; oo_.SmoothedVariables.HPDinf.(names{ii})=oo_.SmoothedVariables.HPDinf.(names{ii})';
@ -84,7 +84,7 @@ if isfield(oo_.SmoothedVariables,'HPDinf')
end end
end end
if isfield(oo_.FilteredVariables,'HPDinf') if isfield(oo_,'FilteredVariables') && isfield(oo_.FilteredVariables,'HPDinf')
names=fieldnames(oo_.FilteredVariables.HPDinf); names=fieldnames(oo_.FilteredVariables.HPDinf);
for ii=1:length(names) for ii=1:length(names)
oo_.FilteredVariables.HPDinf.(names{ii})=oo_.FilteredVariables.HPDinf.(names{ii})'; oo_.FilteredVariables.HPDinf.(names{ii})=oo_.FilteredVariables.HPDinf.(names{ii})';
@ -92,7 +92,7 @@ if isfield(oo_.FilteredVariables,'HPDinf')
end end
end end
if isfield(oo_.SmoothedShocks,'HPDinf') if isfield(oo_,'SmoothedShocks') && isfield(oo_.SmoothedShocks,'HPDinf')
names=fieldnames(oo_.SmoothedShocks.HPDinf); names=fieldnames(oo_.SmoothedShocks.HPDinf);
for ii=1:length(names) for ii=1:length(names)
oo_.SmoothedShocks.HPDinf.(names{ii})=oo_.SmoothedShocks.HPDinf.(names{ii})'; oo_.SmoothedShocks.HPDinf.(names{ii})=oo_.SmoothedShocks.HPDinf.(names{ii})';
@ -100,13 +100,44 @@ if isfield(oo_.SmoothedShocks,'HPDinf')
end end
end end
%% padd classical filtered variables with redundant zeros %% subtract mean from classical Updated variables
if isfield(oo_,'UpdatedVariables')
names=fieldnames(oo_.UpdatedVariables);
for ii=1:length(names)
%make sure Bayesian fields are not affected
if ~strcmp(names{ii},'Mean') && ~strcmp(names{ii},'Median') && ~strcmp(names{ii},'deciles') ...
&& ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup')
current_var_index=find(strmatch(names{ii},deblank(M_.endo_names),'exact'));
if options_.loglinear == 1 %logged steady state must be used
constant_current_variable=log(oo_.dr.ys(current_var_index));
elseif options_.loglinear == 0 %unlogged steady state must be used
constant_current_variable=oo_.dr.ys(current_var_index);
end
oo_.UpdatedVariables.(names{ii})=oo_.UpdatedVariables.(names{ii})-constant_current_variable;
if isfield(oo_.Smoother,'Trend') && isfield(oo_.Smoother.Trend,names{ii})
oo_.UpdatedVariables.(names{ii})=oo_.UpdatedVariables.(names{ii})-oo_.Smoother.Trend.(names{ii});
end
end
end
end
%% padd classical filtered variables with redundant zeros and subtract mean
if isfield(oo_,'FilteredVariables') if isfield(oo_,'FilteredVariables')
names=fieldnames(oo_.FilteredVariables); names=fieldnames(oo_.FilteredVariables);
for ii=1:length(names) for ii=1:length(names)
%make sure Bayesian fields are not affect %make sure Bayesian fields are not affected
if ~strcmp(names{ii},'Mean') && ~strcmp(names{ii},'Median') && ~strcmp(names{ii},'deciles') ... if ~strcmp(names{ii},'Mean') && ~strcmp(names{ii},'Median') && ~strcmp(names{ii},'deciles') ...
&& ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup') && ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup')
current_var_index=find(strmatch(names{ii},deblank(M_.endo_names),'exact'));
if options_.loglinear == 1 %logged steady state must be used
constant_current_variable=log(oo_.dr.ys(current_var_index));
elseif options_.loglinear == 0 %unlogged steady state must be used
constant_current_variable=oo_.dr.ys(current_var_index);
end
oo_.FilteredVariables.(names{ii})=oo_.FilteredVariables.(names{ii})-constant_current_variable;
if isfield(oo_.Smoother,'Trend') && isfield(oo_.Smoother.Trend,names{ii})
oo_.FilteredVariables.(names{ii})=oo_.FilteredVariables.(names{ii})-oo_.Smoother.Trend.(names{ii});
end
oo_.FilteredVariables.(names{ii})=[0; oo_.FilteredVariables.(names{ii}); zeros(options_.nk-1,1)]; oo_.FilteredVariables.(names{ii})=[0; oo_.FilteredVariables.(names{ii}); zeros(options_.nk-1,1)];
end end
end end

View File

@ -43,6 +43,9 @@ else
var2 = var1; var2 = var1;
end end
var1=deblank(var1);
var2=deblank(var2);
if isfield(oo_,[TYPE 'TheoreticalMoments']) if isfield(oo_,[TYPE 'TheoreticalMoments'])
temporary_structure = oo_.([TYPE, 'TheoreticalMoments']); temporary_structure = oo_.([TYPE, 'TheoreticalMoments']);
if isfield(temporary_structure,'dsge') if isfield(temporary_structure,'dsge')

View File

@ -60,6 +60,9 @@ else
var2 = var1; var2 = var1;
end end
var1=deblank(var1);
var2=deblank(var2);
if isfield(oo_,[ TYPE 'TheoreticalMoments']) if isfield(oo_,[ TYPE 'TheoreticalMoments'])
temporary_structure = oo_.([TYPE, 'TheoreticalMoments']); temporary_structure = oo_.([TYPE, 'TheoreticalMoments']);
if isfield(temporary_structure,'dsge') if isfield(temporary_structure,'dsge')

View File

@ -187,7 +187,7 @@ elseif ~options_.hp_filter && options_.one_sided_hp_filter && ~options_.bandpass
[hptrend,y] = one_sided_hp_filter(y,options_.one_sided_hp_filter); [hptrend,y] = one_sided_hp_filter(y,options_.one_sided_hp_filter);
elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && options_.bandpass.indicator elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && options_.bandpass.indicator
data_temp=dseries(y,'0q1'); data_temp=dseries(y,'0q1');
data_temp=baxter_king_filter(data_temp,options_.bandpass.passband(1),options_.bandpass.passband(2),200); data_temp=baxter_king_filter(data_temp,options_.bandpass.passband(1),options_.bandpass.passband(2),12);
y=data_temp.data; y=data_temp.data;
elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpass.indicator elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpass.indicator
y = bsxfun(@minus, y, m); y = bsxfun(@minus, y, m);

View File

@ -179,24 +179,7 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
if np if np
filename = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_1.TeX']; filename = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_1.TeX'];
fidTeX = fopen(filename,'w'); fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); TeXBegin_Bayesian(fidTeX,1,'parameters')
fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (parameters)\n');
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|lcccc} \n');
fprintf(fidTeX,'\\caption{Results from posterior maximization (parameters)}\\\\\n ');
fprintf(fidTeX,'\\label{Table:Posterior:1}\\\\\n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \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. & Posterior mode & s.d. \\\\ \n');
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{6}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
ip = nvx+nvn+ncx+ncn+1; ip = nvx+nvn+ncx+ncn+1;
for i=1:np for i=1:np
fprintf(fidTeX,'$%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n',... fprintf(fidTeX,'$%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n',...
@ -208,33 +191,12 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
stdh(ip)); stdh(ip));
ip = ip + 1; ip = ip + 1;
end end
fprintf(fidTeX,'\\end{longtable}\n '); TeXEnd(fidTeX)
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end end
if nvx if nvx
TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_2.TeX']; TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_2.TeX'];
fidTeX = fopen(TeXfile,'w'); fidTeX = fopen(TeXfile,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); TeXBegin_Bayesian(fidTeX,2,'standard deviation of structural shocks')
fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (standard deviation of structural shocks)\n');
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|lcccc} \n');
fprintf(fidTeX,'\\caption{Results from posterior maximization (standard deviation of structural shocks)}\\\\\n ');
fprintf(fidTeX,'\\label{Table:Posterior:2}\\\\\n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n');
fprintf(fidTeX,'\\hline \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,'\\label{Table:Posterior:2}\\\\\n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n');
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{6}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
ip = 1; ip = 1;
for i=1:nvx for i=1:nvx
k = estim_params_.var_exo(i,1); k = estim_params_.var_exo(i,1);
@ -247,33 +209,12 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
stdh(ip)); stdh(ip));
ip = ip+1; ip = ip+1;
end end
fprintf(fidTeX,'\\end{longtable}\n '); TeXEnd(fidTeX)
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end end
if nvn if nvn
TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_3.TeX']; TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_3.TeX'];
fidTeX = fopen(TeXfile,'w'); fidTeX = fopen(TeXfile,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); TeXBegin_Bayesian(fidTeX,3,'standard deviation of measurement errors')
fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (standard deviation of measurement errors)\n');
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|lcccc} \n');
fprintf(fidTeX,'\\caption{Results from posterior maximization (standard deviation of measurement errors)}\\\\\n ');
fprintf(fidTeX,'\\label{Table:Posterior:3}\\\\\n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n');
fprintf(fidTeX,'\\hline \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,'\\label{Table:Posterior:3}\\\\\n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n');
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{6}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
ip = nvx+1; ip = nvx+1;
for i=1:nvn for i=1:nvn
idx = strmatch(options_.varobs{estim_params_.nvn_observable_correspondence(i,1)},M_.endo_names); idx = strmatch(options_.varobs{estim_params_.nvn_observable_correspondence(i,1)},M_.endo_names);
@ -286,33 +227,12 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
stdh(ip)); stdh(ip));
ip = ip+1; ip = ip+1;
end end
fprintf(fidTeX,'\\end{longtable}\n '); TeXEnd(fidTeX)
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end end
if ncx if ncx
TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_4.TeX']; TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_4.TeX'];
fidTeX = fopen(TeXfile,'w'); fidTeX = fopen(TeXfile,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); TeXBegin_Bayesian(fidTeX,4,'correlation of structural shocks')
fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (correlation of structural shocks)\n');
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|lcccc} \n');
fprintf(fidTeX,'\\caption{Results from posterior parameters (correlation of structural shocks)}\\\\\n ');
fprintf(fidTeX,'\\label{Table:Posterior:4}\\\\\n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n');
fprintf(fidTeX,'\\hline \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,'\\label{Table:Posterior:4}\\\\\n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n');
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{6}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
ip = nvx+nvn+1; ip = nvx+nvn+1;
for i=1:ncx for i=1:ncx
k1 = estim_params_.corrx(i,1); k1 = estim_params_.corrx(i,1);
@ -326,33 +246,12 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
stdh(ip)); stdh(ip));
ip = ip+1; ip = ip+1;
end end
fprintf(fidTeX,'\\end{longtable}\n '); TeXEnd(fidTeX)
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end end
if ncn if ncn
TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_5.TeX']; TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_5.TeX'];
fidTeX = fopen(TeXfile,'w'); fidTeX = fopen(TeXfile,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); TeXBegin_Bayesian(fidTeX,5,'correlation of measurement errors')
fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (correlation of measurement errors)\n');
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|lcccc} \n');
fprintf(fidTeX,'\\caption{Results from posterior parameters (correlation of measurement errors)}\\\\\n ');
fprintf(fidTeX,'\\label{Table:Posterior:5}\\\\\n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n');
fprintf(fidTeX,'\\hline \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,'\\label{Table:Posterior:5}\\\\\n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n');
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{6}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
ip = nvx+nvn+ncx+1; ip = nvx+nvn+ncx+1;
for i=1:ncn for i=1:ncn
k1 = estim_params_.corrn(i,1); k1 = estim_params_.corrn(i,1);
@ -366,34 +265,13 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
stdh(ip)); stdh(ip));
ip = ip+1; ip = ip+1;
end end
fprintf(fidTeX,'\\end{longtable}\n '); TeXEnd(fidTeX)
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end end
elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
if np if np
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_1.TeX']; filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_1.TeX'];
fidTeX = fopen(filename,'w'); fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); TeXBegin_ML(fidTeX,1,'parameters',table_title,LaTeXtitle)
fprintf(fidTeX,['%% RESULTS FROM ' table_title ' MAXIMIZATION (parameters)\n']);
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|lcc} \n');
fprintf(fidTeX,['\\caption{Results from ' table_title ' maximization (parameters)}\\\\\n ']);
fprintf(fidTeX,['\\label{Table:' LaTeXtitle ':1}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fidTeX,'\\hline \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,['\\label{Table:' LaTeXtitle ':1}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{4}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
ip = nvx+nvn+ncx+ncn+1; ip = nvx+nvn+ncx+ncn+1;
for i=1:np for i=1:np
fprintf(fidTeX,'$%s$ & %8.4f & %7.4f & %7.4f\\\\ \n',... fprintf(fidTeX,'$%s$ & %8.4f & %7.4f & %7.4f\\\\ \n',...
@ -403,33 +281,12 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
tstath(ip)); tstath(ip));
ip = ip + 1; ip = ip + 1;
end end
fprintf(fidTeX,'\\end{longtable}\n '); TeXEnd(fidTeX)
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end end
if nvx if nvx
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_2.TeX']; filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_2.TeX'];
fidTeX = fopen(filename,'w'); fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); TeXBegin_ML(fidTeX,2,'standard deviation of structural shocks',table_title,LaTeXtitle)
fprintf(fidTeX,['%% RESULTS FROM ' table_title ' MAXIMIZATION (standard deviation of structural shocks)\n']);
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|lcc} \n');
fprintf(fidTeX,['\\caption{Results from ' table_title ' maximization (standard deviation of structural shocks)}\\\\\n ']);
fprintf(fidTeX,['\\label{Table:' LaTeXtitle ':2}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fidTeX,'\\hline \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,['\\label{Table:' LaTeXtitle ':2}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{4}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
ip = 1; ip = 1;
for i=1:nvx for i=1:nvx
k = estim_params_.var_exo(i,1); k = estim_params_.var_exo(i,1);
@ -440,33 +297,12 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
tstath(ip)); tstath(ip));
ip = ip+1; ip = ip+1;
end end
fprintf(fidTeX,'\\end{longtable}\n '); TeXEnd(fidTeX)
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end end
if nvn if nvn
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_3.TeX']; filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_3.TeX'];
fidTeX = fopen(filename,'w'); fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); TeXBegin_ML(fidTeX,3,'standard deviation of measurement errors',table_title,LaTeXtitle)
fprintf(fidTeX,['%% RESULTS FROM ' table_title ' MAXIMIZATION (standard deviation of measurement errors)\n']);
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|lcc} \n');
fprintf(fidTeX,['\\caption{Results from ' table_title ' maximization (standard deviation of measurement errors)}\\\\\n ']);
fprintf(fidTeX,['\\label{Table:' LaTeXtitle ':3}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fidTeX,'\\hline \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,['\\label{Table:' LaTeXtitle ':3}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{4}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
ip = nvx+1; ip = nvx+1;
for i=1:nvn for i=1:nvn
idx = strmatch(options_.varobs{estim_params_.nvn_observable_correspondence(i,1)},M_.endo_names); idx = strmatch(options_.varobs{estim_params_.nvn_observable_correspondence(i,1)},M_.endo_names);
@ -477,33 +313,12 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
tstath(ip)); tstath(ip));
ip = ip+1; ip = ip+1;
end end
fprintf(fidTeX,'\\end{longtable}\n '); TeXEnd(fidTeX)
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end end
if ncx if ncx
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_4.TeX']; filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_4.TeX'];
fidTeX = fopen(filename,'w'); fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); TeXBegin_ML(fidTeX,4,'correlation of structural shocks',table_title,LaTeXtitle)
fprintf(fidTeX,['%% RESULTS FROM ' table_title ' MAXIMIZATION (correlation of structural shocks)\n']);
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|lcc} \n');
fprintf(fidTeX,['\\caption{Results from ' table_title ' maximization (correlation of structural shocks)}\\\\\n ']);
fprintf(fidTeX,['\\label{Table:' LaTeXtitle ':4}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fidTeX,'\\hline \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,['\\label{Table:' LaTeXtitle ':4}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{4}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
ip = nvx+nvn+1; ip = nvx+nvn+1;
for i=1:ncx for i=1:ncx
k1 = estim_params_.corrx(i,1); k1 = estim_params_.corrx(i,1);
@ -515,33 +330,12 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
tstath(ip)); tstath(ip));
ip = ip+1; ip = ip+1;
end end
fprintf(fidTeX,'\\end{longtable}\n '); TeXEnd(fidTeX)
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end end
if ncn if ncn
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_5.TeX']; filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_5.TeX'];
fidTeX = fopen(filename,'w'); fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); TeXBegin_ML(fidTeX,5,'correlation of measurement errors',table_title,LaTeXtitle)
fprintf(fidTeX,['%% RESULTS FROM ' table_title ' MAXIMIZATION (correlation of measurement errors)\n']);
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,'\\begin{longtable}{l|lcc} \n');
fprintf(fidTeX,['\\caption{Results from ' table_title ' maximization (correlation of measurement errors)}\\\\\n ']);
fprintf(fidTeX,['\\label{Table:' LaTeXtitle ':5}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fidTeX,'\\hline \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,['\\label{Table:' LaTeXtitle ':5}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\hline \\multicolumn{4}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
ip = nvx+nvn+ncx+1; ip = nvx+nvn+ncx+1;
for i=1:ncn for i=1:ncn
k1 = estim_params_.corrn(i,1); k1 = estim_params_.corrn(i,1);
@ -553,10 +347,60 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
tstath(ip)); tstath(ip));
ip = ip+1; ip = ip+1;
end end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end end
TeXEnd(fidTeX)
end end
%% subfunctions:
%
function TeXBegin_Bayesian(fid,fnum,title)
fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n');
fprintf(fid,['%% RESULTS FROM POSTERIOR MAXIMIZATION (' title ')\n']);
fprintf(fid,['%% ' datestr(now,0)]);
fprintf(fid,' \n');
fprintf(fid,' \n');
fprintf(fid,'\\begin{center}\n');
fprintf(fid,'\\begin{longtable}{llcccc} \n');
fprintf(fid,['\\caption{Results from posterior maximization (' title ')}\\\\\n ']);
fprintf(fid,['\\label{Table:Posterior:' int2str(fnum) '}\\\\\n']);
fprintf(fid,'\\toprule \n');
fprintf(fid,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{2}{c}{Posterior} \\\\\n');
fprintf(fid,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n');
fprintf(fid,' & Dist. & Mean & Stdev & Mode & Stdev \\\\ \n');
fprintf(fid,'\\midrule \\endfirsthead \n');
fprintf(fid,'\\caption{(continued)}\\\\\n ');
fprintf(fid,'\\bottomrule \n');
fprintf(fid,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{2}{c}{Posterior} \\\\\n');
fprintf(fid,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n');
fprintf(fid,' & Dist. & Mean & Stdev & Mode & Stdev \\\\ \n');
fprintf(fid,'\\midrule \\endhead \n');
fprintf(fid,'\\bottomrule \\multicolumn{6}{r}{(Continued on next page)}\\endfoot \n');
fprintf(fid,'\\bottomrule\\endlastfoot \n');
function TeXBegin_ML(fid,fnum,title,table_title,LaTeXtitle)
fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n');
fprintf(fid,['%% RESULTS FROM ' table_title ' MAXIMIZATION (' title ')\n']);
fprintf(fid,['%% ' datestr(now,0)]);
fprintf(fid,' \n');
fprintf(fid,' \n');
fprintf(fid,'\\begin{center}\n');
fprintf(fid,'\\begin{longtable}{llcc} \n');
fprintf(fid,['\\caption{Results from ' table_title ' maximization (' title ')}\\\\\n ']);
fprintf(fid,['\\label{Table:' LaTeXtitle ':' int2str(fnum) '}\\\\\n']);
fprintf(fid,'\\toprule \n');
fprintf(fid,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fid,'\\midrule \\endfirsthead \n');
fprintf(fid,'\\caption{(continued)}\\\\\n ');
fprintf(fid,'\\toprule \n');
fprintf(fid,' & Mode & s.d. & t-stat\\\\ \n');
fprintf(fid,'\\midrule \\endhead \n');
fprintf(fid,'\\bottomrule \\multicolumn{4}{r}{(Continued on next page)} \\endfoot \n');
fprintf(fid,'\\bottomrule \\endlastfoot \n');
function TeXEnd(fid)
fprintf(fid,'\\end{longtable}\n ');
fprintf(fid,'\\end{center}\n');
fprintf(fid,'%% End of TeX file.\n');
fclose(fid);

View File

@ -0,0 +1,132 @@
function [a, b] = beta_specification(mu, sigma2, lb, ub, name) % --*-- Unitary tests --*--
% Returns the hyperparameters of the beta distribution given the expectation and variance.
%
% INPUTS
% - mu [double] Expectation of the Gamma random variable.
% - sigma2 [double] Variance of the Gamma random variable.
% - lb [double] Lower bound of the domain (default is zero).
% - ub [double] Upper bound of the domain (default is one).
%
% OUTPUTS
% - a [double] First hyperparameter of the Beta density.
% - b [double] Second hyperparameter of the Beta density.
% 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<3
lb = 0;
ub = 1;
end
if nargin<4
ub = 1;
end
if nargin>4 && ~isempty(name)
name1 = sprintf('of %s ', name);
name2 = sprintf(' (for %s)', name);
else
name1 = '';
name2 = '';
end
if mu<lb
error(['The prior expectation (%f) %scannot be smaller than the lower bound of the Beta distribution (%f)!'], mu, name1, lb)
end
if mu>ub
error('The prior expectation (%f) %scannot be greater than the upper bound of the Beta distribution (%f)!', mu, name1, ub)
end
len = ub-lb;
mu = (mu-lb)/len;
sigma2 = sigma2/(len*len);
if sigma2>(1-mu)*mu
error('Beta prior%s. Given the declared prior expectation, prior lower and upper bounds, the prior std. has to be smaller than %f.',name2,sqrt((1-mu)*mu))
end
a = (1-mu)*mu*mu/sigma2-mu;
b = a*(1/mu-1);
%@test:1
%$ try
%$ [a, b] = beta_specification(.5, .05);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(0.5-a/(a+b))<1e-12;
%$ t(3) = abs(0.05-a*b/((a+b)^2*(a+b+1)))<1e-12;
%$ end
%$ T = all(t);
%@eof:1
%@test:2
%$ try
%$ [a, b] = beta_specification(0.5, .05, 1, 2);
%$ t(1) = false;
%$ catch
%$ t(1) = true;
%$ end
%$
%$ T = all(t);
%@eof:2
%@test:3
%$ try
%$ [a, b] = beta_specification(2.5, .05, 1, 2);
%$ t(1) = false;
%$ catch
%$ t(1) = true;
%$ end
%$
%$ T = all(t);
%@eof:3
%@test:4
%$ try
%$ [a, b] = beta_specification(.4, .6*.4+1e-4);
%$ t(1) = false;
%$ catch
%$ t(1) = true;
%$ end
%$
%$ T = all(t);
%@eof:4
%@test:5
%$ try
%$ [a, b] = beta_specification(.4, .6*.4+1e-6);
%$ t(1) = false;
%$ catch
%$ t(1) = true;
%$ end
%$ try
%$ [a, b] = beta_specification(.4, .6*.4-1e-6);
%$ t(2) = true;
%$ catch
%$ t(2) = false;
%$ end
%$
%$ T = all(t);
%@eof:5

View File

@ -1,4 +1,4 @@
function m = compute_prior_mode(hyperparameters,shape) function m = compute_prior_mode(hyperparameters,shape) % --*-- Unitary tests --*--
% This function computes the mode of the prior distribution given the (two, three or four) hyperparameters % This function computes the mode of the prior distribution given the (two, three or four) hyperparameters
% of the prior distribution. % of the prior distribution.
% %
@ -10,7 +10,8 @@ function m = compute_prior_mode(hyperparameters,shape)
% shape=3 => Gaussian distribution, % shape=3 => Gaussian distribution,
% shape=4 => Inverse Gamma (type 1) distribution, % shape=4 => Inverse Gamma (type 1) distribution,
% shape=5 => Uniform distribution, % shape=5 => Uniform distribution,
% shape=6 => Inverse Gamma (type 2) distribution. % shape=6 => Inverse Gamma (type 2) distribution,
% shape=8 => Weibull distribution.
% %
% OUTPUTS % OUTPUTS
% m [double] scalar or 2*1 vector, the prior mode. % m [double] scalar or 2*1 vector, the prior mode.
@ -22,7 +23,7 @@ function m = compute_prior_mode(hyperparameters,shape)
% [3] The uniform distribution has an infinity of modes. In this case the function returns the prior mean. % [3] The uniform distribution has an infinity of modes. In this case the function returns the prior mean.
% [4] For the beta distribution we can have 1, 2 or an infinity of modes. % [4] For the beta distribution we can have 1, 2 or an infinity of modes.
% Copyright (C) 2009-2015 Dynare Team % Copyright (C) 2009-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -38,6 +39,7 @@ function m = compute_prior_mode(hyperparameters,shape)
% %
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
m = NaN ; m = NaN ;
switch shape switch shape
case 1 case 1
@ -56,6 +58,8 @@ switch shape
m = m*(hyperparameters(4)-hyperparameters(3)) + hyperparameters(3) ; m = m*(hyperparameters(4)-hyperparameters(3)) + hyperparameters(3) ;
end end
case 2 case 2
% a = hyperparameters(1) [shape parameter]
% b = hyperparameters(2) [scale parameter]
if hyperparameters(1)<1 if hyperparameters(1)<1
m = 0; m = 0;
else else
@ -69,7 +73,7 @@ switch shape
case 4 case 4
% s = hyperparameters(1) % s = hyperparameters(1)
% nu = hyperparameters(2) % nu = hyperparameters(2)
m = 1/sqrt((hyperparameters(2)+1)/hyperparameters(1));%sqrt((hyperparameters(2)-1)/hyperparameters(1)) m = 1/sqrt((hyperparameters(2)+1)/hyperparameters(1));
if length(hyperparameters)>2 if length(hyperparameters)>2
m = m + hyperparameters(3); m = m + hyperparameters(3);
end end
@ -82,6 +86,156 @@ switch shape
if length(hyperparameters)>2 if length(hyperparameters)>2
m = m + hyperparameters(3) ; m = m + hyperparameters(3) ;
end end
case 8
% k = hyperparameters(1) [shape parameter]
% s = hyperparameters(2) [scale parameter]
if hyperparameters(1)<=1
m = 0;
else
m = hyperparameters(2)*((hyperparameters(1)-1)/hyperparameters(1))^(1/hyperparameters(1));
end
if length(hyperparameters)>2
% Add location parameter
m = m + hyperparameters(3) ;
end
otherwise otherwise
error('Unknown prior shape!') error('Unknown prior shape!')
end end
%@test:1
%$ % Beta density
%$ try
%$ m1 = compute_prior_mode([2 1],1);
%$ m2 = compute_prior_mode([2 5 1 4],1); % Wolfram Alpha: BetaDistribution[2,5]
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ % Check the results
%$ if t(1)
%$ t(2) = dassert(m1,1,1e-6);
%$ t(3) = dassert(m2,1/5*3+1,1e-6);
%$ end
%$ T = all(t);
%@eof:1
%@test:2
%$ % Gamma density
%$ try
%$ m1 = compute_prior_mode([1 2],2);
%$ m2 = compute_prior_mode([9 0.5 1],2); % Wolfram Alpha: GammaDistribution[9,0.5]
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ % Check the results
%$ if t(1)
%$ t(2) = dassert(m1,0,1e-6);
%$ t(3) = dassert(m2,4+1,1e-6);
%$ end
%$ T = all(t);
%@eof:2
%@test:3
%$ % Normal density
%$ try
%$ m1 = compute_prior_mode([1 1],3);
%$ m2 = compute_prior_mode([2 5],3);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ % Check the results
%$ if t(1)
%$ t(2) = dassert(m1,1,1e-6);
%$ t(3) = dassert(m2,2,1e-6);
%$ end
%$ T = all(t);
%@eof:3
%@test:4
%$ % Inverse Gamma I density
%$ try
%$ m1 = compute_prior_mode([8 2],4);
%$ m2 = compute_prior_mode([8 2 1],4);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ % Check the results
%$ if t(1)
%$ t(2) = dassert(m1,1.632993161855452,1e-6);
%$ t(3) = dassert(m2,1.632993161855452+1,1e-6);
%$ end
%$ T = all(t);
%@eof:4
%@test:5
%$ % Uniform density
%$ try
%$ m1 = compute_prior_mode([0.5 1/sqrt(12)],5);
%$ m2 = compute_prior_mode([2 5 1 2],5);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ % Check the results
%$ if t(1)
%$ t(2) = dassert(m1,0.5,1e-6);
%$ t(3) = dassert(m2,2,1e-6);
%$ end
%$ T = all(t);
%@eof:5
%@test:6
%$ % Inverse Gamma II density, parameterized with s and nu where s=2*beta and nu=2*alpha
%$ try
%$ m1 = compute_prior_mode([8 2],6); % Wolfram Alpha, parameterized with alpha beta: InversegammaDistribution[1,4]
%$ m2 = compute_prior_mode([8 4 1],6); % Wolfram Alpha, parameterized with alpha beta: InversegammaDistribution[2,4]
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ % Check the results
%$ if t(1)
%$ t(2) = dassert(m1,2,1e-6);
%$ t(3) = dassert(m2,1+4/3,1e-6);
%$ end
%$ T = all(t);
%@eof:6
%@test:7
%$ % Weibull density
%$ try
%$ m1 = compute_prior_mode([1 1],8);
%$ m2 = compute_prior_mode([2 1 1],8); % Wolfram Alpha: WeibullDistribution[2,1]
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ % Check the results
%$ if t(1)
%$ t(2) = dassert(m1,0,1e-6);
%$ t(3) = dassert(m2,1+1/sqrt(2),1e-6);
%$ end
%$ T = all(t);
%@eof:7
%@test:8
%$ % Unknown density
%$ try
%$ m1 = compute_prior_mode([1 1],7);
%$ t(1) = false;
%$ catch
%$ t(1) = true;
%$ end
%$
%$ T = all(t);
%@eof:8

View File

@ -0,0 +1,106 @@
function [a, b] = gamma_specification(mu, sigma2, lb, name) % --*-- Unitary tests --*--
% Returns the hyperparameters of the gamma distribution given the expectation and variance.
%
% INPUTS
% - mu [double] Expectation of the Gamma random variable.
% - sigma2 [double] Variance of the Gamma random variable.
% - lb [double] Lower bound of the domain (default is zero).
% - name [string] Name of the parameter (or random variable).
%
% OUTPUTS
% - a [double] First hyperparameter of the Gamma density (shape).
% - b [double] Second hyperparameter of the Gamma density (scale).
% Copyright (C) 2015-2016 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<3
lb = 0;
end
if nargin>3 && ~isempty(name)
name1 = sprintf('for %s ', name);
name2 = sprintf(' (for %s)', name);
else
name1 = '';
name2 = '';
end
if mu<lb
error('The prior expectation (%f) %scannot be smaller than the lower bound of the Gamma distribution (%f)!', mu, name1, lb)
end
if isinf(sigma2)
error('The variance of the Gamma distribution has to be finite%s!', name2)
end
mu = mu-lb;
b = sigma2/mu;
a = mu/b;
%@test:1
%$ try
%$ [a, b] = gamma_specification(.5, 1);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(0.5-a*b)<1e-12;
%$ t(3) = abs(1.0-a*b*b)<1e-12;
%$ end
%$ T = all(t);
%@eof:1
%@test:2
%$ try
%$ [a, b] = gamma_specification(2, 1);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(2.0-a*b)<1e-12;
%$ t(3) = abs(1.0-a*b*b)<1e-12;
%$ end
%$ T = all(t);
%@eof:2
%@test:3
%$ try
%$ [a, b] = gamma_specification(2, 1, 3);
%$ t(1) = false;
%$ catch
%$ t(1) = true;
%$ end
%$
%$ T = all(t);
%@eof:3
%@test:4
%$ try
%$ [a, b] = gamma_specification(2, Inf, 3);
%$ t(1) = false;
%$ catch
%$ t(1) = true;
%$ end
%$
%$ T = all(t);
%@eof:4

View File

@ -1,50 +1,25 @@
function [s,nu] = inverse_gamma_specification(mu,sigma,type,use_fzero_flag) function [s,nu] = inverse_gamma_specification(mu, sigma2, lb, type, use_fzero_flag, name) % --*-- Unitary tests --*--
% Computes the inverse Gamma hyperparameters from the prior mean and standard deviation. % Computes the inverse Gamma hyperparameters from the prior mean and standard deviation.
%
% INPUTS
% - mu [double] scalar, prior mean.
% - sigma2 [double] positive scalar, prior variance.
% - type [integer] scalar equal to 1 or 2, type of the inverse gamma distribution
% - use_fzero_flag [logical] scalar, Use (matlab/octave's implementation of) fzero to solve for nu if true, use
% dynare's implementation of the secant method otherwise.
% - name [string] name of the parameter or random variable.
%
% OUTPUS
% - s [double] scalar, first hyperparameter.
% - nu [double] scalar, second hyperparameter.
%
% REMARK
% The call to the matlab's implementation of the secant method is here for testing purpose and should not be used. This routine fails
% more often in finding an interval for nu containing a signe change because it expands the interval on both sides and eventually
% violates the condition nu>2.
%@info: % Copyright (C) 2003-2015 Dynare Team
%! @deftypefn {Function File} {[@var{s}, @var{nu} ]=} colon (@var{mu}, @var{sigma}, @var{type}, @var{use_fzero_flag})
%! @anchor{distributions/inverse_gamma_specification}
%! @sp 1
%! Computes the inverse Gamma (type 1 or 2) hyperparameters from the prior mean (@var{mu}) and standard deviation (@var{sigma}).
%! @sp 2
%! @strong{Inputs}
%! @sp 1
%! @table @ @var
%! @item mu
%! Double scalar, prior mean.
%! @item sigma
%! Positive double scalar, prior standard deviation.
%! @item type
%! Integer scalar equal to one or two, type of the Inverse-Gamma distribution.
%! @item use_fzero_flag
%! Integer scalar equal to 0 (default) or 1. Use (matlab/octave's implementation of) fzero to solve for @var{nu} if equal to 1, use
%! dynare's implementation of the secant method otherwise.
%! @end table
%! @sp 1
%! @strong{Outputs}
%! @sp 1
%! @table @ @var
%! @item s
%! Positive double scalar (greater than two), first hypermarameter of the Inverse-Gamma prior.
%! @item nu
%! Positive double scala, second hypermarameter of the Inverse-Gamma prior.
%! @end table
%! @sp 2
%! @strong{This function is called by:}
%! @sp 1
%! @ref{set_prior}
%! @sp 2
%! @strong{This function calls:}
%! @sp 2
%! @strong{Remark:}
%! The call to the matlab's implementation of the secant method is here for testing purpose and should not be used. This routine fails
%! more often in finding an interval for nu containing a signe change because it expands the interval on both sides and eventually
%! violates the condition nu>2.
%!
%! @end deftypefn
%@eod:
% Copyright (C) 2003-2012 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -61,16 +36,54 @@ function [s,nu] = inverse_gamma_specification(mu,sigma,type,use_fzero_flag)
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
check_solution_flag = 1; if nargin<4
error('At least four input arguments are required!')
end
if ~isnumeric(mu) || ~isscalar(mu) || ~isreal(mu)
error('First input argument must be a real scalar!')
end
if ~isnumeric(sigma2) || ~isscalar(sigma2) || ~isreal(sigma2) || sigma2<=0
error('Second input argument must be a real positive scalar!')
end
if ~isnumeric(lb) || ~isscalar(lb) || ~isreal(lb)
error('Third input argument must be a real scalar!')
end
if ~isnumeric(type) || ~isscalar(type) || ~ismember(type, [1, 2])
error('Fourth input argument must be equal to 1 or 2!')
end
if nargin==4 || isempty(use_fzero_flag)
use_fzero_flag = false;
else
if ~isscalar(use_fzero_flag) || ~islogical(use_fzero_flag)
error('Fourth input argument must be a scalar logical!')
end
end
if nargin>5 && (~ischar(name) || size(name, 1)>1)
error('Sixth input argument must be a string!')
else
name = '';
end
if ~isempty(name)
name = sprintf(' for %s', name);
end
if mu<=lb
error('The prior mean%s (%f) must be above the lower bound (%f)of the Inverse Gamma (type %d) prior distribution!', mu, lb, name, type);
end
check_solution_flag = true;
s = []; s = [];
nu = []; nu = [];
if nargin==3 sigma = sqrt(sigma2);
use_fzero_flag = 0; mu2 = mu*mu;
end
sigma2 = sigma^2;
mu2 = mu^2;
if type == 2; % Inverse Gamma 2 if type == 2; % Inverse Gamma 2
nu = 2*(2+mu2/sigma2); nu = 2*(2+mu2/sigma2);
@ -120,7 +133,7 @@ elseif type == 1; % Inverse Gamma 1
if abs(log(mu)-log(sqrt(s/2))-gammaln((nu-1)/2)+gammaln(nu/2))>1e-7 if abs(log(mu)-log(sqrt(s/2))-gammaln((nu-1)/2)+gammaln(nu/2))>1e-7
error('inverse_gamma_specification:: Failed in solving for the hyperparameters!'); error('inverse_gamma_specification:: Failed in solving for the hyperparameters!');
end end
if abs(sigma-sqrt(s/(nu-2)-mu^2))>1e-7 if abs(sigma-sqrt(s/(nu-2)-mu*mu))>1e-7
error('inverse_gamma_specification:: Failed in solving for the hyperparameters!'); error('inverse_gamma_specification:: Failed in solving for the hyperparameters!');
end end
end end
@ -133,17 +146,61 @@ else
end end
%@test:1 %@test:1
%$ try
%$ [s, nu] = inverse_gamma_specification(.5, .05, 0, 1);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$ %$
%$ [s0,nu0] = inverse_gamma_specification(.75,.2,1,0); %$ if t(1)
%$ [s1,nu1] = inverse_gamma_specification(.75,.2,1,1); %$ t(2) = abs(0.5-sqrt(.5*s)*gamma(.5*(nu-1))/gamma(.5*nu))<1e-12;
%$ [s3,nu3] = inverse_gamma_specification(.75,.1,1,0); %$ t(3) = abs(0.05-s/(nu-2)+.5^2)<1e-12;
%$ [s4,nu4] = inverse_gamma_specification(.75,.1,1,1); %$ end
%$ % Check the results.
%$ t(1) = dassert(s0,s1,1e-6);
%$ t(2) = dassert(nu0,nu1,1e-6);
%$ t(3) = isnan(s4);
%$ t(4) = isnan(nu4);
%$ t(5) = dassert(s3,16.240907971002265,1e-6);;
%$ t(6) = dassert(nu3,30.368398202624046,1e-6);;
%$ T = all(t); %$ T = all(t);
%@eof:1 %@eof:1
%@test:2
%$ try
%$ [s, nu] = inverse_gamma_specification(.5, .05, 0, 2);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(0.5-s/(nu-2))<1e-12;
%$ t(3) = abs(0.05-2*.5^2/(nu-4))<1e-12;
%$ end
%$ T = all(t);
%@eof:2
%@test:3
%$ try
%$ [s, nu] = inverse_gamma_specification(.5, Inf, 0, 1);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(0.5-sqrt(.5*s)*gamma(.5*(nu-1))/gamma(.5*nu))<1e-12;
%$ t(3) = isequal(nu, 2); %abs(0.05-2*.5^2/(nu-4))<1e-12;
%$ end
%$ T = all(t);
%@eof:3
%@test:4
%$ try
%$ [s, nu] = inverse_gamma_specification(.5, Inf, 0, 2);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(0.5-s/(nu-2))<1e-12;
%$ t(3) = isequal(nu, 4);
%$ end
%$ T = all(t);
%@eof:4

View File

@ -0,0 +1,431 @@
function [ldens,Dldens,D2ldens] = lpdfgweibull(x,a,b,c) % --*-- Unitary tests --*--
% Evaluates the logged Weibull PDF at x.
%
% INPUTS
% - x [double] m*n matrix of points where the (logged) density will be evaluated,
% - a [double] m*n matrix of First Weibull distribution parameters (shape parameter, k),
% - b [double] m*n matrix of Second Weibull distribution parameters (scale parameter, λ),
% - c [double] m*n matrix of Third Weibull distribution parameters (location parameter, default is 0).
%
% OUTPUTS
% - ldens [double] m*n matrix of logged (generalized) Weibull densities.
% - Dldens [double] m*n matrix (first order derivatives w.r.t. x)
% - D2ldens [double] m*n matrix (second order derivatives w.r.t. x)
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2015-2016 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 output arguments
ldens = -Inf(size(x));
if nargout>1
Dldens = NaN(size(x));
D2ldens = NaN(size(x));
end
% Check the number of input arguments
if nargin<3
error('CheckInputArgs','At least three input arguments required!')
end
% Set default value for location parameter(s).
if nargin<4
c = zeros(size(x));
end
% Reshape inputs if needed (and possible)
if ~isscalar(x)
if isscalar(a)
a = repmat(a, size(x));
end
if isscalar(b)
b = repmat(b, size(x));
end
if isscalar(c)
c = repmat(c, size(x));
end
end
% Get indices for which the densty is defined
idx = find((x-c)>=0);
% Check size of the inputs
if (~isequal(size(x), size(a)) || ~isequal(size(x), size(b)) || ~isequal(size(x), size(c)))
error('CheckInputArgs','All input arguments must have the same dimensions!')
end
if isempty(idx), return, end
% Compute the logged density
jdx = find( abs(a-1)<1e-12 & x>=c & (x-c)<1e-12) ;
ldens(jdx) = 1.0;
if ~isempty(idx)
x0 = x(idx)-c(idx);
x1 = x0./b(idx);
x2 = x1.^a(idx);
idx = setdiff(idx, jdx);
ldens(idx) = log(a(idx)) - a(idx).*log(b(idx)) + (a(idx)-1).*log(x0) - x2 ;
end
% Compute the first and second derivatives.
if nargout>1
x3 = (a(idx)-1)./x0;
x4 = a(idx).*x2./x1./b(idx);
Dldens(idx) = x3 - x4;
if nargout>2
D2ldens(idx) = -x3./x0 - (a(idx)-1).*x4./x1./b(idx);
end
end
%@test:1
%$ try
%$ lpdfgweibull(1.0);
%$ t(1) = false;
%$ catch
%$ t(1) = true;
%$ end
%$
%$ T = all(t);
%@eof:1
%@test:2
%$ try
%$ lpdfgweibull(1.0, .5);
%$ t(1) = false;
%$ catch
%$ t(1) = true;
%$ end
%$
%$ T = all(t);
%@eof:2
%@test:3
%$ try
%$ lpdfgweibull(ones(2,2), .5*ones(2,1), .1*ones(3,1));
%$ t(1) = false;
%$ catch
%$ t(1) = true;
%$ end
%$
%$ T = all(t);
%@eof:3
%@test:4
%$ try
%$ a = lpdfgweibull(-1, .5, .1);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = isinf(a);
%$ end
%$
%$ T = all(t);
%@eof:4
%@test:5
%$ try
%$ a = lpdfgweibull(0, 1, 1);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(a-1.0)<1e-10;
%$ end
%$
%$ T = all(t);
%@eof:5
%@test:6
%$ try
%$ a = lpdfgweibull([0, -1], [1 1], [1 1]);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(a(1)-1.0)<1e-10;
%$ t(3) = isinf(a(2));
%$ end
%$
%$ T = all(t);
%@eof:6
%@test:7
%$ scale = 1;
%$ shape = 2;
%$ mode = scale*((shape-1)/shape)^(1/shape);
%$
%$ try
%$ [a, b, c] = lpdfgweibull(mode, shape, scale);
%$ p = rand(1000,1)*4;
%$ am = lpdfgweibull(p, shape*ones(size(p)), scale*ones(size(p)));
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$
%$ t(2) = abs(b)<1e-8;
%$ t(3) = c<0;
%$ t(4) = all(am<a);
%$ end
%$
%$ T = all(t);
%@eof:7
%@test:8
%$ scale = 1;
%$ shape = 2;
%$ density = @(x) exp(lpdfgweibull(x,shape,scale));
%$
%$ try
%$ if isoctave
%$ s = quadv(density, .0000000001, 100000);
%$ else
%$ s = integral(density, 0, 100000);
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(s-1)<1e-6;
%$ end
%$
%$ T = all(t);
%@eof:8
%@test:9
%$ scale = 1;
%$ shape = 1;
%$ density = @(x) exp(lpdfgweibull(x,shape,scale));
%$
%$ try
%$ if isoctave
%$ s = quadv(density, .0000000001, 100000);
%$ else
%$ s = integral(density, 0, 100000);
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(s-1)<1e-6;
%$ end
%$
%$ T = all(t);
%@eof:9
%@test:10
%$ scale = 1;
%$ shape = .5;
%$ density = @(x) exp(lpdfgweibull(x,shape,scale));
%$
%$ try
%$ if isoctave
%$ s = quadv(density, .0000000001, 100000);
%$ else
%$ s = integral(density, 0, 100000);
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(s-1)<1e-6;
%$ end
%$
%$ T = all(t);
%@eof:10
%@test:11
%$ scale = 1;
%$ shape = 2;
%$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale));
%$
%$ try
%$ if isoctave
%$ s = quadv(xdens, .0000000001, 100000);
%$ else
%$ s = integral(xdens, 0, 100000);
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(s-scale*gamma(1+1/shape))<1e-6;
%$ end
%$
%$ T = all(t);
%@eof:11
%@test:12
%$ scale = 1;
%$ shape = 1;
%$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale));
%$
%$ try
%$ if isoctave
%$ s = quadv(xdens, .0000000001, 100000);
%$ else
%$ s = integral(xdens, 0, 100000);
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(s-scale*gamma(1+1/shape))<1e-6;
%$ end
%$
%$ T = all(t);
%@eof:12
%@test:13
%$ scale = 1;
%$ shape = .5;
%$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale));
%$
%$ try
%$ if isoctave
%$ s = quadv(xdens, .0000000001, 100000);
%$ else
%$ s = integral(xdens, 0, 100000);
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = abs(s-scale*gamma(1+1/shape))<1e-6;
%$ end
%$
%$ T = all(t);
%@eof:13
%@test:14
%$ scale = 1;
%$ shape = 2;
%$ density = @(x) exp(lpdfgweibull(x,shape,scale));
%$ n = 200;
%$
%$ try
%$ s = NaN(n, 1);
%$ for i=1:n
%$ if isoctave()
%$ s(i) = quadv(density, .0000000001, .1*i);
%$ else
%$ s(i) = integral(density, 0, .1*i);
%$ end
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ for i=1:n
%$ x = .1*i;
%$ q = 1-exp(-(x/scale)^shape);
%$ t(i+1) = abs(s(i)-q)<1e-6;
%$ end
%$ end
%$
%$ T = all(t);
%@eof:14
%@test:15
%$ scale = 1;
%$ shape = 1;
%$ density = @(x) exp(lpdfgweibull(x,shape,scale));
%$ n = 200;
%$
%$ try
%$ s = NaN(n, 1);
%$ for i=1:n
%$ if isoctave()
%$ s(i) = quadv(density, .0000000001, .1*i);
%$ else
%$ s(i) = integral(density, 0, .1*i);
%$ end
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ for i=1:n
%$ x = .1*i;
%$ q = 1-exp(-(x/scale)^shape);
%$ t(i+1) = abs(s(i)-q)<1e-6;
%$ end
%$ end
%$
%$ T = all(t);
%@eof:15
%@test:16
%$ scale = 1;
%$ shape = .5;
%$ density = @(x) exp(lpdfgweibull(x,shape,scale));
%$ n = 200;
%$
%$ try
%$ s = NaN(n, 1);
%$ for i=1:n
%$ if isoctave()
%$ s(i) = quadv(density, .0000000001, .1*i);
%$ else
%$ s(i) = integral(density, 0, .1*i);
%$ end
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ for i=1:n
%$ x = .1*i;
%$ q = 1-exp(-(x/scale)^shape);
%$ t(i+1) = abs(s(i)-q)<1e-6;
%$ end
%$ end
%$
%$ T = all(t);
%@eof:16

View File

@ -0,0 +1,143 @@
function [shape, scale] = weibull_specification(mu, sigma2, lb, name) % --*-- Unitary tests --*--
% Returns the hyperparameters of the Weibull distribution given the expectation and variance.
%
% INPUTS
%
%
% OUTPUTS
%
%
% Copyright (C) 2015-2016 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<3
lb = 0;
end
if nargin>3 && ~isempty(name)
name1 = sprintf('for %s ', name);
name2 = sprintf(' (for %s)', name);
else
name1 = '';
name2 = '';
end
if mu<lb
error('The prior expectation (%f) %scannot be smaller than the lower bound of the Weibull distribution (%f)!', mu, name1, lb)
end
if isinf(sigma2)
error('The variance of the Gamma distribution has to be finite%s!', name2)
end
scale = NaN;
shape = NaN;
mu = mu-lb;
mu2 = mu*mu;
eqn = @(k) gammaln(1+2./k) - 2*gammaln(1+1./k) - log(1+sigma2/mu2);
eqn2 = @(k) eqn(k).*eqn(k);
kstar = fminbnd(eqn2, 1e-9, 100);
[shape, fval, exitflag] = fzero(eqn, kstar);
if exitflag<1
shape = NaN;
return
end
scale = mu/gamma(1+1/shape);
%@test:1
%$ debug = false;
%$ scales = 1:.01:5;
%$ shapes = .5:.01:2;
%$ n_scales = length(scales);
%$ n_shapes = length(shapes);
%$ mu = NaN(n_scales, n_shapes);
%$ s2 = NaN(n_scales, n_shapes);
%$ for i=1:n_shapes
%$ g1 = gamma(1+1/shapes(i));
%$ g2 = gamma(1+2/shapes(i));
%$ g3 = g1*g1;
%$ for j=1:n_scales
%$ mu(j, i) = scales(j)*g1;
%$ s2(j, i) = scales(j)*scales(j)*(g2-g3);
%$ end
%$ end
%$ if debug
%$ success = [];
%$ failed1 = [];
%$ failed1_ = [];
%$ failed2 = [];
%$ end
%$ try
%$ for i=1:n_shapes
%$ for j=1:n_scales
%$ if debug
%$ disp(sprintf('... mu=%s and s2=%s', num2str(mu(j,i)),num2str(s2(j,i))))
%$ end
%$ if ~isnan(mu(j,i)) && ~isnan(s2(j,i)) && ~isinf(mu(j,i)) && ~isinf(s2(j,i))
%$ [shape, scale] = weibull_specification(mu(j,i), s2(j,i));
%$ if isnan(scale)
%$ t = false;
%$ else
%$ if abs(scales(j)-scale)<1e-9 && abs(shapes(i)-shape)<1e-9
%$ t = true;
%$ else
%$ t = false;
%$ end
%$ end
%$ if ~t && debug
%$ failed1 = [failed1; mu(j,i) s2(j,i)];
%$ failed1_ = [failed1_; shapes(i) scales(j)];
%$ error('UnitTest','Cannot compute scale and shape hyperparameters for mu=%s and s2=%s', num2str(mu(j,i)), num2str(s2(j,i)))
%$ end
%$ if debug
%$ success = [success; mu(j,i) s2(j,i)];
%$ end
%$ else
%$ failed2 = [failed2; shapes(i) scales(j)];
%$ continue % Pass this test
%$ end
%$ end
%$ end
%$ catch
%$ t = false;
%$ end
%$
%$ if debug
%$ figure(1)
%$ plot(success(:,1),success(:,2),'ok');
%$ if ~isempty(failed1)
%$ hold on
%$ plot(failed1(:,1),failed1(:,2),'or');
%$ hold off
%$ figure(2)
%$ plot(failed1_(:,1),failed1_(:,2),'or')
%$ end
%$ if ~isempty(failed2)
%$ figure(2)
%$ plot(failed2(:,1),failed2(:,2),'or');
%$ end
%$ end
%$ T = all(t);
%@eof:1

View File

@ -100,6 +100,12 @@ switch pshape(indx)
end end
abscissa = linspace(infbound,supbound,steps); abscissa = linspace(infbound,supbound,steps);
dens = exp(lpdfig2(abscissa-p3(indx),p6(indx),p7(indx))); dens = exp(lpdfig2(abscissa-p3(indx),p6(indx),p7(indx)));
case 8
density = @(x,a,b,c) exp(lpdfgweibull(x, a, b, c));
infbound = p3(indx)+wblinv(truncprior,p6(indx),p7(indx));
supbound = p3(indx)+wblinv(1-truncprior,p6(indx),p7(indx));
abscissa = linspace(infbound,supbound,steps);
dens = density(abscissa,p6(indx),p7(indx),p3(indx));
otherwise otherwise
error(sprintf('draw_prior_density: unknown distribution shape (index %d, type %d)', indx, pshape(indx))); error(sprintf('draw_prior_density: unknown distribution shape (index %d, type %d)', indx, pshape(indx)));
end end

View File

@ -210,7 +210,7 @@ H = Model.H;
% Test if Q is positive definite. % Test if Q is positive definite.
if ~issquare(Q) || EstimatedParameters.ncx || isfield(EstimatedParameters,'calibrated_covariances') if ~issquare(Q) || EstimatedParameters.ncx || isfield(EstimatedParameters,'calibrated_covariances')
[Q_is_positive_definite, penalty] = ispd(Q); [Q_is_positive_definite, penalty] = ispd(Q(EstimatedParameters.Sigma_e_entries_to_check_for_positive_definiteness,EstimatedParameters.Sigma_e_entries_to_check_for_positive_definiteness));
if ~Q_is_positive_definite if ~Q_is_positive_definite
fval = objective_function_penalty_base+penalty; fval = objective_function_penalty_base+penalty;
exit_flag = 0; exit_flag = 0;
@ -231,7 +231,7 @@ end
% Test if H is positive definite. % Test if H is positive definite.
if ~issquare(H) || EstimatedParameters.ncn || isfield(EstimatedParameters,'calibrated_covariances_ME') if ~issquare(H) || EstimatedParameters.ncn || isfield(EstimatedParameters,'calibrated_covariances_ME')
[H_is_positive_definite, penalty] = ispd(H); [H_is_positive_definite, penalty] = ispd(H(EstimatedParameters.H_entries_to_check_for_positive_definiteness,EstimatedParameters.H_entries_to_check_for_positive_definiteness));
if ~H_is_positive_definite if ~H_is_positive_definite
fval = objective_function_penalty_base+penalty; fval = objective_function_penalty_base+penalty;
exit_flag = 0; exit_flag = 0;
@ -307,14 +307,8 @@ end
% Define the deterministic linear trend of the measurement equation. % Define the deterministic linear trend of the measurement equation.
if BayesInfo.with_trend if BayesInfo.with_trend
trend_coeff = zeros(DynareDataset.vobs,1); [trend_addition, trend_coeff]=compute_trend_coefficients(Model,DynareOptions,DynareDataset.vobs,DynareDataset.nobs);
t = DynareOptions.trend_coeffs; trend = repmat(constant,1,DynareDataset.nobs)+trend_addition;
for i=1:length(t)
if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i});
end
end
trend = repmat(constant,1,DynareDataset.nobs)+trend_coeff*[1:DynareDataset.nobs];
else else
trend_coeff = zeros(DynareDataset.vobs,1); trend_coeff = zeros(DynareDataset.vobs,1);
trend = repmat(constant,1,DynareDataset.nobs); trend = repmat(constant,1,DynareDataset.nobs);
@ -654,30 +648,38 @@ end
% 4. Likelihood evaluation % 4. Likelihood evaluation
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------
singularity_has_been_detected = false;
if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter
if no_missing_data_flag if no_missing_data_flag
if DynareOptions.block if DynareOptions.block
[err, LIK] = block_kalman_filter(T,R,Q,H,Pstar,Y,start,Z,kalman_tol,riccati_tol, Model.nz_state_var, Model.n_diag, Model.nobs_non_statevar); [err, LIK] = block_kalman_filter(T,R,Q,H,Pstar,Y,start,Z,kalman_tol,riccati_tol, Model.nz_state_var, Model.n_diag, Model.nobs_non_statevar);
mexErrCheck('block_kalman_filter', err); mexErrCheck('block_kalman_filter', err);
elseif DynareOptions.fast_kalman_filter
[LIK,lik] = kalman_filter_fast(Y,diffuse_periods+1,size(Y,2), ...
a,Pstar, ...
kalman_tol, riccati_tol, ...
DynareOptions.presample, ...
T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods, ...
analytic_deriv_info{:});
else else
[LIK,lik] = kalman_filter(Y,diffuse_periods+1,size(Y,2), ... [LIK,lik] = kalman_filter(Y,diffuse_periods+1,size(Y,2), ...
a,Pstar, ... a,Pstar, ...
kalman_tol, riccati_tol, ... kalman_tol, riccati_tol, ...
DynareOptions.presample, ... DynareOptions.presample, ...
T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods, ... T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods, ...
analytic_deriv_info{:}); analytic_deriv_info{:});
end end
else else
if 0 %DynareOptions.block if 0 %DynareOptions.block
[err, LIK,lik] = block_kalman_filter(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations,... [err, LIK,lik] = block_kalman_filter(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations,...
T,R,Q,H,Pstar,Y,start,Z,kalman_tol,riccati_tol, Model.nz_state_var, Model.n_diag, Model.nobs_non_statevar); T,R,Q,H,Pstar,Y,start,Z,kalman_tol,riccati_tol, Model.nz_state_var, Model.n_diag, Model.nobs_non_statevar);
else else
[LIK,lik] = missing_observations_kalman_filter(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations,Y,diffuse_periods+1,size(Y,2), ... [LIK,lik] = missing_observations_kalman_filter(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations,Y,diffuse_periods+1,size(Y,2), ...
a, Pstar, ... a, Pstar, ...
kalman_tol, DynareOptions.riccati_tol, ... kalman_tol, DynareOptions.riccati_tol, ...
DynareOptions.presample, ... DynareOptions.presample, ...
T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods); T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods);
end end
end end
if analytic_derivation, if analytic_derivation,
@ -688,6 +690,7 @@ if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter
end end
if isinf(LIK) if isinf(LIK)
if DynareOptions.use_univariate_filters_if_singularity_is_detected if DynareOptions.use_univariate_filters_if_singularity_is_detected
singularity_has_been_detected = true;
if kalman_algo == 1 if kalman_algo == 1
kalman_algo = 2; kalman_algo = 2;
else else
@ -745,19 +748,21 @@ if (kalman_algo==2) || (kalman_algo==4)
Pinf = blkdiag(Pinf,zeros(pp)); Pinf = blkdiag(Pinf,zeros(pp));
H1 = zeros(pp,1); H1 = zeros(pp,1);
mmm = mm+pp; mmm = mm+pp;
if singularity_has_been_detected
a = zeros(mmm,1);
end
end end
end end
if analytic_derivation, if analytic_derivation,
analytic_deriv_info{5}=DH; analytic_deriv_info{5}=DH;
end end
end end
[LIK, lik] = univariate_kalman_filter(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations,Y,diffuse_periods+1,size(Y,2), ... [LIK, lik] = univariate_kalman_filter(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations,Y,diffuse_periods+1,size(Y,2), ...
a,Pstar, ... a,Pstar, ...
DynareOptions.kalman_tol, ... DynareOptions.kalman_tol, ...
DynareOptions.riccati_tol, ... DynareOptions.riccati_tol, ...
DynareOptions.presample, ... DynareOptions.presample, ...
T,Q,R,H1,Z,mmm,pp,rr,Zflag,diffuse_periods,analytic_deriv_info{:}); T,Q,R,H1,Z,mmm,pp,rr,Zflag,diffuse_periods,analytic_deriv_info{:});
if analytic_derivation, if analytic_derivation,
LIK1=LIK; LIK1=LIK;
LIK=LIK1{1}; LIK=LIK1{1};
@ -783,11 +788,11 @@ if analytic_derivation
% Hess0 = getHessian(Y,T,DT,D2T, R*Q*transpose(R),DOm,D2Om,Z,DYss,D2Yss); % Hess0 = getHessian(Y,T,DT,D2T, R*Q*transpose(R),DOm,D2Om,Z,DYss,D2Yss);
end end
if asy_Hess, if asy_Hess,
% if ~((kalman_algo==2) || (kalman_algo==4)), % if ~((kalman_algo==2) || (kalman_algo==4)),
% [Hess] = AHessian(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,start,Z,kalman_tol,riccati_tol); % [Hess] = AHessian(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,start,Z,kalman_tol,riccati_tol);
% else % else
Hess = LIK1{3}; Hess = LIK1{3};
% end % end
end end
end end

View File

@ -1,12 +1,17 @@
function info = dyn_forecast(var_list,task) function [forecast,info] = dyn_forecast(var_list,M,options,oo,task,dataset_info)
% function dyn_forecast(var_list,task) % function dyn_forecast(var_list,M,options,oo,task,dataset_info)
% computes mean forecast for a given value of the parameters % computes mean forecast for a given value of the parameters
% computes also confidence band for the forecast % compues also confidence band for the forecast
% %
% INPUTS % INPUTS
% var_list: list of variables (character matrix) % var_list: list of variables (character matrix)
% M: Dynare model structure
% options: Dynare options structure
% oo: Dynare results structure
% task: indicates how to initialize the forecast % task: indicates how to initialize the forecast
% either 'simul' or 'smoother' % either 'simul' or 'smoother'
% dataset_info: Various informations about the dataset (descriptive statistics and missing observations).
% OUTPUTS % OUTPUTS
% nothing is returned but the procedure saves output % nothing is returned but the procedure saves output
% in oo_.forecast.Mean % in oo_.forecast.Mean
@ -16,7 +21,7 @@ function info = dyn_forecast(var_list,task)
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2003-2015 Dynare Team % Copyright (C) 2003-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -33,17 +38,21 @@ function info = dyn_forecast(var_list,task)
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_ oo_ M_ if nargin<6 && options.prefilter
error('The prefiltering option is not allowed without providing a dataset')
elseif nargin==6
mean_varobs=dataset_info.descriptive.mean';
end
info = 0; info = 0;
make_ex_; oo=make_ex_(M,options,oo);
maximum_lag = M_.maximum_lag; maximum_lag = M.maximum_lag;
endo_names = M_.endo_names; endo_names = M.endo_names;
if isempty(var_list) if isempty(var_list)
var_list = endo_names(1:M_.orig_endo_nbr, :); var_list = endo_names(1:M.orig_endo_nbr, :);
end end
i_var = []; i_var = [];
for i = 1:size(var_list) for i = 1:size(var_list)
@ -59,82 +68,106 @@ n_var = length(i_var);
trend = 0; trend = 0;
switch task switch task
case 'simul' case 'simul'
horizon = options_.periods; horizon = options.periods;
if horizon == 0 if horizon == 0
horizon = 5; horizon = 5;
end end
if isempty(M_.endo_histval) if isempty(M.endo_histval)
y0 = repmat(oo_.dr.ys,1,maximum_lag); y0 = repmat(oo.dr.ys,1,maximum_lag);
else else
y0 = M_.endo_histval; y0 = M.endo_histval;
end end
case 'smoother' case 'smoother'
horizon = options_.forecast; horizon = options.forecast;
y_smoothed = oo_.SmoothedVariables; y_smoothed = oo.SmoothedVariables;
y0 = zeros(M_.endo_nbr,maximum_lag); y0 = zeros(M.endo_nbr,maximum_lag);
for i = 1:M_.endo_nbr for i = 1:M.endo_nbr
v_name = deblank(M_.endo_names(i,:)); v_name = deblank(M.endo_names(i,:));
y0(i,:) = y_smoothed.(v_name)(end-maximum_lag+1:end)+oo_.dr.ys(i); y0(i,:) = y_smoothed.(v_name)(end-maximum_lag+1:end); %includes steady state or mean, but simult_ will subtract only steady state
% 2. Subtract mean/steady state and add steady state; takes care of prefiltering
if isfield(oo.Smoother,'Constant') && isfield(oo.Smoother.Constant,v_name)
y0(i,:)=y0(i,:)-oo.Smoother.Constant.(v_name)(end-maximum_lag+1:end); %subtract mean or steady state
if options.loglinear
y0(i,:)=y0(i,:)+log(oo.dr.ys(strmatch(v_name,deblank(M.endo_names),'exact')));
else
y0(i,:)=y0(i,:)+oo.dr.ys(strmatch(v_name,deblank(M.endo_names),'exact'));
end
end
% 2. Subtract trend
if isfield(oo.Smoother,'Trend') && isfield(oo.Smoother.Trend,v_name)
y0(i,:)=y0(i,:)-oo.Smoother.Trend.(v_name)(end-maximum_lag+1:end); %subtract trend, which is not subtracted by simult_
end
end end
gend = options_.nobs; gend = options.nobs;
if isfield(oo_.Smoother,'TrendCoeffs') if isfield(oo.Smoother,'TrendCoeffs')
var_obs = options_.varobs; var_obs = options.varobs;
endo_names = M_.endo_names; endo_names = M.endo_names;
order_var = oo_.dr.order_var; order_var = oo.dr.order_var;
i_var_obs = []; i_var_obs = [];
trend_coeffs = []; trend_coeffs = [];
for i=1:length(var_obs) for i=1:length(var_obs)
tmp = strmatch(var_obs{i},endo_names(i_var,:),'exact'); tmp = strmatch(var_obs{i},endo_names(i_var,:),'exact');
if ~isempty(tmp) if ~isempty(tmp)
i_var_obs = [ i_var_obs; tmp]; i_var_obs = [ i_var_obs; tmp];
trend_coeffs = [trend_coeffs; oo_.Smoother.TrendCoeffs(i)]; trend_coeffs = [trend_coeffs; oo.Smoother.TrendCoeffs(i)];
end end
end end
if ~isempty(trend_coeffs) if ~isempty(trend_coeffs)
trend = trend_coeffs*(gend+(1-M_.maximum_lag:horizon)); trend = trend_coeffs*(options.first_obs+gend-1+(1-M.maximum_lag:horizon));
if options.prefilter
trend = trend - repmat(mean(trend_coeffs*[options.first_obs:options.first_obs+gend-1],2),1,horizon+1); %subtract mean trend
end
end end
end else
global bayestopt_ trend_coeffs=zeros(length(options.varobs),1);
if isfield(bayestopt_,'mean_varobs')
trend = trend + repmat(bayestopt_.mean_varobs,1,horizon+M_.maximum_lag);
end end
otherwise otherwise
error('Wrong flag value') error('Wrong flag value')
end end
if M_.exo_det_nbr == 0 if M.exo_det_nbr == 0
[yf,int_width] = forcst(oo_.dr,y0,horizon,var_list); [yf,int_width] = forcst(oo.dr,y0,horizon,var_list);
else else
exo_det_length = size(oo_.exo_det_simul,1)-M_.maximum_lag; exo_det_length = size(oo.exo_det_simul,1)-M.maximum_lag;
if horizon > exo_det_length if horizon > exo_det_length
ex = zeros(horizon,M_.exo_nbr); ex = zeros(horizon,M.exo_nbr);
oo_.exo_det_simul = [ oo_.exo_det_simul;... oo.exo_det_simul = [ oo.exo_det_simul;...
repmat(oo_.exo_det_steady_state',... repmat(oo.exo_det_steady_state',...
horizon- ... horizon- ...
exo_det_length,1)]; exo_det_length,1)];
elseif horizon < exo_det_length elseif horizon < exo_det_length
ex = zeros(exo_det_length,M_.exo_nbr); ex = zeros(exo_det_length,M.exo_nbr);
end end
[yf,int_width] = simultxdet(y0,ex,oo_.exo_det_simul,... [yf,int_width] = simultxdet(y0,ex,oo.exo_det_simul,...
options_.order,var_list,M_,oo_,options_); options.order,var_list,M,oo,options);
end end
if ~isscalar(trend) if ~isscalar(trend) %add trend back to forecast
yf(i_var_obs,:) = yf(i_var_obs,:) + trend; yf(i_var_obs,:) = yf(i_var_obs,:) + trend;
end end
if options.loglinear == 1
if options.prefilter == 1 %subtract steady state and add mean for observables
yf(i_var_obs,:)=yf(i_var_obs,:)-repmat(log(oo.dr.ys(i_var_obs)),1,horizon+M.maximum_lag)+ repmat(mean_varobs,1,horizon+M.maximum_lag);
end
else
if options.prefilter == 1 %subtract steady state and add mean for observables
yf(i_var_obs,:)=yf(i_var_obs,:)-repmat(oo.dr.ys(i_var_obs),1,horizon+M.maximum_lag)+ repmat(mean_varobs,1,horizon+M.maximum_lag);
end
end
for i=1:n_var for i=1:n_var
eval(['oo_.forecast.Mean.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+(1:horizon))'';']); vname = deblank(var_list(i,:));
eval(['oo_.forecast.HPDinf.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+(1:horizon))''-' ... forecast.Mean.(vname) = yf(i,maximum_lag+(1:horizon))';
' int_width(1:horizon,' int2str(i) ');']); forecast.HPDinf.(vname)= yf(i,maximum_lag+(1:horizon))' - int_width(1:horizon,i);
eval(['oo_.forecast.HPDsup.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+(1:horizon))''+' ... forecast.HPDsup.(vname) = yf(i,maximum_lag+(1:horizon))' + int_width(1:horizon,i);
' int_width(1:horizon,' int2str(i) ');']);
end end
for i=1:M_.exo_det_nbr for i=1:M.exo_det_nbr
eval(['oo_.forecast.Exogenous.' M_.exo_det_names(i,:) '= oo_.exo_det_simul(maximum_lag+(1:horizon),' int2str(i) ');']); forecast.Exogenous.(deblank(M.exo_det_names(i,:))) = oo.exo_det_simul(maximum_lag+(1:horizon),i);
end end
if options_.nograph == 0 if options.nograph == 0
forecast_graphs(var_list,M_, oo_,options_) oo.forecast = forecast;
forecast_graphs(var_list,M, oo,options)
end end

View File

@ -1,11 +1,11 @@
function dyn_latex_table(M_,title,LaTeXtitle,headers,labels,values,label_width,val_width,val_precis) function dyn_latex_table(M_,title,LaTeXtitle,headers,labels,values,label_width,val_width,val_precis,optional_header)
OutputDirectoryName = CheckPath('Output',M_.dname); OutputDirectoryName = CheckPath('Output',M_.dname);
%% get width of label column %% get width of label column
if ~isempty(label_width) if ~isempty(label_width)
label_width = max(size(deblank(char(headers(1,:),labels)),2)+2, ... label_width = max(size(deblank(char(headers(1,:),labels)),2)+2, ...
label_width); label_width);
else %use default length else %use default length
label_width = max(size(deblank(char(headers(1,:),labels)),2))+2; label_width = max(size(deblank(char(headers(1,:),labels)),2))+2;
end end
@ -21,7 +21,7 @@ if any(values) < 0 %add one character for minus sign
values_length = values_length+1; values_length = values_length+1;
end end
%% get width of header strings %% get width of header strings
headers_length = max(size(deblank(headers(2:end,:)),2)); headers_length = max(size(deblank(headers(2:end,:)),2));
if ~isempty(val_width) if ~isempty(val_width)
val_width = max(max(headers_length,values_length)+4,val_width); val_width = max(max(headers_length,values_length)+4,val_width);
@ -34,7 +34,7 @@ header_string_format = sprintf('$%%%ds$',val_width);
%Create and print header string %Create and print header string
if length(headers) > 0 if length(headers) > 0
header_string = sprintf(label_format_leftbound ,deblank(headers(1,:))); header_string = sprintf(label_format_leftbound ,deblank(headers(1,:)));
header_code_string='l|'; header_code_string='l';
for i=2:size(headers,1) for i=2:size(headers,1)
header_string = [header_string '\t & \t ' sprintf(header_string_format,strrep(deblank(headers(i,:)),'\','\\'))]; header_string = [header_string '\t & \t ' sprintf(header_string_format,strrep(deblank(headers(i,:)),'\','\\'))];
header_code_string= [header_code_string 'c']; header_code_string= [header_code_string 'c'];
@ -49,25 +49,35 @@ fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n'); fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n'); fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,['\\begin{longtable}{%s} \n'],header_code_string); fprintf(fidTeX,['\\begin{longtable}{%s} \n'],header_code_string);
fprintf(fidTeX,['\\caption{',title,'}\\\\\n ']); fprintf(fidTeX,['\\caption{',title,'}\\\\\n ']);
fprintf(fidTeX,['\\label{Table:',LaTeXtitle,'}\\\\\n']); fprintf(fidTeX,['\\label{Table:',LaTeXtitle,'}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n'); fprintf(fidTeX,'\\toprule \n');
if nargin==10
for ii=1:size(optional_header,1)
fprintf(fidTeX,'%s\n',optional_header{ii});
end
end
fprintf(fidTeX,header_string); fprintf(fidTeX,header_string);
fprintf(fidTeX,'\\hline \\endfirsthead \n'); fprintf(fidTeX,'\\midrule \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n '); fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,'\\hline\\hline \\\\ \n'); fprintf(fidTeX,'\\toprule \\\\ \n');
if nargin==10
for ii=1:size(optional_header,1)
fprintf(fidTeX,'%s\n',optional_header{ii});
end
end
fprintf(fidTeX,header_string); fprintf(fidTeX,header_string);
fprintf(fidTeX,'\\hline \\endhead \n'); fprintf(fidTeX,'\\midrule \\endhead \n');
fprintf(fidTeX,['\\hline \\multicolumn{',num2str(size(headers,1)),'}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n']); fprintf(fidTeX,['\\bottomrule \\multicolumn{',num2str(size(headers,1)),'}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n']);
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n'); fprintf(fidTeX,'\\bottomrule \\endlastfoot \n');
for i=1:size(values,1) for i=1:size(values,1)
fprintf(fidTeX,label_format_leftbound,deblank(labels(i,:))); fprintf(fidTeX,label_format_leftbound,deblank(labels(i,:)));
fprintf(fidTeX,['\t & \t' value_format],values(i,:)); fprintf(fidTeX,['\t & \t' value_format],values(i,:));
fprintf(fidTeX,' \\\\ \n'); fprintf(fidTeX,' \\\\ \n');
end end
fprintf(fidTeX,'\\end{longtable}\n '); fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n'); fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n'); fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX); fclose(fidTeX);

View File

@ -15,7 +15,7 @@ function dynareroot = dynare_config(path_to_dynare,verbose)
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2001-2015 Dynare Team % Copyright (C) 2001-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -100,12 +100,6 @@ if isoctave && ~user_has_octave_forge_package('nan')
addpath([dynareroot '/missing/corrcoef']) addpath([dynareroot '/missing/corrcoef'])
end end
% strjoin is missing in older versions of MATLAB and in Octave < 3.8
if (isoctave && octave_ver_less_than('3.8')) || ...
(~isoctave && matlab_ver_less_than('8.1'))
addpath([dynareroot '/missing/strjoin'])
end
% nanmean is in Octave Forge Statistics package and in MATLAB Statistics % nanmean is in Octave Forge Statistics package and in MATLAB Statistics
% toolbox % toolbox
if (isoctave && ~user_has_octave_forge_package('statistics')) ... if (isoctave && ~user_has_octave_forge_package('statistics')) ...

View File

@ -73,6 +73,7 @@ end
if options_.logged_steady_state if options_.logged_steady_state
oo_.dr.ys=exp(oo_.dr.ys); oo_.dr.ys=exp(oo_.dr.ys);
oo_.steady_state=exp(oo_.steady_state); oo_.steady_state=exp(oo_.steady_state);
options_.logged_steady_state=0;
end end

View File

@ -130,7 +130,7 @@ ncn = estim_params_.ncn; % Covariance of the measurement innovations (number of
np = estim_params_.np ; % Number of deep parameters. np = estim_params_.np ; % Number of deep parameters.
nx = nvx+nvn+ncx+ncn+np; % Total number of parameters to be estimated. nx = nvx+nvn+ncx+ncn+np; % Total number of parameters to be estimated.
%% Set the names of the priors. %% Set the names of the priors.
pnames = [' ';'beta ';'gamm ';'norm ';'invg ';'unif ';'invg2']; pnames = [' '; 'beta '; 'gamm '; 'norm '; 'invg '; 'unif '; 'invg2'; ' '; 'weibl'];
dr = oo_.dr; dr = oo_.dr;
@ -170,43 +170,27 @@ end
if isequal(options_.mode_compute,0) && isempty(options_.mode_file) && options_.mh_posterior_mode_estimation==0 if isequal(options_.mode_compute,0) && isempty(options_.mode_file) && options_.mh_posterior_mode_estimation==0
if options_.smoother == 1 if options_.smoother == 1
[atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp] = DsgeSmoother(xparam1,gend,transpose(data),data_index,missing_value); [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp,Trend] = DsgeSmoother(xparam1,gend,transpose(data),data_index,missing_value);
oo_.Smoother.SteadyState = ys; [oo_]=write_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend);
oo_.Smoother.TrendCoeffs = trend_coeff;
if options_.filter_covariance
oo_.Smoother.Variance = P;
end
i_endo = bayestopt_.smoother_saved_var_list;
if options_.nk ~= 0
oo_.FilteredVariablesKStepAhead = ...
aK(options_.filter_step_ahead,i_endo,:);
if ~isempty(PK)
oo_.FilteredVariablesKStepAheadVariances = ...
PK(options_.filter_step_ahead,i_endo,i_endo,:);
end
if ~isempty(decomp)
oo_.FilteredVariablesShockDecomposition = ...
decomp(options_.filter_step_ahead,i_endo,:,:);
end
end
for i=bayestopt_.smoother_saved_var_list'
i1 = dr.order_var(bayestopt_.smoother_var_list(i));
eval(['oo_.SmoothedVariables.' deblank(M_.endo_names(i1,:)) ...
' = atT(i,:)'';']);
if options_.nk > 0
eval(['oo_.FilteredVariables.' deblank(M_.endo_names(i1,:)) ...
' = squeeze(aK(1,i,2:end-(options_.nk-1)));']);
end
eval(['oo_.UpdatedVariables.' deblank(M_.endo_names(i1,:)) ' = updated_variables(i,:)'';']);
end
for i=1:M_.exo_nbr
eval(['oo_.SmoothedShocks.' deblank(M_.exo_names(i,:)) ' = innov(i,:)'';']);
end
end end
return return
end end
% Estimation of the posterior mode or likelihood mode %% Estimation of the posterior mode or likelihood mode
% analytical derivation is not yet available for kalman_filter_fast
if options_.analytic_derivation && options_.fast_kalman_filter
error(['estimation option conflict: analytic_derivation isn''t available ' ...
'for fast_kalman_filter'])
end
% fast kalman filter is only available with kalman_algo == 1,3
if options_.fast_kalman_filter && ...
(options_.kalman_algo == 1 || options_.kalman_algo == 3)
error(['estimation option conflict: fast_kalman_filter is only available ' ...
'with kalman_algo = 1 or kalman_algo = 3'])
end
if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation
%prepare settings for newrat %prepare settings for newrat
if options_.mode_compute==5 if options_.mode_compute==5
@ -413,7 +397,7 @@ end
if (any(bayestopt_.pshape >0 ) && options_.mh_replic) || ... if (any(bayestopt_.pshape >0 ) && options_.mh_replic) || ...
(any(bayestopt_.pshape >0 ) && options_.load_mh_file) %% not ML estimation (any(bayestopt_.pshape >0 ) && options_.load_mh_file) %% not ML estimation
bounds = prior_bounds(bayestopt_,options_); bounds = prior_bounds(bayestopt_, options_.prior_trunc);
outside_bound_pars=find(xparam1 < bounds.lb | xparam1 > bounds.ub); outside_bound_pars=find(xparam1 < bounds.lb | xparam1 > bounds.ub);
if ~isempty(outside_bound_pars) if ~isempty(outside_bound_pars)
for ii=1:length(outside_bound_pars) for ii=1:length(outside_bound_pars)
@ -456,7 +440,7 @@ if (any(bayestopt_.pshape >0 ) && options_.mh_replic) || ...
if options_.mh_replic if options_.mh_replic
[marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_); [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_);
% Store posterior statistics by parameter name % Store posterior statistics by parameter name
oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bayestopt_, oo_); oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bayestopt_, oo_, pnames);
if ~options_.nograph if ~options_.nograph
oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt_, oo_); oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt_, oo_);
end end
@ -499,39 +483,42 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
> 0) && options_.load_mh_file)) ... > 0) && options_.load_mh_file)) ...
|| ~options_.smoother ) && options_.partial_information == 0 % to be fixed || ~options_.smoother ) && options_.partial_information == 0 % to be fixed
%% ML estimation, or posterior mode without metropolis-hastings or metropolis without bayesian smooth variable %% ML estimation, or posterior mode without metropolis-hastings or metropolis without bayesian smooth variable
[atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp] = DsgeSmoother(xparam1,dataset_.nobs,transpose(dataset_.data),dataset_info.missing.aindex,dataset_info.missing.state); [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp,Trend] = DsgeSmoother(xparam1,dataset_.nobs,transpose(dataset_.data),dataset_info.missing.aindex,dataset_info.missing.state);
oo_.Smoother.SteadyState = ys; [oo_,yf]=write_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend);
oo_.Smoother.TrendCoeffs = trend_coeff;
oo_.Smoother.Variance = P; % oo_.Smoother.SteadyState = ys;
i_endo = bayestopt_.smoother_saved_var_list; % oo_.Smoother.TrendCoeffs = trend_coeff;
if ~isempty(options_.nk) && options_.nk ~= 0 && (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file))) % oo_.Smoother.Trend = Trend;
oo_.FilteredVariablesKStepAhead = aK(options_.filter_step_ahead, ... % oo_.Smoother.Variance = P;
i_endo,:); % i_endo = bayestopt_.smoother_saved_var_list;
if isfield(options_,'kalman_algo') % if ~isempty(options_.nk) && options_.nk ~= 0 && (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file)))
if ~isempty(PK) % oo_.FilteredVariablesKStepAhead = aK(options_.filter_step_ahead, ...
oo_.FilteredVariablesKStepAheadVariances = ... % i_endo,:);
PK(options_.filter_step_ahead,i_endo,i_endo,:); % if isfield(options_,'kalman_algo')
end % if ~isempty(PK)
if ~isempty(decomp) % oo_.FilteredVariablesKStepAheadVariances = ...
oo_.FilteredVariablesShockDecomposition = ... % PK(options_.filter_step_ahead,i_endo,i_endo,:);
decomp(options_.filter_step_ahead,i_endo,:,:); % end
end % if ~isempty(decomp)
end % oo_.FilteredVariablesShockDecomposition = ...
end % decomp(options_.filter_step_ahead,i_endo,:,:);
for i=bayestopt_.smoother_saved_var_list' % end
i1 = dr.order_var(bayestopt_.smoother_var_list(i)); % end
eval(['oo_.SmoothedVariables.' deblank(M_.endo_names(i1,:)) ' = ' ... % end
'atT(i,:)'';']); % for i=bayestopt_.smoother_saved_var_list'
if ~isempty(options_.nk) && options_.nk > 0 && ~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file)) % i1 = dr.order_var(bayestopt_.smoother_var_list(i));
eval(['oo_.FilteredVariables.' deblank(M_.endo_names(i1,:)) ... % eval(['oo_.SmoothedVariables.' deblank(M_.endo_names(i1,:)) ' = ' ...
' = squeeze(aK(1,i,2:end-(options_.nk-1)));']); % 'atT(i,:)'';']);
end % if ~isempty(options_.nk) && options_.nk > 0 && ~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file))
eval(['oo_.UpdatedVariables.' deblank(M_.endo_names(i1,:)) ... % eval(['oo_.FilteredVariables.' deblank(M_.endo_names(i1,:)) ...
' = updated_variables(i,:)'';']); % ' = squeeze(aK(1,i,2:end-(options_.nk-1)));']);
end % end
for i=1:M_.exo_nbr % eval(['oo_.UpdatedVariables.' deblank(M_.endo_names(i1,:)) ...
eval(['oo_.SmoothedShocks.' deblank(M_.exo_names(i,:)) ' = innov(i,:)'';']); % ' = updated_variables(i,:)'';']);
end % end
% for i=1:M_.exo_nbr
% eval(['oo_.SmoothedShocks.' deblank(M_.exo_names(i,:)) ' = innov(i,:)'';']);
% end
if ~options_.nograph, if ~options_.nograph,
[nbplt,nr,nc,lr,lc,nstar] = pltorg(M_.exo_nbr); [nbplt,nr,nc,lr,lc,nstar] = pltorg(M_.exo_nbr);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
@ -602,18 +589,16 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
fclose(fidTeX); fclose(fidTeX);
end end
end end
%% % %%
%% Smooth observational errors... % %% Smooth observational errors...
%% % %%
if options_.prefilter == 1 % if options_.prefilter == 1 %as mean is taken after log transformation, no distinction is needed here
yf = atT(bayestopt_.mf,:)+repmat(dataset_info.descriptive.mean',1,gend); % yf = atT(bayestopt_.mf,:)+repmat(dataset_info.descriptive.mean',1,gend)+Trend;
elseif options_.loglinear == 1 % elseif options_.loglinear == 1
yf = atT(bayestopt_.mf,:)+repmat(log(ys(bayestopt_.mfys)),1,gend)+... % yf = atT(bayestopt_.mf,:)+repmat(log(ys(bayestopt_.mfys)),1,gend)+Trend;
trend_coeff*[1:gend]; % else
else % yf = atT(bayestopt_.mf,:)+repmat(ys(bayestopt_.mfys),1,gend)+Trend;
yf = atT(bayestopt_.mf,:)+repmat(ys(bayestopt_.mfys),1,gend)+... % end
trend_coeff*[1:gend];
end
if nvn if nvn
number_of_plots_to_draw = 0; number_of_plots_to_draw = 0;
index = []; index = [];
@ -622,7 +607,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
number_of_plots_to_draw = number_of_plots_to_draw + 1; number_of_plots_to_draw = number_of_plots_to_draw + 1;
index = cat(1,index,i); index = cat(1,index,i);
end end
eval(['oo_.SmoothedMeasurementErrors.' options_.varobs{i} ' = measurement_error(i,:)'';']); % eval(['oo_.SmoothedMeasurementErrors.' options_.varobs{i} ' = measurement_error(i,:)'';']);
end end
if ~options_.nograph if ~options_.nograph
[nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw); [nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw);
@ -773,7 +758,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
end end
if options_.forecast > 0 && options_.mh_replic == 0 && ~options_.load_mh_file if options_.forecast > 0 && options_.mh_replic == 0 && ~options_.load_mh_file
dyn_forecast(var_list_,'smoother'); oo_.forecast = dyn_forecast(var_list_,M_,options_,oo_,'smoother',dataset_info);
end end
if np > 0 if np > 0

View File

@ -315,7 +315,7 @@ if ~isempty(estim_params_) && ~all(strcmp(fieldnames(estim_params_),'full_calibr
plot_priors(bayestopt_,M_,estim_params_,options_) plot_priors(bayestopt_,M_,estim_params_,options_)
end end
% Set prior bounds % Set prior bounds
bounds = prior_bounds(bayestopt_,options_); bounds = prior_bounds(bayestopt_, options_.prior_trunc);
bounds.lb = max(bounds.lb,lb); bounds.lb = max(bounds.lb,lb);
bounds.ub = min(bounds.ub,ub); bounds.ub = min(bounds.ub,ub);
else % estimated parameters but no declared priors else % estimated parameters but no declared priors
@ -375,13 +375,11 @@ if ~isfield(options_,'trend_coeffs') % No!
else% Yes! else% Yes!
bayestopt_.with_trend = 1; bayestopt_.with_trend = 1;
bayestopt_.trend_coeff = {}; bayestopt_.trend_coeff = {};
trend_coeffs = options_.trend_coeffs;
nt = length(trend_coeffs);
for i=1:options_.number_of_observed_variables for i=1:options_.number_of_observed_variables
if i > length(trend_coeffs) if i > length(options_.trend_coeffs)
bayestopt_.trend_coeff{i} = '0'; bayestopt_.trend_coeff{i} = '0';
else else
bayestopt_.trend_coeff{i} = trend_coeffs{i}; bayestopt_.trend_coeff{i} = options_.trend_coeffs{i};
end end
end end
end end
@ -530,11 +528,11 @@ end
[dataset_, dataset_info, newdatainterfaceflag] = makedataset(options_, options_.dsge_var*options_.dsge_varlag, gsa_flag); [dataset_, dataset_info, newdatainterfaceflag] = makedataset(options_, options_.dsge_var*options_.dsge_varlag, gsa_flag);
% Set options_.nobs if needed %set options for old interface from the ones for new interface
if newdatainterfaceflag if ~isempty(dataset_)
options_.nobs = dataset_.nobs; options_.nobs = dataset_.nobs;
options_.first_obs=double(dataset_.init);
end end
% setting steadystate_check_flag option % setting steadystate_check_flag option
if options_.diffuse_filter if options_.diffuse_filter
steadystate_check_flag = 0; steadystate_check_flag = 0;
@ -558,7 +556,7 @@ if info(1)
print_info(info, 0, options_); print_info(info, 0, options_);
end end
if all(abs(oo_.steady_state(bayestopt_.mfys))<1e-9) if (~options_.loglinear && all(abs(oo_.steady_state(bayestopt_.mfys))<1e-9)) || (options_.loglinear && all(abs(log(oo_.steady_state(bayestopt_.mfys)))<1e-9))
options_.noconstant = 1; options_.noconstant = 1;
else else
options_.noconstant = 0; options_.noconstant = 0;
@ -573,3 +571,28 @@ else
error('The option "prefilter" is inconsistent with the non-zero mean measurement equations in the model.') error('The option "prefilter" is inconsistent with the non-zero mean measurement equations in the model.')
end end
end end
%% get the non-zero rows and columns of Sigma_e and H
H_non_zero_rows=find(~all(M_.H==0,1));
H_non_zero_columns=find(~all(M_.H==0,2));
if ~isequal(H_non_zero_rows,H_non_zero_columns')
error('Measurement error matrix not symmetric')
end
if isfield(estim_params_,'nvn_observable_correspondence')
estim_params_.H_entries_to_check_for_positive_definiteness=union(H_non_zero_rows,estim_params_.nvn_observable_correspondence(:,1));
else
estim_params_.H_entries_to_check_for_positive_definiteness=H_non_zero_rows;
end
Sigma_e_non_zero_rows=find(~all(M_.Sigma_e==0,1));
Sigma_e_non_zero_columns=find(~all(M_.Sigma_e==0,2));
if ~isequal(Sigma_e_non_zero_rows,Sigma_e_non_zero_columns')
error('Structual error matrix not symmetric')
end
if isfield(estim_params_,'var_exo') && ~isempty(estim_params_.var_exo)
estim_params_.Sigma_e_entries_to_check_for_positive_definiteness=union(Sigma_e_non_zero_rows,estim_params_.var_exo(:,1));
else
estim_params_.Sigma_e_entries_to_check_for_positive_definiteness=Sigma_e_non_zero_rows;
end

View File

@ -149,9 +149,9 @@ options_ident.analytic_derivation_mode = options_.analytic_derivation_mode;
if prior_exist if prior_exist
if any(bayestopt_.pshape > 0) if any(bayestopt_.pshape > 0)
if options_ident.prior_range if options_ident.prior_range
prior_draw(1,1); prior_draw(bayestopt_, options_.prior_trunc, true);
else else
prior_draw(1); prior_draw(bayestopt_, options_.prior_trunc, false);
end end
else else
options_ident.prior_mc=1; options_ident.prior_mc=1;
@ -234,37 +234,44 @@ if iload <=0,
params = set_prior(estim_params_,M_,options_)'; params = set_prior(estim_params_,M_,options_)';
if all(bayestopt_.pshape == 0) if all(bayestopt_.pshape == 0)
parameters = 'ML_Starting_value'; parameters = 'ML_Starting_value';
parameters_TeX = 'ML starting value';
disp('Testing ML Starting value') disp('Testing ML Starting value')
else else
switch parameters switch parameters
case 'posterior_mode' case 'posterior_mode'
disp('Testing posterior mode') parameters_TeX = 'Posterior mode';
params(1,:) = get_posterior_parameters('mode'); disp('Testing posterior mode')
case 'posterior_mean' params(1,:) = get_posterior_parameters('mode');
disp('Testing posterior mean') case 'posterior_mean'
params(1,:) = get_posterior_parameters('mean'); parameters_TeX = 'Posterior mean';
case 'posterior_median' disp('Testing posterior mean')
disp('Testing posterior median') params(1,:) = get_posterior_parameters('mean');
params(1,:) = get_posterior_parameters('median'); case 'posterior_median'
case 'prior_mode' parameters_TeX = 'Posterior median';
disp('Testing prior mode') disp('Testing posterior median')
params(1,:) = bayestopt_.p5(:); params(1,:) = get_posterior_parameters('median');
case 'prior_mean' case 'prior_mode'
disp('Testing prior mean') parameters_TeX = 'Prior mode';
params(1,:) = bayestopt_.p1; disp('Testing prior mode')
otherwise params(1,:) = bayestopt_.p5(:);
disp('The option parameter_set has to be equal to:') case 'prior_mean'
disp(' ''posterior_mode'', ') parameters_TeX = 'Prior mean';
disp(' ''posterior_mean'', ') disp('Testing prior mean')
disp(' ''posterior_median'', ') params(1,:) = bayestopt_.p1;
disp(' ''prior_mode'' or') otherwise
disp(' ''prior_mean''.') disp('The option parameter_set has to be equal to:')
error; disp(' ''posterior_mode'', ')
end disp(' ''posterior_mean'', ')
disp(' ''posterior_median'', ')
disp(' ''prior_mode'' or')
disp(' ''prior_mean''.')
error;
end
end end
else else
params = [sqrt(diag(M_.Sigma_e))', M_.params']; params = [sqrt(diag(M_.Sigma_e))', M_.params'];
parameters = 'Current_params'; parameters = 'Current_params';
parameters_TeX = 'Current parameter values';
disp('Testing current parameter values') disp('Testing current parameter values')
end end
[idehess_point, idemoments_point, idemodel_point, idelre_point, derivatives_info_point, info] = ... [idehess_point, idemoments_point, idemodel_point, idelre_point, derivatives_info_point, info] = ...
@ -339,7 +346,7 @@ if iload <=0,
save([IdentifDirectoryName '/' M_.fname '_' parameters '_identif.mat'], 'idehess_point', 'idemoments_point','idemodel_point', 'idelre_point','store_options_ident') save([IdentifDirectoryName '/' M_.fname '_' parameters '_identif.mat'], 'idehess_point', 'idemoments_point','idemodel_point', 'idelre_point','store_options_ident')
disp_identification(params, idemodel_point, idemoments_point, name, advanced); disp_identification(params, idemodel_point, idemoments_point, name, advanced);
if ~options_.nograph, if ~options_.nograph,
plot_identification(params,idemoments_point,idehess_point,idemodel_point,idelre_point,advanced,parameters,name,IdentifDirectoryName); plot_identification(params,idemoments_point,idehess_point,idemodel_point,idelre_point,advanced,parameters,name,IdentifDirectoryName,parameters_TeX);
end end
if SampleSize > 1, if SampleSize > 1,
@ -541,7 +548,7 @@ if SampleSize > 1,
disp_identification(pdraws(jmax,:), idemodel_max, idemoments_max, name,1); disp_identification(pdraws(jmax,:), idemodel_max, idemoments_max, name,1);
close all, close all,
if ~options_.nograph, if ~options_.nograph,
plot_identification(pdraws(jmax,:),idemoments_max,idehess_max,idemodel_max,idelre_max,1,tittxt,name,IdentifDirectoryName); plot_identification(pdraws(jmax,:),idemoments_max,idehess_max,idemodel_max,idelre_max,1,tittxt,name,IdentifDirectoryName,tittxt);
end end
[dum,jmin]=min(idemoments.cond); [dum,jmin]=min(idemoments.cond);
fprintf('\n') fprintf('\n')
@ -556,7 +563,7 @@ if SampleSize > 1,
disp_identification(pdraws(jmin,:), idemodel_min, idemoments_min, name,1); disp_identification(pdraws(jmin,:), idemodel_min, idemoments_min, name,1);
close all, close all,
if ~options_.nograph, if ~options_.nograph,
plot_identification(pdraws(jmin,:),idemoments_min,idehess_min,idemodel_min,idelre_min,1,tittxt,name,IdentifDirectoryName); plot_identification(pdraws(jmin,:),idemoments_min,idehess_min,idemodel_min,idelre_min,1,tittxt,name,IdentifDirectoryName,tittxt);
end end
else else
for j=1:length(jcrit), for j=1:length(jcrit),
@ -570,7 +577,7 @@ if SampleSize > 1,
disp_identification(pdraws(jcrit(j),:), idemodel_(j), idemoments_(j), name,1); disp_identification(pdraws(jcrit(j),:), idemodel_(j), idemoments_(j), name,1);
close all, close all,
if ~options_.nograph, if ~options_.nograph,
plot_identification(pdraws(jcrit(j),:),idemoments_(j),idehess_(j),idemodel_(j),idelre_(j),1,tittxt,name,IdentifDirectoryName); plot_identification(pdraws(jcrit(j),:),idemoments_(j),idehess_(j),idemodel_(j),idelre_(j),1,tittxt,name,IdentifDirectoryName,tittxt);
end end
end end
if ~iload, if ~iload,

View File

@ -14,7 +14,7 @@ function [ts,results] = extended_path(initial_conditions,sample_size)
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% Copyright (C) 2009-2015 Dynare Team % Copyright (C) 2009-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -42,6 +42,10 @@ options_.simul.maxit = ep.maxit;
% Prepare a structure needed by the matlab implementation of the perfect foresight model solver % Prepare a structure needed by the matlab implementation of the perfect foresight model solver
pfm = setup_stochastic_perfect_foresight_model_solver(M_,options_,oo_); pfm = setup_stochastic_perfect_foresight_model_solver(M_,options_,oo_);
if M_.exo_det_nbr~=0
error('ep: Extended path does not support varexo_det.')
end
endo_nbr = M_.endo_nbr; endo_nbr = M_.endo_nbr;
exo_nbr = M_.exo_nbr; exo_nbr = M_.exo_nbr;
maximum_lag = M_.maximum_lag; maximum_lag = M_.maximum_lag;
@ -138,7 +142,6 @@ switch ep.innovation_distribution
error(['extended_path:: ' ep.innovation_distribution ' distribution for the structural innovations is not (yet) implemented!']) error(['extended_path:: ' ep.innovation_distribution ' distribution for the structural innovations is not (yet) implemented!'])
end end
% Set waitbar (graphic or text mode) % Set waitbar (graphic or text mode)
hh = dyn_waitbar(0,'Please wait. Extended Path simulations...'); hh = dyn_waitbar(0,'Please wait. Extended Path simulations...');
set(hh,'Name','EP simulations.'); set(hh,'Name','EP simulations.');
@ -182,6 +185,8 @@ oo_.ep.failures.periods = [];
oo_.ep.failures.previous_period = cell(0); oo_.ep.failures.previous_period = cell(0);
oo_.ep.failures.shocks = cell(0); oo_.ep.failures.shocks = cell(0);
oo_.exo_simul = shocks;
% Initializes some variables. % Initializes some variables.
t = 1; t = 1;
tsimul = 1; tsimul = 1;
@ -189,7 +194,7 @@ for k = 1:replic_nbr
results{k} = zeros(endo_nbr,sample_size+1); results{k} = zeros(endo_nbr,sample_size+1);
results{k}(:,1) = initial_conditions; results{k}(:,1) = initial_conditions;
end end
make_ex_; %make_ex_;
exo_simul_ = zeros(maximum_lag+sample_size+maximum_lead,exo_nbr); exo_simul_ = zeros(maximum_lag+sample_size+maximum_lead,exo_nbr);
exo_simul_(1:size(oo_.exo_simul,1),1:size(oo_.exo_simul,2)) = oo_.exo_simul; exo_simul_(1:size(oo_.exo_simul,1),1:size(oo_.exo_simul,2)) = oo_.exo_simul;
% Main loop. % Main loop.
@ -265,78 +270,4 @@ else
end end
end end
assignin('base', 'Simulated_time_series', ts); assignin('base', 'Simulated_time_series', ts);
function [y, info_convergence] = extended_path_core(periods,endo_nbr,exo_nbr,positive_var_indx, ...
exo_simul,init,initial_conditions,...
maximum_lag,maximum_lead,steady_state, ...
verbosity,bytecode_flag,order,M,pfm,algo,solve_algo,stack_solve_algo,...
olmmcp,options,oo)
ep = options.ep;
if init% Compute first order solution (Perturbation)...
endo_simul = simult_(initial_conditions,oo.dr,exo_simul(2:end,:),1);
else
endo_simul = [initial_conditions repmat(steady_state,1,periods+1)];
end
oo.endo_simul = endo_simul;
oo_.endo_simul = endo_simul;
% Solve a perfect foresight model.
% Keep a copy of endo_simul_1
if verbosity
save ep_test_1 endo_simul exo_simul
end
if bytecode_flag && ~ep.stochastic.order
[flag,tmp] = bytecode('dynamic',endo_simul,exo_simul, M_.params, endo_simul, periods);
else
flag = 1;
end
if flag
if order == 0
options.periods = periods;
options.block = pfm.block;
oo.endo_simul = endo_simul;
oo.exo_simul = exo_simul;
oo.steady_state = steady_state;
options.bytecode = bytecode_flag;
options.lmmcp = olmmcp;
options.solve_algo = solve_algo;
options.stack_solve_algo = stack_solve_algo;
[tmp,flag] = perfect_foresight_solver_core(M,options,oo);
if ~flag && ~options.no_homotopy
exo_orig = oo.exo_simul;
endo_simul = repmat(steady_state,1,periods+1);
for i = 1:10
weight = i/10;
oo.endo_simul = [weight*initial_conditions + (1-weight)*steady_state ...
endo_simul];
oo.exo_simul = repmat((1-weight)*oo.exo_steady_state', ...
size(oo.exo_simul,1),1) + weight*exo_orig;
[tmp,flag] = perfect_foresight_solver_core(M,options,oo);
disp([i,flag])
if ~flag
break
end
endo_simul = tmp.endo_simul;
end
end
info_convergence = flag;
else
switch(algo)
case 0
[flag,endo_simul] = ...
solve_stochastic_perfect_foresight_model(endo_simul,exo_simul,pfm,ep.stochastic.quadrature.nodes,ep.stochastic.order);
case 1
[flag,endo_simul] = ...
solve_stochastic_perfect_foresight_model_1(endo_simul,exo_simul,options_,pfm,ep.stochastic.order);
end
tmp.endo_simul = endo_simul;
info_convergence = ~flag;
end
end
if info_convergence
y = tmp.endo_simul(:,2);
else
y = NaN(size(endo_nbr,1));
end

View File

@ -0,0 +1,88 @@
function [y, info_convergence] = extended_path_core(periods,endo_nbr,exo_nbr,positive_var_indx, ...
exo_simul,init,initial_conditions,...
maximum_lag,maximum_lead,steady_state, ...
verbosity,bytecode_flag,order,M,pfm,algo,solve_algo,stack_solve_algo,...
olmmcp,options,oo)
% Copyright (C) 2016 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/>.
ep = options.ep;
if init% Compute first order solution (Perturbation)...
endo_simul = simult_(initial_conditions,oo.dr,exo_simul(2:end,:),1);
else
endo_simul = [initial_conditions repmat(steady_state,1,periods+1)];
end
oo.endo_simul = endo_simul;
% Solve a perfect foresight model.
% Keep a copy of endo_simul_1
if verbosity
save ep_test_1 endo_simul exo_simul
end
if bytecode_flag && ~ep.stochastic.order
[flag,tmp] = bytecode('dynamic',endo_simul,exo_simul, M_.params, endo_simul, periods);
else
flag = 1;
end
if flag
if order == 0
options.periods = periods;
options.block = pfm.block;
oo.endo_simul = endo_simul;
oo.exo_simul = exo_simul;
oo.steady_state = steady_state;
options.bytecode = bytecode_flag;
options.lmmcp = olmmcp;
options.solve_algo = solve_algo;
options.stack_solve_algo = stack_solve_algo;
[tmp,flag] = perfect_foresight_solver_core(M,options,oo);
if ~flag && ~options.no_homotopy
exo_orig = oo.exo_simul;
endo_simul = repmat(steady_state,1,periods+1);
for i = 1:10
weight = i/10;
oo.endo_simul = [weight*initial_conditions + (1-weight)*steady_state ...
endo_simul];
oo.exo_simul = repmat((1-weight)*oo.exo_steady_state', ...
size(oo.exo_simul,1),1) + weight*exo_orig;
[tmp,flag] = perfect_foresight_solver_core(M,options,oo);
disp([i,flag])
if ~flag
break
end
endo_simul = tmp.endo_simul;
end
end
info_convergence = flag;
else
switch(algo)
case 0
[flag,endo_simul] = ...
solve_stochastic_perfect_foresight_model(endo_simul,exo_simul,pfm,ep.stochastic.quadrature.nodes,ep.stochastic.order);
case 1
[flag,endo_simul] = ...
solve_stochastic_perfect_foresight_model_1(endo_simul,exo_simul,options_,pfm,ep.stochastic.order);
end
tmp.endo_simul = endo_simul;
info_convergence = ~flag;
end
end
if info_convergence
y = tmp.endo_simul(:,2);
else
y = NaN(size(endo_nbr,1));
end

View File

@ -70,6 +70,6 @@ if isempty(dataset)
[dataset, dataset_info] = makedataset(options_); [dataset, dataset_info] = makedataset(options_);
end end
llik = -dsge_likelihood(parameters,dataset,dataset_info,options_,M_,estim_params_,bayestopt_,prior_bounds(bayestopt_,options_),oo_); llik = -dsge_likelihood(parameters,dataset,dataset_info,options_,M_,estim_params_,bayestopt_,prior_bounds(bayestopt_,options_.prior_trunc),oo_);
ldens = evaluate_prior(parameters); ldens = evaluate_prior(parameters);
llik = llik - ldens; llik = llik - ldens;

View File

@ -32,6 +32,13 @@ dr = oo.dr;
exo_nbr = M.exo_nbr; exo_nbr = M.exo_nbr;
nstatic = M.nstatic; nstatic = M.nstatic;
nspred = M.nspred; nspred = M.nspred;
if nspred > 180
disp(' ')
disp(['WARNING in evaluate_planner_objective: model too large, can''t evaluate planner ' ...
'objective'])
planner_objective_value = NaN;
return
end
beta = get_optimal_policy_discount_factor(M.params,M.param_names); beta = get_optimal_policy_discount_factor(M.params,M.param_names);
Gy = dr.ghx(nstatic+(1:nspred),:); Gy = dr.ghx(nstatic+(1:nspred),:);

View File

@ -87,35 +87,6 @@ if ischar(parameters)
end end
end end
[atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp] = ... [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp,Trend] = ...
DsgeSmoother(parameters,dataset_.nobs,transpose(dataset_.data),dataset_info.missing.aindex,dataset_info.missing.state); DsgeSmoother(parameters,dataset_.nobs,transpose(dataset_.data),dataset_info.missing.aindex,dataset_info.missing.state);
[oo_]=write_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend);
oo_.Smoother.SteadyState = ys;
oo_.Smoother.TrendCoeffs = trend_coeff;
if options_.filter_covariance
oo_.Smoother.Variance = P;
end
i_endo = bayestopt_.smoother_saved_var_list;
if options_.nk ~= 0
oo_.FilteredVariablesKStepAhead = ...
aK(options_.filter_step_ahead,i_endo,:);
if ~isempty(PK)
oo_.FilteredVariablesKStepAheadVariances = ...
PK(options_.filter_step_ahead,i_endo,i_endo,:);
end
if ~isempty(decomp)
oo_.FilteredVariablesShockDecomposition = ...
decomp(options_.filter_step_ahead,i_endo,:,:);
end
end
for i=bayestopt_.smoother_saved_var_list'
i1 = oo_.dr.order_var(bayestopt_.smoother_var_list(i));
eval(['oo_.SmoothedVariables.' deblank(M_.endo_names(i1,:)) ' = atT(i,:)'';']);
if options_.nk>0
eval(['oo_.FilteredVariables.' deblank(M_.endo_names(i1,:)) ' = squeeze(aK(1,i,:));']);
end
eval(['oo_.UpdatedVariables.' deblank(M_.endo_names(i1,:)) ' = updated_variables(i,:)'';']);
end
for i=1:M_.exo_nbr
eval(['oo_.SmoothedShocks.' deblank(M_.exo_names(i,:)) ' = innov(i,:)'';']);
end

View File

@ -22,7 +22,7 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2001-2013 Dynare Team % Copyright (C) 2001-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -48,7 +48,9 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
if length(M.aux_vars) > 0 if length(M.aux_vars) > 0
h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']); h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']);
ys_init = h_set_auxiliary_variables(ys_init,exo_ss,M.params); if ~steadystate_flag
ys_init = h_set_auxiliary_variables(ys_init,exo_ss,M.params);
end
end end
if options.ramsey_policy if options.ramsey_policy
@ -58,7 +60,7 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
options); options);
%test whether it solves model conditional on the instruments %test whether it solves model conditional on the instruments
resids = evaluate_static_model(ys,exo_ss,params,M,options); resids = evaluate_static_model(ys,exo_ss,params,M,options);
n_multipliers=M.endo_nbr-M.orig_endo_nbr; n_multipliers=M.ramsey_eq_nbr;
nan_indices=find(isnan(resids(n_multipliers+1:end))); nan_indices=find(isnan(resids(n_multipliers+1:end)));
if ~isempty(nan_indices) if ~isempty(nan_indices)

View File

@ -19,7 +19,7 @@ function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options)
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2001-2012 Dynare Team % Copyright (C) 2001-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -36,11 +36,14 @@ function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options)
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
debug = false;
ys = []; ys = [];
params = [];
info = 0;
params = M.params; params = M.params;
info = 0;
fname = M.fname; fname = M.fname;
if options.steadystate_flag == 1 if options.steadystate_flag == 1
% old format % old format
assignin('base','tmp_00_',params); assignin('base','tmp_00_',params);
@ -88,13 +91,46 @@ function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options)
% adding values for auxiliary variables % adding values for auxiliary variables
if length(M.aux_vars) > 0 && ~options.ramsey_policy if length(M.aux_vars) > 0 && ~options.ramsey_policy
if debug
ys0 = ys;
end
ys = h_set_auxiliary_variables(ys,exo_ss,params); ys = h_set_auxiliary_variables(ys,exo_ss,params);
if debug
ys1 = ys;
end
ys = h_set_auxiliary_variables(ys,exo_ss,params);
if debug
ys2 = ys;
end
if debug
ys = h_set_auxiliary_variables(ys,exo_ss,params);
ys3 = ys;
idx = find(abs(ys0-ys1)>0);
if ~isempty(idx)
M.endo_names(idx,:)
else
disp('1-invariant')
end
idx = find(abs(ys2-ys1)>0);
if ~isempty(idx)
M.endo_names(idx,:)
else
disp('2-invariant')
end
idx = find(abs(ys3-ys3)>0);
if ~isempty(idx)
M.endo_names(idx,:)
else
disp('3-invariant')
end
pause
end
end end
check1 = 0; check1 = 0;
if ~options.steadystate.nocheck if ~options.steadystate.nocheck
% Check whether the steady state obtained from the _steadystate file is a steady state. % Check whether the steady state obtained from the _steadystate file is a steady state.
[residuals,check] = evaluate_static_model(ys,exo_ss,params,M,options); [residuals, check] = evaluate_static_model(ys, exo_ss, params, M, options);
if check if check
info(1) = 19; info(1) = 19;
info(2) = check; % to be improved info(2) = check; % to be improved

View File

@ -62,7 +62,7 @@ if strcmpi(type,'posterior')
n_draws=options_.sub_draws; n_draws=options_.sub_draws;
prior = false; prior = false;
elseif strcmpi(type,'prior') elseif strcmpi(type,'prior')
prior_draw(1); prior_draw(bayestopt_, options_.prior_trunc);
else else
error('EXECUTE_POSTERIOR_FUNCTION: Unknown type!') error('EXECUTE_POSTERIOR_FUNCTION: Unknown type!')
end end

View File

@ -17,7 +17,7 @@ function [yf,int_width]=forcst(dr,y0,horizon,var_list)
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2003-2012 Dynare Team % Copyright (C) 2003-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -34,9 +34,9 @@ function [yf,int_width]=forcst(dr,y0,horizon,var_list)
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ options_ global M_ oo_ options_
make_ex_; oo_=make_ex_(M_,options_,oo_);
yf = simult_(y0,dr,zeros(horizon,M_.exo_nbr),1); yf = simult_(y0,dr,zeros(horizon,M_.exo_nbr),1);
nstatic = M_.nstatic; nstatic = M_.nstatic;
nspred = M_.nspred; nspred = M_.nspred;

View File

@ -1,5 +1,16 @@
function yf=forcst2(y0,horizon,dr,n) function yf=forcst2(y0,horizon,dr,n)
% function yf=forcst2(y0,horizon,dr,n)
%
% computes forecasts based on first order model solution, given shocks drawn from the shock distribution
% Inputs:
% - y0 [endo_nbr by maximum_endo_lag] matrix of starting values
% - dr [structure] structure with Dynare decision rules
% - e [horizon by exo_nbr] matrix with shocks
% - n [scalar] number of repetitions
%
% Outputs:
% - yf [horizon+ykmin_ by endo_nbr by n] array of forecasts
%
% Copyright (C) 2008-2010 Dynare Team % Copyright (C) 2008-2010 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
@ -24,14 +35,10 @@ endo_nbr = M_.endo_nbr;
exo_nbr = M_.exo_nbr; exo_nbr = M_.exo_nbr;
ykmin_ = M_.maximum_endo_lag; ykmin_ = M_.maximum_endo_lag;
order = options_.order;
k1 = [ykmin_:-1:1]; k1 = [ykmin_:-1:1];
k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]); k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]);
k2 = k2(:,1)+(ykmin_+1-k2(:,2))*endo_nbr; k2 = k2(:,1)+(ykmin_+1-k2(:,2))*endo_nbr;
it_ = ykmin_ + 1 ;
% eliminate shocks with 0 variance % eliminate shocks with 0 variance
i_exo_var = setdiff([1:exo_nbr],find(diag(Sigma_e_) == 0)); i_exo_var = setdiff([1:exo_nbr],find(diag(Sigma_e_) == 0));
nxs = length(i_exo_var); nxs = length(i_exo_var);

View File

@ -1,6 +1,15 @@
function yf=forcst2a(y0,dr,e) function yf=forcst2a(y0,dr,e)
% function yf=forcst2a(y0,dr,e)
% Copyright (C) 2008-2010 Dynare Team % computes forecasts based on first order model solution, assuming the absence of shocks
% Inputs:
% - y0 [endo_nbr by maximum_endo_lag] matrix of starting values
% - dr [structure] structure with Dynare decision rules
% - e [horizon by exo_nbr] matrix with shocks
%
% Outputs:
% - yf [horizon+maximum_endo_lag,endo_nbr] matrix of forecasts
%
% Copyright (C) 2008-2015 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -19,13 +28,10 @@ function yf=forcst2a(y0,dr,e)
global M_ options_ global M_ options_
Sigma_e_ = M_.Sigma_e;
endo_nbr = M_.endo_nbr; endo_nbr = M_.endo_nbr;
exo_nbr = M_.exo_nbr;
ykmin_ = M_.maximum_endo_lag; ykmin_ = M_.maximum_endo_lag;
horizon = size(e,1); horizon = size(e,1);
order = options_.order;
k1 = [ykmin_:-1:1]; k1 = [ykmin_:-1:1];
k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]); k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]);

View File

@ -11,7 +11,7 @@ function ext = get_file_extension(file)
% REMARKS % REMARKS
% If the provided file name has no extension, the routine will return an empty array. % If the provided file name has no extension, the routine will return an empty array.
% Copyright (C) 2013 Dynare Team % Copyright (C) 2013-2015 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -28,15 +28,9 @@ function ext = get_file_extension(file)
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% Clean-up path [dir, fname, ext] = fileparts(file);
file = strrep(file, '../', '');
file = strrep(file, './', '');
remain = file; if ~isempty(ext)
while ~isempty(remain) % Removes the leading dot.
[ext, remain] = strtok(remain,'.'); ext = ext(2:end);
end
if strcmp(ext,file)
ext = [];
end end

View File

@ -11,7 +11,7 @@ function global_initialization()
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2003-2015 Dynare Team % Copyright (C) 2003-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -407,7 +407,7 @@ options_.filtered_vars = 0;
options_.first_obs = NaN; options_.first_obs = NaN;
options_.nobs = NaN; options_.nobs = NaN;
options_.kalman_algo = 0; options_.kalman_algo = 0;
options_.fast_kalman = 0; options_.fast_kalman_filter = 0;
options_.kalman_tol = 1e-10; options_.kalman_tol = 1e-10;
options_.diffuse_kalman_tol = 1e-6; options_.diffuse_kalman_tol = 1e-6;
options_.use_univariate_filters_if_singularity_is_detected = 1; options_.use_univariate_filters_if_singularity_is_detected = 1;
@ -510,6 +510,16 @@ M_.Correlation_matrix = [];
M_.Correlation_matrix_ME = []; M_.Correlation_matrix_ME = [];
M_.parameter_used_with_lead_lag = false; M_.parameter_used_with_lead_lag = false;
M_.xref1.param = {};
M_.xref1.endo = {};
M_.xref1.exo = {};
M_.xref1.exo_det = {};
M_.xref2.param = {};
M_.xref2.endo = {};
M_.xref2.exo = {};
M_.xref2.exo_det = {};
% homotopy for steady state % homotopy for steady state
options_.homotopy_mode = 0; options_.homotopy_mode = 0;
options_.homotopy_steps = 1; options_.homotopy_steps = 1;

View File

@ -105,7 +105,7 @@ for j=1:nvar
fprintf(fidTeX,'\\centering \n'); fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,['\\includegraphics[scale=0.5]{%s_shock_decomposition_%s}\n'],DynareModel.fname,deblank(endo_names(i_var(j),:))); fprintf(fidTeX,['\\includegraphics[scale=0.5]{%s_shock_decomposition_%s}\n'],DynareModel.fname,deblank(endo_names(i_var(j),:)));
fprintf(fidTeX,'\\label{Fig:shock_decomp:%s}\n',deblank(endo_names(i_var(j),:))); fprintf(fidTeX,'\\label{Fig:shock_decomp:%s}\n',deblank(endo_names(i_var(j),:)));
fprintf(fidTeX,'\\caption{Historical shock decomposition: %s}\n',deblank(endo_names(i_var(j),:))); fprintf(fidTeX,'\\caption{Historical shock decomposition: $ %s $}\n',deblank(DynareModel.endo_names_tex(i_var(j),:)));
fprintf(fidTeX,'\\end{figure}\n'); fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n'); fprintf(fidTeX,' \n');
end end

View File

@ -366,11 +366,14 @@ else
end end
if options_.opt_gsa.ppost if options_.opt_gsa.ppost
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],options_);
create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnprior')
else else
if options_.opt_gsa.pprior if options_.opt_gsa.pprior
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnprior',int2str(ifig) ],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnprior',int2str(ifig) ],options_);
create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnprior')
else else
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnprior',int2str(ifig) ],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnprior',int2str(ifig) ],options_);
create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnprior')
end end
end end
end end
@ -408,12 +411,15 @@ else
end end
if options_.opt_gsa.ppost if options_.opt_gsa.ppost
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnlik',int2str(ifig) ],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnlik',int2str(ifig) ],options_);
create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnprio')
else else
if options_.opt_gsa.pprior if options_.opt_gsa.pprior
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnlik',int2str(ifig)],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnlik',int2str(ifig)],options_);
create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_lnlik',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnlik')
else else
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnlik',int2str(ifig) ],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnlik',int2str(ifig) ],options_);
end create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_lnlik',int2str(ifig) ],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnlik')
end
end end
end end
end end
@ -450,11 +456,14 @@ else
end end
if options_.opt_gsa.ppost if options_.opt_gsa.ppost
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],options_);
create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnpost')
else else
if options_.opt_gsa.pprior if options_.opt_gsa.pprior
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnpost',int2str(ifig)],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnpost',int2str(ifig)],options_);
create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_lnpost',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnpost')
else else
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnpost',int2str(ifig)],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnpost',int2str(ifig)],options_);
create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_lnpost',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnpost')
end end
end end
end end
@ -662,11 +671,14 @@ else
%set(findobj(get(h0,'children'),'type','text'),'interpreter','none') %set(findobj(get(h0,'children'),'type','text'),'interpreter','none')
if options_.opt_gsa.ppost if options_.opt_gsa.ppost
dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_); dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_);
create_TeX_loader(options_,[ OutDir filesep fname_ '_rmse_post_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],ix,[temp_name,' observed variable ',deblank(vvarvecm(iy,:))],['rmse_post_' deblank(vvarvecm(iy,:))])
else else
if options_.opt_gsa.pprior if options_.opt_gsa.pprior
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_' deblank(vvarvecm(iy,:)) '_' int2str(ix) ],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_' deblank(vvarvecm(iy,:)) '_' int2str(ix) ],options_);
create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_' deblank(vvarvecm(iy,:)) '_' int2str(ix) ],ix,[temp_name,' observed variable ',deblank(vvarvecm(iy,:))],['rmse_prior_' deblank(vvarvecm(iy,:))])
else else
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_);
create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],ix,[temp_name,' observed variable ',deblank(vvarvecm(iy,:))],['rmse_mc_' deblank(vvarvecm(iy,:))])
end end
end end
end end
@ -720,11 +732,14 @@ else
%set(findobj(get(h0,'children'),'type','text'),'interpreter','none') %set(findobj(get(h0,'children'),'type','text'),'interpreter','none')
if options_.opt_gsa.ppost if options_.opt_gsa.ppost
dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_params_' int2str(ix)],options_); dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_params_' int2str(ix)],options_);
create_TeX_loader(options_,[ OutDir filesep fname_ '_rmse_post_params_' int2str(ix)],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_post_params')
else else
if options_.opt_gsa.pprior if options_.opt_gsa.pprior
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],options_);
create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_prior_params')
else else
dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],options_); dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],options_);
create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_mc_params')
end end
end end
end end
@ -789,4 +804,19 @@ else
% % close all % % close all
% end % end
end end
function []=create_TeX_loader(options_,figpath,label_number,caption,label_name)
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([figpath '.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by filt_mc_.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s}\n',strrep(figpath,'\','/'));
fprintf(fidTeX,'\\caption{%s.}',caption);
fprintf(fidTeX,'\\label{Fig:%s:%u}\n',label_name,label_number);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end

View File

@ -1,6 +1,6 @@
function map_calibration(OutputDirectoryName, Model, DynareOptions, DynareResults, EstimatedParameters, BayesInfo) function map_calibration(OutputDirectoryName, Model, DynareOptions, DynareResults, EstimatedParameters, BayesInfo)
% Copyright (C) 2014 Dynare Team % Copyright (C) 2014-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -303,8 +303,8 @@ if ~isempty(indx_irf),
end end
if ~DynareOptions.nograph, if ~DynareOptions.nograph,
dyn_saveas(h1,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],DynareOptions); dyn_saveas(h1,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],DynareOptions);
create_TeX_loader(DynareOptions,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],[type ' evaluation of irf restrictions'],'irf_restrictions',type)
end end
skipline() skipline()
end end
@ -495,9 +495,24 @@ if ~isempty(indx_moment)
end end
if ~DynareOptions.nograph, if ~DynareOptions.nograph,
dyn_saveas(h2,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],DynareOptions); dyn_saveas(h2,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],DynareOptions);
create_TeX_loader(DynareOptions,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],[type ' evaluation of moment restrictions'],'moment_restrictions',type)
end end
skipline() skipline()
end end
return return
function []=create_TeX_loader(options,figpath,caption,label_name,label_type)
if options.TeX && any(strcmp('eps',cellstr(options.graph_format)))
fidTeX = fopen([figpath '.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by map_calibration.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s}\n',strrep(figpath,'\','/'));
fprintf(fidTeX,'\\caption{%s.}',caption);
fprintf(fidTeX,'\\label{Fig:%s:%s}\n',label_name,label_type);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end

View File

@ -100,6 +100,7 @@ if opt_gsa.load_ident_files==0,
title(M_.exo_names(j,:),'interpreter','none') title(M_.exo_names(j,:),'interpreter','none')
if mod(j,6)==0 | j==M_.exo_nbr, if mod(j,6)==0 | j==M_.exo_nbr,
dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],options_); dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],options_);
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],ifig,['Variance decomposition shocks'],'vdec_exo')
end end
end end
end end
@ -223,6 +224,7 @@ if opt_gsa.morris==1,
xlabel(' ') xlabel(' ')
title('Elementary effects variance decomposition') title('Elementary effects variance decomposition')
dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_vdec'],options_); dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_vdec'],options_);
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_vdec'],1,'Screening identification: variance decomposition','morris_vdec')
else else
save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'vdec') save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'vdec')
@ -328,6 +330,8 @@ if opt_gsa.morris==1,
xlabel(' ') xlabel(' ')
title('Elementary effects in the moments') title('Elementary effects in the moments')
dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_moments'],options_); dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_moments'],options_);
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_moments'],1,'Screening identification: theoretical moments','morris_moments')
% close(gcf), % close(gcf),
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -724,6 +728,7 @@ if opt_gsa.morris==1,
xlabel(' ') xlabel(' ')
title('Elementary effects in the model') title('Elementary effects in the model')
dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_par'],options_); dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_par'],options_);
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_par'],1,'Screening identification: model','morris_par')
% hh=dyn_figure(options_); %bar(SAmunorm(:,irel)) % hh=dyn_figure(options_); %bar(SAmunorm(:,irel))
% % boxplot(SAmunorm','whis',10,'symbol','r.') % % boxplot(SAmunorm','whis',10,'symbol','r.')
@ -1508,7 +1513,7 @@ else, % main effects analysis
% SAmeanexo=mean(SAmomN(:,1:nshock)); % SAmeanexo=mean(SAmomN(:,1:nshock));
% figure, bar(latent'*SAcc), % figure, bar(latent'*SAcc),
hh=dyn_figure(options_); hh=dyn_figure(options_,'Name',['Identifiability indices in the ',fsuffix,' moments.']);
bar(sum(SAcc)), bar(sum(SAcc)),
set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
set(gca,'xlim',[0.5 npT+0.5]) set(gca,'xlim',[0.5 npT+0.5])
@ -1522,7 +1527,8 @@ else, % main effects analysis
xlabel(' ') xlabel(' ')
title(['Identifiability indices in the ',fsuffix,' moments.'],'interpreter','none') title(['Identifiability indices in the ',fsuffix,' moments.'],'interpreter','none')
dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],options_); dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],options_);
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],1,['Identifiability indices in the ',fsuffix,' moments.'],['ident_ALL',fsuffix]')
% figure, bar(SAmeanexo), % figure, bar(SAmeanexo),
% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:nshock]) % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:nshock])
% set(gca,'xlim',[0.5 nshock+0.5]) % set(gca,'xlim',[0.5 nshock+0.5])
@ -1541,3 +1547,19 @@ else, % main effects analysis
end end
return return
function []=create_TeX_loader(options_,figpath,ifig_number,caption,label_name)
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([figpath '.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by map_ident_.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s}\n',strrep(figpath,'\','/'));
fprintf(fidTeX,'\\caption{%s.}',caption);
fprintf(fidTeX,'\\label{Fig:%s:%u}\n',label_name,ifig_number);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end

View File

@ -1,8 +1,5 @@
function pdraw = prior_draw_gsa(init,rdraw) function pdraw = prior_draw_gsa(init,rdraw)
% Draws from the prior distributions % Draws from the prior distributions for use with Sensitivity Toolbox for DYNARE
% Adapted by M. Ratto from prior_draw (of DYNARE, copyright M. Juillard),
% for use with Sensitivity Toolbox for DYNARE
%
% %
% INPUTS % INPUTS
% o init [integer] scalar equal to 1 (first call) or 0. % o init [integer] scalar equal to 1 (first call) or 0.
@ -25,7 +22,7 @@ function pdraw = prior_draw_gsa(init,rdraw)
% Reference: % Reference:
% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006. % M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
% Copyright (C) 2012 Dynare Team % Copyright (C) 2012-2015 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -58,7 +55,7 @@ if init
[junk1,junk2,junk3,lb,ub,junk4] = set_prior(estim_params_,M_,options_); %Prepare bounds [junk1,junk2,junk3,lb,ub,junk4] = set_prior(estim_params_,M_,options_); %Prepare bounds
if ~isempty(bayestopt_) && any(bayestopt_.pshape > 0) if ~isempty(bayestopt_) && any(bayestopt_.pshape > 0)
% Set prior bounds % Set prior bounds
bounds = prior_bounds(bayestopt_,options_); bounds = prior_bounds(bayestopt_, options_.prior_trunc);
bounds.lb = max(bounds.lb,lb); bounds.lb = max(bounds.lb,lb);
bounds.ub = min(bounds.ub,ub); bounds.ub = min(bounds.ub,ub);
else % estimated parameters but no declared priors else % estimated parameters but no declared priors
@ -90,6 +87,9 @@ if init
% TO BE CHECKED % TO BE CHECKED
lbcum(i) = gamcdf(1/(bounds.ub(i)-p3(i)),p7(i)/2,2/p6(i)); lbcum(i) = gamcdf(1/(bounds.ub(i)-p3(i)),p7(i)/2,2/p6(i));
ubcum(i) = gamcdf(1/(bounds.lb(i)-p3(i)),p7(i)/2,2/p6(i)); ubcum(i) = gamcdf(1/(bounds.lb(i)-p3(i)),p7(i)/2,2/p6(i));
case 8
lbcum(i) = weibcdf(bounds.lb(i)-p3(i),p6(i),p7(i));
ubcum(i) = weibcdf(bounds.ub(i)-p3(i),p6(i),p7(i));
otherwise otherwise
% Nothing to do here. % Nothing to do here.
end end
@ -115,6 +115,8 @@ for i = 1:npar
case 6% INV-GAMMA2 distribution case 6% INV-GAMMA2 distribution
% TO BE CHECKED % TO BE CHECKED
pdraw(:,i) = 1./gaminv(rdraw(:,i),p7(i)/2,2/p6(i))+p3(i); pdraw(:,i) = 1./gaminv(rdraw(:,i),p7(i)/2,2/p6(i))+p3(i);
case 8
pdraw(:,i) = wblinv(rdraw(:,i),p6(i),p7(i))+p3(i);
otherwise otherwise
% Nothing to do here. % Nothing to do here.
end end

View File

@ -1,14 +1,17 @@
function [xcum] = priorcdf(para, pshape, p6, p7, p3, p4) function xcum = priorcdf(para, pshape, p6, p7, p3, p4)
% This procedure transforms x vectors into cumulative values
% This procedure transforms x vectors into cumulative values
% pshape: 0 is point mass, both para and p2 are ignored % pshape: 0 is point mass, both para and p2 are ignored
% 1 is BETA(mean,stdd) % 1 is BETA(mean,stdd)
% 2 is GAMMA(mean,stdd) % 2 is GAMMA(mean,stdd)
% 3 is NORMAL(mean,stdd) % 3 is NORMAL(mean,stdd)
% 4 is INVGAMMA(s^2,nu) % 4 is INVGAMMA(s^2,nu) type I
% 5 is UNIFORM [p1,p2] % 5 is UNIFORM [p1,p2]
% 6 is INNGAMMA(s^2,nu) type II
% 8 is WEIBULL(s, k)
% Adapted by M. Ratto from MJ priordens.m % Adapted by M. Ratto from MJ priordens.m
% Copyright (C) 2012 Dynare Team % Copyright (C) 2012-2015 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -25,43 +28,24 @@ function [xcum] = priorcdf(para, pshape, p6, p7, p3, p4)
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
nprio = length(pshape); for i=1:length(pshape)
switch pshape(i)
i = 1; case 1 % (generalized) BETA Prior
while i <= nprio; para(:,i) = (para(:,i)-p3(i))./(p4(i)-p3(i));
a = 0; xcum(:,i) = betainc(para(:,i),p6(i),p7(i));
b = 0; case 2 % GAMMA PRIOR
if pshape(i) == 1; % (generalized) BETA Prior xcum(:,i) = gamcdf(para(:,i)-p3(i),p6(i),p7(i));
% mu = (p1(i)-p3(i))/(p4(i)-p3(i)); case 3 % GAUSSIAN PRIOR
% stdd = p2(i)/(p4(i)-p3(i)); xcum(:,i) = 0.5 * erfc(-(para(:,i)-p6(i))/p7(i) ./ sqrt(2));
% a = (1-mu)*mu^2/stdd^2 - mu; case 4 % INVGAMMA1 PRIOR
% b = a*(1/mu - 1); xcum(:,i) = gamcdf(1./(para(:,i)-p3(i)).^2,p7(i)/2,2/p6(i));
%lnprior = lnprior + lpdfgbeta(para(i),a,b,p3(i),p4(i)) ; case 5 % UNIFORM PRIOR
para(:,i) = (para(:,i)-p3(i))./(p4(i)-p3(i)); xcum(:,i) = (para(:,i)-p3(i))./(p4(i)-p3(i));
% xcum(:,i) = betacdf(para(:,i),a,b) ; case 6 % INVGAMMA2 PRIOR
xcum(:,i) = betainc(para(:,i),p6(i),p7(i)); xcum(:,i) = gamcdf(1./(para(:,i)-p3(i)),p7(i)/2,2/p6(i));
elseif pshape(i) == 2; % GAMMA PRIOR case 8 % WEIBULL
% b = p2(i)^2/(p1(i)-p3(i)); xcum(:,i) = wblcdf(para(:,i)-p3(i),p6(i),p7(i));
% a = (p1(i)-p3(i))/b; otherwise
%lnprior = lnprior + lpdfgam(para(i)-p3(i),a,b); error('Unknown prior shape!')
% xcum(:,i) = gamcdf(para(:,i)-p3(i),a,b); end
xcum(:,i) = gamcdf(para(:,i)-p3(i),p6(i),p7(i)); end
elseif pshape(i) == 3; % GAUSSIAN PRIOR
%lnprior = lnprior + lpdfnorm(para(i),p1(i),p2(i));
% xcum(:,i) = normcdf(para(:,i),p1(i),p2(i));
xcum(:,i) = 0.5 * erfc(-(para(:,i)-p6(i))/p7(i) ./ sqrt(2));
elseif pshape(i) == 4; % INVGAMMA1 PRIOR
%lnprior = lnprior + lpdfig1(para(i),p1(i),p2(i));
% xcum(:,i) = gamcdf(1/para(:,i).^2,p2(i)/2,2/p1(i));
xcum(:,i) = gamcdf(1./(para(:,i)-p3(i)).^2,p7(i)/2,2/p6(i));
elseif pshape(i) == 5; % UNIFORM PRIOR
%lnprior = lnprior + log(1/(p2(i)-p1(i)));
xcum(:,i) = (para(:,i)-p3(i))./(p4(i)-p3(i));
elseif pshape(i) == 6; % INVGAMMA2 PRIOR
% lnprior = lnprior + lpdfig2(para(i),p1(i),p2(i));
% xcum(:,i) = gamcdf(1/para(:,i),p2(i)/2,2/p1(i));
xcum(:,i) = gamcdf(1./(para(:,i)-p3(i)),p7(i)/2,2/p6(i));
end;
i = i+1;
end;

View File

@ -24,7 +24,7 @@ function [gend, data] = read_data()
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_ bayestopt_ global options_
rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range); rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range);
@ -36,8 +36,7 @@ if options_.loglinear == 1 & ~options_.logdata
rawdata = log(rawdata); rawdata = log(rawdata);
end end
if options_.prefilter == 1 if options_.prefilter == 1
bayestopt_.mean_varobs = mean(rawdata,1); data = transpose(rawdata-ones(gend,1)* mean(rawdata,1));
data = transpose(rawdata-ones(gend,1)*bayestopt_.mean_varobs);
else else
data = transpose(rawdata); data = transpose(rawdata);
end end

View File

@ -56,7 +56,7 @@ pvalue_corr = options_gsa_.alpha2_redform;
pnames = M_.param_names(estim_params_.param_vals(:,1),:); pnames = M_.param_names(estim_params_.param_vals(:,1),:);
fname_ = M_.fname; fname_ = M_.fname;
bounds = prior_bounds(bayestopt_,options_); bounds = prior_bounds(bayestopt_, options_.prior_trunc);
if nargin==0, if nargin==0,
dirname=''; dirname='';
@ -189,6 +189,7 @@ for j=1:size(anamendo,1)
hold off, hold off,
title([namendo,' vs ', namexo ' - threshold [' num2str(threshold(1)) ' ' num2str(threshold(2)) ']'],'interpreter','none') title([namendo,' vs ', namexo ' - threshold [' num2str(threshold(1)) ' ' num2str(threshold(2)) ']'],'interpreter','none')
dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namexo],options_); dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namexo],options_);
create_TeX_loader(options_,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namexo],['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs ', namexo],[type '_' namendo,'_vs_', namexo])
end end
si(:,js) = NaN(np,1); si(:,js) = NaN(np,1);
delete([xdir, '/*threshold*.*']) delete([xdir, '/*threshold*.*'])
@ -255,8 +256,9 @@ for j=1:size(anamendo,1)
text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
end end
title([logflag,' ',namendo,' vs ',namexo],'interpreter','none') title([logflag,' ',namendo,' vs ',namexo],'interpreter','none')
if iplo==9, if iplo==9
dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_); dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_);
create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],[logflag,' ',namendo,' vs ',namexo],['redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)])
end end
end end
@ -265,6 +267,7 @@ for j=1:size(anamendo,1)
end end
if iplo<9 && iplo>0 && ifig && ~options_.nograph, if iplo<9 && iplo>0 && ifig && ~options_.nograph,
dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_); dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_);
create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],[logflag,' ',namendo,' vs ',namexo],['redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)])
end end
ifig=0; ifig=0;
iplo=0; iplo=0;
@ -322,6 +325,7 @@ for j=1:size(anamendo,1)
hold off, hold off,
title([namendo,' vs lagged ', namlagendo ' - threshold [' num2str(threshold(1)) ' ' num2str(threshold(2)) ']'],'interpreter','none') 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_); dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo],options_);
create_TeX_loader(options_,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo],['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs lagged ', namlagendo],[type '_' namendo,'_vs_', namlagendo])
end end
delete([xdir, '/*threshold*.*']) delete([xdir, '/*threshold*.*'])
@ -391,6 +395,7 @@ for j=1:size(anamendo,1)
title([logflag,' ',namendo,' vs ',namlagendo,'(-1)'],'interpreter','none') title([logflag,' ',namendo,' vs ',namlagendo,'(-1)'],'interpreter','none')
if iplo==9, if iplo==9,
dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_); dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_);
create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],[logflag,' ',namendo,' vs ',namlagendo,'(-1)'],[redform_', namendo,'_vs_lags_',logflag,':',num2str(ifig)])
end end
end end
@ -399,6 +404,7 @@ for j=1:size(anamendo,1)
end end
if iplo<9 && iplo>0 && ifig && ~options_.nograph, if iplo<9 && iplo>0 && ifig && ~options_.nograph,
dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_); dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_);
create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],[logflag,' ',namendo,' vs ',namlagendo,'(-1)'],[redform_', namendo,'_vs_lags_',logflag,':',num2str(ifig)])
end end
end end
@ -417,7 +423,8 @@ if isempty(threshold) && ~options_.nograph,
end end
title('Reduced form GSA') title('Reduced form GSA')
dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_gsa'],options_); dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_gsa'],options_);
create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_gsa'],'Reduced Form GSA','redform_gsa')
else else
hfig=dyn_figure(options_,'name','Reduced Form GSA'); %bar(silog) hfig=dyn_figure(options_,'name','Reduced Form GSA'); %bar(silog)
% boxplot(silog','whis',10,'symbol','r.') % boxplot(silog','whis',10,'symbol','r.')
@ -432,6 +439,7 @@ if isempty(threshold) && ~options_.nograph,
end end
title('Reduced form GSA - Log-transformed elements') title('Reduced form GSA - Log-transformed elements')
dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_gsa_log'],options_); dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_gsa_log'],options_);
create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_gsa_log'],'Reduced form GSA - Log-transformed elements','redform_gsa_log')
end end
end end
@ -602,7 +610,8 @@ end
title(['Out-of-sample prediction - R2=' num2str(r2,2)],'interpreter','none') title(['Out-of-sample prediction - R2=' num2str(r2,2)],'interpreter','none')
end end
dyn_saveas(hfig,fname,options_); dyn_saveas(hfig,fname,options_);
create_TeX_loader(options_,fname,['Out-of-sample prediction - R2=' num2str(r2,2)],'redform_gsa_log')
if options_.nodisplay if options_.nodisplay
close(hmap); close(hmap);
end end
@ -617,6 +626,8 @@ else
plot(y0,[yf y0],'.'), plot(y0,[yf y0],'.'),
title([namy,' vs ', namx,' pred'],'interpreter','none') title([namy,' vs ', namx,' pred'],'interpreter','none')
dyn_saveas(hfig,[fname '_pred'],options_); dyn_saveas(hfig,[fname '_pred'],options_);
create_TeX_loader(options_,[fname '_pred'],options_map.title,[namy,' vs ', namx,' pred'])
end end
end end
% si = gsa_.multivariate.si; % si = gsa_.multivariate.si;
@ -735,5 +746,21 @@ if ~isoctave
end end
dyn_saveas(hfig,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],options_); dyn_saveas(hfig,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],options_);
create_TeX_loader(options_,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],options_mcf.amcf_title,[options_mcf.fname_,'_',options_mcf.amcf_name])
return return
function []=create_TeX_loader(options_,figpath,caption,label_name)
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([figpath '.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by redform_map.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s}\n',strrep(figpath,'\','/'));
fprintf(fidTeX,'\\caption{%s.}',caption);
fprintf(fidTeX,'\\label{Fig:%s}\n',label_name);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end

View File

@ -90,7 +90,8 @@ for j=1:size(anamendo,1),
end end
title([namendo,' vs. ',namexo],'interpreter','none') title([namendo,' vs. ',namexo],'interpreter','none')
if iplo==9, if iplo==9,
dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],options_); dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],options_);
create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'])
end end
end end
@ -98,6 +99,7 @@ for j=1:size(anamendo,1),
end end
if iplo<9 && iplo>0 && ifig, if iplo<9 && iplo>0 && ifig,
dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shocks_',num2str(ifig)],options_); dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shocks_',num2str(ifig)],options_);
create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'])
end end
iplo=0; iplo=0;
@ -132,16 +134,18 @@ for j=1:size(anamendo,1),
title([namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none') title([namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none')
if iplo==9, if iplo==9,
dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_); dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_);
create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'])
end end
end end
end end
end end
if iplo<9 && iplo>0 && ifig, if iplo<9 && iplo>0 && ifig,
dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_); dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_);
create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'])
end end
end end
hh=dyn_figure(options_); hh=dyn_figure(options_,'Name','Reduced form screening');
%bar(SA) %bar(SA)
% boxplot(SA','whis',10,'symbol','r.') % boxplot(SA','whis',10,'symbol','r.')
myboxplot(SA',[],'.',[],10) myboxplot(SA',[],'.',[],10)
@ -156,3 +160,21 @@ xlabel(' ')
ylabel('Elementary Effects') ylabel('Elementary Effects')
title('Reduced form screening') title('Reduced form screening')
dyn_saveas(hh,[dirname,'/',M_.fname,'_redform_screen'],options_); dyn_saveas(hh,[dirname,'/',M_.fname,'_redform_screen'],options_);
create_TeX_loader(options_,[dirname,'/',M_.fname,'_redform_screen'],1,'Reduced form screening','redform_screen')
function []=create_TeX_loader(options_,figpath,label_number,caption,label_name)
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([figpath '.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by redform_screen.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s}\n',strrep(figpath,'\','/'));
fprintf(fidTeX,'\\caption{%s.}',caption);
fprintf(fidTeX,'\\label{Fig:%s:%u}\n',label_name,label_number);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end

View File

@ -164,4 +164,17 @@ end
if ~nograph, if ~nograph,
dyn_saveas(hh,[dirname,filesep,fig_nam_],DynareOptions); dyn_saveas(hh,[dirname,filesep,fig_nam_],DynareOptions);
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
fidTeX = fopen([dirname,'/',fig_nam_ '.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s}\n',[dirname,'/',fig_nam_]);
fprintf(fidTeX,'\\caption{%s.}',figtitle);
fprintf(fidTeX,'\\label{Fig:%s}\n',fig_nam_);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
end end

View File

@ -38,7 +38,7 @@ function x0 = stab_map_(OutputDirectoryName,opt_gsa)
% Reference: % Reference:
% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006. % M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
% Copyright (C) 2012-2013 Dynare Team % Copyright (C) 2012-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -99,7 +99,7 @@ p4 = bayestopt_.p4(nshock+1:end);
[junk1,junk2,junk3,lb,ub,junk4] = set_prior(estim_params_,M_,options_); %Prepare bounds [junk1,junk2,junk3,lb,ub,junk4] = set_prior(estim_params_,M_,options_); %Prepare bounds
if ~isempty(bayestopt_) && any(bayestopt_.pshape > 0) if ~isempty(bayestopt_) && any(bayestopt_.pshape > 0)
% Set prior bounds % Set prior bounds
bounds = prior_bounds(bayestopt_,options_); bounds = prior_bounds(bayestopt_, options_.prior_trunc);
bounds.lb = max(bounds.lb,lb); bounds.lb = max(bounds.lb,lb);
bounds.ub = min(bounds.ub,ub); bounds.ub = min(bounds.ub,ub);
else % estimated parameters but no declared priors else % estimated parameters but no declared priors
@ -130,7 +130,6 @@ options_.periods=0;
options_.nomoments=1; options_.nomoments=1;
options_.irf=0; options_.irf=0;
options_.noprint=1; options_.noprint=1;
options_.simul=0;
if fload==0, if fload==0,
% if prepSA % if prepSA
% T=zeros(size(dr_.ghx,1),size(dr_.ghx,2)+size(dr_.ghu,2),Nsam/2); % T=zeros(size(dr_.ghx,1),size(dr_.ghx,2)+size(dr_.ghu,2),Nsam/2);
@ -660,9 +659,7 @@ if isfield(opt,'nomoments'),
end end
options_.irf=opt.irf; options_.irf=opt.irf;
options_.noprint=opt.noprint; options_.noprint=opt.noprint;
if isfield(opt,'simul'),
options_.simul=opt.simul;
end

View File

@ -102,8 +102,34 @@ if iplot && ~options_.nograph
end end
if nparplot>12, if nparplot>12,
dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA_',int2str(i)],options_); dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA_',int2str(i)],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([dirname,filesep,fname_,'_',aname,'_SA_',int2str(i) '.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s}\n',[dirname,filesep,fname_,'_',aname,'_SA_',int2str(i)]);
fprintf(fidTeX,'\\caption{%s.}',atitle);
fprintf(fidTeX,'\\label{Fig:%s:%u}\n',atitle,i);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
else else
dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA'],options_); dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA'],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([dirname,filesep,fname_,'_',aname,'_SA.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s}\n',[dirname,filesep,fname_,'_',aname,'_SA']);
fprintf(fidTeX,'\\caption{%s.}',atitle);
fprintf(fidTeX,'\\label{Fig:%s}\n',atitle);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
end end
end end
end end

View File

@ -114,6 +114,19 @@ for j=1:npar,
title(['cc = ',num2str(c0(i2(jx),j))]) title(['cc = ',num2str(c0(i2(jx),j))])
if (mod(j2,12)==0) && j2>0, if (mod(j2,12)==0) && j2>0,
dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_); dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([dirname,filesep,fig_nam_,int2str(ifig),'.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s}\n',[dirname,filesep,fig_nam_,int2str(ifig)]);
fprintf(fidTeX,'\\caption{%s.}',[figtitle,' sample bivariate projection ', num2str(ifig)]);
fprintf(fidTeX,'\\label{Fig:%s:%u}\n',fig_nam_,ifig);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
end end
end end
end end
@ -122,6 +135,19 @@ for j=1:npar,
end end
if ~nograph && (j==(npar)) && j2>0 && (mod(j2,12)~=0), if ~nograph && (j==(npar)) && j2>0 && (mod(j2,12)~=0),
dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_); dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([dirname,filesep,fig_nam_,int2str(ifig),'.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s}\n',[dirname,filesep,fig_nam_,int2str(ifig)]);
fprintf(fidTeX,'\\caption{%s.}',[figtitle,' sample bivariate projection ', num2str(ifig)]);
fprintf(fidTeX,'\\label{Fig:%s:%u}\n',fig_nam_,ifig);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
end end
end end

View File

@ -73,14 +73,22 @@ for ll = 1:n,
fprintf(fidTeX,['%% ' datestr(now,0)]); fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n'); fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n'); fprintf(fidTeX,' \n');
fprintf(fidTeX,'{\\tiny \n'); fprintf(fidTeX,'{\\tiny \n');
fprintf(fidTeX,'\\begin{table}\n'); fprintf(fidTeX,'\\begin{longtable}{llc} \n');
fprintf(fidTeX,'\\centering\n'); fprintf(fidTeX,['\\caption{Collinearity patterns with ',int2str(ll),' parameter(s)}\n ']);
fprintf(fidTeX,'\\begin{tabular}{l|lc} \n'); fprintf(fidTeX,['\\label{Table:CollinearityPatterns:',int2str(ll),'}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n'); fprintf(fidTeX,'\\toprule \n');
fprintf(fidTeX,' Parameter & Explanatory & cosn \\\\ \n'); fprintf(fidTeX,' Parameter & Explanatory & cosn \\\\ \n');
fprintf(fidTeX,' & parameter(s) & \\\\ \n'); fprintf(fidTeX,' & parameter(s) & \\\\ \n');
fprintf(fidTeX,'\\hline \\\\ \n'); fprintf(fidTeX,'\\midrule \\endfirsthead \n');
fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
fprintf(fidTeX,'\\bottomrule \n');
fprintf(fidTeX,' Parameter & Explanatory & cosn \\\\ \n');
fprintf(fidTeX,' & parameter(s) & \\\\ \n');
fprintf(fidTeX,'\\midrule \\endhead \n');
fprintf(fidTeX,'\\bottomrule \\multicolumn{3}{r}{(Continued on next page)}\\endfoot \n');
fprintf(fidTeX,'\\bottomrule\\endlastfoot \n');
for i=1:k, for i=1:k,
plist=''; plist='';
for ii=1:ll, for ii=1:ll,
@ -93,11 +101,8 @@ for ll = 1:n,
plist,... plist,...
cosnJ(i,ll)); cosnJ(i,ll));
end end
fprintf(fidTeX,'\\hline\\hline \n'); fprintf(fidTeX,'\\bottomrule \n');
fprintf(fidTeX,'\\end{tabular}\n '); fprintf(fidTeX,'\\end{longtable}\n');
fprintf(fidTeX,['\\caption{Collinearity patterns with ',int2str(ll),' parameter(s)}\n ']);
fprintf(fidTeX,['\\label{Table:CollinearityPatterns:',int2str(ll),'}\n']);
fprintf(fidTeX,'\\end{table}\n');
fprintf(fidTeX,'} \n'); fprintf(fidTeX,'} \n');
fprintf(fidTeX,'%% End of TeX file.\n'); fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX); fclose(fidTeX);

View File

@ -147,7 +147,7 @@ if info(1)==0,
info = stoch_simul(char(options_.varobs)); info = stoch_simul(char(options_.varobs));
dataset_ = dseries(oo_.endo_simul(options_.varobs_id,100+1:end)',dates('1Q1'), options_.varobs); dataset_ = dseries(oo_.endo_simul(options_.varobs_id,100+1:end)',dates('1Q1'), options_.varobs);
derivatives_info.no_DLIK=1; derivatives_info.no_DLIK=1;
bounds = prior_bounds(bayestopt_,options_); bounds = prior_bounds(bayestopt_, options_.prior_trunc);
[fval,DLIK,AHess,cost_flag,ys,trend_coeff,info,M_,options_,bayestopt_,oo_] = dsge_likelihood(params',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_,derivatives_info); [fval,DLIK,AHess,cost_flag,ys,trend_coeff,info,M_,options_,bayestopt_,oo_] = dsge_likelihood(params',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_,derivatives_info);
% fval = DsgeLikelihood(xparam1,data_info,options_,M_,estim_params_,bayestopt_,oo_); % fval = DsgeLikelihood(xparam1,data_info,options_,M_,estim_params_,bayestopt_,oo_);
options_.analytic_derivation = analytic_derivation; options_.analytic_derivation = analytic_derivation;

View File

@ -19,7 +19,7 @@ function DynareResults = initial_estimation_checks(objective_function,xparam1,Dy
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2003-2015 Dynare Team % Copyright (C) 2003-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -40,6 +40,10 @@ function DynareResults = initial_estimation_checks(objective_function,xparam1,Dy
%singularity check %singularity check
maximum_number_non_missing_observations=max(sum(~isnan(DynareDataset.data),2)); maximum_number_non_missing_observations=max(sum(~isnan(DynareDataset.data),2));
if DynareOptions.order>1 && any(any(isnan(DynareDataset.data)))
error('initial_estimation_checks:: particle filtering does not support missing observations')
end
if maximum_number_non_missing_observations>Model.exo_nbr+EstimatedParameters.nvn if maximum_number_non_missing_observations>Model.exo_nbr+EstimatedParameters.nvn
error(['initial_estimation_checks:: Estimation can''t take place because there are less declared shocks than observed variables!']) error(['initial_estimation_checks:: Estimation can''t take place because there are less declared shocks than observed variables!'])
end end
@ -62,6 +66,10 @@ if DynareOptions.TaRB.use_TaRB && (DynareOptions.TaRB.new_block_probability<0 ||
error(['initial_estimation_checks:: The tarb_new_block_probability must be between 0 and 1!']) error(['initial_estimation_checks:: The tarb_new_block_probability must be between 0 and 1!'])
end end
if (any(BayesInfo.pshape >0 ) && DynareOptions.mh_replic) && DynareOptions.mh_nblck<1
error(['initial_estimation_checks:: Bayesian estimation cannot be conducted with mh_nblocks=0.'])
end
old_steady_params=Model.params; %save initial parameters for check if steady state changes param values old_steady_params=Model.params; %save initial parameters for check if steady state changes param values
% % check if steady state solves static model (except if diffuse_filter == 1) % % check if steady state solves static model (except if diffuse_filter == 1)
@ -78,7 +86,7 @@ if isfield(EstimatedParameters,'param_vals') && ~isempty(EstimatedParameters.par
if ~isempty(changed_par_indices) if ~isempty(changed_par_indices)
fprintf('\nThe steady state file internally changed the values of the following estimated parameters:\n') fprintf('\nThe steady state file internally changed the values of the following estimated parameters:\n')
disp(Model.param_names(changed_par_indices,:)); disp(Model.param_names(EstimatedParameters.param_vals(changed_par_indices,1),:));
fprintf('This will override the parameter values drawn from the proposal density and may lead to wrong results.\n') 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') fprintf('Check whether this is really intended.\n')
warning('The steady state file internally changes the values of the estimated parameters.') warning('The steady state file internally changes the values of the estimated parameters.')
@ -153,10 +161,12 @@ if info(1) > 0
print_info(info, DynareOptions.noprint, DynareOptions) print_info(info, DynareOptions.noprint, DynareOptions)
end end
if any(abs(DynareResults.steady_state(BayesInfo.mfys))>1e-9) && (DynareOptions.prefilter==1) if DynareOptions.prefilter==1
disp(['You are trying to estimate a model with a non zero steady state for the observed endogenous']) if (~DynareOptions.loglinear && any(abs(DynareResults.steady_state(BayesInfo.mfys))>1e-9)) || (DynareOptions.loglinear && any(abs(log(DynareResults.steady_state(BayesInfo.mfys)))>1e-9))
disp(['variables using demeaned data!']) disp(['You are trying to estimate a model with a non zero steady state for the observed endogenous'])
error('You should change something in your mod file...') disp(['variables using demeaned data!'])
error('You should change something in your mod file...')
end
end end
if ~isequal(DynareOptions.mode_compute,11) if ~isequal(DynareOptions.mode_compute,11)

View File

@ -85,7 +85,7 @@ notsteady = 1;
F_singular = 1; F_singular = 1;
s = 0; s = 0;
while notsteady & t<=last while notsteady && t<=last
s = t-start+1; s = t-start+1;
d_index = data_index{t}; d_index = data_index{t};
if isempty(d_index) if isempty(d_index)

View File

@ -0,0 +1 @@
list_of_functions = {'discretionary_policy_1', 'dsge_var_likelihood', 'dyn_first_order_solver', 'dyn_waitbar', 'ep_residuals', 'evaluate_likelihood', 'evaluate_smoother', 'prior_draw_gsa', 'identification_analysis', 'computeDLIK', 'univariate_computeDLIK', 'metropolis_draw', 'flag_implicit_skip_nan', 'moment_function', 'non_linear_dsge_likelihood', 'mr_hessian', 'masterParallel', 'auxiliary_initialization', 'auxiliary_particle_filter', 'conditional_filter_proposal', 'conditional_particle_filter', 'gaussian_filter', 'gaussian_filter_bank', 'gaussian_mixture_filter', 'gaussian_mixture_filter_bank', 'Kalman_filter', 'online_auxiliary_filter', 'sequential_importance_particle_filter', 'solve_model_for_online_filter', 'perfect_foresight_simulation', 'prior_draw', 'priordens', 'smm_objective'};

View File

@ -1,5 +1,5 @@
function [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,varargin) function [x,f,fvec,check]=lnsrch1(xold, fold, g, p, stpmax, func, j1, j2, tolx, varargin)
% function [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,varargin) % function [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,tolx,varargin)
% Computes the optimal step by minimizing the residual sum of squares % Computes the optimal step by minimizing the residual sum of squares
% %
% INPUTS % INPUTS
@ -11,6 +11,7 @@ function [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,varargin)
% func: name of the function % func: name of the function
% j1: equations index to be solved % j1: equations index to be solved
% j2: unknowns index % j2: unknowns index
% tolx: tolerance parameter
% varargin: list of arguments following j2 % varargin: list of arguments following j2
% %
% OUTPUTS % OUTPUTS
@ -23,7 +24,7 @@ function [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,varargin)
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2001-2010 Dynare Team % Copyright (C) 2001-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -40,15 +41,13 @@ function [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,varargin)
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_
alf = 1e-4 ; alf = 1e-4 ;
tolx = options_.solve_tolx;
alam = 1; alam = 1;
x = xold; x = xold;
nn = length(j2); nn = length(j2);
summ = sqrt(sum(p.*p)) ; summ = sqrt(p'*p);
if ~isfinite(summ) if ~isfinite(summ)
eq_number_string=[]; eq_number_string=[];
for ii=1:length(j1)-1 for ii=1:length(j1)-1
@ -73,7 +72,7 @@ if ~isfinite(summ)
end end
if summ > stpmax if summ > stpmax
p=p.*stpmax/summ ; p = p*stpmax/summ ;
end end
slope = g'*p ; slope = g'*p ;
@ -90,19 +89,16 @@ while 1
check = 1 ; check = 1 ;
return return
end end
x(j2) = xold(j2) + (alam*p) ; x(j2) = xold(j2) + (alam*p) ;
fvec = feval(func,x,varargin{:}) ; fvec = feval(func,x,varargin{:}) ;
fvec = fvec(j1); fvec = fvec(j1);
f = 0.5*fvec'*fvec ; f = 0.5*(fvec'*fvec) ;
if any(isnan(fvec)) if any(isnan(fvec))
alam = alam/2 ; alam = alam/2 ;
alam2 = alam ; alam2 = alam ;
f2 = f ; f2 = f ;
fold2 = fold ; fold2 = fold ;
else else
if f <= fold+alf*alam*slope if f <= fold+alf*alam*slope
check = 0; check = 0;
break ; break ;
@ -124,15 +120,11 @@ while 1
else else
tmplam = (-b+sqrt(disc))/(3*a) ; tmplam = (-b+sqrt(disc))/(3*a) ;
end end
end end
if tmplam > 0.5*alam if tmplam > 0.5*alam
tmplam = 0.5*alam; tmplam = 0.5*alam;
end end
end end
alam2 = alam ; alam2 = alam ;
f2 = f ; f2 = f ;
fold2 = fold ; fold2 = fold ;

View File

@ -10,7 +10,7 @@ function info = load_last_mh_history_file(MetropolisFolder, ModelName)
% Notes: The record structure is written to the caller workspace via an % Notes: The record structure is written to the caller workspace via an
% assignin statement. % assignin statement.
% Copyright (C) 2013 Dynare Team % Copyright (C) 2013-16 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -53,6 +53,7 @@ if format_mh_history_file %needed to preserve backward compatibility
record.AcceptanceRatio = record.AcceptationRates; record.AcceptanceRatio = record.AcceptationRates;
record.InitialSeeds = NaN; % This information is forever lost... record.InitialSeeds = NaN; % This information is forever lost...
record.MCMCConcludedSuccessfully = NaN; % This information is forever lost... record.MCMCConcludedSuccessfully = NaN; % This information is forever lost...
record.MAX_nruns=NaN(size(record.MhDraws,1),1); % This information is forever lost...
record = rmfield(record,'LastLogLiK'); record = rmfield(record,'LastLogLiK');
record = rmfield(record,'InitialLogLiK'); record = rmfield(record,'InitialLogLiK');
record = rmfield(record,'Seeds'); record = rmfield(record,'Seeds');
@ -64,6 +65,9 @@ else
if ~isfield(record,'MCMCConcludedSuccessfully') if ~isfield(record,'MCMCConcludedSuccessfully')
record.MCMCConcludedSuccessfully = NaN; % This information is forever lost... record.MCMCConcludedSuccessfully = NaN; % This information is forever lost...
end end
if ~isfield(record,'MAX_nruns')
record.MAX_nruns=NaN(size(record.MhDraws,1),1); % This information is forever lost...
end
end end
if isequal(nargout,0) if isequal(nargout,0)

View File

@ -3,8 +3,8 @@ function [ldens,Dldens,D2ldens] = lpdfgam(x,a,b);
% %
% INPUTS % INPUTS
% x [double] m*n matrix of locations, % x [double] m*n matrix of locations,
% a [double] m*n matrix or scalar, First GAMMA distribution parameters, % a [double] m*n matrix or scalar, First GAMMA distribution parameters (shape),
% b [double] m*n matrix or scalar, Second GAMMA distribution parameters, % b [double] m*n matrix or scalar, Second GAMMA distribution parameters (scale),
% %
% OUTPUTS % OUTPUTS
% ldens [double] m*n matrix of logged GAMMA densities evaluated at x. % ldens [double] m*n matrix of logged GAMMA densities evaluated at x.
@ -13,7 +13,7 @@ function [ldens,Dldens,D2ldens] = lpdfgam(x,a,b);
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 2003-2011 Dynare Team % Copyright (C) 2003-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %

View File

@ -1,6 +1,6 @@
function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck, nruns, NewFile, MAX_nruns, d ] = ... function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npar, NumberOfBlocks, 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(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 ] = ... % function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npar, NumberOfBlocks, 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(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
% Metropolis-Hastings initialization. % Metropolis-Hastings initialization.
% %
@ -19,16 +19,16 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck,
% o oo_ outputs structure % o oo_ outputs structure
% %
% OUTPUTS % OUTPUTS
% o ix2 [double] (nblck*npar) vector of starting points for different chains % o ix2 [double] (NumberOfBlocks*npar) vector of starting points for different chains
% o ilogpo2 [double] (nblck*1) vector of initial posterior values for different chains % o ilogpo2 [double] (NumberOfBlocks*1) vector of initial posterior values for different chains
% o ModelName [string] name of the mod-file % o ModelName [string] name of the mod-file
% o MetropolisFolder [string] path to the Metropolis subfolder % 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 FirstBlock [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 FirstLine [double] (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery)
% o npar [scalar] number of parameters estimated % o npar [scalar] number of parameters estimated
% o nblck [scalar] Number of MCM chains requested % o NumberOfBlocks [scalar] Number of MCM chains requested
% o nruns [double] (nblck*1) number of draws in each chain % o nruns [double] (NumberOfBlocks*1) number of draws in each chain
% o NewFile [scalar] (nblck*1) vector storing the number % o NewFile [scalar] (NumberOfBlocks*1) vector storing the number
% of the first MH-file to created for each chain when saving additional % of the first MH-file to created for each chain when saving additional
% draws % draws
% o MAX_nruns [scalar] maximum number of draws in each MH-file on the harddisk % o MAX_nruns [scalar] maximum number of draws in each MH-file on the harddisk
@ -59,10 +59,10 @@ ix2 = [];
ilogpo2 = []; ilogpo2 = [];
ModelName = []; ModelName = [];
MetropolisFolder = []; MetropolisFolder = [];
fblck = []; FirstBlock = [];
fline = []; FirstLine = [];
npar = []; npar = [];
nblck = []; NumberOfBlocks = [];
nruns = []; nruns = [];
NewFile = []; NewFile = [];
MAX_nruns = []; MAX_nruns = [];
@ -76,15 +76,15 @@ end
MetropolisFolder = CheckPath('metropolis',M_.dname); MetropolisFolder = CheckPath('metropolis',M_.dname);
BaseName = [MetropolisFolder filesep ModelName]; BaseName = [MetropolisFolder filesep ModelName];
nblck = options_.mh_nblck; NumberOfBlocks = options_.mh_nblck;
nruns = ones(nblck,1)*options_.mh_replic; nruns = ones(NumberOfBlocks,1)*options_.mh_replic;
npar = length(xparam1); npar = length(xparam1);
MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8); MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8);
d = chol(vv); d = chol(vv);
if ~options_.load_mh_file && ~options_.mh_recover 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 if NumberOfBlocks > 1
disp('Estimation::mcmc: Multiple chains mode.') disp('Estimation::mcmc: Multiple chains mode.')
else else
disp('Estimation::mcmc: One Chain mode.') disp('Estimation::mcmc: One Chain mode.')
@ -108,16 +108,17 @@ if ~options_.load_mh_file && ~options_.mh_recover
fprintf(fidlog,' \n\n'); fprintf(fidlog,' \n\n');
fprintf(fidlog,'%% Session 1.\n'); fprintf(fidlog,'%% Session 1.\n');
fprintf(fidlog,' \n'); fprintf(fidlog,' \n');
fprintf(fidlog,[' Number of blocks...............: ' int2str(nblck) '\n']); fprintf(fidlog,[' Number of blocks...............: ' int2str(NumberOfBlocks) '\n']);
fprintf(fidlog,[' Number of simulations per block: ' int2str(nruns(1)) '\n']); fprintf(fidlog,[' Number of simulations per block: ' int2str(nruns(1)) '\n']);
fprintf(fidlog,' \n'); fprintf(fidlog,' \n');
% Find initial values for the nblck chains... % Find initial values for the NumberOfBlocks chains...
if nblck > 1% Case 1: multiple chains if NumberOfBlocks > 1% Case 1: multiple chains
set_dynare_seed('default');
fprintf(fidlog,[' Initial values of the parameters:\n']); fprintf(fidlog,[' Initial values of the parameters:\n']);
disp('Estimation::mcmc: Searching for initial values...') disp('Estimation::mcmc: Searching for initial values...')
ix2 = zeros(nblck,npar); ix2 = zeros(NumberOfBlocks,npar);
ilogpo2 = zeros(nblck,1); ilogpo2 = zeros(NumberOfBlocks,1);
for j=1:nblck for j=1:NumberOfBlocks
validate = 0; validate = 0;
init_iter = 0; init_iter = 0;
trial = 1; trial = 1;
@ -183,22 +184,23 @@ if ~options_.load_mh_file && ~options_.mh_recover
fprintf(fidlog,' \n'); fprintf(fidlog,' \n');
end end
fprintf(fidlog,' \n'); fprintf(fidlog,' \n');
fblck = 1; FirstBlock = 1;
fline = ones(nblck,1); FirstLine = ones(NumberOfBlocks,1);
NewFile = ones(nblck,1); NewFile = ones(NumberOfBlocks,1);
% Delete the mh-history files % Delete the mh-history files
delete_mh_history_files(MetropolisFolder, ModelName); delete_mh_history_files(MetropolisFolder, ModelName);
% Create a new record structure % Create a new record structure
fprintf(['Estimation::mcmc: Write details about the MCMC... ']); fprintf(['Estimation::mcmc: Write details about the MCMC... ']);
AnticipatedNumberOfFiles = ceil(nruns(1)/MAX_nruns); AnticipatedNumberOfFiles = ceil(nruns(1)/MAX_nruns);
AnticipatedNumberOfLinesInTheLastFile = nruns(1) - (AnticipatedNumberOfFiles-1)*MAX_nruns; AnticipatedNumberOfLinesInTheLastFile = nruns(1) - (AnticipatedNumberOfFiles-1)*MAX_nruns;
record.Nblck = nblck; record.Nblck = NumberOfBlocks;
record.MhDraws = zeros(1,3); record.MhDraws = zeros(1,3);
record.MhDraws(1,1) = nruns(1); record.MhDraws(1,1) = nruns(1);
record.MhDraws(1,2) = AnticipatedNumberOfFiles; record.MhDraws(1,2) = AnticipatedNumberOfFiles;
record.MhDraws(1,3) = AnticipatedNumberOfLinesInTheLastFile; record.MhDraws(1,3) = AnticipatedNumberOfLinesInTheLastFile;
record.AcceptanceRatio = zeros(1,nblck); record.MAX_nruns=MAX_nruns;
for j=1:nblck record.AcceptanceRatio = zeros(1,NumberOfBlocks);
for j=1:NumberOfBlocks
% we set a different seed for the random generator for each block then we record the corresponding random generator state (vector) % we set a different seed for the random generator for each block then we record the corresponding random generator state (vector)
set_dynare_seed(options_.DynareRandomStreams.seed+j); set_dynare_seed(options_.DynareRandomStreams.seed+j);
% record.Seeds keeps a vector of the random generator state and not the scalar seed despite its name % record.Seeds keeps a vector of the random generator state and not the scalar seed despite its name
@ -206,8 +208,8 @@ if ~options_.load_mh_file && ~options_.mh_recover
end end
record.InitialParameters = ix2; record.InitialParameters = ix2;
record.InitialLogPost = ilogpo2; record.InitialLogPost = ilogpo2;
record.LastParameters = zeros(nblck,npar); record.LastParameters = zeros(NumberOfBlocks,npar);
record.LastLogPost = zeros(nblck,1); record.LastLogPost = zeros(NumberOfBlocks,1);
record.LastFileNumber = AnticipatedNumberOfFiles ; record.LastFileNumber = AnticipatedNumberOfFiles ;
record.LastLineNumber = AnticipatedNumberOfLinesInTheLastFile; record.LastLineNumber = AnticipatedNumberOfLinesInTheLastFile;
record.MCMCConcludedSuccessfully = 0; record.MCMCConcludedSuccessfully = 0;
@ -219,7 +221,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
fprintf(fidlog,[' Expected number of files per block.......: ' int2str(AnticipatedNumberOfFiles) '.\n']); fprintf(fidlog,[' Expected number of files per block.......: ' int2str(AnticipatedNumberOfFiles) '.\n']);
fprintf(fidlog,[' Expected number of lines in the last file: ' int2str(AnticipatedNumberOfLinesInTheLastFile) '.\n']); fprintf(fidlog,[' Expected number of lines in the last file: ' int2str(AnticipatedNumberOfLinesInTheLastFile) '.\n']);
fprintf(fidlog,['\n']); fprintf(fidlog,['\n']);
for j = 1:nblck, for j = 1:NumberOfBlocks,
fprintf(fidlog,[' Initial state of the Gaussian random number generator for chain number ',int2str(j),':\n']); fprintf(fidlog,[' Initial state of the Gaussian random number generator for chain number ',int2str(j),':\n']);
for i=1:length(record.InitialSeeds(j).Normal) for i=1:length(record.InitialSeeds(j).Normal)
fprintf(fidlog,[' ' num2str(record.InitialSeeds(j).Normal(i)') '\n']); fprintf(fidlog,[' ' num2str(record.InitialSeeds(j).Normal(i)') '\n']);
@ -247,30 +249,30 @@ elseif options_.load_mh_file && ~options_.mh_recover
fprintf(fidlog,'\n'); fprintf(fidlog,'\n');
fprintf(fidlog,['%% Session ' int2str(length(record.MhDraws(:,1))+1) '.\n']); fprintf(fidlog,['%% Session ' int2str(length(record.MhDraws(:,1))+1) '.\n']);
fprintf(fidlog,' \n'); fprintf(fidlog,' \n');
fprintf(fidlog,[' Number of blocks...............: ' int2str(nblck) '\n']); fprintf(fidlog,[' Number of blocks...............: ' int2str(NumberOfBlocks) '\n']);
fprintf(fidlog,[' Number of simulations per block: ' int2str(nruns(1)) '\n']); fprintf(fidlog,[' Number of simulations per block: ' int2str(nruns(1)) '\n']);
fprintf(fidlog,' \n'); fprintf(fidlog,' \n');
past_number_of_blocks = record.Nblck; past_number_of_blocks = record.Nblck;
if past_number_of_blocks ~= nblck if past_number_of_blocks ~= NumberOfBlocks
disp('Estimation::mcmc: The specified number of blocks doesn''t match with the previous number of blocks!') disp('Estimation::mcmc: The specified number of blocks doesn''t match with the previous number of blocks!')
disp(['Estimation::mcmc: You declared ' int2str(nblck) ' blocks, but the previous number of blocks was ' int2str(past_number_of_blocks) '.']) disp(['Estimation::mcmc: You declared ' int2str(NumberOfBlocks) ' blocks, but the previous number of blocks was ' int2str(past_number_of_blocks) '.'])
disp(['Estimation::mcmc: I will run the Metropolis-Hastings with ' int2str(past_number_of_blocks) ' blocks.' ]) disp(['Estimation::mcmc: I will run the Metropolis-Hastings with ' int2str(past_number_of_blocks) ' blocks.' ])
nblck = past_number_of_blocks; NumberOfBlocks = past_number_of_blocks;
options_.mh_nblck = nblck; options_.mh_nblck = NumberOfBlocks;
end 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; LastFileNumber = record.LastFileNumber;
LastLineNumber = record.LastLineNumber; LastLineNumber = record.LastLineNumber;
if LastLineNumber < MAX_nruns if LastLineNumber < MAX_nruns
NewFile = ones(nblck,1)*LastFileNumber; NewFile = ones(NumberOfBlocks,1)*LastFileNumber;
fline = ones(nblck,1)*(LastLineNumber+1); FirstLine = ones(NumberOfBlocks,1)*(LastLineNumber+1);
else else
NewFile = ones(nblck,1)*(LastFileNumber+1); NewFile = ones(NumberOfBlocks,1)*(LastFileNumber+1);
fline = ones(nblck,1); FirstLine = ones(NumberOfBlocks,1);
end end
ilogpo2 = record.LastLogPost; ilogpo2 = record.LastLogPost;
ix2 = record.LastParameters; ix2 = record.LastParameters;
fblck = 1; FirstBlock = 1;
NumberOfPreviousSimulations = sum(record.MhDraws(:,1),1); NumberOfPreviousSimulations = sum(record.MhDraws(:,1),1);
fprintf('Estimation::mcmc: I am writing a new mh-history file... '); fprintf('Estimation::mcmc: I am writing a new mh-history file... ');
record.MhDraws = [record.MhDraws;zeros(1,3)]; record.MhDraws = [record.MhDraws;zeros(1,3)];
@ -283,6 +285,7 @@ elseif options_.load_mh_file && ~options_.mh_recover
record.MhDraws(end,1) = nruns(1); record.MhDraws(end,1) = nruns(1);
record.MhDraws(end,2) = AnticipatedNumberOfFiles; record.MhDraws(end,2) = AnticipatedNumberOfFiles;
record.MhDraws(end,3) = AnticipatedNumberOfLinesInTheLastFile; record.MhDraws(end,3) = AnticipatedNumberOfLinesInTheLastFile;
record.MAX_nruns = [record.MAX_nruns;MAX_nruns];
record.InitialSeeds = record.LastSeeds; record.InitialSeeds = record.LastSeeds;
write_mh_history_file(MetropolisFolder, ModelName, record); write_mh_history_file(MetropolisFolder, ModelName, record);
fprintf('Done.\n') fprintf('Done.\n')
@ -293,83 +296,143 @@ elseif options_.mh_recover
% The previous metropolis-hastings crashed before the end! I try to recover the saved draws... % The previous metropolis-hastings crashed before the end! I try to recover the saved draws...
disp('Estimation::mcmc: Recover mode!') disp('Estimation::mcmc: Recover mode!')
load_last_mh_history_file(MetropolisFolder, ModelName); load_last_mh_history_file(MetropolisFolder, ModelName);
nblck = record.Nblck;% Number of "parallel" mcmc chains. NumberOfBlocks = record.Nblck;% Number of "parallel" mcmc chains.
options_.mh_nblck = nblck; options_.mh_nblck = NumberOfBlocks;
%% check consistency of options
if record.MhDraws(end,1)~=options_.mh_replic
fprintf('\nEstimation::mcmc: You cannot specify a different mh_replic than in the chain you are trying to recover\n')
fprintf('Estimation::mcmc: I am resetting mh_replic to %u\n',record.MhDraws(end,1))
options_.mh_replic=record.MhDraws(end,1);
nruns = ones(NumberOfBlocks,1)*options_.mh_replic;
end
if ~isnan(record.MAX_nruns(end,1)) %field exists
if record.MAX_nruns(end,1)~=MAX_nruns
fprintf('\nEstimation::mcmc: You cannot specify a different MaxNumberOfBytes than in the chain you are trying to recover\n')
fprintf('Estimation::mcmc: I am resetting MAX_nruns to %u\n',record.MAX_nruns(end,1))
MAX_nruns=record.MAX_nruns(end,1);
end
end
%% do tentative initialization as if full last run of MCMC were to be redone
if size(record.MhDraws,1) == 1 if size(record.MhDraws,1) == 1
OldMh = 0;% The crashed metropolis was the first session. OldMhExists = 0;% The crashed metropolis was the first session.
else else
OldMh = 1;% The crashed metropolis wasn't the first session. OldMhExists = 1;% The crashed metropolis wasn't the first session.
end end
% Default initialization: % Default initialization:
if OldMh if OldMhExists
ilogpo2 = record.LastLogPost; ilogpo2 = record.LastLogPost;
ix2 = record.LastParameters; ix2 = record.LastParameters;
else else
ilogpo2 = record.InitialLogPost; ilogpo2 = record.InitialLogPost;
ix2 = record.InitialParameters; ix2 = record.InitialParameters;
end end
% Set NewFile, a nblck*1 vector of integers, and fline (first line), a nblck*1 vector of integers. % Set NewFile, a NumberOfBlocks*1 vector of integers, and FirstLine (first line), a NumberOfBlocks*1 vector of integers.
if OldMh % Relevant for starting at the correct file and potentially filling a file from the previous run that was not yet full
if OldMhExists
LastLineNumberInThePreviousMh = record.MhDraws(end-1,3);% Number of lines in the last mh files of the previous session. LastLineNumberInThePreviousMh = record.MhDraws(end-1,3);% Number of lines in the last mh files of the previous session.
LastFileNumberInThePreviousMh = sum(record.MhDraws(1:end-1,2),1);% Number of mh files in the the previous sessions. LastFileNumberInThePreviousMh = sum(record.MhDraws(1:end-1,2),1);% Number of mh files in the the previous sessions.
if LastLineNumberInThePreviousMh < MAX_nruns% Test if the last mh files of the previous session are not complete (yes) %Test if the last mh files of the previous session were not full yet
NewFile = ones(nblck,1)*LastFileNumberInThePreviousMh; if LastLineNumberInThePreviousMh < MAX_nruns%not full
fline = ones(nblck,1)*(LastLineNumberInThePreviousMh+1); %store starting point if whole chain needs to be redone
else% The last mh files of the previous session are complete. NewFile = ones(NumberOfBlocks,1)*LastFileNumberInThePreviousMh;
NewFile = ones(nblck,1)*(LastFileNumberInThePreviousMh+1); FirstLine = ones(NumberOfBlocks,1)*(LastLineNumberInThePreviousMh+1);
fline = ones(nblck,1); LastFileFullIndicator=0;
else% The last mh files of the previous session were full
%store starting point if whole chain needs to be redone
NewFile = ones(NumberOfBlocks,1)*(LastFileNumberInThePreviousMh+1);
FirstLine = ones(NumberOfBlocks,1);
LastFileFullIndicator=1;
end end
else else
LastLineNumberInThePreviousMh = 0; LastLineNumberInThePreviousMh = 0;
LastFileNumberInThePreviousMh = 0; LastFileNumberInThePreviousMh = 0;
NewFile = ones(nblck,1); NewFile = ones(NumberOfBlocks,1);
fline = ones(nblck,1); FirstLine = ones(NumberOfBlocks,1);
LastFileFullIndicator=1;
end end
% Set fblck (First block), an integer targeting the crashed mcmc chain.
fblck = 1; %% Now find out what exactly needs to be redone
% 1. Check if really something needs to be done
% How many mh files should we have ? % How many mh files should we have ?
ExpectedNumberOfMhFilesPerBlock = sum(record.MhDraws(:,2),1); ExpectedNumberOfMhFilesPerBlock = sum(record.MhDraws(:,2),1);
ExpectedNumberOfMhFiles = ExpectedNumberOfMhFilesPerBlock*nblck; ExpectedNumberOfMhFiles = ExpectedNumberOfMhFilesPerBlock*NumberOfBlocks;
% I count the total number of saved mh files... % How many mh files do we actually have ?
AllMhFiles = dir([BaseName '_mh*_blck*.mat']); AllMhFiles = dir([BaseName '_mh*_blck*.mat']);
TotalNumberOfMhFiles = length(AllMhFiles); TotalNumberOfMhFiles = length(AllMhFiles);
% And I quit if I can't find a crashed mcmc chain. % Quit if no crashed mcmc chain can be found as there are as many files as expected
if (TotalNumberOfMhFiles==ExpectedNumberOfMhFiles) if (TotalNumberOfMhFiles==ExpectedNumberOfMhFiles)
disp('Estimation::mcmc: It appears that you don''t need to use the mh_recover option!') 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(' You have to edit the mod file and remove the mh_recover option')
disp(' in the estimation command') disp(' in the estimation command')
error('Estimation::mcmc: mh_recover option not required!') error('Estimation::mcmc: mh_recover option not required!')
end end
% I count the number of saved mh files per block. % 2. Something needs to be done; find out what
NumberOfMhFilesPerBlock = zeros(nblck,1); % Count the number of saved mh files per block.
for b = 1:nblck NumberOfMhFilesPerBlock = zeros(NumberOfBlocks,1);
for b = 1:NumberOfBlocks
BlckMhFiles = dir([BaseName '_mh*_blck' int2str(b) '.mat']); BlckMhFiles = dir([BaseName '_mh*_blck' int2str(b) '.mat']);
NumberOfMhFilesPerBlock(b) = length(BlckMhFiles); NumberOfMhFilesPerBlock(b) = length(BlckMhFiles);
end end
% Is there a chain with less mh files than expected ? % Find FirstBlock (First block), an integer targeting the crashed mcmc chain.
while fblck <= nblck FirstBlock = 1; %initialize
if NumberOfMhFilesPerBlock(fblck) < ExpectedNumberOfMhFilesPerBlock while FirstBlock <= NumberOfBlocks
disp(['Estimation::mcmc: Chain ' int2str(fblck) ' is not complete!']) if NumberOfMhFilesPerBlock(FirstBlock) < ExpectedNumberOfMhFilesPerBlock
disp(['Estimation::mcmc: Chain ' int2str(FirstBlock) ' is not complete!'])
break break
% The mh_recover session will start from chain fblck. % The mh_recover session will start from chain FirstBlock.
else else
disp(['Estimation::mcmc: Chain ' int2str(fblck) ' is complete!']) disp(['Estimation::mcmc: Chain ' int2str(FirstBlock) ' is complete!'])
end end
fblck = fblck+1; FirstBlock = FirstBlock+1;
end end
%% 3. Overwrite default settings for
% How many mh-files are saved in this block? % How many mh-files are saved in this block?
NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(fblck); NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(FirstBlock);
% Correct the number of saved mh files if the crashed Metropolis was not the first session (so ExistingDrawsInLastMCFile=0; %initialize: no MCMC draws of current MCMC are in file from last run
% that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain % Check whether last present file is a file included in the last MCMC run
% of the current session). if ~LastFileFullIndicator
if OldMh if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only that last file exists, but no files from current MCMC
NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh; loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']);
%check whether that last file was filled
if size(loaded_results.x2,1)==MAX_nruns %file is full
NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one
FirstLine(FirstBlock) = 1; %use first line of next file
ExistingDrawsInLastMCFile=MAX_nruns-record.MhDraws(end-1,3);
else
ExistingDrawsInLastMCFile=0;
end
end
elseif LastFileFullIndicator
ExistingDrawsInLastMCFile=0;
if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only the last file exists, but no files from current MCMC
NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one
end
end end
NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh; % % 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 OldMhExists
% NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh;
% end
% NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh;
% Correct initial conditions. % Correct initial conditions.
if NumberOfSavedMhFiles if NumberOfSavedMhFilesInTheCrashedBlck<ExpectedNumberOfMhFilesPerBlock
load([BaseName '_mh' int2str(NumberOfSavedMhFiles) '_blck' int2str(fblck) '.mat']); loaded_results=load([BaseName '_mh' int2str(NumberOfSavedMhFilesInTheCrashedBlck) '_blck' int2str(FirstBlock) '.mat']);
ilogpo2(fblck) = logpo2(end); ilogpo2(FirstBlock) = loaded_results.logpo2(end);
ix2(fblck,:) = x2(end,:); ix2(FirstBlock,:) = loaded_results.x2(end,:);
nruns(FirstBlock)=nruns(FirstBlock)-ExistingDrawsInLastMCFile-(NumberOfSavedMhFilesInTheCrashedBlck-LastFileNumberInThePreviousMh)*MAX_nruns;
%reset seed if possible
if isfield(loaded_results,'LastSeeds')
record.InitialSeeds(FirstBlock).Unifor=loaded_results.LastSeeds.(['file' int2str(NumberOfSavedMhFilesInTheCrashedBlck)]).Unifor;
record.InitialSeeds(FirstBlock).Normal=loaded_results.LastSeeds.(['file' int2str(NumberOfSavedMhFilesInTheCrashedBlck)]).Normal;
else
fprintf('Estimation::mcmc: You are trying to recover a chain generated with an older Dynare version.\n')
fprintf('Estimation::mcmc: I am using the default seeds to continue the chain.\n')
end
write_mh_history_file(MetropolisFolder, ModelName, record);
end end
end end

View File

@ -0,0 +1,149 @@
function p = wblcdf(x, scale, shape) % --*-- Unitary tests --*--
% Cumulative distribution function for the Weibull distribution.
%
% INPUTS
% - x [double] Positive real scalar.
% - scale [double] Positive hyperparameter.
% - shape [double] Positive hyperparameter.
%
% OUTPUTS
% - p [double] Positive scalar between
% 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/>.
% Check input arguments.
if nargin<3
error('Three input arguments required!')
end
if ~isnumeric(x) || ~isscalar(x) || ~isreal(x)
error('First input argument must be a real scalar!')
end
if ~isnumeric(scale) || ~isscalar(scale) || ~isreal(scale) || scale<=0
error('Second input argument must be a real positive scalar (scale parameter of the Weibull distribution)!')
end
if ~isnumeric(shape) || ~isscalar(shape) || ~isreal(shape) || shape<=0
error('Third input argument must be a real positive scalar (shape parameter of the Weibull distribution)!')
end
% Filter trivial polar cases.
if x<=0
p = 0;
return
end
if isinf(x)
p = 1;
return
end
% Evaluate the CDF.
p = 1-exp(-(x/scale)^shape);
%@test:1
%$ try
%$ p = wblcdf(-1, .5, .1);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ % Check the results
%$ if t(1)
%$ t(2) = isequal(p, 0);
%$ end
%$ T = all(t);
%@eof:1
%@test:2
%$ try
%$ p = wblcdf(Inf, .5, .1);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ % Check the results
%$ if t(1)
%$ t(2) = isequal(p, 1);
%$ end
%$ T = all(t);
%@eof:2
%@test:3
%$ % Set the hyperparameters of a Weibull definition.
%$ scale = .5;
%$ shape = 1.5;
%$
%$ % Compute the median of the weibull distribution.
%$ m = scale*log(2)^(1/shape);
%$
%$ try
%$ p = wblcdf(m, scale, shape);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ % Check the results
%$ if t(1)
%$ t(2) = abs(p-.5)<1e-12;
%$ end
%$ T = all(t);
%@eof:3
%@test:4
%$ % Consistency check between wblinv and wblcdf.
%$
%$ % Set the hyperparameters of a Weibull definition.
%$ scale = .5;
%$ shape = 1.5;
%$
%$ % Compute quatiles of the weibull distribution.
%$ q = 0:.05:1;
%$ m = zeros(size(q));
%$ p = zeros(size(q));
%$ for i=1:length(q)
%$ m(i) = wblinv(q(i), scale, shape);
%$ end
%$
%$ try
%$ for i=1:length(q)
%$ p(i) = wblcdf(m(i), scale, shape);
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ % Check the results
%$ if t(1)
%$ for i=1:length(q)
%$ t(i+1) = abs(p(i)-q(i))<1e-12;
%$ end
%$ end
%$ T = all(t);
%@eof:4

View File

@ -0,0 +1,164 @@
function t = wblinv(proba, scale, shape) % --*-- Unitary tests --*--
% Inverse cumulative distribution function.
%
% INPUTS
% - proba [double] Probability, scalar between 0 and 1.
% - scale [double] Positive hyperparameter.
% - shape [double] Positive hyperparameter.
%
% OUTPUTS
% - t [double] scalar such that P(X<=t)=proba
% 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/>.
% Check input arguments.
if nargin<3
error('Three input arguments required!')
end
if ~isnumeric(proba) || ~isscalar(proba) || ~isreal(proba) || proba<0 || proba>1
error('First input argument must be a real scalar between 0 and 1 (probability)!')
end
if ~isnumeric(scale) || ~isscalar(scale) || ~isreal(scale) || scale<=0
error('Second input argument must be a real positive scalar (scale parameter of the Weibull distribution)!')
end
if ~isnumeric(shape) || ~isscalar(shape) || ~isreal(shape) || shape<=0
error('Third input argument must be a real positive scalar (shape parameter of the Weibull distribution)!')
end
if proba<2*eps()
t = 0;
return
end
if proba>1-2*eps()
t = Inf;
return
end
t = exp(log(scale)+log(-log(1-proba))/shape);
%@test:1
%$ try
%$ x = wblinv(0, 1, 2);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = isequal(x, 0);
%$ end
%$ T = all(t);
%@eof:1
%@test:2
%$ try
%$ x = wblinv(1, 1, 2);
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ t(2) = isinf(x);
%$ end
%$ T = all(t);
%@eof:2
%@test:3
%$ scales = [.5, 1, 5];
%$ shapes = [.1, 1, 2];
%$ x = NaN(9,1);
%$
%$ try
%$ k = 0;
%$ for i=1:3
%$ for j=1:3
%$ k = k+1;
%$ x(k) = wblinv(.5, scales(i), shapes(j));
%$ end
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ k = 1;
%$ for i=1:3
%$ for j=1:3
%$ k = k+1;
%$ t(k) = abs(x(k-1)-scales(i)*log(2)^(1/shapes(j)))<1e-12;
%$ end
%$ end
%$ end
%$ T = all(t);
%@eof:3
%@test:4
%$ debug = false;
%$ scales = [ .5, 1, 5];
%$ shapes = [ 1, 2, 3];
%$ x = NaN(9,1);
%$ p = 1e-1;
%$
%$ try
%$ k = 0;
%$ for i=1:3
%$ for j=1:3
%$ k = k+1;
%$ x(k) = wblinv(p, scales(i), shapes(j));
%$ end
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end
%$
%$ if t(1)
%$ k = 1;
%$ for i=1:3
%$ for j=1:3
%$ k = k+1;
%$ shape = shapes(j);
%$ scale = scales(i);
%$ density = @(z) exp(lpdfgweibull(z,shape,scale));
%$ if debug
%$ [shape, scale, x(k-1)]
%$ end
%$ if isoctave
%$ s = quadv(density, 0, x(k-1));
%$ else
%$ s = integral(density, 0, x(k-1));
%$ end
%$ if debug
%$ [s, abs(p-s)]
%$ end
%$ t(k) = abs(p-s)<1e-12;
%$ end
%$ end
%$ end
%$ T = all(t);
%@eof:4

View File

@ -0,0 +1,43 @@
function rnd = wblrnd(a, b)
% This function produces independent random variates from the Weibull distribution.
%
% INPUTS
% a [double] m*n matrix of positive parameters (scale).
% b [double] m*n matrix of positive parameters (shape).
%
% OUTPUT
% rnd [double] m*n matrix of independent variates from the beta(a,b) distribution.
% 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)
error('Two input arguments required!');
end
if (any(a(:)<0)) || (any(b(:)<0)) || (any(a(:)==Inf)) || (any(b(:)==Inf))
error('Input arguments must be finite and positive!');
end
[ma,na] = size(a);
[mb,nb] = size(b);
if ma~=mb || na~=nb
error('Input arguments must have the same size!');
end
rnd = a.*(-log(rand(ma, na))).^(1./b);

View File

@ -39,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 % Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98). % Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2015 Dynare Team % Copyright (C) 2004-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -116,7 +116,7 @@ while rank(Pinf(:,:,t+1),diffuse_kalman_tol) && t<smpl
alphahat = Inf; alphahat = Inf;
return return
else else
a(:,:,t+1) = T*a(:,:,t); a(:,t+1) = T*a(:,t);
Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+QQ; Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T); Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T);
end end
@ -125,7 +125,7 @@ while rank(Pinf(:,:,t+1),diffuse_kalman_tol) && t<smpl
Kstar(:,:,t) = Pstar(:,:,t)*ZZ'*iFstar(:,:,t); Kstar(:,:,t) = Pstar(:,:,t)*ZZ'*iFstar(:,:,t);
Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T); Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T);
Pstar(:,:,t+1) = T*(Pstar(:,:,t)-Pstar(:,:,t)*ZZ'*Kstar(:,:,t)')*T'+QQ; Pstar(:,:,t+1) = T*(Pstar(:,:,t)-Pstar(:,:,t)*ZZ'*Kstar(:,:,t)')*T'+QQ;
a(:,:,t+1) = T*(a(:,:,t)+Kstar(:,:,t)*v(:,t)); a(:,t+1) = T*(a(:,t)+Kstar(:,:,t)*v(:,t));
end end
end end
else else

View File

@ -197,9 +197,11 @@ for plt = 1:nbplt,
fprintf(fidTeX,'\\label{Fig:CheckPlots:%s}\n',int2str(plt)); fprintf(fidTeX,'\\label{Fig:CheckPlots:%s}\n',int2str(plt));
fprintf(fidTeX,'\\end{figure}\n'); fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n'); fprintf(fidTeX,' \n');
fclose(fidTeX);
end end
end end
if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
fclose(fidTeX);
end
OutputDirectoryName = CheckPath('modecheck',Model.dname); OutputDirectoryName = CheckPath('modecheck',Model.dname);
save([OutputDirectoryName '/check_plot_data'],'mcheck'); save([OutputDirectoryName '/check_plot_data'],'mcheck');

@ -1 +1 @@
Subproject commit cb29cec352522cf2e8b029a2febe5ae502f86859 Subproject commit f37d5230207dc4ddcb5a8fbe9c2ee21721db8e7c

@ -1 +1 @@
Subproject commit 34eb3107612dcb0c9371d83e9bd3c473d3c63e19 Subproject commit 6ded531eabbe6ee5f6be842805733b5e2c6e97b0

@ -1 +1 @@
Subproject commit ca8b9ee0319db287e70e4fcd9dcb38484ba15d85 Subproject commit 19ddc69ca430f3fa6afdb5588ebda7baced29302

View File

@ -166,7 +166,7 @@ Q = Model.Sigma_e;
H = Model.H; H = Model.H;
if ~issquare(Q) || EstimatedParameters.ncx || isfield(EstimatedParameters,'calibrated_covariances') if ~issquare(Q) || EstimatedParameters.ncx || isfield(EstimatedParameters,'calibrated_covariances')
[Q_is_positive_definite, penalty] = ispd(Q); [Q_is_positive_definite, penalty] = ispd(Q(EstimatedParameters.Sigma_e_entries_to_check_for_positive_definiteness,EstimatedParameters.Sigma_e_entries_to_check_for_positive_definiteness));
if ~Q_is_positive_definite if ~Q_is_positive_definite
fval = objective_function_penalty_base+penalty; fval = objective_function_penalty_base+penalty;
exit_flag = 0; exit_flag = 0;
@ -187,7 +187,7 @@ if ~issquare(Q) || EstimatedParameters.ncx || isfield(EstimatedParameters,'calib
end end
if ~issquare(H) || EstimatedParameters.ncn || isfield(EstimatedParameters,'calibrated_covariances_ME') if ~issquare(H) || EstimatedParameters.ncn || isfield(EstimatedParameters,'calibrated_covariances_ME')
[H_is_positive_definite, penalty] = ispd(H); [H_is_positive_definite, penalty] = ispd(H(EstimatedParameters.H_entries_to_check_for_positive_definiteness,EstimatedParameters.H_entries_to_check_for_positive_definiteness));
if ~H_is_positive_definite if ~H_is_positive_definite
fval = objective_function_penalty_base+penalty; fval = objective_function_penalty_base+penalty;
exit_flag = 0; exit_flag = 0;
@ -227,6 +227,21 @@ end
% Define a vector of indices for the observed variables. Is this really usefull?... % Define a vector of indices for the observed variables. Is this really usefull?...
BayesInfo.mf = BayesInfo.mf1; BayesInfo.mf = BayesInfo.mf1;
% Define the deterministic linear trend of the measurement equation.
if DynareOptions.noconstant
constant = zeros(DynareDataset.vobs,1);
else
constant = SteadyState(BayesInfo.mfys);
end
% Define the deterministic linear trend of the measurement equation.
if BayesInfo.with_trend
[trend_addition, trend_coeff]=compute_trend_coefficients(Model,DynareOptions,DynareDataset.vobs,DynareDataset.nobs);
trend = repmat(constant,1,DynareDataset.info.ntobs)+trend_addition;
else
trend = repmat(constant,1,DynareDataset.nobs);
end
% Get needed informations for kalman filter routines. % Get needed informations for kalman filter routines.
start = DynareOptions.presample+1; start = DynareOptions.presample+1;
np = size(T,1); np = size(T,1);

View File

@ -88,8 +88,8 @@ if isempty(hh)
end end
if max(htol0)>htol if max(htol0)>htol
skipline() skipline()
disp_verbose('Numerical noise in the likelihood') disp_verbose('Numerical noise in the likelihood',Verbose)
disp_verbose('Tolerance has to be relaxed') disp_verbose('Tolerance has to be relaxed',Verbose)
skipline() skipline()
end end
else else

View File

@ -21,7 +21,7 @@ function osr_res = osr(var_list,params,i_var,W)
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none. % none.
% %
% Copyright (C) 2001-2012 Dynare Team % Copyright (C) 2001-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -46,7 +46,7 @@ if isempty(options_.qz_criterium)
options_.qz_criterium = 1+1e-6; options_.qz_criterium = 1+1e-6;
end end
make_ex_; oo_=make_ex_(M_,options_,oo_);
np = size(params,1); np = size(params,1);
i_params = zeros(np,1); i_params = zeros(np,1);

View File

@ -12,7 +12,7 @@ function data_set = det_cond_forecast(varargin)
% dataset [dseries] Returns a dseries containing the forecasted endgenous variables and shocks % dataset [dseries] Returns a dseries containing the forecasted endgenous variables and shocks
% %
% %
% Copyright (C) 2013-2014 Dynare Team % Copyright (C) 2013-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -33,8 +33,9 @@ global options_ oo_ M_
pp = 2; pp = 2;
initial_conditions = oo_.steady_state; initial_conditions = oo_.steady_state;
verbosity = options_.verbosity; verbosity = options_.verbosity;
options_.verbosity = 0; if options_.periods == 0
options_.periods = 25;
end;
%We have to get an initial guess for the conditional forecast %We have to get an initial guess for the conditional forecast
% and terminal conditions for the non-stationary variables, we % and terminal conditions for the non-stationary variables, we
% use the first order approximation of the rational expectation solution. % use the first order approximation of the rational expectation solution.
@ -104,7 +105,14 @@ else
sym_dset = dset(dates(-range(1)):dates(range(range.ndat))); sym_dset = dset(dates(-range(1)):dates(range(range.ndat)));
periods = options_.periods + M_.maximum_lag + M_.maximum_lead; periods = options_.periods + M_.maximum_lag + M_.maximum_lead;
oo_.exo_simul = repmat(oo_.exo_steady_state',max(range.ndat + 1, periods),1); if isfield(oo_, 'exo_simul')
if size(oo_.exo_simul, 1) ~= max(range.ndat + 1, periods)
oo_.exo_simul = repmat(oo_.exo_steady_state',max(range.ndat + 1, periods),1);
end
else
oo_.exo_simul = repmat(oo_.exo_steady_state',max(range.ndat + 1, periods),1);
end
oo_.endo_simul = repmat(oo_.steady_state, 1, max(range.ndat + 1, periods)); oo_.endo_simul = repmat(oo_.steady_state, 1, max(range.ndat + 1, periods));
for i = 1:sym_dset.vobs for i = 1:sym_dset.vobs
@ -134,11 +142,19 @@ else
oo_.endo_simul(M_.aux_vars(i).endo_index, 1:sym_dset.nobs) = repmat(oo_.steady_state(M_.aux_vars(i).endo_index), 1, range.ndat + 1); oo_.endo_simul(M_.aux_vars(i).endo_index, 1:sym_dset.nobs) = repmat(oo_.steady_state(M_.aux_vars(i).endo_index), 1, range.ndat + 1);
end end
end end
%Compute the initial path using the first order solution around the %Compute the initial path using the the steady-state
% steady-state % steady-state
for jj = 2 : (options_.periods + 2) for jj = 2 : (options_.periods + 2)
oo_.endo_simul(:, jj) = oo_.steady_state; oo_.endo_simul(:, jj) = oo_.steady_state;
end end
missings = isnan(oo_.endo_simul(:,1));
if any(missings)
for jj = 1:M_.endo_nbr
if missings(jj)
oo_.endo_simul(jj,1) = oo_.steady_state(jj,1);
end
end
end
if options_.bytecode if options_.bytecode
save_options_dynatol_f = options_.dynatol.f; save_options_dynatol_f = options_.dynatol.f;
@ -165,6 +181,15 @@ else
end end
end end
data_set = [dset(dset.dates(1):(plan.date(1)-1)) ; data_set]; data_set = [dset(dset.dates(1):(plan.date(1)-1)) ; data_set];
for i=1:M_.exo_nbr
pos = find(strcmp(strtrim(M_.exo_names(i,:)),dset.name));
if isempty(pos)
data_set{strtrim(M_.exo_names(i,:))} = dseries(exo(1+M_.maximum_lag:end,i), plan.date(1), strtrim(M_.exo_names(i,:)));
else
data_set{strtrim(M_.exo_names(i,:))}(plan.date(1):plan.date(1)+ (size(exo, 1) - M_.maximum_lag)) = exo(1+M_.maximum_lag:end,i);
end
end
data_set = merge(dset(dset.dates(1):(plan.date(1)-1)), data_set);
return; return;
union_names = union(data_set.name, dset.name); union_names = union(data_set.name, dset.name);
dif = setdiff(union_names, data_set.name); dif = setdiff(union_names, data_set.name);
@ -387,8 +412,8 @@ if pf && ~surprise
indx_endo(col_count : col_count + constrained_periods - 1) = constrained_vars(j) + (time_index_constraint - 1) * ny; indx_endo(col_count : col_count + constrained_periods - 1) = constrained_vars(j) + (time_index_constraint - 1) * ny;
col_count = col_count + constrained_periods; col_count = col_count + constrained_periods;
end; end;
make_ex_; oo_=make_ex_(M_,options_,oo_);
make_y_; oo_=make_y_(M_,options_,oo_);
it = 1; it = 1;
convg = 0; convg = 0;
normra = 1e+50; normra = 1e+50;
@ -588,13 +613,13 @@ else
disp(['t=' int2str(t) ' conditional (surprise=' int2str(surprise) ' perfect foresight=' int2str(pf) ') unconditional (surprise=' int2str(b_surprise) ' perfect foresight=' int2str(b_pf) ')']); disp(['t=' int2str(t) ' conditional (surprise=' int2str(surprise) ' perfect foresight=' int2str(pf) ') unconditional (surprise=' int2str(b_surprise) ' perfect foresight=' int2str(b_pf) ')']);
disp('==============================================================================================='); disp('===============================================================================================');
if t == 1 if t == 1
make_ex_; oo_=make_ex_(M_,options_,oo_);
if maximum_lag > 0 if maximum_lag > 0
exo_init = oo_.exo_simul; exo_init = oo_.exo_simul;
else else
exo_init = zeros(size(oo_.exo_simul)); exo_init = zeros(size(oo_.exo_simul));
end end
make_y_; oo_=make_y_(M_,options_,oo_);
end; end;
%exo_init %exo_init
oo_.exo_simul = exo_init; oo_.exo_simul = exo_init;

View File

@ -1,18 +1,20 @@
function make_ex_() function oo_=make_ex_(M_,options_,oo_)
% forms oo_.exo_simul and oo_.exo_det_simul % forms oo_.exo_simul and oo_.exo_det_simul
% %
% INPUTS % INPUTS
% none % M_: Dynare model structure
% options_: Dynare options structure
% oo_: Dynare results structure
% %
% OUTPUTS % OUTPUTS
% none % oo_: Dynare results structure
% %
% ALGORITHM % ALGORITHM
% %
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% %
% Copyright (C) 1996-2014 Dynare Team % Copyright (C) 1996-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -29,7 +31,7 @@ function make_ex_()
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ oo_ ex0_ global ex0_
if isempty(oo_.exo_steady_state) if isempty(oo_.exo_steady_state)
oo_.exo_steady_state = zeros(M_.exo_nbr,1); oo_.exo_steady_state = zeros(M_.exo_nbr,1);

View File

@ -1,18 +1,22 @@
function make_y_() function oo_=make_y_(M_,options_,oo_)
% function make_y_ % function oo_=make_y_(M_,options_,oo_)
% forms oo_.endo_simul as guess values for deterministic simulations % forms oo_.endo_simul as guess values for deterministic simulations
% %
% INPUTS % INPUTS
% ... % M_: Dynare model structure
% options_: Dynare options structure
% oo_: Dynare results structure
%
% OUTPUTS % OUTPUTS
% ... % oo_: Dynare results structure
%
% ALGORITHM % ALGORITHM
% ... % ...
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% %
% Copyright (C) 1996-2014 Dynare Team % Copyright (C) 1996-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -29,7 +33,7 @@ function make_y_()
% You should have received a copy of the GNU General Public License % You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ oo_ ys0_ global ys0_
if options_.steadystate_flag if options_.steadystate_flag
[oo_.steady_state,M_.params,check] = ... [oo_.steady_state,M_.params,check] = ...

View File

@ -12,7 +12,7 @@ function perfect_foresight_setup()
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% none % none
% Copyright (C) 1996-2014 Dynare Team % Copyright (C) 1996-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -53,8 +53,8 @@ end
if ~options_.initval_file if ~options_.initval_file
if isempty(options_.datafile) if isempty(options_.datafile)
make_ex_; oo_=make_ex_(M_,options_,oo_);
make_y_; oo_=make_y_(M_,options_,oo_);
else else
read_data_; read_data_;
end end

View File

@ -13,7 +13,7 @@ function oo = sim1(M, options, oo)
% SPECIAL REQUIREMENTS % SPECIAL REQUIREMENTS
% None. % None.
% Copyright (C) 1996-2015 Dynare Team % Copyright (C) 1996-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -57,9 +57,11 @@ endo_simul = oo.endo_simul;
exo_simul = oo.exo_simul; exo_simul = oo.exo_simul;
i_cols_1 = nonzeros(lead_lag_incidence(2:3,:)'); i_cols_1 = nonzeros(lead_lag_incidence(2:3,:)');
i_cols_A1 = find(lead_lag_incidence(2:3,:)'); i_cols_A1 = find(lead_lag_incidence(2:3,:)');
i_cols_A1 = i_cols_A1(:);
i_cols_T = nonzeros(lead_lag_incidence(1:2,:)'); i_cols_T = nonzeros(lead_lag_incidence(1:2,:)');
i_cols_0 = nonzeros(lead_lag_incidence(2,:)'); i_cols_0 = nonzeros(lead_lag_incidence(2,:)');
i_cols_A0 = find(lead_lag_incidence(2,:)'); i_cols_A0 = find(lead_lag_incidence(2,:)');
i_cols_A0 = i_cols_A0(:);
i_cols_j = (1:nd)'; i_cols_j = (1:nd)';
i_upd = maximum_lag*ny+(1:periods*ny); i_upd = maximum_lag*ny+(1:periods*ny);
@ -92,6 +94,7 @@ for iter = 1:options.simul.maxit
i_rows = (1:ny)'; i_rows = (1:ny)';
i_cols_A = find(lead_lag_incidence'); i_cols_A = find(lead_lag_incidence');
i_cols_A = i_cols_A(:);
i_cols = i_cols_A+(maximum_lag-1)*ny; i_cols = i_cols_A+(maximum_lag-1)*ny;
m = 0; m = 0;
for it = (maximum_lag+1):(maximum_lag+periods) for it = (maximum_lag+1):(maximum_lag+periods)
@ -99,16 +102,16 @@ for iter = 1:options.simul.maxit
steady_state,it); steady_state,it);
if it == maximum_lag+periods && it == maximum_lag+1 if it == maximum_lag+periods && it == maximum_lag+1
[r,c,v] = find(jacobian(:,i_cols_0)); [r,c,v] = find(jacobian(:,i_cols_0));
iA((1:length(v))+m,:) = [i_rows(r),i_cols_A0(c),v]; iA((1:length(v))+m,:) = [i_rows(r(:)),i_cols_A0(c(:)),v(:)];
elseif it == maximum_lag+periods elseif it == maximum_lag+periods
[r,c,v] = find(jacobian(:,i_cols_T)); [r,c,v] = find(jacobian(:,i_cols_T));
iA((1:length(v))+m,:) = [i_rows(r),i_cols_A(i_cols_T(c)),v]; iA((1:length(v))+m,:) = [i_rows(r(:)),i_cols_A(i_cols_T(c(:))),v(:)];
elseif it == maximum_lag+1 elseif it == maximum_lag+1
[r,c,v] = find(jacobian(:,i_cols_1)); [r,c,v] = find(jacobian(:,i_cols_1));
iA((1:length(v))+m,:) = [i_rows(r),i_cols_A1(c),v]; iA((1:length(v))+m,:) = [i_rows(r(:)),i_cols_A1(c(:)),v(:)];
else else
[r,c,v] = find(jacobian(:,i_cols_j)); [r,c,v] = find(jacobian(:,i_cols_j));
iA((1:length(v))+m,:) = [i_rows(r),i_cols_A(c),v]; iA((1:length(v))+m,:) = [i_rows(r(:)),i_cols_A(c(:)),v(:)];
end end
m = m + length(v); m = m + length(v);

View File

@ -1,4 +1,4 @@
function plot_identification(params,idemoments,idehess,idemodel, idelre, advanced, tittxt, name, IdentifDirectoryName) function plot_identification(params,idemoments,idehess,idemodel, idelre, advanced, tittxt, name, IdentifDirectoryName,tit_TeX)
% function plot_identification(params,idemoments,idehess,idemodel, idelre, advanced, tittxt, name, IdentifDirectoryName) % function plot_identification(params,idemoments,idehess,idemodel, idelre, advanced, tittxt, name, IdentifDirectoryName)
% %
% INPUTS % INPUTS
@ -11,6 +11,7 @@ function plot_identification(params,idemoments,idehess,idemodel, idelre, advance
% o tittxt [char] name of the results to plot % o tittxt [char] name of the results to plot
% o name [char] list of names % o name [char] list of names
% o IdentifDirectoryName [char] directory name % o IdentifDirectoryName [char] directory name
% o tittxt [char] TeX-name of the results to plot
% %
% OUTPUTS % OUTPUTS
% None % None
@ -101,6 +102,19 @@ if SampleSize == 1,
else else
title('Sensitivity component with moments Information matrix (log-scale)') title('Sensitivity component with moments Information matrix (log-scale)')
end end
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([IdentifDirectoryName '/' M_.fname '_ident_strength_' tittxt1,'.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_ident_strength_%s}\n',[IdentifDirectoryName '/' M_.fname],tittxt1);
fprintf(fidTeX,'\\caption{%s - Identification using info from observables.}',tit_TeX);
fprintf(fidTeX,'\\label{Fig:ident:%s}\n',deblank(tittxt));
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_strength_' tittxt1],options_); dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_strength_' tittxt1],options_);
if advanced, if advanced,
@ -131,6 +145,19 @@ if SampleSize == 1,
legend('Moments','Model','LRE model','Location','Best') legend('Moments','Model','LRE model','Location','Best')
title('Sensitivity bars using derivatives (log-scale)') title('Sensitivity bars using derivatives (log-scale)')
dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_sensitivity_' tittxt1 ],options_); dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_sensitivity_' tittxt1 ],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([IdentifDirectoryName '/' M_.fname '_sensitivity_' tittxt1,'.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_sensitivity_%s}\n',[IdentifDirectoryName '/' M_.fname],tittxt1);
fprintf(fidTeX,'\\caption{%s - Sensitivity plot.}',tit_TeX);
fprintf(fidTeX,'\\label{Fig:sensitivity:%s}\n',deblank(tittxt));
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
end end
% identificaton patterns % identificaton patterns
for j=1:size(idemoments.cosnJ,2), for j=1:size(idemoments.cosnJ,2),
@ -171,6 +198,19 @@ if SampleSize == 1,
set(gca,'ygrid','on') set(gca,'ygrid','on')
xlabel([tittxt,' - Collinearity patterns with ', int2str(j) ,' parameter(s)'],'interpreter','none') xlabel([tittxt,' - Collinearity patterns with ', int2str(j) ,' parameter(s)'],'interpreter','none')
dyn_saveas(hh,[ IdentifDirectoryName '/' M_.fname '_ident_collinearity_' tittxt1 '_' int2str(j) ],options_); dyn_saveas(hh,[ IdentifDirectoryName '/' M_.fname '_ident_collinearity_' tittxt1 '_' int2str(j) ],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_ident_collinearity_' tittxt1 '_' int2str(j),'.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_ident_collinearity_%s_%u}\n',[IdentifDirectoryName '/' M_.fname],tittxt1,j);
fprintf(fidTeX,'\\caption{%s - Collinearity patterns with %u parameter(s).}',tit_TeX,j);
fprintf(fidTeX,'\\label{Fig:collinearity:%s:%u_pars}\n',deblank(tittxt),j);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
end end
skipline() skipline()
[U,S,V]=svd(idehess.AHess,0); [U,S,V]=svd(idehess.AHess,0);
@ -178,18 +218,24 @@ if SampleSize == 1,
if idehess.flag_score, if idehess.flag_score,
if nparam<5, if nparam<5,
f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (Information matrix)']); f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (Information matrix)']);
tex_tit_1=[tittxt,' - Identification patterns (Information matrix)'];
else else
f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (Information matrix): SMALLEST SV']); f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (Information matrix): SMALLEST SV']);
tex_tit_1=[tittxt,' - Identification patterns (Information matrix): SMALLEST SV'];
f2 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (Information matrix): HIGHEST SV']); f2 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (Information matrix): HIGHEST SV']);
tex_tit_2=[tittxt,' - Identification patterns (Information matrix): HIGHEST SV'];
end end
else else
% S = idemoments.S; % S = idemoments.S;
% V = idemoments.V; % V = idemoments.V;
if nparam<5, if nparam<5,
f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (moments Information matrix)']); f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (moments Information matrix)']);
tex_tit_1=[tittxt,' - Identification patterns (moments Information matrix)'];
else else
f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (moments Information matrix): SMALLEST SV']); f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (moments Information matrix): SMALLEST SV']);
tex_tit_1=[tittxt,' - Identification patterns (moments Information matrix): SMALLEST SV'];
f2 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (moments Information matrix): HIGHEST SV']); f2 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (moments Information matrix): HIGHEST SV']);
tex_tit_2=[tittxt,' - Identification patterns (moments Information matrix): HIGHEST SV'];
end end
end end
for j=1:min(nparam,8), for j=1:min(nparam,8),
@ -217,8 +263,34 @@ if SampleSize == 1,
title(['Singular value ',num2str(Stit)]) title(['Singular value ',num2str(Stit)])
end end
dyn_saveas(f1,[ IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_1' ],options_); dyn_saveas(f1,[ IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_1' ],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_1','.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_ident_pattern_%s_1}\n',[IdentifDirectoryName '/' M_.fname],tittxt1);
fprintf(fidTeX,'\\caption{%s.}',tex_tit_1);
fprintf(fidTeX,'\\label{Fig:ident_pattern:%s:1}\n',tittxt1);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
if nparam>4, if nparam>4,
dyn_saveas(f2,[ IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_2' ],options_); dyn_saveas(f2,[ IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_2' ],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_2.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_ident_pattern_%s_2}\n',[IdentifDirectoryName '/' M_.fname],tittxt1);
fprintf(fidTeX,'\\caption{%s.}',tex_tit_2);
fprintf(fidTeX,'\\label{Fig:ident_pattern:%s:2}\n',tittxt1);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
end end
end end
@ -250,6 +322,20 @@ else
end end
title('MC mean of sensitivity measures') title('MC mean of sensitivity measures')
dyn_saveas(hh,[ IdentifDirectoryName '/' M_.fname '_MC_sensitivity' ],options_); dyn_saveas(hh,[ IdentifDirectoryName '/' M_.fname '_MC_sensitivity' ],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_MC_sensitivity.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_MC_sensitivity}\n',[IdentifDirectoryName '/' M_.fname]);
fprintf(fidTeX,'\\caption{MC mean of sensitivity measures}');
fprintf(fidTeX,'\\label{Fig:_MC_sensitivity}\n');
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
if advanced, if advanced,
if ~options_.nodisplay, if ~options_.nodisplay,
skipline() skipline()
@ -304,9 +390,12 @@ else
if nparam<5, if nparam<5,
f1 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']); f1 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']);
tex_tit_1=[tittxt,' - MC Identification patterns (moments): HIGHEST SV'];
else else
f1 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): SMALLEST SV']); f1 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): SMALLEST SV']);
tex_tit_1=[tittxt,' - MC Identification patterns (moments): SMALLEST SV'];
f2 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']); f2 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']);
tex_tit_2=[tittxt,' - MC Identification patterns (moments): HIGHEST SV'];
end end
nplots=min(nparam,8); nplots=min(nparam,8);
if nplots>4, if nplots>4,
@ -343,8 +432,34 @@ else
title(['MEAN Singular value ',num2str(Stit)]) title(['MEAN Singular value ',num2str(Stit)])
end end
dyn_saveas(f1,[IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_1' ],options_); dyn_saveas(f1,[IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_1' ],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_1.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_MC_ident_pattern_1}\n',[IdentifDirectoryName '/' M_.fname]);
fprintf(fidTeX,'\\caption{%s.}',tex_tit_1);
fprintf(fidTeX,'\\label{Fig:MC_ident_pattern:1}\n');
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
if nparam>4, if nparam>4,
dyn_saveas(f2,[ IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_2' ],options_); dyn_saveas(f2,[ IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_2' ],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_2.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_MC_ident_pattern_2}\n',[IdentifDirectoryName '/' M_.fname]);
fprintf(fidTeX,'\\caption{%s.}',tex_tit_2);
fprintf(fidTeX,'\\label{Fig:MC_ident_pattern:2}\n');
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
end end
end end
end end

View File

@ -38,7 +38,7 @@ T2 = strvcat(T2, l2);
prior_trunc_backup = DynareOptions.prior_trunc ; prior_trunc_backup = DynareOptions.prior_trunc ;
DynareOptions.prior_trunc = (1-DynareOptions.prior_interval)/2 ; DynareOptions.prior_trunc = (1-DynareOptions.prior_interval)/2 ;
PriorIntervals = prior_bounds(BayesInfo,DynareOptions) ; PriorIntervals = prior_bounds(BayesInfo, DynareOptions.prior_trunc) ;
DynareOptions.prior_trunc = prior_trunc_backup ; DynareOptions.prior_trunc = prior_trunc_backup ;
RESIZE = false; RESIZE = false;

View File

@ -1,4 +1,4 @@
function bounds = prior_bounds(bayestopt,options) function bounds = prior_bounds(bayestopt, prior_trunc)
%@info: %@info:
%! @deftypefn {Function File} {@var{bounds} =} prior_bounds (@var{bayesopt},@var{option}) %! @deftypefn {Function File} {@var{bounds} =} prior_bounds (@var{bayesopt},@var{option})
@ -69,7 +69,6 @@ p3 = bayestopt.p3;
p4 = bayestopt.p4; p4 = bayestopt.p4;
p6 = bayestopt.p6; p6 = bayestopt.p6;
p7 = bayestopt.p7; p7 = bayestopt.p7;
prior_trunc = options.prior_trunc;
bounds.lb = zeros(length(p6),1); bounds.lb = zeros(length(p6),1);
bounds.ub = zeros(length(p6),1); bounds.ub = zeros(length(p6),1);
@ -151,6 +150,14 @@ for i=1:length(p6)
end end
end end
end end
case 8
if prior_trunc == 0
bounds.lb(i) = p3(i);
bounds.ub(i) = Inf;
else
bounds.lb(i) = p3(i)+wblinv(prior_trunc,p6(i),p7(i));
bounds.ub(i) = p3(i)+wblinv(1-prior_trunc,p6(i),p7(i));
end
otherwise otherwise
error(sprintf('prior_bounds: unknown distribution shape (index %d, type %d)', i, pshape(i))); error(sprintf('prior_bounds: unknown distribution shape (index %d, type %d)', i, pshape(i)));
end end

View File

@ -1,4 +1,5 @@
function pdraw = prior_draw(init,uniform) % --*-- Unitary tests --*-- function pdraw = prior_draw(BayesInfo, prior_trunc, uniform) % --*-- Unitary tests --*--
% This function generate one draw from the joint prior distribution and % This function generate one draw from the joint prior distribution and
% allows sampling uniformly from the prior support (uniform==1 when called with init==1) % allows sampling uniformly from the prior support (uniform==1 when called with init==1)
% %
@ -25,7 +26,7 @@ function pdraw = prior_draw(init,uniform) % --*-- Unitary tests --*--
% NOTE 3. This code relies on bayestopt_ as created in the base workspace % NOTE 3. This code relies on bayestopt_ as created in the base workspace
% by the preprocessor (or as updated in subsequent pieces of code and handed to the base workspace) % by the preprocessor (or as updated in subsequent pieces of code and handed to the base workspace)
% %
% Copyright (C) 2006-2015 Dynare Team % Copyright (C) 2006-2016 Dynare Team
% %
% This file is part of Dynare. % This file is part of Dynare.
% %
@ -43,59 +44,64 @@ function pdraw = prior_draw(init,uniform) % --*-- Unitary tests --*--
% along with Dynare. If not, see <http://www.gnu.org/licenses/>. % along with Dynare. If not, see <http://www.gnu.org/licenses/>.
persistent p6 p7 p3 p4 lb ub persistent p6 p7 p3 p4 lb ub
persistent uniform_index gaussian_index gamma_index beta_index inverse_gamma_1_index inverse_gamma_2_index persistent uniform_index gaussian_index gamma_index beta_index inverse_gamma_1_index inverse_gamma_2_index weibull_index
persistent uniform_draws gaussian_draws gamma_draws beta_draws inverse_gamma_1_draws inverse_gamma_2_draws persistent uniform_draws gaussian_draws gamma_draws beta_draws inverse_gamma_1_draws inverse_gamma_2_draws weibull_draws
if nargin>0
if nargin>0 && init p6 = BayesInfo.p6;
p6 = evalin('base', 'bayestopt_.p6'); p7 = BayesInfo.p7;
p7 = evalin('base', 'bayestopt_.p7'); p3 = BayesInfo.p3;
p3 = evalin('base', 'bayestopt_.p3'); p4 = BayesInfo.p4;
p4 = evalin('base', 'bayestopt_.p4'); bounds = prior_bounds(BayesInfo, prior_trunc);
bounds = evalin('base', 'prior_bounds(bayestopt_,options_)');
lb = bounds.lb; lb = bounds.lb;
ub = bounds.ub; ub = bounds.ub;
number_of_estimated_parameters = length(p6); number_of_estimated_parameters = length(p6);
if nargin>1 && uniform if nargin>2 && uniform
prior_shape = repmat(5,number_of_estimated_parameters,1); prior_shape = repmat(5,number_of_estimated_parameters,1);
else else
prior_shape = evalin('base', 'bayestopt_.pshape'); prior_shape = BayesInfo.pshape;
end end
beta_index = find(prior_shape==1); beta_index = find(prior_shape==1);
if isempty(beta_index) if isempty(beta_index)
beta_draws = 0; beta_draws = false;
else else
beta_draws = 1; beta_draws = true;
end end
gamma_index = find(prior_shape==2); gamma_index = find(prior_shape==2);
if isempty(gamma_index) if isempty(gamma_index)
gamma_draws = 0; gamma_draws = false;
else else
gamma_draws = 1; gamma_draws = true;
end end
gaussian_index = find(prior_shape==3); gaussian_index = find(prior_shape==3);
if isempty(gaussian_index) if isempty(gaussian_index)
gaussian_draws = 0; gaussian_draws = false;
else else
gaussian_draws = 1; gaussian_draws = true;
end end
inverse_gamma_1_index = find(prior_shape==4); inverse_gamma_1_index = find(prior_shape==4);
if isempty(inverse_gamma_1_index) if isempty(inverse_gamma_1_index)
inverse_gamma_1_draws = 0; inverse_gamma_1_draws = false;
else else
inverse_gamma_1_draws = 1; inverse_gamma_1_draws = true;
end end
uniform_index = find(prior_shape==5); uniform_index = find(prior_shape==5);
if isempty(uniform_index) if isempty(uniform_index)
uniform_draws = 0; uniform_draws = false;
else else
uniform_draws = 1; uniform_draws = true;
end end
inverse_gamma_2_index = find(prior_shape==6); inverse_gamma_2_index = find(prior_shape==6);
if isempty(inverse_gamma_2_index) if isempty(inverse_gamma_2_index)
inverse_gamma_2_draws = 0; inverse_gamma_2_draws = false;
else else
inverse_gamma_2_draws = 1; inverse_gamma_2_draws = true;
end
weibull_index = find(prior_shape==8);
if isempty(weibull_index)
weibull_draws = false;
else
weibull_draws = true;
end end
pdraw = NaN(number_of_estimated_parameters,1); pdraw = NaN(number_of_estimated_parameters,1);
return return
@ -159,369 +165,110 @@ if inverse_gamma_2_draws
end end
end end
if weibull_draws
pdraw(weibull_index) = wblrnd(p7(weibull_index), p6(weibull_index)) + p3(weibull_index);
out_of_bound = find( (pdraw(weibull_index)'>ub(weibull_index)) | (pdraw(weibull_index)'<lb(weibull_index)));
while ~isempty(out_of_bound),
pdraw(weibull_index(out_of_bound)) = wblrnd(p7(weibull_index(out_of_bound)),p6(weibull_index(out_of_bound)))+p3(weibull_index(out_of_bound));
out_of_bound = find( (pdraw(weibull_index)'>ub(weibull_index)) | (pdraw(weibull_index)'<lb(weibull_index)));
end
end
%@test:1 %@test:1
%$ %% Initialize required structures %$ % Fill global structures with required fields...
%$ options_.prior_trunc=0; %$ prior_trunc = 1e-10;
%$ options_.initialize_estimated_parameters_with_the_prior_mode=0; %$ p0 = repmat([1; 2; 3; 4; 5; 6; 8], 2, 1); % Prior shape
%$ %$ p1 = .4*ones(14,1); % Prior mean
%$ M_.dname='test'; %$ p2 = .2*ones(14,1); % Prior std.
%$ M_.param_names = 'alp'; %$ p3 = NaN(14,1);
%$ ndraws=100000; %$ p4 = NaN(14,1);
%$ global estim_params_ %$ p5 = NaN(14,1);
%$ estim_params_.var_exo = []; %$ p6 = NaN(14,1);
%$ estim_params_.var_endo = []; %$ p7 = NaN(14,1);
%$ estim_params_.corrx = []; %$
%$ estim_params_.corrn = []; %$ for i=1:14
%$ estim_params_.param_vals = []; %$ switch p0(i)
%$ estim_params_.param_vals = [1, NaN, (-Inf), Inf, 1, 0.356, 0.02, NaN, NaN, NaN ]; %$ case 1
%$ %$ % Beta distribution
%$ %% beta %$ p3(i) = 0;
%$ estim_params_.param_vals(1,3)= -Inf;%LB %$ p4(i) = 1;
%$ estim_params_.param_vals(1,4)= +Inf;%UB %$ [p6(i), p7(i)] = beta_specification(p1(i), p2(i)^2, p3(i), p4(i));
%$ estim_params_.param_vals(1,5)= 1;%Shape %$ p5(i) = compute_prior_mode([p6(i) p7(i)], 1);
%$ estim_params_.param_vals(1,6)=0.5; %$ case 2
%$ estim_params_.param_vals(1,7)=0.01; %$ % Gamma distribution
%$ estim_params_.param_vals(1,8)=NaN; %$ p3(i) = 0;
%$ estim_params_.param_vals(1,9)=NaN; %$ p4(i) = Inf;
%$ %$ [p6(i), p7(i)] = gamma_specification(p1(i), p2(i)^2, p3(i), p4(i));
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_); %$ p5(i) = compute_prior_mode([p6(i) p7(i)], 2);
%$ %$ case 3
%$ pdraw = prior_draw(1,0); %$ % Normal distribution
%$ pdraw_vec=NaN(ndraws,1); %$ p3(i) = -Inf;
%$ for ii=1:ndraws %$ p4(i) = Inf;
%$ pdraw_vec(ii)=prior_draw(0,0); %$ p6(i) = p1(i);
%$ p7(i) = p2(i);
%$ p5(i) = p1(i);
%$ case 4
%$ % Inverse Gamma (type I) distribution
%$ p3(i) = 0;
%$ p4(i) = Inf;
%$ [p6(i), p7(i)] = inverse_gamma_specification(p1(i), p2(i)^2, p3(i), 1, false);
%$ p5(i) = compute_prior_mode([p6(i) p7(i)], 4);
%$ case 5
%$ % Uniform distribution
%$ [p1(i), p2(i), p6(i), p7(i)] = uniform_specification(p1(i), p2(i), p3(i), p4(i));
%$ p3(i) = p6(i);
%$ p4(i) = p7(i);
%$ p5(i) = compute_prior_mode([p6(i) p7(i)], 5);
%$ case 6
%$ % Inverse Gamma (type II) distribution
%$ p3(i) = 0;
%$ p4(i) = Inf;
%$ [p6(i), p7(i)] = inverse_gamma_specification(p1(i), p2(i)^2, p3(i), 2, false);
%$ p5(i) = compute_prior_mode([p6(i) p7(i)], 6);
%$ case 8
%$ % Weibull distribution
%$ p3(i) = 0;
%$ p4(i) = Inf;
%$ [p6(i), p7(i)] = weibull_specification(p1(i), p2(i)^2, p3(i));
%$ p5(i) = compute_prior_mode([p6(i) p7(i)], 8);
%$ otherwise
%$ error('This density is not implemented!')
%$ end
%$ end %$ end
%$ %$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4 || any(pdraw_vec<0) || any(pdraw_vec>1) %$ BayesInfo.pshape = p0;
%$ error('Beta prior wrong') %$ BayesInfo.p1 = p1;
%$ BayesInfo.p2 = p2;
%$ BayesInfo.p3 = p3;
%$ BayesInfo.p4 = p4;
%$ BayesInfo.p5 = p5;
%$ BayesInfo.p6 = p6;
%$ BayesInfo.p7 = p7;
%$
%$ ndraws = 1e5;
%$ m0 = BayesInfo.p1; %zeros(14,1);
%$ v0 = diag(BayesInfo.p2.^2); %zeros(14);
%$
%$ % Call the tested routine
%$ try
%$ % Initialization of prior_draws.
%$ prior_draw(BayesInfo, prior_trunc, false);
%$ % Do simulations in a loop and estimate recursively the mean and teh variance.
%$ for i = 1:ndraws
%$ draw = transpose(prior_draw());
%$ m1 = m0 + (draw-m0)/i;
%$ m2 = m1*m1';
%$ v0 = v0 + ((draw*draw'-m2-v0) + (i-1)*(m0*m0'-m2'))/i;
%$ m0 = m1;
%$ end
%$ t(1) = true;
%$ catch
%$ t(1) = false;
%$ end %$ end
%$ %$
%$ %$ if t(1)
%$ %% Gamma %$ t(2) = all(abs(m0-BayesInfo.p1)<3e-3);
%$ estim_params_.param_vals(1,3)= -Inf;%LB %$ t(3) = all(all(abs(v0-diag(BayesInfo.p2.^2))<2e-3));
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 2;%Shape
%$ estim_params_.param_vals(1,6)=0.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=NaN;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end %$ end
%$ %$ T = all(t);
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4 || any(pdraw_vec<0) %@eof:1
%$ error('Gamma prior wrong')
%$ end
%$
%$ %% Normal
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 3;%Shape
%$ estim_params_.param_vals(1,6)=0.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=NaN;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4
%$ error('Normal prior wrong')
%$ end
%$
%$ %% inverse gamma distribution (type 1)
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 4;%Shape
%$ estim_params_.param_vals(1,6)=0.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=NaN;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4 || any(pdraw_vec<0)
%$ error('inverse gamma distribution (type 1) prior wrong')
%$ end
%$
%$ %% Uniform
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 5;%Shape
%$ estim_params_.param_vals(1,6)=0.5;
%$ estim_params_.param_vals(1,7)=sqrt(12)^(-1)*(1-0);
%$ estim_params_.param_vals(1,8)=NaN;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>1e-2 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-3 || any(pdraw_vec<0) || any(pdraw_vec>1)
%$ error('Uniform prior wrong')
%$ end
%$
%$ %% inverse gamma distribution (type 2)
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 6;%Shape
%$ estim_params_.param_vals(1,6)=0.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=NaN;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4 || any(pdraw_vec<0)
%$ error('inverse gamma distribution (type 2) prior wrong')
%$ end
%$
%$
%$ %%%%%%%%%%%%%%%%%%%%%% Generalized distributions %%%%%%%%%%%%%%%%%%%%%
%$
%$ %% beta
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 1;%Shape
%$ estim_params_.param_vals(1,6)=1.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=1;
%$ estim_params_.param_vals(1,9)=3;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4 || any(pdraw_vec<estim_params_.param_vals(1,3)) || any(pdraw_vec>estim_params_.param_vals(1,4))
%$ error('Beta prior wrong')
%$ end
%$
%$ %% Gamma
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 2;%Shape
%$ estim_params_.param_vals(1,6)=1.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=1;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4 || any(pdraw_vec<estim_params_.param_vals(1,8))
%$ error('Gamma prior wrong')
%$ end
%$
%$ %% inverse gamma distribution (type 1)
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 4;%Shape
%$ estim_params_.param_vals(1,6)=1.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=1;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4 || any(pdraw_vec<estim_params_.param_vals(1,8))
%$ error('inverse gamma distribution (type 1) prior wrong')
%$ end
%$
%$ %% Uniform
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 5;%Shape
%$ estim_params_.param_vals(1,6)=1.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=NaN;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4 || any(pdraw_vec<estim_params_.param_vals(1,3)) || any(pdraw_vec>estim_params_.param_vals(1,4))
%$ error('Uniform prior wrong')
%$ end
%$
%$ %% inverse gamma distribution (type 2)
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 6;%Shape
%$ estim_params_.param_vals(1,6)=1.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=1;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4 || any(pdraw_vec<estim_params_.param_vals(1,8))
%$ error('inverse gamma distribution (type 2) prior wrong')
%$ end
%$
%$ %%%%%%%%%%%% With prior truncation
%$ options_.prior_trunc=.4;
%$
%$ %% beta
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 1;%Shape
%$ estim_params_.param_vals(1,6)=1.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=1;
%$ estim_params_.param_vals(1,9)=3;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$ bounds = prior_bounds(bayestopt_,options_)';
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>5e-3 || any(pdraw_vec<bounds.lb) || any(pdraw_vec>bounds.ub)
%$ error('Beta prior wrong')
%$ end
%$
%$ %% Gamma
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 2;%Shape
%$ estim_params_.param_vals(1,6)=1.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=1;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$ bounds = prior_bounds(bayestopt_,options_)';
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>5e-3 || any(pdraw_vec<bounds.lb) || any(pdraw_vec>bounds.ub)
%$ error('Gamma prior wrong')
%$ end
%$
%$ %% inverse gamma distribution (type 1)
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 4;%Shape
%$ estim_params_.param_vals(1,6)=1.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=1;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$ bounds = prior_bounds(bayestopt_,options_)';
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>5e-3 || any(pdraw_vec<bounds.lb) || any(pdraw_vec>bounds.ub)
%$ error('inverse gamma distribution (type 1) prior wrong')
%$ end
%$
%$ %% Uniform
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 5;%Shape
%$ estim_params_.param_vals(1,6)=1.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=NaN;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$ bounds = prior_bounds(bayestopt_,options_)';
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>5e-3 || any(pdraw_vec<bounds.lb) || any(pdraw_vec>bounds.ub)
%$ error('Uniform prior wrong')
%$ end
%$
%$
%$ %% inverse gamma distribution (type 2)
%$ estim_params_.param_vals(1,3)= -Inf;%LB
%$ estim_params_.param_vals(1,4)= +Inf;%UB
%$ estim_params_.param_vals(1,5)= 6;%Shape
%$ estim_params_.param_vals(1,6)=1.5;
%$ estim_params_.param_vals(1,7)=0.01;
%$ estim_params_.param_vals(1,8)=1;
%$ estim_params_.param_vals(1,9)=NaN;
%$
%$ [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params_, M_, options_);
%$ bounds = prior_bounds(bayestopt_,options_)';
%$
%$ pdraw = prior_draw(1,0);
%$ pdraw_vec=NaN(ndraws,1);
%$ for ii=1:ndraws
%$ pdraw_vec(ii)=prior_draw(0,0);
%$ end
%$
%$ if abs(mean(pdraw_vec)-estim_params_.param_vals(1,6))>5e-3 || any(pdraw_vec<bounds.lb) || any(pdraw_vec>bounds.ub)
%$ error('inverse gamma distribution (type 2) prior wrong')
%$ end
%$
%@eof:1

View File

@ -44,7 +44,8 @@ Y = transpose(dataset.data);
gend = dataset.nobs; gend = dataset.nobs;
data_index = dataset_info.missing.aindex; data_index = dataset_info.missing.aindex;
missing_value = dataset_info.missing.state; missing_value = dataset_info.missing.state;
bayestopt_.mean_varobs = dataset_info.descriptive.mean'; mean_varobs = dataset_info.descriptive.mean;
nvx = estim_params_.nvx; nvx = estim_params_.nvx;
nvn = estim_params_.nvn; nvn = estim_params_.nvn;
@ -63,6 +64,7 @@ nvobs = length(options_.varobs);
iendo = 1:endo_nbr; iendo = 1:endo_nbr;
horizon = options_.forecast; horizon = options_.forecast;
filtered_vars = options_.filtered_vars; filtered_vars = options_.filtered_vars;
IdObs = bayestopt_.mfys;
if horizon if horizon
i_last_obs = gend+(1-M_.maximum_endo_lag:0); i_last_obs = gend+(1-M_.maximum_endo_lag:0);
end end
@ -106,8 +108,6 @@ if horizon
MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8)); MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8));
MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ... MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ...
8)); 8));
IdObs = bayestopt_.mfys;
end end
MAX_momentsno = min(B,ceil(MaxNumberOfBytes/(get_moments_size(options_)*8))); MAX_momentsno = min(B,ceil(MaxNumberOfBytes/(get_moments_size(options_)*8)));
@ -161,15 +161,16 @@ localVars.Y=Y;
localVars.data_index=data_index; localVars.data_index=data_index;
localVars.missing_value=missing_value; localVars.missing_value=missing_value;
localVars.varobs=options_.varobs; localVars.varobs=options_.varobs;
localVars.mean_varobs=mean_varobs;
localVars.irun=irun; localVars.irun=irun;
localVars.endo_nbr=endo_nbr; localVars.endo_nbr=endo_nbr;
localVars.nvn=nvn; localVars.nvn=nvn;
localVars.naK=naK; localVars.naK=naK;
localVars.horizon=horizon; localVars.horizon=horizon;
localVars.iendo=iendo; localVars.iendo=iendo;
localVars.IdObs=IdObs;
if horizon if horizon
localVars.i_last_obs=i_last_obs; localVars.i_last_obs=i_last_obs;
localVars.IdObs=IdObs;
localVars.MAX_nforc1=MAX_nforc1; localVars.MAX_nforc1=MAX_nforc1;
localVars.MAX_nforc2=MAX_nforc2; localVars.MAX_nforc2=MAX_nforc2;
end end

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