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 \
license.txt \
README.md \
COPYING \
CONTRIBUTING.md \
windows/dynare.nsi \
windows/mexopts-win32.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
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
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.
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"
```
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:
```
./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```
- **(Optional)** To compile Dynare mex files for use on Octave:
- ```brew install octave```
- ```brew install suite-sparse```
- To see the available options for compiling Dynare, type:
- ```brew info dynare```
- Install Dynare via a command of the form:

View File

@ -64,7 +64,7 @@ AC_PROG_MKDIR_P
AM_PROG_LEX
# Hack to get lex include dir, ticket #575
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])
if test "x$YACC" = "x"; then

View File

@ -11,7 +11,7 @@
\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
this document under the terms of the GNU Free Documentation
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
CEPREMAP. E-mail:
\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
@ -169,7 +169,7 @@ $$\left[
$$\left[
\begin{array}{cc}
0 & 0 \\
0 & 0
0 & 0
\end{array}
\right]
=
@ -499,7 +499,7 @@ The syntax for computing the marginal density is:
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}

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
potentially useful when running @code{dynare} on a large @file{.mod}
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
@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:
@deffn Command var @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})]@dots{};
@deffnx Command var (log_deflator = @var{MODEL_EXPRESSION}) @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})] [(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
@ -1139,19 +1143,25 @@ multiplicative trend).
@item long_name = @var{QUOTED_STRING}
This is the long version of the variable name. Its value is stored in
@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
@examplehead
@example
var c gnp q1 q2;
var c gnp q1 (country=`US') q2 (country=`FR');
var(deflator=A) i b;
var c $C$ (long_name=`Consumption');
@end example
@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
@ -1169,6 +1179,9 @@ will concatenate them.
@table @code
@item long_name = @var{QUOTED_STRING}
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
@examplehead
@ -1179,7 +1192,7 @@ varexo m gov;
@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
@ -1203,6 +1216,9 @@ Dynare will concatenate them.
@table @code
@item long_name = @var{QUOTED_STRING}
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
@examplehead
@ -1216,7 +1232,7 @@ varexo_det tau;
@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
@ -1235,6 +1251,9 @@ Dynare will concatenate them.
@table @code
@item long_name = @var{QUOTED_STRING}
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
@examplehead
@ -2672,9 +2691,9 @@ Specifies the correlation of two variables.
@end table
In an estimation context, it is also possible to specify variances and
covariances on endogenous variables: in that case, these values are
interpreted as the calibration of the measurement errors on these
variables. This requires the @code{var_obs}-command to be specified before the @code{shocks}-block.
covariances on endogenous variables: in that case, these values are interpreted
as the calibration of the measurement errors on these variables. This requires
the @code{varobs} command to be specified before the @code{shocks} block.
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}.
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
@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.
@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
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
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
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
@ref{prior_3rd_parameter}. In this case the prior density is effectively
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},
@code{gamma_pdf}, @code{normal_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
@code{inv_gamma1_pdf}
@ -4565,7 +4597,7 @@ that @code{inv_gamma_pdf} is equivalent to
@item @var{PRIOR_3RD_PARAMETER}
@anchor{prior_3rd_parameter}
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}
@anchor{prior_4th_parameter}
@ -4838,7 +4870,7 @@ first observation of the rolling window.
@item prefilter = @var{INTEGER}
@anchor{prefilter}
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}
@anchor{presample}
@ -4973,8 +5005,12 @@ Metropolis-Hastings chain. Default: 2*@code{mh_scale}
@item mh_recover
@anchor{mh_recover} Attempts to recover a Metropolis-Hastings
simulation that crashed prematurely. Shouldn't be used together with
@code{load_mh_file}
simulation that crashed prematurely, starting with the last available saved
@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}
@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
@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}
@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.
@item irf_shocks = ( @var{VARIABLE_NAME} [[,] @var{VARIABLE_NAME} @dots{}] )
@xref{irf_shocks}. Only used if @ref{bayesian_irf} is passed. Cannot be used
with @ref{dsge_var}.
@xref{irf_shocks}. Only used if @ref{bayesian_irf} is passed.
@item irf_plot_threshold = @var{DOUBLE}
@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
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.
@xref{Auxiliary
@ -7078,8 +7119,10 @@ This command accepts the following options:
@table @code
@anchor{planner_discount}
@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{})
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
@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{})
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
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).
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}
@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
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},
@code{graphicx}, @code{epstopdf}, @code{longtable}, and @code{float}
Requires the following @LaTeX{} packages: @code{breqn}, @code{psfrag},
@code{graphicx}, @code{epstopdf}, @code{longtable}, @code{booktabs}, @code{caption},
@code{float}, and @code{morefloats}
@end deffn
@ -11917,6 +11963,28 @@ ts1 is a dseries object:
@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}])
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
@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})
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
@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
to graphs begin with `@code{graph}' while options specific to tables begin with
`@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
@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}
@item tableNegColor, @code{LATEX_COLOR}
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,''
@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
Ireland, Peter (2004): ``A Method for Taking Models to the Data,''
@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;
varexo e, u;
verbatim;
% I want these comments included in
% example1.m
%
var = 1;
end;
parameters beta, rho, alpha, delta, theta, psi, tau;
alpha = 0.36;
@ -79,4 +96,4 @@ r = report();
@#endfor
r.write();
r.compile();
r.compile();

View File

@ -1,6 +1,6 @@
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Dynare
Upstream-Contact: Dynare Team, whose members in 2015 are:
Upstream-Contact: Dynare Team, whose members in 2016 are:
Stéphane Adjemian <stephane.adjemian@univ-lemans.fr>
Houtan Bastani <houtan@dynare.org>
Michel Juillard <michel.juillard@mjui.fr>
@ -14,7 +14,7 @@ Upstream-Contact: Dynare Team, whose members in 2015 are:
Source: http://www.dynare.org
Files: *
Copyright: 1996-2015 Dynare Team
Copyright: 1996-2016 Dynare Team
License: GPL-3+
Files: matlab/AIM/SP*
@ -98,11 +98,6 @@ Copyright: 1995-2007 Kurt Hornik
2008-2009 Dynare Team
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
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>
@ -144,7 +139,7 @@ License: permissive
distribute this software.
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+
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 This file is part of Dynare.
dnl
@ -22,6 +22,9 @@ AC_REQUIRE([AX_MATLAB])
AC_MSG_CHECKING([for MATLAB version])
if test "x$MATLAB_VERSION" != "x"; then
case $MATLAB_VERSION in
*2015b | *2015B)
MATLAB_VERSION="8.6"
;;
*2015a | *2015A)
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 This file is part of Dynare.
dnl
@ -98,6 +98,32 @@ else
AC_MSG_RESULT([unknown])
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_DEFS])
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.
%
% 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
%
% 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 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 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.
@ -23,7 +23,8 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,de
% matrices (meaningless for periods 1:d)
% o decomp 4D array of shock decomposition of k-step ahead
% filtered variables
%
% o trend_addition [double] (n_observed_series*T) pure trend component; stored in options_.varobs order
%
% ALGORITHM
% Diffuse Kalman filter (Durbin and Koopman)
%
@ -93,15 +94,10 @@ else
end
trend_coeff = zeros(vobs,1);
if bayestopt_.with_trend == 1
trend_coeff = zeros(vobs,1);
t = options_.trend_coeffs;
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);
[trend_addition, trend_coeff] =compute_trend_coefficients(M_,options_,vobs,gend);
trend = constant*ones(1,gend)+trend_addition;
else
trend_addition=zeros(size(constant,1),gend);
trend = constant*ones(1,gend);
end
start = options_.presample+1;

View File

@ -34,7 +34,7 @@ switch type
case 'posterior'
[xparams, logpost] = metropolis_draw(0);
case 'prior'
xparams = prior_draw(0);
xparams = prior_draw();
if nargout>1
logpost = evaluate_posterior_kernel(xparams');
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
% (+updates of oo_ & TeX output).
%
@ -8,6 +8,7 @@ function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bay
% options_ [structure]
% bayestopt_ [structure]
% oo_ [structure]
% pnames [char] Array of char, names of the prior shapes available
%
% OUTPUTS
% oo_ [structure]
@ -15,7 +16,7 @@ function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bay
% SPECIAL REQUIREMENTS
% None.
% Copyright (C) 2006-2013 Dynare Team
% Copyright (C) 2006-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -59,7 +60,6 @@ FirstMhFile = record.KeepedDraws.FirstMhFile;
NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws);
clear record;
pnames=[' ';'beta ';'gamma';'norm ';'invg ';'unif ';'invg2'];
header_width = row_header_width(M_,estim_params_,bayestopt_);
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');
@ -336,22 +336,23 @@ fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \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,['\\label{Table:MHPosterior:' int2str(fnum) '}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,[' & Prior distribution & Prior mean & Prior ' ...
's.d. & Posterior mean & Posterior s.d. & HPD inf & HPD sup\\\\ \n']);
fprintf(fidTeX,'\\hline \\endfirsthead \n');
fprintf(fidTeX,['\\caption{(continued)}']);
fprintf(fidTeX,['\\label{Table:MHPosterior:' int2str(fnum) '}\\\\\n']);
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,[' & Prior distribution & Prior mean & Prior ' ...
's.d. & Posterior mean & Posterior s.d. & HPD inf & HPD sup\\\\ \n']);
fprintf(fidTeX,'\\hline \\endhead \n');
fprintf(fidTeX,'\\toprule \n');
fprintf(fidTeX,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{4}{c}{Posterior} \\\\\n');
fprintf(fidTeX,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-8}\n');
fprintf(fidTeX,' & Dist. & Mean & Stdev. & Mean & Stdev. & HPD inf & HPD sup\\\\\n');
fprintf(fidTeX,'\\midrule \\endfirsthead \n');
fprintf(fidTeX,['\\caption{(continued)}\\\\']);
fprintf(fidTeX,'\\toprule \n');
fprintf(fidTeX,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{4}{c}{Posterior} \\\\\n');
fprintf(fidTeX,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-8}\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,'\\hline \\hline \\endlastfoot \n');
fprintf(fidTeX,'\\bottomrule \\multicolumn{8}{r}{(Continued on next page)} \\endfoot \n');
fprintf(fidTeX,'\\bottomrule \\endlastfoot \n');
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));
first_obs_end_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(2)*NumberOfDraws*(1-options_.mh_drop));
param_name=[];
for jj=1:npar
param_name = strvcat(param_name,get_the_name(jj,options_.TeX,M_,estim_params_,options_));
if options_.TeX
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
fprintf('\nGeweke (1992) Convergence Tests, based on means of draws %d to %d vs %d to %d.\n',first_obs_begin_sample,last_obs_begin_sample,first_obs_end_sample,NumberOfDraws);
fprintf('p-values are for Chi2-test for equality of means.\n');
Geweke_header={'Parameter', 'Post. Mean', 'Post. Std', 'p-val No Taper'};
print_string=['%',num2str(size(param_name,2)+3),'s \t %12.3f \t %12.3f \t %12.3f'];
print_string_header=['%',num2str(size(param_name,2)+3),'s \t %12s \t %12s \t %12s'];
Geweke_header=char('Parameter', 'Post. Mean', 'Post. Std', 'p-val No Taper');
for ii=1:length(options_.convergence.geweke.taper_steps)
Geweke_header=[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'];
Geweke_header=char(Geweke_header,['p-val ' num2str(options_.convergence.geweke.taper_steps(ii)),'% Taper']);
end
print_string=[print_string,'\n'];
print_string_header=[print_string_header,'\n'];
fprintf(print_string_header,Geweke_header{1,:});
datamat=NaN(npar,3+length(options_.convergence.geweke.taper_steps));
for jj=1:npar
startline=0;
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_);
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
skipline(2);
return;

View File

@ -77,7 +77,7 @@ if options_.dsge_var
NumberOfLagsTimesNvobs = myinputs.NumberOfLagsTimesNvobs;
Companion_matrix = myinputs.Companion_matrix;
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

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)]);
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
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');
fprintf(fidlog,['\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)
% Copyright (C) 2015 Dynare Team
% Copyright (C) 2015-2016 Dynare Team
%
% This file is part of Dynare.
%
@ -29,7 +29,7 @@ if exist('OCTAVE_VERSION')
else
% Add win32 specific paths for Dynare Windows package
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')
mexpath = tmp;
if modifypath
@ -48,7 +48,7 @@ else
end
end
else
tmp = [dynareroot '../mex/matlab/win64-7.8-8.5/'];
tmp = [dynareroot '../mex/matlab/win64-7.8-8.6/'];
if exist(tmp, 'dir')
mexpath = tmp;
if modifypath

View File

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

View File

@ -12,7 +12,7 @@ function bvar_density(maxnlags)
% none
% Copyright (C) 2003-2007 Christopher Sims
% Copyright (C) 2007-2009 Dynare Team
% Copyright (C) 2007-2016 Dynare Team
%
% 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
% 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
[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);
oo_.bvar.log_marginal_data_density(nlags)=log_dnsty;
skipline()
fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ...
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).
@ -19,37 +19,44 @@ function clear_persistent_variables(folder)
% You should have received a copy of the GNU General Public License
% 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();
end
if ~exist('list_of_functions_to_be_cleared.mat') || isolder(sprintf('%slist_of_functions_to_be_cleared.mat', DYNARE_FOLDER), DYNARE_FOLDER)
if isunix() || ismac()
[status, output] = system(sprintf('grep -lr ^persistent %s', folder));
list_of_files = strsplit(output);
list_of_files(find(cellfun(@isempty, list_of_files))) = [];
else
[status, output] = system(sprintf('findstr /B/S/M persistent %s\\*', folder));
list_of_files = strsplit(output);
list_of_files(find(cellfun(@isempty, list_of_files))) = [];
i = 1; mobius = true;
while mobius
if i>length(list_of_files)
break
end
if ismember(list_of_files{i},{'FINDSTR:', 'ignored', '//'})
list_of_files(i) = [];
else
i = i + 1;
DYNARE_FOLDER = strrep(which('dynare'),'dynare.m','');
if writelistofroutinestobecleared
if ~exist('list_of_functions_to_be_cleared.m') || isolder(sprintf('%slist_of_functions_to_be_cleared.m', DYNARE_FOLDER), DYNARE_FOLDER)
if isunix() || ismac()
[status, output] = system(sprintf('grep -lr ^persistent %s', folder));
list_of_files = strsplit(output);
list_of_files(find(cellfun(@isempty, list_of_files))) = [];
else
[status, output] = system(sprintf('findstr /B/S/M persistent %s\\*', folder));
list_of_files = strsplit(output);
list_of_files(find(cellfun(@isempty, list_of_files))) = [];
i = 1; mobius = true;
while mobius
if i>length(list_of_files)
break
end
if ismember(list_of_files{i},{'FINDSTR:', 'ignored', '//'})
list_of_files(i) = [];
else
i = i + 1;
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
[paths, list_of_functions, extensions] = cellfun(@fileparts, list_of_files, 'UniformOutput',false);
save(sprintf('%slist_of_functions_to_be_cleared.mat', DYNARE_FOLDER), 'list_of_functions');
else
load('list_of_functions_to_be_cleared');
return
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'];
fid=fopen(f_name_binder,'w+');
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{graphicx}');
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{breqn}');
fprintf(fid,'%s \n','\usepackage{float}');
fprintf(fid,'%s \n','\usepackage{float,morefloats,caption}');
fprintf(fid,'%s \n','\begin{document}');
%% Root directory
@ -60,7 +61,7 @@ for ii=1:length(TeX_Files)
end
end
%5 graphs directory
%% graphs directory
TeX_Files=dir([M_.dname filesep 'graphs' filesep M_.fname '*.TeX']);
for ii=1:length(TeX_Files)
[pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
@ -69,6 +70,24 @@ for ii=1:length(TeX_Files)
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
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
% 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.
%
@ -60,7 +60,10 @@ if isempty(exogenous_variable_index)
return
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' ])
temporary_structure = oo_.([TYPE 'TheoreticalMoments']);
if isfield(temporary_structure,'dsge')
@ -112,13 +115,16 @@ for i=1:length(Steps)
p_hpdinf(i) = hpd_interval(1);
p_hpdsup(i) = hpd_interval(2);
end
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.Steps = Steps;
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.Mean.(name) = p_mean;
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.Median.(name) = p_median;
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.Variance.(name) = p_variance;
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.HPDinf.(name) = p_hpdinf;
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.HPDsup.(name) = p_hpdsup;
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.deciles.(name) = p_deciles;
FirstField = sprintf('%sTheoreticalMoments', TYPE);
oo_.(FirstField).dsge.ConditionalVarianceDecomposition.Steps = Steps;
oo_.(FirstField).dsge.ConditionalVarianceDecomposition.Mean.(name_1).(name_2) = p_mean;
oo_.(FirstField).dsge.ConditionalVarianceDecomposition.Median.(name_1).(name_2) = p_median;
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
oo_.([TYPE 'TheoreticalMoments']).dsge.ConditionalVarianceDecomposition.density.(name) = p_density;
oo_.(FirstField).dsge.ConditionalVarianceDecomposition.density.(name_1).(name_2) = p_density;
end

View File

@ -52,7 +52,7 @@ if isfield(oo_,'PointForecast')
end
%% 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);
for ii=1:length(names)
oo_.PointForecast.HPDinf.(names{ii})=oo_.PointForecast.HPDinf.(names{ii})';
@ -60,7 +60,7 @@ if isfield(oo_.PointForecast,'HPDinf')
end
end
if isfield(oo_.MeanForecast,'HPDinf')
if isfield(oo_,'MeanForecast') && isfield(oo_.MeanForecast,'HPDinf')
names=fieldnames(oo_.MeanForecast.HPDinf);
for ii=1:length(names)
oo_.MeanForecast.HPDinf.(names{ii})=oo_.MeanForecast.HPDinf.(names{ii})';
@ -68,7 +68,7 @@ if isfield(oo_.MeanForecast,'HPDinf')
end
end
if isfield(oo_.UpdatedVariables,'HPDinf')
if isfield(oo_,'UpdatedVariables') && isfield(oo_.UpdatedVariables,'HPDinf')
names=fieldnames(oo_.UpdatedVariables.HPDinf);
for ii=1:length(names)
oo_.UpdatedVariables.HPDinf.(names{ii})=oo_.UpdatedVariables.HPDinf.(names{ii})';
@ -76,7 +76,7 @@ if isfield(oo_.UpdatedVariables,'HPDinf')
end
end
if isfield(oo_.SmoothedVariables,'HPDinf')
if isfield(oo_,'SmoothedVariables') && isfield(oo_.SmoothedVariables,'HPDinf')
names=fieldnames(oo_.SmoothedVariables.HPDinf);
for ii=1:length(names)
oo_.SmoothedVariables.HPDinf.(names{ii})=oo_.SmoothedVariables.HPDinf.(names{ii})';
@ -84,7 +84,7 @@ if isfield(oo_.SmoothedVariables,'HPDinf')
end
end
if isfield(oo_.FilteredVariables,'HPDinf')
if isfield(oo_,'FilteredVariables') && isfield(oo_.FilteredVariables,'HPDinf')
names=fieldnames(oo_.FilteredVariables.HPDinf);
for ii=1:length(names)
oo_.FilteredVariables.HPDinf.(names{ii})=oo_.FilteredVariables.HPDinf.(names{ii})';
@ -92,7 +92,7 @@ if isfield(oo_.FilteredVariables,'HPDinf')
end
end
if isfield(oo_.SmoothedShocks,'HPDinf')
if isfield(oo_,'SmoothedShocks') && isfield(oo_.SmoothedShocks,'HPDinf')
names=fieldnames(oo_.SmoothedShocks.HPDinf);
for ii=1:length(names)
oo_.SmoothedShocks.HPDinf.(names{ii})=oo_.SmoothedShocks.HPDinf.(names{ii})';
@ -100,13 +100,44 @@ if isfield(oo_.SmoothedShocks,'HPDinf')
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')
names=fieldnames(oo_.FilteredVariables);
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') ...
&& ~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)];
end
end

View File

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

View File

@ -60,6 +60,9 @@ else
var2 = var1;
end
var1=deblank(var1);
var2=deblank(var2);
if isfield(oo_,[ TYPE 'TheoreticalMoments'])
temporary_structure = oo_.([TYPE, 'TheoreticalMoments']);
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);
elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && options_.bandpass.indicator
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;
elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpass.indicator
y = bsxfun(@minus, y, m);

View File

@ -179,24 +179,7 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
if np
filename = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_1.TeX'];
fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
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');
TeXBegin_Bayesian(fidTeX,1,'parameters')
ip = nvx+nvn+ncx+ncn+1;
for i=1:np
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));
ip = ip + 1;
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
TeXEnd(fidTeX)
end
if nvx
TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_2.TeX'];
fidTeX = fopen(TeXfile,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
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');
TeXBegin_Bayesian(fidTeX,2,'standard deviation of structural shocks')
ip = 1;
for i=1:nvx
k = estim_params_.var_exo(i,1);
@ -247,33 +209,12 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
stdh(ip));
ip = ip+1;
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
TeXEnd(fidTeX)
end
if nvn
TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_3.TeX'];
fidTeX = fopen(TeXfile,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
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');
TeXBegin_Bayesian(fidTeX,3,'standard deviation of measurement errors')
ip = nvx+1;
for i=1:nvn
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));
ip = ip+1;
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
TeXEnd(fidTeX)
end
if ncx
TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_4.TeX'];
fidTeX = fopen(TeXfile,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
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');
TeXBegin_Bayesian(fidTeX,4,'correlation of structural shocks')
ip = nvx+nvn+1;
for i=1:ncx
k1 = estim_params_.corrx(i,1);
@ -326,33 +246,12 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
stdh(ip));
ip = ip+1;
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
TeXEnd(fidTeX)
end
if ncn
TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_5.TeX'];
fidTeX = fopen(TeXfile,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
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');
TeXBegin_Bayesian(fidTeX,5,'correlation of measurement errors')
ip = nvx+nvn+ncx+1;
for i=1:ncn
k1 = estim_params_.corrn(i,1);
@ -366,34 +265,13 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
stdh(ip));
ip = ip+1;
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
TeXEnd(fidTeX)
end
elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
if np
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_1.TeX'];
fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
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');
TeXBegin_ML(fidTeX,1,'parameters',table_title,LaTeXtitle)
ip = nvx+nvn+ncx+ncn+1;
for i=1:np
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));
ip = ip + 1;
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
TeXEnd(fidTeX)
end
if nvx
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_2.TeX'];
fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
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');
TeXBegin_ML(fidTeX,2,'standard deviation of structural shocks',table_title,LaTeXtitle)
ip = 1;
for i=1:nvx
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));
ip = ip+1;
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
TeXEnd(fidTeX)
end
if nvn
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_3.TeX'];
fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
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');
TeXBegin_ML(fidTeX,3,'standard deviation of measurement errors',table_title,LaTeXtitle)
ip = nvx+1;
for i=1:nvn
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));
ip = ip+1;
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
TeXEnd(fidTeX)
end
if ncx
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_4.TeX'];
fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
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');
TeXBegin_ML(fidTeX,4,'correlation of structural shocks',table_title,LaTeXtitle)
ip = nvx+nvn+1;
for i=1:ncx
k1 = estim_params_.corrx(i,1);
@ -515,33 +330,12 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
tstath(ip));
ip = ip+1;
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
TeXEnd(fidTeX)
end
if ncn
filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_5.TeX'];
fidTeX = fopen(filename,'w');
fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
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');
TeXBegin_ML(fidTeX,5,'correlation of measurement errors',table_title,LaTeXtitle)
ip = nvx+nvn+ncx+1;
for i=1:ncn
k1 = estim_params_.corrn(i,1);
@ -553,10 +347,60 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
tstath(ip));
ip = ip+1;
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end
TeXEnd(fidTeX)
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
% of the prior distribution.
%
@ -10,7 +10,8 @@ function m = compute_prior_mode(hyperparameters,shape)
% shape=3 => Gaussian distribution,
% shape=4 => Inverse Gamma (type 1) distribution,
% shape=5 => Uniform distribution,
% shape=6 => Inverse Gamma (type 2) distribution.
% shape=6 => Inverse Gamma (type 2) distribution,
% shape=8 => Weibull distribution.
%
% OUTPUTS
% 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.
% [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.
%
@ -38,6 +39,7 @@ function m = compute_prior_mode(hyperparameters,shape)
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
m = NaN ;
switch shape
case 1
@ -56,6 +58,8 @@ switch shape
m = m*(hyperparameters(4)-hyperparameters(3)) + hyperparameters(3) ;
end
case 2
% a = hyperparameters(1) [shape parameter]
% b = hyperparameters(2) [scale parameter]
if hyperparameters(1)<1
m = 0;
else
@ -69,7 +73,7 @@ switch shape
case 4
% s = hyperparameters(1)
% 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
m = m + hyperparameters(3);
end
@ -82,6 +86,156 @@ switch shape
if length(hyperparameters)>2
m = m + hyperparameters(3) ;
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
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.
%
% 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:
%! @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
% Copyright (C) 2003-2015 Dynare Team
%
% 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
% 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 = [];
nu = [];
if nargin==3
use_fzero_flag = 0;
end
sigma2 = sigma^2;
mu2 = mu^2;
sigma = sqrt(sigma2);
mu2 = mu*mu;
if type == 2; % Inverse Gamma 2
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
error('inverse_gamma_specification:: Failed in solving for the hyperparameters!');
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!');
end
end
@ -133,17 +146,61 @@ else
end
%@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);
%$ [s1,nu1] = inverse_gamma_specification(.75,.2,1,1);
%$ [s3,nu3] = inverse_gamma_specification(.75,.1,1,0);
%$ [s4,nu4] = inverse_gamma_specification(.75,.1,1,1);
%$ % 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);;
%$ if t(1)
%$ t(2) = abs(0.5-sqrt(.5*s)*gamma(.5*(nu-1))/gamma(.5*nu))<1e-12;
%$ t(3) = abs(0.05-s/(nu-2)+.5^2)<1e-12;
%$ end
%$ 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
abscissa = linspace(infbound,supbound,steps);
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
error(sprintf('draw_prior_density: unknown distribution shape (index %d, type %d)', indx, pshape(indx)));
end

View File

@ -210,7 +210,7 @@ H = Model.H;
% Test if Q is positive definite.
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
fval = objective_function_penalty_base+penalty;
exit_flag = 0;
@ -231,7 +231,7 @@ end
% Test if H is positive definite.
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
fval = objective_function_penalty_base+penalty;
exit_flag = 0;
@ -307,14 +307,8 @@ end
% Define the deterministic linear trend of the measurement equation.
if BayesInfo.with_trend
trend_coeff = zeros(DynareDataset.vobs,1);
t = DynareOptions.trend_coeffs;
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];
[trend_addition, trend_coeff]=compute_trend_coefficients(Model,DynareOptions,DynareDataset.vobs,DynareDataset.nobs);
trend = repmat(constant,1,DynareDataset.nobs)+trend_addition;
else
trend_coeff = zeros(DynareDataset.vobs,1);
trend = repmat(constant,1,DynareDataset.nobs);
@ -654,30 +648,38 @@ end
% 4. Likelihood evaluation
%------------------------------------------------------------------------------
singularity_has_been_detected = false;
if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter
if no_missing_data_flag
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);
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
[LIK,lik] = kalman_filter(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{:});
a,Pstar, ...
kalman_tol, riccati_tol, ...
DynareOptions.presample, ...
T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods, ...
analytic_deriv_info{:});
end
else
if 0 %DynareOptions.block
[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
[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, ...
kalman_tol, DynareOptions.riccati_tol, ...
DynareOptions.presample, ...
T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods);
a, Pstar, ...
kalman_tol, DynareOptions.riccati_tol, ...
DynareOptions.presample, ...
T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods);
end
end
if analytic_derivation,
@ -688,6 +690,7 @@ if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter
end
if isinf(LIK)
if DynareOptions.use_univariate_filters_if_singularity_is_detected
singularity_has_been_detected = true;
if kalman_algo == 1
kalman_algo = 2;
else
@ -745,19 +748,21 @@ if (kalman_algo==2) || (kalman_algo==4)
Pinf = blkdiag(Pinf,zeros(pp));
H1 = zeros(pp,1);
mmm = mm+pp;
if singularity_has_been_detected
a = zeros(mmm,1);
end
end
end
if analytic_derivation,
analytic_deriv_info{5}=DH;
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), ...
a,Pstar, ...
DynareOptions.kalman_tol, ...
DynareOptions.riccati_tol, ...
DynareOptions.presample, ...
T,Q,R,H1,Z,mmm,pp,rr,Zflag,diffuse_periods,analytic_deriv_info{:});
a,Pstar, ...
DynareOptions.kalman_tol, ...
DynareOptions.riccati_tol, ...
DynareOptions.presample, ...
T,Q,R,H1,Z,mmm,pp,rr,Zflag,diffuse_periods,analytic_deriv_info{:});
if analytic_derivation,
LIK1=LIK;
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);
end
if asy_Hess,
% 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);
% else
% 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);
% else
Hess = LIK1{3};
% end
% end
end
end

View File

@ -1,12 +1,17 @@
function info = dyn_forecast(var_list,task)
% function dyn_forecast(var_list,task)
function [forecast,info] = dyn_forecast(var_list,M,options,oo,task,dataset_info)
% function dyn_forecast(var_list,M,options,oo,task,dataset_info)
% 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
% var_list: list of variables (character matrix)
% M: Dynare model structure
% options: Dynare options structure
% oo: Dynare results structure
% task: indicates how to initialize the forecast
% either 'simul' or 'smoother'
% dataset_info: Various informations about the dataset (descriptive statistics and missing observations).
% OUTPUTS
% nothing is returned but the procedure saves output
% in oo_.forecast.Mean
@ -16,7 +21,7 @@ function info = dyn_forecast(var_list,task)
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2015 Dynare Team
% Copyright (C) 2003-2016 Dynare Team
%
% 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
% 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;
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)
var_list = endo_names(1:M_.orig_endo_nbr, :);
var_list = endo_names(1:M.orig_endo_nbr, :);
end
i_var = [];
for i = 1:size(var_list)
@ -59,82 +68,106 @@ n_var = length(i_var);
trend = 0;
switch task
case 'simul'
horizon = options_.periods;
horizon = options.periods;
if horizon == 0
horizon = 5;
end
if isempty(M_.endo_histval)
y0 = repmat(oo_.dr.ys,1,maximum_lag);
if isempty(M.endo_histval)
y0 = repmat(oo.dr.ys,1,maximum_lag);
else
y0 = M_.endo_histval;
y0 = M.endo_histval;
end
case 'smoother'
horizon = options_.forecast;
y_smoothed = oo_.SmoothedVariables;
y0 = zeros(M_.endo_nbr,maximum_lag);
for i = 1:M_.endo_nbr
v_name = deblank(M_.endo_names(i,:));
y0(i,:) = y_smoothed.(v_name)(end-maximum_lag+1:end)+oo_.dr.ys(i);
horizon = options.forecast;
y_smoothed = oo.SmoothedVariables;
y0 = zeros(M.endo_nbr,maximum_lag);
for i = 1:M.endo_nbr
v_name = deblank(M.endo_names(i,:));
y0(i,:) = y_smoothed.(v_name)(end-maximum_lag+1:end); %includes steady state or mean, but simult_ will subtract only steady state
% 2. Subtract mean/steady state and add steady state; takes care of prefiltering
if isfield(oo.Smoother,'Constant') && isfield(oo.Smoother.Constant,v_name)
y0(i,:)=y0(i,:)-oo.Smoother.Constant.(v_name)(end-maximum_lag+1:end); %subtract mean or steady state
if options.loglinear
y0(i,:)=y0(i,:)+log(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
gend = options_.nobs;
if isfield(oo_.Smoother,'TrendCoeffs')
var_obs = options_.varobs;
endo_names = M_.endo_names;
order_var = oo_.dr.order_var;
gend = options.nobs;
if isfield(oo.Smoother,'TrendCoeffs')
var_obs = options.varobs;
endo_names = M.endo_names;
order_var = oo.dr.order_var;
i_var_obs = [];
trend_coeffs = [];
for i=1:length(var_obs)
tmp = strmatch(var_obs{i},endo_names(i_var,:),'exact');
if ~isempty(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
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
global bayestopt_
if isfield(bayestopt_,'mean_varobs')
trend = trend + repmat(bayestopt_.mean_varobs,1,horizon+M_.maximum_lag);
else
trend_coeffs=zeros(length(options.varobs),1);
end
otherwise
error('Wrong flag value')
end
if M_.exo_det_nbr == 0
[yf,int_width] = forcst(oo_.dr,y0,horizon,var_list);
if M.exo_det_nbr == 0
[yf,int_width] = forcst(oo.dr,y0,horizon,var_list);
else
exo_det_length = size(oo_.exo_det_simul,1)-M_.maximum_lag;
exo_det_length = size(oo.exo_det_simul,1)-M.maximum_lag;
if horizon > exo_det_length
ex = zeros(horizon,M_.exo_nbr);
oo_.exo_det_simul = [ oo_.exo_det_simul;...
repmat(oo_.exo_det_steady_state',...
ex = zeros(horizon,M.exo_nbr);
oo.exo_det_simul = [ oo.exo_det_simul;...
repmat(oo.exo_det_steady_state',...
horizon- ...
exo_det_length,1)];
elseif horizon < exo_det_length
ex = zeros(exo_det_length,M_.exo_nbr);
ex = zeros(exo_det_length,M.exo_nbr);
end
[yf,int_width] = simultxdet(y0,ex,oo_.exo_det_simul,...
options_.order,var_list,M_,oo_,options_);
[yf,int_width] = simultxdet(y0,ex,oo.exo_det_simul,...
options.order,var_list,M,oo,options);
end
if ~isscalar(trend)
if ~isscalar(trend) %add trend back to forecast
yf(i_var_obs,:) = yf(i_var_obs,:) + trend;
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
eval(['oo_.forecast.Mean.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+(1:horizon))'';']);
eval(['oo_.forecast.HPDinf.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+(1:horizon))''-' ...
' int_width(1:horizon,' int2str(i) ');']);
eval(['oo_.forecast.HPDsup.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+(1:horizon))''+' ...
' int_width(1:horizon,' int2str(i) ');']);
vname = deblank(var_list(i,:));
forecast.Mean.(vname) = yf(i,maximum_lag+(1:horizon))';
forecast.HPDinf.(vname)= yf(i,maximum_lag+(1:horizon))' - int_width(1:horizon,i);
forecast.HPDsup.(vname) = yf(i,maximum_lag+(1:horizon))' + int_width(1:horizon,i);
end
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) ');']);
for i=1:M.exo_det_nbr
forecast.Exogenous.(deblank(M.exo_det_names(i,:))) = oo.exo_det_simul(maximum_lag+(1:horizon),i);
end
if options_.nograph == 0
forecast_graphs(var_list,M_, oo_,options_)
if options.nograph == 0
oo.forecast = forecast;
forecast_graphs(var_list,M, oo,options)
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);
%% 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);
label_width);
else %use default length
label_width = max(size(deblank(char(headers(1,:),labels)),2))+2;
end
@ -21,7 +21,7 @@ if any(values) < 0 %add one character for minus sign
values_length = values_length+1;
end
%% get width of header strings
%% get width of header strings
headers_length = max(size(deblank(headers(2:end,:)),2));
if ~isempty(val_width)
val_width = max(max(headers_length,values_length)+4,val_width);
@ -34,7 +34,7 @@ header_string_format = sprintf('$%%%ds$',val_width);
%Create and print header string
if length(headers) > 0
header_string = sprintf(label_format_leftbound ,deblank(headers(1,:)));
header_code_string='l|';
header_code_string='l';
for i=2:size(headers,1)
header_string = [header_string '\t & \t ' sprintf(header_string_format,strrep(deblank(headers(i,:)),'\','\\'))];
header_code_string= [header_code_string 'c'];
@ -49,25 +49,35 @@ fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{center}\n');
fprintf(fidTeX,['\\begin{longtable}{%s} \n'],header_code_string);
fprintf(fidTeX,['\\caption{',title,'}\\\\\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,'\\hline \\endfirsthead \n');
fprintf(fidTeX,'\\midrule \\endfirsthead \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,'\\hline \\endhead \n');
fprintf(fidTeX,['\\hline \\multicolumn{',num2str(size(headers,1)),'}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n']);
fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
fprintf(fidTeX,'\\midrule \\endhead \n');
fprintf(fidTeX,['\\bottomrule \\multicolumn{',num2str(size(headers,1)),'}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n']);
fprintf(fidTeX,'\\bottomrule \\endlastfoot \n');
for i=1:size(values,1)
fprintf(fidTeX,label_format_leftbound,deblank(labels(i,:)));
fprintf(fidTeX,['\t & \t' value_format],values(i,:));
fprintf(fidTeX,' \\\\ \n');
end
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{longtable}\n ');
fprintf(fidTeX,'\\end{center}\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);

View File

@ -15,7 +15,7 @@ function dynareroot = dynare_config(path_to_dynare,verbose)
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2001-2015 Dynare Team
% Copyright (C) 2001-2016 Dynare Team
%
% This file is part of Dynare.
%
@ -100,12 +100,6 @@ if isoctave && ~user_has_octave_forge_package('nan')
addpath([dynareroot '/missing/corrcoef'])
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
% toolbox
if (isoctave && ~user_has_octave_forge_package('statistics')) ...

View File

@ -73,6 +73,7 @@ end
if options_.logged_steady_state
oo_.dr.ys=exp(oo_.dr.ys);
oo_.steady_state=exp(oo_.steady_state);
options_.logged_steady_state=0;
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.
nx = nvx+nvn+ncx+ncn+np; % Total number of parameters to be estimated.
%% Set the names of the priors.
pnames = [' ';'beta ';'gamm ';'norm ';'invg ';'unif ';'invg2'];
pnames = [' '; 'beta '; 'gamm '; 'norm '; 'invg '; 'unif '; 'invg2'; ' '; 'weibl'];
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 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);
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 = 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
[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_]=write_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend);
end
return
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
%prepare settings for newrat
if options_.mode_compute==5
@ -413,7 +397,7 @@ end
if (any(bayestopt_.pshape >0 ) && options_.mh_replic) || ...
(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);
if ~isempty(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
[marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_);
% 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
oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt_, oo_);
end
@ -499,39 +483,42 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
> 0) && options_.load_mh_file)) ...
|| ~options_.smoother ) && options_.partial_information == 0 % to be fixed
%% 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);
oo_.Smoother.SteadyState = ys;
oo_.Smoother.TrendCoeffs = trend_coeff;
oo_.Smoother.Variance = P;
i_endo = 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)))
oo_.FilteredVariablesKStepAhead = aK(options_.filter_step_ahead, ...
i_endo,:);
if isfield(options_,'kalman_algo')
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
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 ~isempty(options_.nk) && options_.nk > 0 && ~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file))
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
[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_,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.SteadyState = ys;
% oo_.Smoother.TrendCoeffs = trend_coeff;
% oo_.Smoother.Trend = Trend;
% oo_.Smoother.Variance = P;
% i_endo = 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)))
% oo_.FilteredVariablesKStepAhead = aK(options_.filter_step_ahead, ...
% i_endo,:);
% if isfield(options_,'kalman_algo')
% 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
% 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 ~isempty(options_.nk) && options_.nk > 0 && ~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file))
% 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
if ~options_.nograph,
[nbplt,nr,nc,lr,lc,nstar] = pltorg(M_.exo_nbr);
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);
end
end
%%
%% Smooth observational errors...
%%
if options_.prefilter == 1
yf = atT(bayestopt_.mf,:)+repmat(dataset_info.descriptive.mean',1,gend);
elseif options_.loglinear == 1
yf = atT(bayestopt_.mf,:)+repmat(log(ys(bayestopt_.mfys)),1,gend)+...
trend_coeff*[1:gend];
else
yf = atT(bayestopt_.mf,:)+repmat(ys(bayestopt_.mfys),1,gend)+...
trend_coeff*[1:gend];
end
% %%
% %% Smooth observational errors...
% %%
% 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)+Trend;
% elseif options_.loglinear == 1
% yf = atT(bayestopt_.mf,:)+repmat(log(ys(bayestopt_.mfys)),1,gend)+Trend;
% else
% yf = atT(bayestopt_.mf,:)+repmat(ys(bayestopt_.mfys),1,gend)+Trend;
% end
if nvn
number_of_plots_to_draw = 0;
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;
index = cat(1,index,i);
end
eval(['oo_.SmoothedMeasurementErrors.' options_.varobs{i} ' = measurement_error(i,:)'';']);
% eval(['oo_.SmoothedMeasurementErrors.' options_.varobs{i} ' = measurement_error(i,:)'';']);
end
if ~options_.nograph
[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
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
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_)
end
% Set prior bounds
bounds = prior_bounds(bayestopt_,options_);
bounds = prior_bounds(bayestopt_, options_.prior_trunc);
bounds.lb = max(bounds.lb,lb);
bounds.ub = min(bounds.ub,ub);
else % estimated parameters but no declared priors
@ -375,13 +375,11 @@ if ~isfield(options_,'trend_coeffs') % No!
else% Yes!
bayestopt_.with_trend = 1;
bayestopt_.trend_coeff = {};
trend_coeffs = options_.trend_coeffs;
nt = length(trend_coeffs);
for i=1:options_.number_of_observed_variables
if i > length(trend_coeffs)
if i > length(options_.trend_coeffs)
bayestopt_.trend_coeff{i} = '0';
else
bayestopt_.trend_coeff{i} = trend_coeffs{i};
bayestopt_.trend_coeff{i} = options_.trend_coeffs{i};
end
end
end
@ -530,11 +528,11 @@ end
[dataset_, dataset_info, newdatainterfaceflag] = makedataset(options_, options_.dsge_var*options_.dsge_varlag, gsa_flag);
% Set options_.nobs if needed
if newdatainterfaceflag
%set options for old interface from the ones for new interface
if ~isempty(dataset_)
options_.nobs = dataset_.nobs;
options_.first_obs=double(dataset_.init);
end
% setting steadystate_check_flag option
if options_.diffuse_filter
steadystate_check_flag = 0;
@ -558,7 +556,7 @@ if info(1)
print_info(info, 0, options_);
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;
else
options_.noconstant = 0;
@ -573,3 +571,28 @@ else
error('The option "prefilter" is inconsistent with the non-zero mean measurement equations in the model.')
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 any(bayestopt_.pshape > 0)
if options_ident.prior_range
prior_draw(1,1);
prior_draw(bayestopt_, options_.prior_trunc, true);
else
prior_draw(1);
prior_draw(bayestopt_, options_.prior_trunc, false);
end
else
options_ident.prior_mc=1;
@ -234,37 +234,44 @@ if iload <=0,
params = set_prior(estim_params_,M_,options_)';
if all(bayestopt_.pshape == 0)
parameters = 'ML_Starting_value';
parameters_TeX = 'ML starting value';
disp('Testing ML Starting value')
else
switch parameters
case 'posterior_mode'
disp('Testing posterior mode')
params(1,:) = get_posterior_parameters('mode');
case 'posterior_mean'
disp('Testing posterior mean')
params(1,:) = get_posterior_parameters('mean');
case 'posterior_median'
disp('Testing posterior median')
params(1,:) = get_posterior_parameters('median');
case 'prior_mode'
disp('Testing prior mode')
params(1,:) = bayestopt_.p5(:);
case 'prior_mean'
disp('Testing prior mean')
params(1,:) = bayestopt_.p1;
otherwise
disp('The option parameter_set has to be equal to:')
disp(' ''posterior_mode'', ')
disp(' ''posterior_mean'', ')
disp(' ''posterior_median'', ')
disp(' ''prior_mode'' or')
disp(' ''prior_mean''.')
error;
end
switch parameters
case 'posterior_mode'
parameters_TeX = 'Posterior mode';
disp('Testing posterior mode')
params(1,:) = get_posterior_parameters('mode');
case 'posterior_mean'
parameters_TeX = 'Posterior mean';
disp('Testing posterior mean')
params(1,:) = get_posterior_parameters('mean');
case 'posterior_median'
parameters_TeX = 'Posterior median';
disp('Testing posterior median')
params(1,:) = get_posterior_parameters('median');
case 'prior_mode'
parameters_TeX = 'Prior mode';
disp('Testing prior mode')
params(1,:) = bayestopt_.p5(:);
case 'prior_mean'
parameters_TeX = 'Prior mean';
disp('Testing prior mean')
params(1,:) = bayestopt_.p1;
otherwise
disp('The option parameter_set has to be equal to:')
disp(' ''posterior_mode'', ')
disp(' ''posterior_mean'', ')
disp(' ''posterior_median'', ')
disp(' ''prior_mode'' or')
disp(' ''prior_mean''.')
error;
end
end
else
params = [sqrt(diag(M_.Sigma_e))', M_.params'];
parameters = 'Current_params';
parameters_TeX = 'Current parameter values';
disp('Testing current parameter values')
end
[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')
disp_identification(params, idemodel_point, idemoments_point, name, advanced);
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
if SampleSize > 1,
@ -541,7 +548,7 @@ if SampleSize > 1,
disp_identification(pdraws(jmax,:), idemodel_max, idemoments_max, name,1);
close all,
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
[dum,jmin]=min(idemoments.cond);
fprintf('\n')
@ -556,7 +563,7 @@ if SampleSize > 1,
disp_identification(pdraws(jmin,:), idemodel_min, idemoments_min, name,1);
close all,
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
else
for j=1:length(jcrit),
@ -570,7 +577,7 @@ if SampleSize > 1,
disp_identification(pdraws(jcrit(j),:), idemodel_(j), idemoments_(j), name,1);
close all,
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
if ~iload,

View File

@ -14,7 +14,7 @@ function [ts,results] = extended_path(initial_conditions,sample_size)
%
% SPECIAL REQUIREMENTS
% Copyright (C) 2009-2015 Dynare Team
% Copyright (C) 2009-2016 Dynare Team
%
% 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
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;
exo_nbr = M_.exo_nbr;
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!'])
end
% Set waitbar (graphic or text mode)
hh = dyn_waitbar(0,'Please wait. Extended Path simulations...');
set(hh,'Name','EP simulations.');
@ -182,6 +185,8 @@ oo_.ep.failures.periods = [];
oo_.ep.failures.previous_period = cell(0);
oo_.ep.failures.shocks = cell(0);
oo_.exo_simul = shocks;
% Initializes some variables.
t = 1;
tsimul = 1;
@ -189,7 +194,7 @@ for k = 1:replic_nbr
results{k} = zeros(endo_nbr,sample_size+1);
results{k}(:,1) = initial_conditions;
end
make_ex_;
%make_ex_;
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;
% Main loop.
@ -265,78 +270,4 @@ else
end
end
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
assignin('base', 'Simulated_time_series', ts);

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_);
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);
llik = llik - ldens;

View File

@ -32,6 +32,13 @@ dr = oo.dr;
exo_nbr = M.exo_nbr;
nstatic = M.nstatic;
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);
Gy = dr.ghx(nstatic+(1:nspred),:);

View File

@ -87,35 +87,6 @@ if ischar(parameters)
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);
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
[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);

View File

@ -22,7 +22,7 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2001-2013 Dynare Team
% Copyright (C) 2001-2016 Dynare Team
%
% 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
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
if options.ramsey_policy
@ -58,7 +60,7 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
options);
%test whether it solves model conditional on the instruments
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)));
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
% none
% Copyright (C) 2001-2012 Dynare Team
% Copyright (C) 2001-2016 Dynare Team
%
% 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
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
debug = false;
ys = [];
params = [];
info = 0;
params = M.params;
info = 0;
fname = M.fname;
if options.steadystate_flag == 1
% old format
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
if length(M.aux_vars) > 0 && ~options.ramsey_policy
if debug
ys0 = ys;
end
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
check1 = 0;
if ~options.steadystate.nocheck
% 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
info(1) = 19;
info(2) = check; % to be improved

View File

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

View File

@ -17,7 +17,7 @@ function [yf,int_width]=forcst(dr,y0,horizon,var_list)
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2012 Dynare Team
% Copyright (C) 2003-2016 Dynare Team
%
% 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
% 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);
nstatic = M_.nstatic;
nspred = M_.nspred;

View File

@ -1,5 +1,16 @@
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
%
% This file is part of Dynare.
@ -24,14 +35,10 @@ endo_nbr = M_.endo_nbr;
exo_nbr = M_.exo_nbr;
ykmin_ = M_.maximum_endo_lag;
order = options_.order;
k1 = [ykmin_:-1:1];
k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]);
k2 = k2(:,1)+(ykmin_+1-k2(:,2))*endo_nbr;
it_ = ykmin_ + 1 ;
% eliminate shocks with 0 variance
i_exo_var = setdiff([1:exo_nbr],find(diag(Sigma_e_) == 0));
nxs = length(i_exo_var);

View File

@ -1,6 +1,15 @@
function yf=forcst2a(y0,dr,e)
% Copyright (C) 2008-2010 Dynare Team
% function yf=forcst2a(y0,dr,e)
% 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.
%
@ -19,13 +28,10 @@ function yf=forcst2a(y0,dr,e)
global M_ options_
Sigma_e_ = M_.Sigma_e;
endo_nbr = M_.endo_nbr;
exo_nbr = M_.exo_nbr;
ykmin_ = M_.maximum_endo_lag;
horizon = size(e,1);
order = options_.order;
k1 = [ykmin_:-1:1];
k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]);

View File

@ -11,7 +11,7 @@ function ext = get_file_extension(file)
% REMARKS
% 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.
%
@ -28,15 +28,9 @@ function ext = get_file_extension(file)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% Clean-up path
file = strrep(file, '../', '');
file = strrep(file, './', '');
[dir, fname, ext] = fileparts(file);
remain = file;
while ~isempty(remain)
[ext, remain] = strtok(remain,'.');
end
if strcmp(ext,file)
ext = [];
if ~isempty(ext)
% Removes the leading dot.
ext = ext(2:end);
end

View File

@ -11,7 +11,7 @@ function global_initialization()
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2015 Dynare Team
% Copyright (C) 2003-2016 Dynare Team
%
% This file is part of Dynare.
%
@ -407,7 +407,7 @@ options_.filtered_vars = 0;
options_.first_obs = NaN;
options_.nobs = NaN;
options_.kalman_algo = 0;
options_.fast_kalman = 0;
options_.fast_kalman_filter = 0;
options_.kalman_tol = 1e-10;
options_.diffuse_kalman_tol = 1e-6;
options_.use_univariate_filters_if_singularity_is_detected = 1;
@ -510,6 +510,16 @@ M_.Correlation_matrix = [];
M_.Correlation_matrix_ME = [];
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
options_.homotopy_mode = 0;
options_.homotopy_steps = 1;

View File

@ -105,7 +105,7 @@ for j=1:nvar
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,'\\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,' \n');
end

View File

@ -366,11 +366,14 @@ else
end
if options_.opt_gsa.ppost
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
if options_.opt_gsa.pprior
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
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
@ -408,12 +411,15 @@ else
end
if options_.opt_gsa.ppost
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
if options_.opt_gsa.pprior
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
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
@ -450,11 +456,14 @@ else
end
if options_.opt_gsa.ppost
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
if options_.opt_gsa.pprior
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
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
@ -662,11 +671,14 @@ else
%set(findobj(get(h0,'children'),'type','text'),'interpreter','none')
if options_.opt_gsa.ppost
dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_);
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
if options_.opt_gsa.pprior
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
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
@ -720,11 +732,14 @@ else
%set(findobj(get(h0,'children'),'type','text'),'interpreter','none')
if options_.opt_gsa.ppost
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
if options_.opt_gsa.pprior
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
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
@ -789,4 +804,19 @@ else
% % close all
% 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)
% Copyright (C) 2014 Dynare Team
% Copyright (C) 2014-2016 Dynare Team
%
% This file is part of Dynare.
%
@ -303,8 +303,8 @@ if ~isempty(indx_irf),
end
if ~DynareOptions.nograph,
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
skipline()
end
@ -495,9 +495,24 @@ if ~isempty(indx_moment)
end
if ~DynareOptions.nograph,
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
skipline()
end
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')
if mod(j,6)==0 | j==M_.exo_nbr,
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
@ -223,6 +224,7 @@ if opt_gsa.morris==1,
xlabel(' ')
title('Elementary effects variance decomposition')
dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_vdec'],options_);
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_vdec'],1,'Screening identification: variance decomposition','morris_vdec')
else
save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'vdec')
@ -328,6 +330,8 @@ if opt_gsa.morris==1,
xlabel(' ')
title('Elementary effects in the moments')
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),
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -724,6 +728,7 @@ if opt_gsa.morris==1,
xlabel(' ')
title('Elementary effects in the model')
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))
% % boxplot(SAmunorm','whis',10,'symbol','r.')
@ -1508,7 +1513,7 @@ else, % main effects analysis
% SAmeanexo=mean(SAmomN(:,1:nshock));
% figure, bar(latent'*SAcc),
hh=dyn_figure(options_);
hh=dyn_figure(options_,'Name',['Identifiability indices in the ',fsuffix,' moments.']);
bar(sum(SAcc)),
set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
set(gca,'xlim',[0.5 npT+0.5])
@ -1522,7 +1527,8 @@ else, % main effects analysis
xlabel(' ')
title(['Identifiability indices in the ',fsuffix,' moments.'],'interpreter','none')
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),
% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:nshock])
% set(gca,'xlim',[0.5 nshock+0.5])
@ -1541,3 +1547,19 @@ else, % main effects analysis
end
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)
% Draws from the prior distributions
% Adapted by M. Ratto from prior_draw (of DYNARE, copyright M. Juillard),
% for use with Sensitivity Toolbox for DYNARE
%
% Draws from the prior distributions for use with Sensitivity Toolbox for DYNARE
%
% INPUTS
% o init [integer] scalar equal to 1 (first call) or 0.
@ -25,7 +22,7 @@ function pdraw = prior_draw_gsa(init,rdraw)
% Reference:
% 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.
%
@ -58,7 +55,7 @@ if init
[junk1,junk2,junk3,lb,ub,junk4] = set_prior(estim_params_,M_,options_); %Prepare bounds
if ~isempty(bayestopt_) && any(bayestopt_.pshape > 0)
% Set prior bounds
bounds = prior_bounds(bayestopt_,options_);
bounds = prior_bounds(bayestopt_, options_.prior_trunc);
bounds.lb = max(bounds.lb,lb);
bounds.ub = min(bounds.ub,ub);
else % estimated parameters but no declared priors
@ -90,6 +87,9 @@ if init
% TO BE CHECKED
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));
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
% Nothing to do here.
end
@ -115,6 +115,8 @@ for i = 1:npar
case 6% INV-GAMMA2 distribution
% TO BE CHECKED
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
% Nothing to do here.
end

View File

@ -1,14 +1,17 @@
function [xcum] = priorcdf(para, pshape, p6, p7, p3, p4)
% This procedure transforms x vectors into cumulative values
function xcum = priorcdf(para, pshape, p6, p7, p3, p4)
% This procedure transforms x vectors into cumulative values
% pshape: 0 is point mass, both para and p2 are ignored
% 1 is BETA(mean,stdd)
% 2 is GAMMA(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]
% 6 is INNGAMMA(s^2,nu) type II
% 8 is WEIBULL(s, k)
% 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.
%
@ -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
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
nprio = length(pshape);
i = 1;
while i <= nprio;
a = 0;
b = 0;
if pshape(i) == 1; % (generalized) BETA Prior
% mu = (p1(i)-p3(i))/(p4(i)-p3(i));
% stdd = p2(i)/(p4(i)-p3(i));
% a = (1-mu)*mu^2/stdd^2 - mu;
% b = a*(1/mu - 1);
%lnprior = lnprior + lpdfgbeta(para(i),a,b,p3(i),p4(i)) ;
para(:,i) = (para(:,i)-p3(i))./(p4(i)-p3(i));
% xcum(:,i) = betacdf(para(:,i),a,b) ;
xcum(:,i) = betainc(para(:,i),p6(i),p7(i));
elseif pshape(i) == 2; % GAMMA PRIOR
% b = p2(i)^2/(p1(i)-p3(i));
% a = (p1(i)-p3(i))/b;
%lnprior = lnprior + lpdfgam(para(i)-p3(i),a,b);
% xcum(:,i) = gamcdf(para(:,i)-p3(i),a,b);
xcum(:,i) = gamcdf(para(:,i)-p3(i),p6(i),p7(i));
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;
for i=1:length(pshape)
switch pshape(i)
case 1 % (generalized) BETA Prior
para(:,i) = (para(:,i)-p3(i))./(p4(i)-p3(i));
xcum(:,i) = betainc(para(:,i),p6(i),p7(i));
case 2 % GAMMA PRIOR
xcum(:,i) = gamcdf(para(:,i)-p3(i),p6(i),p7(i));
case 3 % GAUSSIAN PRIOR
xcum(:,i) = 0.5 * erfc(-(para(:,i)-p6(i))/p7(i) ./ sqrt(2));
case 4 % INVGAMMA1 PRIOR
xcum(:,i) = gamcdf(1./(para(:,i)-p3(i)).^2,p7(i)/2,2/p6(i));
case 5 % UNIFORM PRIOR
xcum(:,i) = (para(:,i)-p3(i))./(p4(i)-p3(i));
case 6 % INVGAMMA2 PRIOR
xcum(:,i) = gamcdf(1./(para(:,i)-p3(i)),p7(i)/2,2/p6(i));
case 8 % WEIBULL
xcum(:,i) = wblcdf(para(:,i)-p3(i),p6(i),p7(i));
otherwise
error('Unknown prior shape!')
end
end

View File

@ -24,7 +24,7 @@ function [gend, data] = read_data()
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_ bayestopt_
global options_
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);
end
if options_.prefilter == 1
bayestopt_.mean_varobs = mean(rawdata,1);
data = transpose(rawdata-ones(gend,1)*bayestopt_.mean_varobs);
data = transpose(rawdata-ones(gend,1)* mean(rawdata,1));
else
data = transpose(rawdata);
end

View File

@ -56,7 +56,7 @@ pvalue_corr = options_gsa_.alpha2_redform;
pnames = M_.param_names(estim_params_.param_vals(:,1),:);
fname_ = M_.fname;
bounds = prior_bounds(bayestopt_,options_);
bounds = prior_bounds(bayestopt_, options_.prior_trunc);
if nargin==0,
dirname='';
@ -189,6 +189,7 @@ for j=1:size(anamendo,1)
hold off,
title([namendo,' vs ', namexo ' - threshold [' num2str(threshold(1)) ' ' num2str(threshold(2)) ']'],'interpreter','none')
dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namexo],options_);
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
si(:,js) = NaN(np,1);
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')
end
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_);
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
@ -265,6 +267,7 @@ for j=1:size(anamendo,1)
end
if iplo<9 && iplo>0 && ifig && ~options_.nograph,
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
ifig=0;
iplo=0;
@ -322,6 +325,7 @@ for j=1:size(anamendo,1)
hold off,
title([namendo,' vs lagged ', namlagendo ' - threshold [' num2str(threshold(1)) ' ' num2str(threshold(2)) ']'],'interpreter','none')
dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo],options_);
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
delete([xdir, '/*threshold*.*'])
@ -391,6 +395,7 @@ for j=1:size(anamendo,1)
title([logflag,' ',namendo,' vs ',namlagendo,'(-1)'],'interpreter','none')
if iplo==9,
dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_);
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
@ -399,6 +404,7 @@ for j=1:size(anamendo,1)
end
if iplo<9 && iplo>0 && ifig && ~options_.nograph,
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
@ -417,7 +423,8 @@ if isempty(threshold) && ~options_.nograph,
end
title('Reduced form GSA')
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
hfig=dyn_figure(options_,'name','Reduced Form GSA'); %bar(silog)
% boxplot(silog','whis',10,'symbol','r.')
@ -432,6 +439,7 @@ if isempty(threshold) && ~options_.nograph,
end
title('Reduced form GSA - Log-transformed elements')
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
@ -602,7 +610,8 @@ end
title(['Out-of-sample prediction - R2=' num2str(r2,2)],'interpreter','none')
end
dyn_saveas(hfig,fname,options_);
create_TeX_loader(options_,fname,['Out-of-sample prediction - R2=' num2str(r2,2)],'redform_gsa_log')
if options_.nodisplay
close(hmap);
end
@ -617,6 +626,8 @@ else
plot(y0,[yf y0],'.'),
title([namy,' vs ', namx,' pred'],'interpreter','none')
dyn_saveas(hfig,[fname '_pred'],options_);
create_TeX_loader(options_,[fname '_pred'],options_map.title,[namy,' vs ', namx,' pred'])
end
end
% si = gsa_.multivariate.si;
@ -735,5 +746,21 @@ if ~isoctave
end
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
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
title([namendo,' vs. ',namexo],'interpreter','none')
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
@ -98,6 +99,7 @@ for j=1:size(anamendo,1),
end
if iplo<9 && iplo>0 && ifig,
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
iplo=0;
@ -132,16 +134,18 @@ for j=1:size(anamendo,1),
title([namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none')
if iplo==9,
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
if iplo<9 && iplo>0 && ifig,
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
hh=dyn_figure(options_);
hh=dyn_figure(options_,'Name','Reduced form screening');
%bar(SA)
% boxplot(SA','whis',10,'symbol','r.')
myboxplot(SA',[],'.',[],10)
@ -156,3 +160,21 @@ xlabel(' ')
ylabel('Elementary Effects')
title('Reduced form screening')
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,
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

View File

@ -38,7 +38,7 @@ function x0 = stab_map_(OutputDirectoryName,opt_gsa)
% Reference:
% 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.
%
@ -99,7 +99,7 @@ p4 = bayestopt_.p4(nshock+1:end);
[junk1,junk2,junk3,lb,ub,junk4] = set_prior(estim_params_,M_,options_); %Prepare bounds
if ~isempty(bayestopt_) && any(bayestopt_.pshape > 0)
% Set prior bounds
bounds = prior_bounds(bayestopt_,options_);
bounds = prior_bounds(bayestopt_, options_.prior_trunc);
bounds.lb = max(bounds.lb,lb);
bounds.ub = min(bounds.ub,ub);
else % estimated parameters but no declared priors
@ -130,7 +130,6 @@ options_.periods=0;
options_.nomoments=1;
options_.irf=0;
options_.noprint=1;
options_.simul=0;
if fload==0,
% if prepSA
% 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
options_.irf=opt.irf;
options_.noprint=opt.noprint;
if isfield(opt,'simul'),
options_.simul=opt.simul;
end

View File

@ -102,8 +102,34 @@ if iplot && ~options_.nograph
end
if nparplot>12,
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
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

View File

@ -114,6 +114,19 @@ for j=1:npar,
title(['cc = ',num2str(c0(i2(jx),j))])
if (mod(j2,12)==0) && j2>0,
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
@ -122,6 +135,19 @@ for j=1:npar,
end
if ~nograph && (j==(npar)) && j2>0 && (mod(j2,12)~=0),
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

View File

@ -73,14 +73,22 @@ for ll = 1:n,
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
fprintf(fidTeX,'{\\tiny \n');
fprintf(fidTeX,'\\begin{table}\n');
fprintf(fidTeX,'\\centering\n');
fprintf(fidTeX,'\\begin{tabular}{l|lc} \n');
fprintf(fidTeX,'\\hline\\hline \\\\ \n');
fprintf(fidTeX,'\\begin{longtable}{llc} \n');
fprintf(fidTeX,['\\caption{Collinearity patterns with ',int2str(ll),' parameter(s)}\n ']);
fprintf(fidTeX,['\\label{Table:CollinearityPatterns:',int2str(ll),'}\\\\\n']);
fprintf(fidTeX,'\\toprule \n');
fprintf(fidTeX,' Parameter & Explanatory & cosn \\\\ \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,
plist='';
for ii=1:ll,
@ -93,11 +101,8 @@ for ll = 1:n,
plist,...
cosnJ(i,ll));
end
fprintf(fidTeX,'\\hline\\hline \n');
fprintf(fidTeX,'\\end{tabular}\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,'\\bottomrule \n');
fprintf(fidTeX,'\\end{longtable}\n');
fprintf(fidTeX,'} \n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);

View File

@ -147,7 +147,7 @@ if info(1)==0,
info = stoch_simul(char(options_.varobs));
dataset_ = dseries(oo_.endo_simul(options_.varobs_id,100+1:end)',dates('1Q1'), options_.varobs);
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 = DsgeLikelihood(xparam1,data_info,options_,M_,estim_params_,bayestopt_,oo_);
options_.analytic_derivation = analytic_derivation;

View File

@ -19,7 +19,7 @@ function DynareResults = initial_estimation_checks(objective_function,xparam1,Dy
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2003-2015 Dynare Team
% Copyright (C) 2003-2016 Dynare Team
%
% This file is part of Dynare.
%
@ -40,6 +40,10 @@ function DynareResults = initial_estimation_checks(objective_function,xparam1,Dy
%singularity check
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
error(['initial_estimation_checks:: Estimation can''t take place because there are less declared shocks than observed variables!'])
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!'])
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
% % 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)
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('Check whether this is really intended.\n')
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)
end
if any(abs(DynareResults.steady_state(BayesInfo.mfys))>1e-9) && (DynareOptions.prefilter==1)
disp(['You are trying to estimate a model with a non zero steady state for the observed endogenous'])
disp(['variables using demeaned data!'])
error('You should change something in your mod file...')
if DynareOptions.prefilter==1
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(['You are trying to estimate a model with a non zero steady state for the observed endogenous'])
disp(['variables using demeaned data!'])
error('You should change something in your mod file...')
end
end
if ~isequal(DynareOptions.mode_compute,11)

View File

@ -85,7 +85,7 @@ notsteady = 1;
F_singular = 1;
s = 0;
while notsteady & t<=last
while notsteady && t<=last
s = t-start+1;
d_index = data_index{t};
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,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,tolx,varargin)
% Computes the optimal step by minimizing the residual sum of squares
%
% 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
% j1: equations index to be solved
% j2: unknowns index
% tolx: tolerance parameter
% varargin: list of arguments following j2
%
% OUTPUTS
@ -23,7 +24,7 @@ function [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,varargin)
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2001-2010 Dynare Team
% Copyright (C) 2001-2016 Dynare Team
%
% 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
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global options_
alf = 1e-4 ;
tolx = options_.solve_tolx;
alam = 1;
x = xold;
nn = length(j2);
summ = sqrt(sum(p.*p)) ;
summ = sqrt(p'*p);
if ~isfinite(summ)
eq_number_string=[];
for ii=1:length(j1)-1
@ -73,7 +72,7 @@ if ~isfinite(summ)
end
if summ > stpmax
p=p.*stpmax/summ ;
p = p*stpmax/summ ;
end
slope = g'*p ;
@ -90,19 +89,16 @@ while 1
check = 1 ;
return
end
x(j2) = xold(j2) + (alam*p) ;
fvec = feval(func,x,varargin{:}) ;
fvec = fvec(j1);
f = 0.5*fvec'*fvec ;
f = 0.5*(fvec'*fvec) ;
if any(isnan(fvec))
alam = alam/2 ;
alam2 = alam ;
f2 = f ;
fold2 = fold ;
else
if f <= fold+alf*alam*slope
check = 0;
break ;
@ -124,15 +120,11 @@ while 1
else
tmplam = (-b+sqrt(disc))/(3*a) ;
end
end
if tmplam > 0.5*alam
tmplam = 0.5*alam;
end
end
alam2 = alam ;
f2 = f ;
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
% assignin statement.
% Copyright (C) 2013 Dynare Team
% Copyright (C) 2013-16 Dynare Team
%
% 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.InitialSeeds = 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,'InitialLogLiK');
record = rmfield(record,'Seeds');
@ -64,6 +65,9 @@ else
if ~isfield(record,'MCMCConcludedSuccessfully')
record.MCMCConcludedSuccessfully = NaN; % This information is forever lost...
end
if ~isfield(record,'MAX_nruns')
record.MAX_nruns=NaN(size(record.MhDraws,1),1); % This information is forever lost...
end
end
if isequal(nargout,0)

View File

@ -3,8 +3,8 @@ function [ldens,Dldens,D2ldens] = lpdfgam(x,a,b);
%
% INPUTS
% x [double] m*n matrix of locations,
% a [double] m*n matrix or scalar, First GAMMA distribution parameters,
% b [double] m*n matrix or scalar, Second 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 (scale),
%
% OUTPUTS
% 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
% none
% Copyright (C) 2003-2011 Dynare Team
% Copyright (C) 2003-2016 Dynare Team
%
% 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_)
%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.
%
@ -19,16 +19,16 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck,
% o oo_ outputs structure
%
% OUTPUTS
% o ix2 [double] (nblck*npar) vector of starting points for different chains
% o ilogpo2 [double] (nblck*1) vector of initial posterior values for different chains
% o ix2 [double] (NumberOfBlocks*npar) vector of starting points 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 MetropolisFolder [string] path to the Metropolis subfolder
% o fblck [scalar] number of the first MH chain to be run (not equal to 1 in case of recovery)
% o fline [double] (nblck*1) vector of first draw in each chain (not equal to 1 in case of recovery)
% o FirstBlock [scalar] number of the first MH chain to be run (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 nblck [scalar] Number of MCM chains requested
% o nruns [double] (nblck*1) number of draws in each chain
% o NewFile [scalar] (nblck*1) vector storing the number
% o NumberOfBlocks [scalar] Number of MCM chains requested
% o nruns [double] (NumberOfBlocks*1) number of draws in each chain
% o NewFile [scalar] (NumberOfBlocks*1) vector storing the number
% of the first MH-file to created for each chain when saving additional
% draws
% o MAX_nruns [scalar] maximum number of draws in each MH-file on the harddisk
@ -59,10 +59,10 @@ ix2 = [];
ilogpo2 = [];
ModelName = [];
MetropolisFolder = [];
fblck = [];
fline = [];
FirstBlock = [];
FirstLine = [];
npar = [];
nblck = [];
NumberOfBlocks = [];
nruns = [];
NewFile = [];
MAX_nruns = [];
@ -76,15 +76,15 @@ end
MetropolisFolder = CheckPath('metropolis',M_.dname);
BaseName = [MetropolisFolder filesep ModelName];
nblck = options_.mh_nblck;
nruns = ones(nblck,1)*options_.mh_replic;
NumberOfBlocks = options_.mh_nblck;
nruns = ones(NumberOfBlocks,1)*options_.mh_replic;
npar = length(xparam1);
MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8);
d = chol(vv);
if ~options_.load_mh_file && ~options_.mh_recover
% Here we start a new Metropolis-Hastings, previous draws are discarded.
if nblck > 1
if NumberOfBlocks > 1
disp('Estimation::mcmc: Multiple chains mode.')
else
disp('Estimation::mcmc: One Chain mode.')
@ -108,16 +108,17 @@ if ~options_.load_mh_file && ~options_.mh_recover
fprintf(fidlog,' \n\n');
fprintf(fidlog,'%% Session 1.\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,' \n');
% Find initial values for the nblck chains...
if nblck > 1% Case 1: multiple chains
% Find initial values for the NumberOfBlocks chains...
if NumberOfBlocks > 1% Case 1: multiple chains
set_dynare_seed('default');
fprintf(fidlog,[' Initial values of the parameters:\n']);
disp('Estimation::mcmc: Searching for initial values...')
ix2 = zeros(nblck,npar);
ilogpo2 = zeros(nblck,1);
for j=1:nblck
ix2 = zeros(NumberOfBlocks,npar);
ilogpo2 = zeros(NumberOfBlocks,1);
for j=1:NumberOfBlocks
validate = 0;
init_iter = 0;
trial = 1;
@ -183,22 +184,23 @@ if ~options_.load_mh_file && ~options_.mh_recover
fprintf(fidlog,' \n');
end
fprintf(fidlog,' \n');
fblck = 1;
fline = ones(nblck,1);
NewFile = ones(nblck,1);
FirstBlock = 1;
FirstLine = ones(NumberOfBlocks,1);
NewFile = ones(NumberOfBlocks,1);
% Delete the mh-history files
delete_mh_history_files(MetropolisFolder, ModelName);
% Create a new record structure
fprintf(['Estimation::mcmc: Write details about the MCMC... ']);
AnticipatedNumberOfFiles = ceil(nruns(1)/MAX_nruns);
AnticipatedNumberOfLinesInTheLastFile = nruns(1) - (AnticipatedNumberOfFiles-1)*MAX_nruns;
record.Nblck = nblck;
record.Nblck = NumberOfBlocks;
record.MhDraws = zeros(1,3);
record.MhDraws(1,1) = nruns(1);
record.MhDraws(1,2) = AnticipatedNumberOfFiles;
record.MhDraws(1,3) = AnticipatedNumberOfLinesInTheLastFile;
record.AcceptanceRatio = zeros(1,nblck);
for j=1:nblck
record.MAX_nruns=MAX_nruns;
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)
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
@ -206,8 +208,8 @@ if ~options_.load_mh_file && ~options_.mh_recover
end
record.InitialParameters = ix2;
record.InitialLogPost = ilogpo2;
record.LastParameters = zeros(nblck,npar);
record.LastLogPost = zeros(nblck,1);
record.LastParameters = zeros(NumberOfBlocks,npar);
record.LastLogPost = zeros(NumberOfBlocks,1);
record.LastFileNumber = AnticipatedNumberOfFiles ;
record.LastLineNumber = AnticipatedNumberOfLinesInTheLastFile;
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 lines in the last file: ' int2str(AnticipatedNumberOfLinesInTheLastFile) '.\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']);
for i=1:length(record.InitialSeeds(j).Normal)
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,['%% Session ' int2str(length(record.MhDraws(:,1))+1) '.\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,' \n');
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: 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.' ])
nblck = past_number_of_blocks;
options_.mh_nblck = nblck;
NumberOfBlocks = past_number_of_blocks;
options_.mh_nblck = NumberOfBlocks;
end
% I read the last line of the last mh-file for initialization of the new Metropolis-Hastings simulations:
LastFileNumber = record.LastFileNumber;
LastLineNumber = record.LastLineNumber;
if LastLineNumber < MAX_nruns
NewFile = ones(nblck,1)*LastFileNumber;
fline = ones(nblck,1)*(LastLineNumber+1);
NewFile = ones(NumberOfBlocks,1)*LastFileNumber;
FirstLine = ones(NumberOfBlocks,1)*(LastLineNumber+1);
else
NewFile = ones(nblck,1)*(LastFileNumber+1);
fline = ones(nblck,1);
NewFile = ones(NumberOfBlocks,1)*(LastFileNumber+1);
FirstLine = ones(NumberOfBlocks,1);
end
ilogpo2 = record.LastLogPost;
ix2 = record.LastParameters;
fblck = 1;
FirstBlock = 1;
NumberOfPreviousSimulations = sum(record.MhDraws(:,1),1);
fprintf('Estimation::mcmc: I am writing a new mh-history file... ');
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,2) = AnticipatedNumberOfFiles;
record.MhDraws(end,3) = AnticipatedNumberOfLinesInTheLastFile;
record.MAX_nruns = [record.MAX_nruns;MAX_nruns];
record.InitialSeeds = record.LastSeeds;
write_mh_history_file(MetropolisFolder, ModelName, record);
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...
disp('Estimation::mcmc: Recover mode!')
load_last_mh_history_file(MetropolisFolder, ModelName);
nblck = record.Nblck;% Number of "parallel" mcmc chains.
options_.mh_nblck = nblck;
NumberOfBlocks = record.Nblck;% Number of "parallel" mcmc chains.
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
OldMh = 0;% The crashed metropolis was the first session.
OldMhExists = 0;% The crashed metropolis was the first session.
else
OldMh = 1;% The crashed metropolis wasn't the first session.
OldMhExists = 1;% The crashed metropolis wasn't the first session.
end
% Default initialization:
if OldMh
if OldMhExists
ilogpo2 = record.LastLogPost;
ix2 = record.LastParameters;
else
ilogpo2 = record.InitialLogPost;
ix2 = record.InitialParameters;
end
% Set NewFile, a nblck*1 vector of integers, and fline (first line), a nblck*1 vector of integers.
if OldMh
% Set NewFile, a NumberOfBlocks*1 vector of integers, and FirstLine (first line), a NumberOfBlocks*1 vector of integers.
% 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.
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)
NewFile = ones(nblck,1)*LastFileNumberInThePreviousMh;
fline = ones(nblck,1)*(LastLineNumberInThePreviousMh+1);
else% The last mh files of the previous session are complete.
NewFile = ones(nblck,1)*(LastFileNumberInThePreviousMh+1);
fline = ones(nblck,1);
%Test if the last mh files of the previous session were not full yet
if LastLineNumberInThePreviousMh < MAX_nruns%not full
%store starting point if whole chain needs to be redone
NewFile = ones(NumberOfBlocks,1)*LastFileNumberInThePreviousMh;
FirstLine = ones(NumberOfBlocks,1)*(LastLineNumberInThePreviousMh+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
else
LastLineNumberInThePreviousMh = 0;
LastFileNumberInThePreviousMh = 0;
NewFile = ones(nblck,1);
fline = ones(nblck,1);
NewFile = ones(NumberOfBlocks,1);
FirstLine = ones(NumberOfBlocks,1);
LastFileFullIndicator=1;
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 ?
ExpectedNumberOfMhFilesPerBlock = sum(record.MhDraws(:,2),1);
ExpectedNumberOfMhFiles = ExpectedNumberOfMhFilesPerBlock*nblck;
% I count the total number of saved mh files...
ExpectedNumberOfMhFiles = ExpectedNumberOfMhFilesPerBlock*NumberOfBlocks;
% How many mh files do we actually have ?
AllMhFiles = dir([BaseName '_mh*_blck*.mat']);
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)
disp('Estimation::mcmc: It appears that you don''t need to use the mh_recover option!')
disp(' You have to edit the mod file and remove the mh_recover option')
disp(' in the estimation command')
error('Estimation::mcmc: mh_recover option not required!')
end
% I count the number of saved mh files per block.
NumberOfMhFilesPerBlock = zeros(nblck,1);
for b = 1:nblck
% 2. Something needs to be done; find out what
% Count the number of saved mh files per block.
NumberOfMhFilesPerBlock = zeros(NumberOfBlocks,1);
for b = 1:NumberOfBlocks
BlckMhFiles = dir([BaseName '_mh*_blck' int2str(b) '.mat']);
NumberOfMhFilesPerBlock(b) = length(BlckMhFiles);
end
% Is there a chain with less mh files than expected ?
while fblck <= nblck
if NumberOfMhFilesPerBlock(fblck) < ExpectedNumberOfMhFilesPerBlock
disp(['Estimation::mcmc: Chain ' int2str(fblck) ' is not complete!'])
% Find FirstBlock (First block), an integer targeting the crashed mcmc chain.
FirstBlock = 1; %initialize
while FirstBlock <= NumberOfBlocks
if NumberOfMhFilesPerBlock(FirstBlock) < ExpectedNumberOfMhFilesPerBlock
disp(['Estimation::mcmc: Chain ' int2str(FirstBlock) ' is not complete!'])
break
% The mh_recover session will start from chain fblck.
% The mh_recover session will start from chain FirstBlock.
else
disp(['Estimation::mcmc: Chain ' int2str(fblck) ' is complete!'])
disp(['Estimation::mcmc: Chain ' int2str(FirstBlock) ' is complete!'])
end
fblck = fblck+1;
FirstBlock = FirstBlock+1;
end
%% 3. Overwrite default settings for
% How many mh-files are saved in this block?
NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(fblck);
% Correct the number of saved mh files if the crashed Metropolis was not the first session (so
% that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain
% of the current session).
if OldMh
NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh;
NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(FirstBlock);
ExistingDrawsInLastMCFile=0; %initialize: no MCMC draws of current MCMC are in file from last run
% Check whether last present file is a file included in the last MCMC run
if ~LastFileFullIndicator
if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only that last file exists, but no files from current MCMC
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
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.
if NumberOfSavedMhFiles
load([BaseName '_mh' int2str(NumberOfSavedMhFiles) '_blck' int2str(fblck) '.mat']);
ilogpo2(fblck) = logpo2(end);
ix2(fblck,:) = x2(end,:);
if NumberOfSavedMhFilesInTheCrashedBlck<ExpectedNumberOfMhFilesPerBlock
loaded_results=load([BaseName '_mh' int2str(NumberOfSavedMhFilesInTheCrashedBlck) '_blck' int2str(FirstBlock) '.mat']);
ilogpo2(FirstBlock) = loaded_results.logpo2(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

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
% 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.
%
@ -116,7 +116,7 @@ while rank(Pinf(:,:,t+1),diffuse_kalman_tol) && t<smpl
alphahat = Inf;
return
else
a(:,:,t+1) = T*a(:,:,t);
a(:,t+1) = T*a(:,t);
Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+QQ;
Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T);
end
@ -125,7 +125,7 @@ while rank(Pinf(:,:,t+1),diffuse_kalman_tol) && t<smpl
Kstar(:,:,t) = Pstar(:,:,t)*ZZ'*iFstar(:,:,t);
Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T);
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
else

View File

@ -197,9 +197,11 @@ for plt = 1:nbplt,
fprintf(fidTeX,'\\label{Fig:CheckPlots:%s}\n',int2str(plt));
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
fclose(fidTeX);
end
end
if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
fclose(fidTeX);
end
OutputDirectoryName = CheckPath('modecheck',Model.dname);
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;
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
fval = objective_function_penalty_base+penalty;
exit_flag = 0;
@ -187,7 +187,7 @@ if ~issquare(Q) || EstimatedParameters.ncx || isfield(EstimatedParameters,'calib
end
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
fval = objective_function_penalty_base+penalty;
exit_flag = 0;
@ -227,6 +227,21 @@ end
% Define a vector of indices for the observed variables. Is this really usefull?...
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.
start = DynareOptions.presample+1;
np = size(T,1);

View File

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

View File

@ -21,7 +21,7 @@ function osr_res = osr(var_list,params,i_var,W)
% SPECIAL REQUIREMENTS
% none.
%
% Copyright (C) 2001-2012 Dynare Team
% Copyright (C) 2001-2016 Dynare Team
%
% This file is part of Dynare.
%
@ -46,7 +46,7 @@ if isempty(options_.qz_criterium)
options_.qz_criterium = 1+1e-6;
end
make_ex_;
oo_=make_ex_(M_,options_,oo_);
np = size(params,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
%
%
% Copyright (C) 2013-2014 Dynare Team
% Copyright (C) 2013-2016 Dynare Team
%
% This file is part of Dynare.
%
@ -33,8 +33,9 @@ global options_ oo_ M_
pp = 2;
initial_conditions = oo_.steady_state;
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
% and terminal conditions for the non-stationary variables, we
% 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)));
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));
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);
end
end
%Compute the initial path using the first order solution around the
%Compute the initial path using the the steady-state
% steady-state
for jj = 2 : (options_.periods + 2)
oo_.endo_simul(:, jj) = oo_.steady_state;
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
save_options_dynatol_f = options_.dynatol.f;
@ -165,6 +181,15 @@ else
end
end
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;
union_names = union(data_set.name, dset.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;
col_count = col_count + constrained_periods;
end;
make_ex_;
make_y_;
oo_=make_ex_(M_,options_,oo_);
oo_=make_y_(M_,options_,oo_);
it = 1;
convg = 0;
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('===============================================================================================');
if t == 1
make_ex_;
oo_=make_ex_(M_,options_,oo_);
if maximum_lag > 0
exo_init = oo_.exo_simul;
else
exo_init = zeros(size(oo_.exo_simul));
end
make_y_;
oo_=make_y_(M_,options_,oo_);
end;
%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
%
% INPUTS
% none
% M_: Dynare model structure
% options_: Dynare options structure
% oo_: Dynare results structure
%
% OUTPUTS
% none
% oo_: Dynare results structure
%
% ALGORITHM
%
% SPECIAL REQUIREMENTS
%
% Copyright (C) 1996-2014 Dynare Team
% Copyright (C) 1996-2016 Dynare Team
%
% 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
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ oo_ ex0_
global ex0_
if isempty(oo_.exo_steady_state)
oo_.exo_steady_state = zeros(M_.exo_nbr,1);

View File

@ -1,18 +1,22 @@
function make_y_()
% function make_y_
function oo_=make_y_(M_,options_,oo_)
% function oo_=make_y_(M_,options_,oo_)
% forms oo_.endo_simul as guess values for deterministic simulations
%
% INPUTS
% ...
% M_: Dynare model structure
% options_: Dynare options structure
% oo_: Dynare results structure
%
% OUTPUTS
% ...
% oo_: Dynare results structure
%
% ALGORITHM
% ...
% SPECIAL REQUIREMENTS
% none
%
% Copyright (C) 1996-2014 Dynare Team
% Copyright (C) 1996-2016 Dynare Team
%
% 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
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ options_ oo_ ys0_
global ys0_
if options_.steadystate_flag
[oo_.steady_state,M_.params,check] = ...

View File

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

View File

@ -13,7 +13,7 @@ function oo = sim1(M, options, oo)
% SPECIAL REQUIREMENTS
% None.
% Copyright (C) 1996-2015 Dynare Team
% Copyright (C) 1996-2016 Dynare Team
%
% This file is part of Dynare.
%
@ -57,9 +57,11 @@ endo_simul = oo.endo_simul;
exo_simul = oo.exo_simul;
i_cols_1 = nonzeros(lead_lag_incidence(2:3,:)');
i_cols_A1 = find(lead_lag_incidence(2:3,:)');
i_cols_A1 = i_cols_A1(:);
i_cols_T = nonzeros(lead_lag_incidence(1:2,:)');
i_cols_0 = nonzeros(lead_lag_incidence(2,:)');
i_cols_A0 = find(lead_lag_incidence(2,:)');
i_cols_A0 = i_cols_A0(:);
i_cols_j = (1:nd)';
i_upd = maximum_lag*ny+(1:periods*ny);
@ -92,6 +94,7 @@ for iter = 1:options.simul.maxit
i_rows = (1:ny)';
i_cols_A = find(lead_lag_incidence');
i_cols_A = i_cols_A(:);
i_cols = i_cols_A+(maximum_lag-1)*ny;
m = 0;
for it = (maximum_lag+1):(maximum_lag+periods)
@ -99,16 +102,16 @@ for iter = 1:options.simul.maxit
steady_state,it);
if it == maximum_lag+periods && it == maximum_lag+1
[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
[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
[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
[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
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)
%
% INPUTS
@ -11,6 +11,7 @@ function plot_identification(params,idemoments,idehess,idemodel, idelre, advance
% o tittxt [char] name of the results to plot
% o name [char] list of names
% o IdentifDirectoryName [char] directory name
% o tittxt [char] TeX-name of the results to plot
%
% OUTPUTS
% None
@ -101,6 +102,19 @@ if SampleSize == 1,
else
title('Sensitivity component with moments Information matrix (log-scale)')
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_);
if advanced,
@ -131,6 +145,19 @@ if SampleSize == 1,
legend('Moments','Model','LRE model','Location','Best')
title('Sensitivity bars using derivatives (log-scale)')
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
% identificaton patterns
for j=1:size(idemoments.cosnJ,2),
@ -171,6 +198,19 @@ if SampleSize == 1,
set(gca,'ygrid','on')
xlabel([tittxt,' - Collinearity patterns with ', int2str(j) ,' parameter(s)'],'interpreter','none')
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
skipline()
[U,S,V]=svd(idehess.AHess,0);
@ -178,18 +218,24 @@ if SampleSize == 1,
if idehess.flag_score,
if nparam<5,
f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (Information matrix)']);
tex_tit_1=[tittxt,' - Identification patterns (Information matrix)'];
else
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']);
tex_tit_2=[tittxt,' - Identification patterns (Information matrix): HIGHEST SV'];
end
else
% S = idemoments.S;
% V = idemoments.V;
if nparam<5,
f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (moments Information matrix)']);
tex_tit_1=[tittxt,' - Identification patterns (moments Information matrix)'];
else
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']);
tex_tit_2=[tittxt,' - Identification patterns (moments Information matrix): HIGHEST SV'];
end
end
for j=1:min(nparam,8),
@ -217,8 +263,34 @@ if SampleSize == 1,
title(['Singular value ',num2str(Stit)])
end
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,
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
@ -250,6 +322,20 @@ else
end
title('MC mean of sensitivity measures')
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 ~options_.nodisplay,
skipline()
@ -304,9 +390,12 @@ else
if nparam<5,
f1 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']);
tex_tit_1=[tittxt,' - MC Identification patterns (moments): HIGHEST SV'];
else
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']);
tex_tit_2=[tittxt,' - MC Identification patterns (moments): HIGHEST SV'];
end
nplots=min(nparam,8);
if nplots>4,
@ -343,8 +432,34 @@ else
title(['MEAN Singular value ',num2str(Stit)])
end
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,
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

View File

@ -38,7 +38,7 @@ T2 = strvcat(T2, l2);
prior_trunc_backup = DynareOptions.prior_trunc ;
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 ;
RESIZE = false;

View File

@ -1,4 +1,4 @@
function bounds = prior_bounds(bayestopt,options)
function bounds = prior_bounds(bayestopt, prior_trunc)
%@info:
%! @deftypefn {Function File} {@var{bounds} =} prior_bounds (@var{bayesopt},@var{option})
@ -69,7 +69,6 @@ p3 = bayestopt.p3;
p4 = bayestopt.p4;
p6 = bayestopt.p6;
p7 = bayestopt.p7;
prior_trunc = options.prior_trunc;
bounds.lb = zeros(length(p6),1);
bounds.ub = zeros(length(p6),1);
@ -151,6 +150,14 @@ for i=1:length(p6)
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
error(sprintf('prior_bounds: unknown distribution shape (index %d, type %d)', i, pshape(i)));
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
% 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
% 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.
%
@ -43,59 +44,64 @@ function pdraw = prior_draw(init,uniform) % --*-- Unitary tests --*--
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
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_draws gaussian_draws gamma_draws beta_draws inverse_gamma_1_draws inverse_gamma_2_draws
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 weibull_draws
if nargin>0 && init
p6 = evalin('base', 'bayestopt_.p6');
p7 = evalin('base', 'bayestopt_.p7');
p3 = evalin('base', 'bayestopt_.p3');
p4 = evalin('base', 'bayestopt_.p4');
bounds = evalin('base', 'prior_bounds(bayestopt_,options_)');
if nargin>0
p6 = BayesInfo.p6;
p7 = BayesInfo.p7;
p3 = BayesInfo.p3;
p4 = BayesInfo.p4;
bounds = prior_bounds(BayesInfo, prior_trunc);
lb = bounds.lb;
ub = bounds.ub;
number_of_estimated_parameters = length(p6);
if nargin>1 && uniform
if nargin>2 && uniform
prior_shape = repmat(5,number_of_estimated_parameters,1);
else
prior_shape = evalin('base', 'bayestopt_.pshape');
prior_shape = BayesInfo.pshape;
end
beta_index = find(prior_shape==1);
if isempty(beta_index)
beta_draws = 0;
beta_draws = false;
else
beta_draws = 1;
beta_draws = true;
end
gamma_index = find(prior_shape==2);
if isempty(gamma_index)
gamma_draws = 0;
gamma_draws = false;
else
gamma_draws = 1;
gamma_draws = true;
end
gaussian_index = find(prior_shape==3);
if isempty(gaussian_index)
gaussian_draws = 0;
gaussian_draws = false;
else
gaussian_draws = 1;
gaussian_draws = true;
end
inverse_gamma_1_index = find(prior_shape==4);
if isempty(inverse_gamma_1_index)
inverse_gamma_1_draws = 0;
inverse_gamma_1_draws = false;
else
inverse_gamma_1_draws = 1;
inverse_gamma_1_draws = true;
end
uniform_index = find(prior_shape==5);
if isempty(uniform_index)
uniform_draws = 0;
uniform_draws = false;
else
uniform_draws = 1;
uniform_draws = true;
end
inverse_gamma_2_index = find(prior_shape==6);
if isempty(inverse_gamma_2_index)
inverse_gamma_2_draws = 0;
inverse_gamma_2_draws = false;
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
pdraw = NaN(number_of_estimated_parameters,1);
return
@ -159,369 +165,110 @@ if inverse_gamma_2_draws
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
%$ %% Initialize required structures
%$ options_.prior_trunc=0;
%$ options_.initialize_estimated_parameters_with_the_prior_mode=0;
%$
%$ M_.dname='test';
%$ M_.param_names = 'alp';
%$ ndraws=100000;
%$ global estim_params_
%$ estim_params_.var_exo = [];
%$ estim_params_.var_endo = [];
%$ estim_params_.corrx = [];
%$ estim_params_.corrn = [];
%$ estim_params_.param_vals = [];
%$ estim_params_.param_vals = [1, NaN, (-Inf), Inf, 1, 0.356, 0.02, NaN, NaN, NaN ];
%$
%$ %% 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)=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);
%$ % Fill global structures with required fields...
%$ prior_trunc = 1e-10;
%$ p0 = repmat([1; 2; 3; 4; 5; 6; 8], 2, 1); % Prior shape
%$ p1 = .4*ones(14,1); % Prior mean
%$ p2 = .2*ones(14,1); % Prior std.
%$ p3 = NaN(14,1);
%$ p4 = NaN(14,1);
%$ p5 = NaN(14,1);
%$ p6 = NaN(14,1);
%$ p7 = NaN(14,1);
%$
%$ for i=1:14
%$ switch p0(i)
%$ case 1
%$ % Beta distribution
%$ p3(i) = 0;
%$ p4(i) = 1;
%$ [p6(i), p7(i)] = beta_specification(p1(i), p2(i)^2, p3(i), p4(i));
%$ p5(i) = compute_prior_mode([p6(i) p7(i)], 1);
%$ case 2
%$ % Gamma distribution
%$ p3(i) = 0;
%$ p4(i) = Inf;
%$ [p6(i), p7(i)] = gamma_specification(p1(i), p2(i)^2, p3(i), p4(i));
%$ p5(i) = compute_prior_mode([p6(i) p7(i)], 2);
%$ case 3
%$ % Normal distribution
%$ p3(i) = -Inf;
%$ p4(i) = Inf;
%$ 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
%$
%$ 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)
%$ error('Beta prior wrong')
%$
%$ BayesInfo.pshape = p0;
%$ 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
%$
%$
%$ %% 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)=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);
%$
%$ if t(1)
%$ t(2) = all(abs(m0-BayesInfo.p1)<3e-3);
%$ t(3) = all(all(abs(v0-diag(BayesInfo.p2.^2))<2e-3));
%$ 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('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
%$ T = all(t);
%@eof:1

View File

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

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