diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..82db8052d --- /dev/null +++ b/CONTRIBUTING.md @@ -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/<>/dynare.git` +1. Create a branch to work on + * `git checkout -b <>` +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 <>` + * `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 <>` + * `git commit -m "<> Closes #<>"` +1. Push to your forked Dynare repository + * `git push personal <>` +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 diff --git a/Makefile.am b/Makefile.am index 7b23cec88..1eb1fc0ec 100644 --- a/Makefile.am +++ b/Makefile.am @@ -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 \ diff --git a/README.md b/README.md index 2e16a7640..026f321ab 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,10 @@ Described on the homepage: Most users should use the precompiled package available for your OS, also available via the Dynare homepage: . +# 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: diff --git a/configure.ac b/configure.ac index 379b92433..94183a47a 100755 --- a/configure.ac +++ b/configure.ac @@ -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 diff --git a/doc/bvar-a-la-sims.tex b/doc/bvar-a-la-sims.tex index 637bc5cad..593e17759 100644 --- a/doc/bvar-a-la-sims.tex +++ b/doc/bvar-a-la-sims.tex @@ -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} diff --git a/doc/dynare.texi b/doc/dynare.texi index 07c9f88ed..c06b434c0 100644 --- a/doc/dynare.texi +++ b/doc/dynare.texi @@ -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{<>_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 diff --git a/tests/reporting/example1.mod b/examples/example1_reporting.mod similarity index 65% rename from tests/reporting/example1.mod rename to examples/example1_reporting.mod index 10b2aef3c..a39c98da9 100644 --- a/tests/reporting/example1.mod +++ b/examples/example1_reporting.mod @@ -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 . + */ + + 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(); \ No newline at end of file +r.compile(); diff --git a/license.txt b/license.txt index 034eb86ee..651cc0e36 100644 --- a/license.txt +++ b/license.txt @@ -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 Houtan Bastani Michel Juillard @@ -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 - 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 @@ -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 diff --git a/m4/ax_matlab_version.m4 b/m4/ax_matlab_version.m4 index 211da8477..b3047770e 100644 --- a/m4/ax_matlab_version.m4 +++ b/m4/ax_matlab_version.m4 @@ -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" ;; diff --git a/m4/ax_mexopts.m4 b/m4/ax_mexopts.m4 index c245e2511..94648df9f 100644 --- a/m4/ax_mexopts.m4 +++ b/m4/ax_mexopts.m4 @@ -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]) diff --git a/matlab/DsgeSmoother.m b/matlab/DsgeSmoother.m index 0140ecf12..53cfc1098 100644 --- a/matlab/DsgeSmoother.m +++ b/matlab/DsgeSmoother.m @@ -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; diff --git a/matlab/GetOneDraw.m b/matlab/GetOneDraw.m index 1f3572745..82d4c088f 100644 --- a/matlab/GetOneDraw.m +++ b/matlab/GetOneDraw.m @@ -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 diff --git a/matlab/GetPosteriorParametersStatistics.m b/matlab/GetPosteriorParametersStatistics.m index c51e0a2ba..a8ee9a58b 100644 --- a/matlab/GetPosteriorParametersStatistics.m +++ b/matlab/GetPosteriorParametersStatistics.m @@ -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; diff --git a/matlab/McMCDiagnostics.m b/matlab/McMCDiagnostics.m index 540b43d63..1333f7cf8 100644 --- a/matlab/McMCDiagnostics.m +++ b/matlab/McMCDiagnostics.m @@ -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; diff --git a/matlab/PosteriorIRF_core1.m b/matlab/PosteriorIRF_core1.m index cbfe2ee31..5213637b9 100644 --- a/matlab/PosteriorIRF_core1.m +++ b/matlab/PosteriorIRF_core1.m @@ -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 diff --git a/matlab/TaRB_metropolis_hastings_core.m b/matlab/TaRB_metropolis_hastings_core.m index 7259c8ff8..f8e5d8915 100644 --- a/matlab/TaRB_metropolis_hastings_core.m +++ b/matlab/TaRB_metropolis_hastings_core.m @@ -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']); diff --git a/matlab/add_path_to_mex_files.m b/matlab/add_path_to_mex_files.m index 8d5f718af..ff0f84114 100644 --- a/matlab/add_path_to_mex_files.m +++ b/matlab/add_path_to_mex_files.m @@ -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 diff --git a/matlab/basic_plan.m b/matlab/basic_plan.m index cd7b09a8b..c7b4cb360 100644 --- a/matlab/basic_plan.m +++ b/matlab/basic_plan.m @@ -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)))]; diff --git a/matlab/bvar_density.m b/matlab/bvar_density.m index 665a9dae5..ecde347c6 100644 --- a/matlab/bvar_density.m +++ b/matlab/bvar_density.m @@ -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 . +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); diff --git a/matlab/cellofchar2mfile.m b/matlab/cellofchar2mfile.m new file mode 100644 index 000000000..6cfce7c5f --- /dev/null +++ b/matlab/cellofchar2mfile.m @@ -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 . + +[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); \ No newline at end of file diff --git a/matlab/clear_persistent_variables.m b/matlab/clear_persistent_variables.m index e6d4aa5a3..e2fe5666f 100644 --- a/matlab/clear_persistent_variables.m +++ b/matlab/clear_persistent_variables.m @@ -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 . -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{:}); \ No newline at end of file diff --git a/matlab/collect_LaTeX_Files.m b/matlab/collect_LaTeX_Files.m index d6cb76d56..961a41947 100644 --- a/matlab/collect_LaTeX_Files.m +++ b/matlab/collect_LaTeX_Files.m @@ -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}'); diff --git a/matlab/compute_trend_coefficients.m b/matlab/compute_trend_coefficients.m new file mode 100644 index 000000000..9686867e2 --- /dev/null +++ b/matlab/compute_trend_coefficients.m @@ -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 . + + +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 diff --git a/matlab/conditional_variance_decomposition_mc_analysis.m b/matlab/conditional_variance_decomposition_mc_analysis.m index c165a62be..3e09d0f2b 100644 --- a/matlab/conditional_variance_decomposition_mc_analysis.m +++ b/matlab/conditional_variance_decomposition_mc_analysis.m @@ -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 \ No newline at end of file diff --git a/matlab/convert_dyn_45_to_44.m b/matlab/convert_dyn_45_to_44.m index 3de191c90..afd795a47 100644 --- a/matlab/convert_dyn_45_to_44.m +++ b/matlab/convert_dyn_45_to_44.m @@ -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 diff --git a/matlab/correlation_mc_analysis.m b/matlab/correlation_mc_analysis.m index 372fda45d..6eba19485 100644 --- a/matlab/correlation_mc_analysis.m +++ b/matlab/correlation_mc_analysis.m @@ -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') diff --git a/matlab/covariance_mc_analysis.m b/matlab/covariance_mc_analysis.m index ccb0a0c30..60753407b 100644 --- a/matlab/covariance_mc_analysis.m +++ b/matlab/covariance_mc_analysis.m @@ -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') diff --git a/matlab/disp_moments.m b/matlab/disp_moments.m index e6a9f3bcc..42479db69 100644 --- a/matlab/disp_moments.m +++ b/matlab/disp_moments.m @@ -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); diff --git a/matlab/display_estimation_results_table.m b/matlab/display_estimation_results_table.m index d813d3f5a..93fa62102 100644 --- a/matlab/display_estimation_results_table.m +++ b/matlab/display_estimation_results_table.m @@ -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); \ No newline at end of file diff --git a/matlab/distributions/beta_specification.m b/matlab/distributions/beta_specification.m new file mode 100644 index 000000000..33a38085d --- /dev/null +++ b/matlab/distributions/beta_specification.m @@ -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 . + +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 muub + 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 \ No newline at end of file diff --git a/matlab/distributions/compute_prior_mode.m b/matlab/distributions/compute_prior_mode.m index e6d35920c..3286c08ea 100644 --- a/matlab/distributions/compute_prior_mode.m +++ b/matlab/distributions/compute_prior_mode.m @@ -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 . + 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 \ No newline at end of file +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 diff --git a/matlab/distributions/gamma_specification.m b/matlab/distributions/gamma_specification.m new file mode 100644 index 000000000..0f7301193 --- /dev/null +++ b/matlab/distributions/gamma_specification.m @@ -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 . + +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 mu2. -%@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 . -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 \ No newline at end of file +%@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 \ No newline at end of file diff --git a/matlab/distributions/lpdfgweibull.m b/matlab/distributions/lpdfgweibull.m new file mode 100644 index 000000000..a046c1dd2 --- /dev/null +++ b/matlab/distributions/lpdfgweibull.m @@ -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 . + +% 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. + +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. -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 diff --git a/matlab/dyn_latex_table.m b/matlab/dyn_latex_table.m index 0251179e9..3bb4c92ce 100644 --- a/matlab/dyn_latex_table.m +++ b/matlab/dyn_latex_table.m @@ -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); \ No newline at end of file diff --git a/matlab/dynare_config.m b/matlab/dynare_config.m index 3351b4b31..fec6e9bec 100644 --- a/matlab/dynare_config.m +++ b/matlab/dynare_config.m @@ -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')) ... diff --git a/matlab/dynare_estimation.m b/matlab/dynare_estimation.m index 4aaf0d18b..bb1b47c34 100644 --- a/matlab/dynare_estimation.m +++ b/matlab/dynare_estimation.m @@ -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 diff --git a/matlab/dynare_estimation_1.m b/matlab/dynare_estimation_1.m index 58282eba5..77a65da5f 100644 --- a/matlab/dynare_estimation_1.m +++ b/matlab/dynare_estimation_1.m @@ -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 diff --git a/matlab/dynare_estimation_init.m b/matlab/dynare_estimation_init.m index 9ef77b87c..3166f1f3a 100644 --- a/matlab/dynare_estimation_init.m +++ b/matlab/dynare_estimation_init.m @@ -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 + diff --git a/matlab/dynare_identification.m b/matlab/dynare_identification.m index 2da320f4c..01d549389 100644 --- a/matlab/dynare_identification.m +++ b/matlab/dynare_identification.m @@ -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, diff --git a/matlab/ep/extended_path.m b/matlab/ep/extended_path.m index 3fc811add..f610a53e8 100644 --- a/matlab/ep/extended_path.m +++ b/matlab/ep/extended_path.m @@ -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); \ No newline at end of file diff --git a/matlab/ep/extended_path_core.m b/matlab/ep/extended_path_core.m new file mode 100644 index 000000000..b3c83b486 --- /dev/null +++ b/matlab/ep/extended_path_core.m @@ -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 . + +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 diff --git a/matlab/evaluate_likelihood.m b/matlab/evaluate_likelihood.m index 7e6c1f087..39affdc5e 100644 --- a/matlab/evaluate_likelihood.m +++ b/matlab/evaluate_likelihood.m @@ -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; \ No newline at end of file diff --git a/matlab/evaluate_planner_objective.m b/matlab/evaluate_planner_objective.m index 69f24c6e5..40f186590 100644 --- a/matlab/evaluate_planner_objective.m +++ b/matlab/evaluate_planner_objective.m @@ -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),:); diff --git a/matlab/evaluate_smoother.m b/matlab/evaluate_smoother.m index 76b8444c0..4348a65f2 100644 --- a/matlab/evaluate_smoother.m +++ b/matlab/evaluate_smoother.m @@ -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 \ No newline at end of file +[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); \ No newline at end of file diff --git a/matlab/evaluate_steady_state.m b/matlab/evaluate_steady_state.m index 461d6a905..aec3a1b3f 100644 --- a/matlab/evaluate_steady_state.m +++ b/matlab/evaluate_steady_state.m @@ -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) diff --git a/matlab/evaluate_steady_state_file.m b/matlab/evaluate_steady_state_file.m index d83045fd0..4a1c38c59 100644 --- a/matlab/evaluate_steady_state_file.m +++ b/matlab/evaluate_steady_state_file.m @@ -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 . + 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 diff --git a/matlab/execute_prior_posterior_function.m b/matlab/execute_prior_posterior_function.m index 378d2237f..7e77a6ae8 100644 --- a/matlab/execute_prior_posterior_function.m +++ b/matlab/execute_prior_posterior_function.m @@ -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 diff --git a/matlab/forcst.m b/matlab/forcst.m index dc269e511..2684df8ee 100644 --- a/matlab/forcst.m +++ b/matlab/forcst.m @@ -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 . -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; diff --git a/matlab/forcst2.m b/matlab/forcst2.m index 41bf18f48..efa5d463b 100644 --- a/matlab/forcst2.m +++ b/matlab/forcst2.m @@ -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); diff --git a/matlab/forcst2a.m b/matlab/forcst2a.m index ecfb665af..16fcdc143 100644 --- a/matlab/forcst2a.m +++ b/matlab/forcst2a.m @@ -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]); diff --git a/matlab/get_file_extension.m b/matlab/get_file_extension.m index 56c140d83..d922b36ac 100644 --- a/matlab/get_file_extension.m +++ b/matlab/get_file_extension.m @@ -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 . -% 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 \ No newline at end of file diff --git a/matlab/global_initialization.m b/matlab/global_initialization.m index f4ac9dbaa..c3e70fac4 100644 --- a/matlab/global_initialization.m +++ b/matlab/global_initialization.m @@ -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; diff --git a/matlab/graph_decomp.m b/matlab/graph_decomp.m index abf1bc9fe..f1ef56e47 100644 --- a/matlab/graph_decomp.m +++ b/matlab/graph_decomp.m @@ -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 diff --git a/matlab/gsa/filt_mc_.m b/matlab/gsa/filt_mc_.m index 60fb43976..8809f4baf 100644 --- a/matlab/gsa/filt_mc_.m +++ b/matlab/gsa/filt_mc_.m @@ -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 \ No newline at end of file +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 diff --git a/matlab/gsa/map_calibration.m b/matlab/gsa/map_calibration.m index 6dae9fe51..c16658f6f 100644 --- a/matlab/gsa/map_calibration.m +++ b/matlab/gsa/map_calibration.m @@ -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 diff --git a/matlab/gsa/map_ident_.m b/matlab/gsa/map_ident_.m index 61db1cafd..2ce547480 100644 --- a/matlab/gsa/map_ident_.m +++ b/matlab/gsa/map_ident_.m @@ -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 diff --git a/matlab/gsa/prior_draw_gsa.m b/matlab/gsa/prior_draw_gsa.m index 5dc30b79f..1e6672050 100644 --- a/matlab/gsa/prior_draw_gsa.m +++ b/matlab/gsa/prior_draw_gsa.m @@ -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 diff --git a/matlab/gsa/priorcdf.m b/matlab/gsa/priorcdf.m index 5527b6b49..7d91c59e0 100644 --- a/matlab/gsa/priorcdf.m +++ b/matlab/gsa/priorcdf.m @@ -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 . -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 diff --git a/matlab/gsa/read_data.m b/matlab/gsa/read_data.m index c5851c0be..0324b8d1c 100644 --- a/matlab/gsa/read_data.m +++ b/matlab/gsa/read_data.m @@ -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 . -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 diff --git a/matlab/gsa/redform_map.m b/matlab/gsa/redform_map.m index 448b1a634..0e2e00f83 100644 --- a/matlab/gsa/redform_map.m +++ b/matlab/gsa/redform_map.m @@ -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 diff --git a/matlab/gsa/redform_screen.m b/matlab/gsa/redform_screen.m index cdbd2d596..56b5a7d80 100644 --- a/matlab/gsa/redform_screen.m +++ b/matlab/gsa/redform_screen.m @@ -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 + diff --git a/matlab/gsa/scatter_mcf.m b/matlab/gsa/scatter_mcf.m index 8f8bdd82c..736e3dc5a 100644 --- a/matlab/gsa/scatter_mcf.m +++ b/matlab/gsa/scatter_mcf.m @@ -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 \ No newline at end of file diff --git a/matlab/gsa/stab_map_.m b/matlab/gsa/stab_map_.m index c52b381e4..3b76e2cd0 100644 --- a/matlab/gsa/stab_map_.m +++ b/matlab/gsa/stab_map_.m @@ -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 + diff --git a/matlab/gsa/stab_map_1.m b/matlab/gsa/stab_map_1.m index 681db4724..072f0c544 100644 --- a/matlab/gsa/stab_map_1.m +++ b/matlab/gsa/stab_map_1.m @@ -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 diff --git a/matlab/gsa/stab_map_2.m b/matlab/gsa/stab_map_2.m index 7848de1c6..2bafb48a7 100644 --- a/matlab/gsa/stab_map_2.m +++ b/matlab/gsa/stab_map_2.m @@ -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 diff --git a/matlab/ident_bruteforce.m b/matlab/ident_bruteforce.m index 57a54984c..a2234f531 100644 --- a/matlab/ident_bruteforce.m +++ b/matlab/ident_bruteforce.m @@ -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); diff --git a/matlab/identification_analysis.m b/matlab/identification_analysis.m index 7eac2d199..b948d91a1 100644 --- a/matlab/identification_analysis.m +++ b/matlab/identification_analysis.m @@ -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; diff --git a/matlab/initial_estimation_checks.m b/matlab/initial_estimation_checks.m index dff2d4dfe..86e17fba1 100644 --- a/matlab/initial_estimation_checks.m +++ b/matlab/initial_estimation_checks.m @@ -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) diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter.m b/matlab/kalman/likelihood/missing_observations_kalman_filter.m index 4c64bd28d..fab3bfb89 100644 --- a/matlab/kalman/likelihood/missing_observations_kalman_filter.m +++ b/matlab/kalman/likelihood/missing_observations_kalman_filter.m @@ -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) diff --git a/matlab/list_of_functions_to_be_cleared.m b/matlab/list_of_functions_to_be_cleared.m new file mode 100644 index 000000000..e482add52 --- /dev/null +++ b/matlab/list_of_functions_to_be_cleared.m @@ -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'}; \ No newline at end of file diff --git a/matlab/lnsrch1.m b/matlab/lnsrch1.m index 80af34462..dbcbc5918 100644 --- a/matlab/lnsrch1.m +++ b/matlab/lnsrch1.m @@ -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 . -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 ; diff --git a/matlab/load_last_mh_history_file.m b/matlab/load_last_mh_history_file.m index 3e54f9853..7dfcbb0ef 100644 --- a/matlab/load_last_mh_history_file.m +++ b/matlab/load_last_mh_history_file.m @@ -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) diff --git a/matlab/lpdfgam.m b/matlab/lpdfgam.m index 037284456..b82e43234 100644 --- a/matlab/lpdfgam.m +++ b/matlab/lpdfgam.m @@ -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. % diff --git a/matlab/metropolis_hastings_initialization.m b/matlab/metropolis_hastings_initialization.m index 27e8f4c74..fd6c52654 100644 --- a/matlab/metropolis_hastings_initialization.m +++ b/matlab/metropolis_hastings_initialization.m @@ -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. + + +% 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 + diff --git a/matlab/missing/stats/wblinv.m b/matlab/missing/stats/wblinv.m new file mode 100644 index 000000000..93ac84ffa --- /dev/null +++ b/matlab/missing/stats/wblinv.m @@ -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 . + +% 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 + diff --git a/matlab/missing/stats/wblrnd.m b/matlab/missing/stats/wblrnd.m new file mode 100644 index 000000000..2f55bc8b7 --- /dev/null +++ b/matlab/missing/stats/wblrnd.m @@ -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 . + +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); \ No newline at end of file diff --git a/matlab/missing_DiffuseKalmanSmootherH1_Z.m b/matlab/missing_DiffuseKalmanSmootherH1_Z.m index b50416072..198c03ab7 100644 --- a/matlab/missing_DiffuseKalmanSmootherH1_Z.m +++ b/matlab/missing_DiffuseKalmanSmootherH1_Z.m @@ -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) && thtol 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 diff --git a/matlab/osr.m b/matlab/osr.m index 8d03864ed..37a81793a 100644 --- a/matlab/osr.m +++ b/matlab/osr.m @@ -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); diff --git a/matlab/perfect-foresight-models/det_cond_forecast.m b/matlab/perfect-foresight-models/det_cond_forecast.m index 0c1070dc1..e261de89c 100644 --- a/matlab/perfect-foresight-models/det_cond_forecast.m +++ b/matlab/perfect-foresight-models/det_cond_forecast.m @@ -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; diff --git a/matlab/perfect-foresight-models/make_ex_.m b/matlab/perfect-foresight-models/make_ex_.m index 8ad894825..73ab28f43 100644 --- a/matlab/perfect-foresight-models/make_ex_.m +++ b/matlab/perfect-foresight-models/make_ex_.m @@ -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 . -global M_ options_ oo_ ex0_ +global ex0_ if isempty(oo_.exo_steady_state) oo_.exo_steady_state = zeros(M_.exo_nbr,1); diff --git a/matlab/perfect-foresight-models/make_y_.m b/matlab/perfect-foresight-models/make_y_.m index 1085b9030..1badcb5e4 100644 --- a/matlab/perfect-foresight-models/make_y_.m +++ b/matlab/perfect-foresight-models/make_y_.m @@ -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 . -global M_ options_ oo_ ys0_ +global ys0_ if options_.steadystate_flag [oo_.steady_state,M_.params,check] = ... diff --git a/matlab/perfect-foresight-models/perfect_foresight_setup.m b/matlab/perfect-foresight-models/perfect_foresight_setup.m index 081eaf887..3b2825432 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_setup.m +++ b/matlab/perfect-foresight-models/perfect_foresight_setup.m @@ -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 diff --git a/matlab/perfect-foresight-models/sim1.m b/matlab/perfect-foresight-models/sim1.m index 71eb06001..13e404f22 100644 --- a/matlab/perfect-foresight-models/sim1.m +++ b/matlab/perfect-foresight-models/sim1.m @@ -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); diff --git a/matlab/plot_identification.m b/matlab/plot_identification.m index 16e4a83d1..e3a20013a 100644 --- a/matlab/plot_identification.m +++ b/matlab/plot_identification.m @@ -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 diff --git a/matlab/print_table_prior.m b/matlab/print_table_prior.m index 26e60fc4b..605adfabf 100644 --- a/matlab/print_table_prior.m +++ b/matlab/print_table_prior.m @@ -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; diff --git a/matlab/prior_bounds.m b/matlab/prior_bounds.m index a224c69a0..2bf1173ed 100644 --- a/matlab/prior_bounds.m +++ b/matlab/prior_bounds.m @@ -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 diff --git a/matlab/prior_draw.m b/matlab/prior_draw.m index 7bf27e260..4eb628df9 100644 --- a/matlab/prior_draw.m +++ b/matlab/prior_draw.m @@ -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 . 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)'ub(weibull_index)) | (pdraw(weibull_index)'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_vecestim_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_vec1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4 || any(pdraw_vec1e-4 || abs(std(pdraw_vec)-estim_params_.param_vals(1,7))>1e-4 || any(pdraw_vecestim_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_vec5e-3 || any(pdraw_vecbounds.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_vecbounds.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_vecbounds.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_vecbounds.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_vecbounds.ub) -%$ error('inverse gamma distribution (type 2) prior wrong') -%$ end -%$ -%@eof:1 +%$ T = all(t); +%@eof:1 \ No newline at end of file diff --git a/matlab/prior_posterior_statistics.m b/matlab/prior_posterior_statistics.m index a2f43343e..aa4114629 100644 --- a/matlab/prior_posterior_statistics.m +++ b/matlab/prior_posterior_statistics.m @@ -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 diff --git a/matlab/prior_posterior_statistics_core.m b/matlab/prior_posterior_statistics_core.m index 26b793c08..44df174a4 100644 --- a/matlab/prior_posterior_statistics_core.m +++ b/matlab/prior_posterior_statistics_core.m @@ -57,15 +57,16 @@ Y=myinputs.Y; data_index=myinputs.data_index; missing_value=myinputs.missing_value; varobs=myinputs.varobs; +mean_varobs=myinputs.mean_varobs; irun=myinputs.irun; endo_nbr=myinputs.endo_nbr; nvn=myinputs.nvn; naK=myinputs.naK; horizon=myinputs.horizon; iendo=myinputs.iendo; +IdObs=myinputs.IdObs; %index of observables if horizon i_last_obs=myinputs.i_last_obs; - IdObs=myinputs.IdObs; MAX_nforc1=myinputs.MAX_nforc1; MAX_nforc2=myinputs.MAX_nforc2; end @@ -166,10 +167,10 @@ for b=fpar:B if run_smoother [dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_); - [alphahat,etahat,epsilonhat,alphatilde,SteadyState,trend_coeff,aK] = ... + [alphahat,etahat,epsilonhat,alphatilde,SteadyState,trend_coeff,aK,junk1,junk2,junk3,junk4,junk5,trend_addition] = ... DsgeSmoother(deep,gend,Y,data_index,missing_value); - if options_.loglinear + if options_.loglinear %reads values from smoother results, which are in dr-order and put them into declaration order stock_smooth(dr.order_var,:,irun(1)) = alphahat(1:endo_nbr,:)+ ... repmat(log(SteadyState(dr.order_var)),1,gend); stock_update(dr.order_var,:,irun(1)) = alphatilde(1:endo_nbr,:)+ ... @@ -180,22 +181,61 @@ for b=fpar:B stock_update(dr.order_var,:,irun(1)) = alphatilde(1:endo_nbr,:)+ ... repmat(SteadyState(dr.order_var),1,gend); end + %% Compute constant for observables + if options_.prefilter == 1 %as mean is taken after log transformation, no distinction is needed here + constant_part=repmat(mean_varobs',1,gend); + elseif options_.prefilter == 0 && options_.loglinear == 1 %logged steady state must be used + constant_part=repmat(log(SteadyState(IdObs)),1,gend); + elseif options_.prefilter == 0 && options_.loglinear == 0 %unlogged steady state must be used + constant_part=repmat(SteadyState(IdObs),1,gend); + end + %add trend to observables + if options_.prefilter + %do correction for prefiltering for observed variables + if options_.loglinear + mean_correction=-repmat(log(SteadyState(IdObs)),1,gend)+constant_part; + else + mean_correction=-repmat(SteadyState(IdObs),1,gend)+constant_part; + end + %smoothed variables are E_T(y_t) so no trend shift is required + stock_smooth(IdObs,:,irun(1))=stock_smooth(IdObs,:,irun(1))+trend_addition+mean_correction; + %updated variables are E_t(y_t) so no trend shift is required + stock_update(IdObs,:,irun(1))=stock_update(IdObs,:,irun(1))+trend_addition+mean_correction; + else + stock_smooth(IdObs,:,irun(1))=stock_smooth(IdObs,:,irun(1))+trend_addition; + stock_update(IdObs,:,irun(1))=stock_update(IdObs,:,irun(1))+trend_addition; + end stock_innov(:,:,irun(2)) = etahat; if nvn stock_error(:,:,irun(3)) = epsilonhat; end if naK + %filtered variable E_t(y_t+k) requires to shift trend by k periods + %write percentage deviation of variables into declaration order stock_filter_step_ahead(:,dr.order_var,:,irun(4)) = aK(options_.filter_step_ahead,1:endo_nbr,:); + + %now add trend and constant to filtered variables + for ii=1:length(options_.filter_step_ahead) + stock_filter_step_ahead(ii,IdObs,:,irun(4)) = squeeze(stock_filter_step_ahead(ii,IdObs,:,irun(4)))... + +repmat(constant_part(:,1),1,gend+max(options_.filter_step_ahead))... %constant + +[trend_addition repmat(trend_addition(:,end),1,max(options_.filter_step_ahead))+trend_coeff*[1:max(options_.filter_step_ahead)]]; %trend + end end if horizon yyyy = alphahat(iendo,i_last_obs); yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr)); - if options_.prefilter - yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ... + if options_.prefilter + % add mean + yf(:,IdObs) = yf(:,IdObs)+repmat(mean_varobs, ... horizon+maxlag,1); + % add trend, taking into account that last point of sample is still included in forecasts and only cut off later + yf(:,IdObs) = yf(:,IdObs)+((options_.first_obs-1)+gend+[1-maxlag:horizon]')*trend_coeff'-... + repmat(mean(trend_coeff*[options_.first_obs:options_.first_obs+gend-1],2)',length(1-maxlag:horizon),1); %center trend + else + % add trend, taking into account that last point of sample is still included in forecasts and only cut off later + yf(:,IdObs) = yf(:,IdObs)+((options_.first_obs-1)+gend+[1-maxlag:horizon]')*trend_coeff'; end - yf(:,IdObs) = yf(:,IdObs)+(gend+[1-maxlag:horizon]')*trend_coeff'; if options_.loglinear yf = yf+repmat(log(SteadyState'),horizon+maxlag,1); else @@ -203,11 +243,17 @@ for b=fpar:B end yf1 = forcst2(yyyy,horizon,dr,1); if options_.prefilter == 1 + % add mean yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ... - repmat(bayestopt_.mean_varobs',[horizon+maxlag,1,1]); + repmat(mean_varobs,[horizon+maxlag,1,1]); + % add trend, taking into account that last point of sample is still included in forecasts and only cut off later + yf1(:,IdObs) = yf1(:,IdObs)+((options_.first_obs-1)+gend+[1-maxlag:horizon]')*trend_coeff'-... + repmat(mean(trend_coeff*[options_.first_obs:options_.first_obs+gend-1],2)',length(1-maxlag:horizon),1); %center trend + else + % add trend, taking into account that last point of sample is still included in forecasts and only cut off later + yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat(((options_.first_obs-1)+gend+[1-maxlag:horizon]')* ... + trend_coeff',[1,1,1]); end - yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-maxlag:horizon]')* ... - trend_coeff',[1,1,1]); if options_.loglinear yf1 = yf1 + repmat(log(SteadyState'),[horizon+maxlag,1,1]); else diff --git a/matlab/prior_sampler.m b/matlab/prior_sampler.m index 87ffe449f..9e525709b 100644 --- a/matlab/prior_sampler.m +++ b/matlab/prior_sampler.m @@ -31,7 +31,7 @@ function results = prior_sampler(drsave,M_,bayestopt_,options_,oo_,estim_params_ % along with Dynare. If not, see . % Initialization. -prior_draw(1); +prior_draw(bayestopt_, options_.prior_trunc); PriorDirectoryName = CheckPath('prior/draws',M_.dname); work = ~drsave; iteration = 0; diff --git a/matlab/priordens.m b/matlab/priordens.m index f3e5fd619..f760680cf 100644 --- a/matlab/priordens.m +++ b/matlab/priordens.m @@ -1,4 +1,4 @@ -function [logged_prior_density, dlprior, d2lprior, info] = priordens(x, pshape, p6, p7, p3, p4,initialization) +function [logged_prior_density, dlprior, d2lprior, info] = priordens(x, pshape, p6, p7, p3, p4, initialization) % --*-- Unitary tests --*-- % Computes a prior density for the structural parameters of DSGE models % % INPUTS @@ -15,7 +15,7 @@ function [logged_prior_density, dlprior, d2lprior, info] = priordens(x, pshape, % info [double] error code for index of Inf-prior parameter % -% Copyright (C) 2003-2012 Dynare Team +% Copyright (C) 2003-2015 Dynare Team % % This file is part of Dynare. % @@ -32,49 +32,54 @@ function [logged_prior_density, dlprior, d2lprior, info] = priordens(x, pshape, % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -persistent id1 id2 id3 id4 id5 id6 -persistent tt1 tt2 tt3 tt4 tt5 tt6 +persistent id1 id2 id3 id4 id5 id6 id8 +persistent tt1 tt2 tt3 tt4 tt5 tt6 tt8 info=0; -if nargin > 6 && initialization == 1 +if nargin > 6 && initialization % Beta indices. - tt1 = 1; + tt1 = true; id1 = find(pshape==1); if isempty(id1) - tt1 = 0; + tt1 = false; end % Gamma indices. - tt2 = 1; + tt2 = true; id2 = find(pshape==2); if isempty(id2) - tt2 = 0; + tt2 = false; end % Gaussian indices. - tt3 = 1; + tt3 = true; id3 = find(pshape==3); if isempty(id3) - tt3 = 0; + tt3 = false; end % Inverse-Gamma-1 indices. - tt4 = 1; + tt4 = true; id4 = find(pshape==4); if isempty(id4) - tt4 = 0; + tt4 = false; end % Uniform indices. - tt5 = 1; + tt5 = true; id5 = find(pshape==5); if isempty(id5) - tt5 = 0; + tt5 = false; end % Inverse-Gamma-2 indices. - tt6 = 1; + tt6 = true; id6 = find(pshape==6); if isempty(id6) - tt6 = 0; + tt6 = false; + end + % Weibull indices. + tt8 = true; + id8 = find(pshape==8); + if isempty(id8) + tt8 = false; end - pflag = 1; end logged_prior_density = 0.0; @@ -167,6 +172,104 @@ if tt6 end end +if tt8 + logged_prior_density = logged_prior_density + sum(lpdfgweibull(x(id8),p6(id8),p7(id8))); + if isinf(logged_prior_density) + if nargout ==4 + info=id8(isinf(log(lpdfgweibull(x(id8),p6(id8),p7(id8))))); + end + return + end + if nargout==2 + [tmp, dlprior(id8)] = lpdfgweibull(x(id8),p6(id8),p7(id8)) + elseif nargout==3 + [tmp, dlprior(id8), ds2lprior(id8)] = lpdfgweibull(x(id8),p6(id8),p7(id8)) + end +end + if nargout==3, d2lprior = diag(d2lprior); -end \ No newline at end of file +end + +%@test:1 +%$ % 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 +%$ +%$ % Call the tested routine +%$ try +%$ % Initialization of priordens. +%$ lpdstar = priordens(p5, p0, p6, p7, p3, p4, true); +%$ % Do simulations in a loop and estimate recursively the mean and teh variance. +%$ LPD = NaN(10000,1); +%$ for i = 1:10000 +%$ draw = p5+randn(size(p5))*.02; +%$ LPD(i) = priordens(p5, p0, p6, p7, p3, p4); +%$ end +%$ t(1) = true; +%$ catch +%$ t(1) = false; +%$ end +%$ +%$ if t(1) +%$ t(2) = all(LPD<=lpdstar); +%$ end +%$ T = all(t); +%@eof:1 \ No newline at end of file diff --git a/matlab/random_walk_metropolis_hastings_core.m b/matlab/random_walk_metropolis_hastings_core.m index 2c26de0e5..83bbb48aa 100644 --- a/matlab/random_walk_metropolis_hastings_core.m +++ b/matlab/random_walk_metropolis_hastings_core.m @@ -109,6 +109,7 @@ proposal_covariance_Cholesky_decomposition = d*diag(bayestopt_.jscale); block_iter=0; for curr_block = fblck:nblck, + LastSeeds=[]; block_iter=block_iter+1; try % This will not work if the master uses a random number generator not @@ -171,7 +172,8 @@ for curr_block = fblck:nblck, dyn_waitbar(prtfrc,hh,[ 'MH (' int2str(curr_block) '/' int2str(options_.mh_nblck) ') ' sprintf('Current acceptance ratio %4.3f', accepted_draws_this_chain/draw_iter)]); end if (draw_index_current_file == InitSizeArray(curr_block)) || (draw_iter == nruns(curr_block)) % Now I save the simulations, either because the current file is full or the chain is done - save([BaseName '_mh' int2str(NewFile(curr_block)) '_blck' int2str(curr_block) '.mat'],'x2','logpo2'); + [LastSeeds.(['file' int2str(NewFile(curr_block))]).Unifor, LastSeeds.(['file' int2str(NewFile(curr_block))]).Normal] = get_dynare_random_generator_state(); + save([BaseName '_mh' int2str(NewFile(curr_block)) '_blck' int2str(curr_block) '.mat'],'x2','logpo2','LastSeeds'); fidlog = fopen([MetropolisFolder '/metropolis.log'],'a'); fprintf(fidlog,['\n']); fprintf(fidlog,['%% Mh' int2str(NewFile(curr_block)) 'Blck' int2str(curr_block) ' (' datestr(now,0) ')\n']); diff --git a/matlab/reversed_extended_path.m b/matlab/reversed_extended_path.m index 415804f40..f400e01cc 100644 --- a/matlab/reversed_extended_path.m +++ b/matlab/reversed_extended_path.m @@ -14,7 +14,7 @@ function innovation_paths = reversed_extended_path(controlled_variable_names, co % % SPECIAL REQUIREMENTS -% Copyright (C) 2010-2011 Dynare Team. +% Copyright (C) 2010-2016 Dynare Team. % % This file is part of Dynare. % @@ -56,10 +56,10 @@ options_.order = old_options_order; options_.periods = 100; % Set-up oo_.exo_simul. -make_ex_; +oo_=make_ex_(M_,options_,oo_); % Set-up oo_.endo_simul. -make_y_; +oo_=make_y_(M_,options_,oo_); % Get indices of the controlled endogenous variables in endo_simul. n = length(controlled_variable_names); diff --git a/matlab/set_prior.m b/matlab/set_prior.m index f94b25962..64931ce11 100644 --- a/matlab/set_prior.m +++ b/matlab/set_prior.m @@ -168,18 +168,7 @@ bayestopt_.p3(k(k1)) = zeros(length(k1),1); k1 = find(isnan(bayestopt_.p4(k))); bayestopt_.p4(k(k1)) = ones(length(k1),1); for i=1:length(k) - if (bayestopt_.p1(k(i))bayestopt_.p4(k(i))) - error(['The prior mean of ' bayestopt_.name{k(i)} ' has to be between the lower (' num2str(bayestopt_.p3(k(i))) ') and upper (' num2str(bayestopt_.p4(k(i))) ') bounds of the beta prior density!']); - end - mu = (bayestopt_.p1(k(i))-bayestopt_.p3(k(i)))/(bayestopt_.p4(k(i))-bayestopt_.p3(k(i))); - stdd = bayestopt_.p2(k(i))/(bayestopt_.p4(k(i))-bayestopt_.p3(k(i))); - if stdd^2 > (1-mu)*mu - error(sprintf(['Error in prior for %s: in a beta distribution with ' ... - 'mean %f, the standard error can''t be larger than' ... - ' %f.'], bayestopt_.name{k(i)},mu,sqrt((1-mu)*mu))) - end - bayestopt_.p6(k(i)) = (1-mu)*mu^2/stdd^2 - mu ; - bayestopt_.p7(k(i)) = bayestopt_.p6(k(i))*(1/mu-1) ; + [bayestopt_.p6(k(i)), bayestopt_.p7(k(i))] = beta_specification(bayestopt_.p1(k(i)), bayestopt_.p2(k(i))^2, bayestopt_.p3(k(i)), bayestopt_.p4(k(i)), bayestopt_.name{k(i)}); m = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) , bayestopt_.p4(k(i)) ],1); if length(m)==1 bayestopt_.p5(k(i)) = m; @@ -196,29 +185,19 @@ k2 = find(isnan(bayestopt_.p4(k))); bayestopt_.p3(k(k1)) = zeros(length(k1),1); bayestopt_.p4(k(k2)) = Inf(length(k2),1); for i=1:length(k) - if (bayestopt_.p1(k(i))bayestopt_.p4(k(i))) - error(['The prior mean of ' bayestopt_.name{k(i)} ' has to be above the lower (' num2str(bayestopt_.p3(k(i))) ') bound of the Gamma prior density!']); - end - if isinf(bayestopt_.p2(k(i))) - error(['Infinite prior standard deviation for parameter ' bayestopt_.name{k(i)} ' is not allowed (Gamma prior)!']) - end - mu = bayestopt_.p1(k(i))-bayestopt_.p3(k(i)); - bayestopt_.p7(k(i)) = bayestopt_.p2(k(i))^2/mu ; - bayestopt_.p6(k(i)) = mu/bayestopt_.p7(k(i)) ; + [bayestopt_.p6(k(i)), bayestopt_.p7(k(i))] = gamma_specification(bayestopt_.p1(k(i)), bayestopt_.p2(k(i))^2, bayestopt_.p3(k(i)), bayestopt_.name{k(i)}); bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 2) ; end % truncation parameters by default for normal distribution k = find(bayestopt_.pshape == 3); k1 = find(isnan(bayestopt_.p3(k))); +k2 = find(isnan(bayestopt_.p4(k))); bayestopt_.p3(k(k1)) = -Inf*ones(length(k1),1); -k1 = find(isnan(bayestopt_.p4(k))); -bayestopt_.p4(k(k1)) = Inf*ones(length(k1),1); -for i=1:length(k) - bayestopt_.p6(k(i)) = bayestopt_.p1(k(i)) ; - bayestopt_.p7(k(i)) = bayestopt_.p2(k(i)) ; - bayestopt_.p5(k(i)) = bayestopt_.p1(k(i)) ; -end +bayestopt_.p4(k(k2)) = Inf*ones(length(k2),1); +bayestopt_.p6(k) = bayestopt_.p1(k); +bayestopt_.p7(k) = bayestopt_.p2(k); +bayestopt_.p5(k) = bayestopt_.p1(k); % inverse gamma distribution (type 1) k = find(bayestopt_.pshape == 4); @@ -227,13 +206,9 @@ k2 = find(isnan(bayestopt_.p4(k))); bayestopt_.p3(k(k1)) = zeros(length(k1),1); bayestopt_.p4(k(k2)) = Inf(length(k2),1); for i=1:length(k) - if (bayestopt_.p1(k(i))bayestopt_.p4(k(i))) - error(['The prior mean of ' bayestopt_.name{k(i)} ' has to be above the lower (' num2str(bayestopt_.p3(k(i))) ') bound of the Inverse Gamma prior density!']); - end - [bayestopt_.p6(k(i)),bayestopt_.p7(k(i))] = ... - inverse_gamma_specification(bayestopt_.p1(k(i))-bayestopt_.p3(k(i)),bayestopt_.p2(k(i)),1,0) ; - bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 4) ; -end + [bayestopt_.p6(k(i)),bayestopt_.p7(k(i))] = inverse_gamma_specification(bayestopt_.p1(k(i)), bayestopt_.p2(k(i))^2, bayestopt_.p3(k(i)), 1, false, bayestopt_.name{k(i)}); + bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 4); +end % uniform distribution k = find(bayestopt_.pshape == 5); @@ -252,14 +227,22 @@ k2 = find(isnan(bayestopt_.p4(k))); bayestopt_.p3(k(k1)) = zeros(length(k1),1); bayestopt_.p4(k(k2)) = Inf(length(k2),1); for i=1:length(k) - if (bayestopt_.p1(k(i))bayestopt_.p4(k(i))) - error(['The prior mean of ' bayestopt_.name{k(i)} ' has to be above the lower (' num2str(bayestopt_.p3(k(i))) ') bound of the Inverse Gamma II prior density!']); - end [bayestopt_.p6(k(i)),bayestopt_.p7(k(i))] = ... - inverse_gamma_specification(bayestopt_.p1(k(i))-bayestopt_.p3(k(i)),bayestopt_.p2(k(i)),2,0); + inverse_gamma_specification(bayestopt_.p1(k(i)), bayestopt_.p2(k(i))^2, bayestopt_.p3(k(i)), 2, false, bayestopt_.name{k(i)}); bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 6) ; end +% Weibull distribution +k = find(bayestopt_.pshape == 8); +k1 = find(isnan(bayestopt_.p3(k))); +k2 = find(isnan(bayestopt_.p4(k))); +bayestopt_.p3(k(k1)) = zeros(length(k1),1); +bayestopt_.p4(k(k2)) = Inf(length(k2),1); +for i=1:length(k) + [bayestopt_.p6(k(i)),bayestopt_.p7(k(i))] = weibull_specification(bayestopt_.p1(k(i)), bayestopt_.p2(k(i))^2, bayestopt_.p3(k(i)), bayestopt_.name{k(i)}); + bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 8) ; +end + k = find(isnan(xparam1)); if ~isempty(k) xparam1(k) = bayestopt_.p1(k); @@ -273,6 +256,8 @@ if options_.initialize_estimated_parameters_with_the_prior_mode end end + + % I create subfolder M_.dname/prior if needed. CheckPath('prior',M_.dname); diff --git a/matlab/simul_backward_nonlinear_model.m b/matlab/simul_backward_nonlinear_model.m index dd15d7e8f..582376aad 100644 --- a/matlab/simul_backward_nonlinear_model.m +++ b/matlab/simul_backward_nonlinear_model.m @@ -1,4 +1,4 @@ -function DynareOutput = simul_backward_nonlinear_model(sample_size,DynareOptions,DynareModel,DynareOutput) +function DynareOutput = simul_backward_nonlinear_model(sample_size, DynareOptions, DynareModel, DynareOutput) %@info: %! @deftypefn {Function File} {@var{DynareOutput} =} simul_backward_nonlinear_model (@var{sample_size},@var{DynareOptions}, @var{DynareModel}, @var{DynareOutput}) @@ -34,7 +34,7 @@ function DynareOutput = simul_backward_nonlinear_model(sample_size,DynareOptions %! @end deftypefn %@eod: -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2016 Dynare Team % % This file is part of Dynare. % @@ -101,14 +101,18 @@ y = NaN(length(idx)+ny1,1); DynareOutput.endo_simul = NaN(DynareModel.endo_nbr,sample_size+1); DynareOutput.endo_simul(:,1) = DynareOutput.steady_state; +Y = DynareOutput.endo_simul; + % Simulations (call a Newton-like algorithm for each period). for it = 2:sample_size+1 - y(jdx) = DynareOutput.endo_simul(:,it-1); % A good guess for the initial conditions is the previous values for the endogenous variables. + y(jdx) = Y(:,it-1); % A good guess for the initial conditions is the previous values for the endogenous variables. y(hdx) = y(jdx(iy1)); % Set lagged variables. - y(jdx) = solve1(model_dynamic, y, idx, jdx, 1, DynareOptions.gstep, ... + z = solve1(model_dynamic, y, idx, jdx, 1, DynareOptions.gstep, ... DynareOptions.solve_tolf,DynareOptions.solve_tolx, ... DynareOptions.simul.maxit,DynareOptions.debug, ... DynareOutput.exo_simul, DynareModel.params, ... DynareOutput.steady_state, it); - DynareOutput.endo_simul(:,it) = y(jdx); -end \ No newline at end of file + Y(:,it) = z(jdx); +end + +DynareOutput.endo_simul = Y; \ No newline at end of file diff --git a/matlab/simult_.m b/matlab/simult_.m index a4ebe4dba..31daa3a6c 100644 --- a/matlab/simult_.m +++ b/matlab/simult_.m @@ -4,7 +4,7 @@ function y_=simult_(y0,dr,ex_,iorder) % % INPUTS % y0 [double] n*1 vector, initial value (n is the number of declared endogenous variables plus the number -% of auxilliary variables for lags and leads) +% of auxilliary variables for lags and leads); must be in declaration order, i.e. as in M_.endo_names % dr [struct] matlab's structure where the reduced form solution of the model is stored. % ex_ [double] T*q matrix of innovations. % iorder [integer] order of the taylor approximation. @@ -41,6 +41,10 @@ exo_nbr = M_.exo_nbr; y_ = zeros(size(y0,1),iter+M_.maximum_lag); y_(:,1) = y0; +if options_.loglinear && ~options_.logged_steady_state + dr.ys=log(dr.ys); +end + if ~options_.k_order_solver || (options_.k_order_solver && options_.pruning) %if k_order_pert is not used or if we do not use Dynare++ with k_order_pert if iorder==1 y_(:,1) = y_(:,1)-dr.ys; diff --git a/matlab/solve1.m b/matlab/solve1.m index 5fecdd356..937909d09 100644 --- a/matlab/solve1.m +++ b/matlab/solve1.m @@ -23,7 +23,7 @@ function [x,check] = solve1(func,x,j1,j2,jacobian_flag,gstep,tolf,tolx,maxit,deb % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2014 Dynare Team +% Copyright (C) 2001-2016 Dynare Team % % This file is part of Dynare. % @@ -62,7 +62,7 @@ if ~isempty(i) return; end -f = 0.5*fvec'*fvec ; +f = 0.5*(fvec'*fvec) ; if max(abs(fvec)) < tolf return ; @@ -108,7 +108,7 @@ for its = 1:maxit xold = x ; fold = f ; - [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,varargin{:}); + [x, f, fvec, check] = lnsrch1(xold, fold, g, p, stpmax, func, j1, j2, tolx, varargin{:}); if debug disp([its f]) diff --git a/matlab/solve_one_boundary.m b/matlab/solve_one_boundary.m index b1a7ed793..2ce90c7bc 100644 --- a/matlab/solve_one_boundary.m +++ b/matlab/solve_one_boundary.m @@ -55,7 +55,7 @@ function [y, info] = solve_one_boundary(fname, y, x, params, steady_state, ... % none. % -% Copyright (C) 1996-2015 Dynare Team +% Copyright (C) 1996-2016 Dynare Team % % This file is part of Dynare. % @@ -247,10 +247,10 @@ for it_=start:incr:finish if is_dynamic [ya,f,r,check]=lnsrch1(y(it_,:)',f,g,p,stpmax, ... 'lnsrch1_wrapper_one_boundary',nn, ... - y_index_eq, y_index_eq, fname, y, x, params, steady_state, it_); + y_index_eq, options.solve_tolx, y_index_eq, fname, y, x, params, steady_state, it_); dx = ya' - y(it_, :); else - [ya,f,r,check]=lnsrch1(y,f,g,p,stpmax,fname,nn,y_index_eq,x, ... + [ya,f,r,check]=lnsrch1(y,f,g,p,stpmax,fname,nn,y_index_eq, options.solve_tolx, x, ... params, steady_state,0); dx = ya - y(y_index_eq); end diff --git a/matlab/solve_two_boundaries.m b/matlab/solve_two_boundaries.m index cf00fdacb..136d3e1ac 100644 --- a/matlab/solve_two_boundaries.m +++ b/matlab/solve_two_boundaries.m @@ -46,7 +46,7 @@ function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_inde % none. % -% Copyright (C) 1996-2015 Dynare Team +% Copyright (C) 1996-2016 Dynare Team % % This file is part of Dynare. % @@ -307,7 +307,7 @@ while ~(cvg==1 || iter>maxit_) g = (ra'*g1a)'; f = 0.5*ra'*ra; p = -g1a\ra; - [yn,f,ra,check]=lnsrch1(ya,f,g,p,stpmax,'lnsrch1_wrapper_two_boundaries',nn,nn, fname, y, y_index,x, params, steady_state, periods, y_kmin, Blck_size,options.periods); + [yn,f,ra,check]=lnsrch1(ya,f,g,p,stpmax,'lnsrch1_wrapper_two_boundaries',nn,nn, options.solve_tolx, fname, y, y_index,x, params, steady_state, periods, y_kmin, Blck_size,options.periods); dx = ya - yn; y(1+y_kmin:periods+y_kmin,y_index)=reshape(yn',length(y_index),periods)'; end diff --git a/matlab/stoch_simul.m b/matlab/stoch_simul.m index 750bd4929..0de085f49 100644 --- a/matlab/stoch_simul.m +++ b/matlab/stoch_simul.m @@ -78,14 +78,16 @@ else if options_.logged_steady_state %if steady state was previously logged, undo this oo_.dr.ys=exp(oo_.dr.ys); oo_.steady_state=exp(oo_.steady_state); + options_.logged_steady_state=0; end [oo_.dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_); end -if options_.loglinear && isfield(oo_.dr,'ys') %log steady state for correct display of decision rules and simulations +if options_.loglinear && isfield(oo_.dr,'ys') && options_.logged_steady_state==0 %log steady state for correct display of decision rule oo_.dr.ys=log(oo_.dr.ys); oo_.steady_state=log(oo_.steady_state); - options_old.logged_steady_state = 1; + options_old.logged_steady_state = 1; %make sure option is preserved outside of stoch_simul + options_.logged_steady_state=1; %set option for use in stoch_simul end if info(1) options_ = options_old; diff --git a/matlab/trace_plot.m b/matlab/trace_plot.m index bc7322737..759afe94b 100644 --- a/matlab/trace_plot.m +++ b/matlab/trace_plot.m @@ -1,7 +1,7 @@ function trace_plot(options_,M_,estim_params_,type,blck,name1,name2) % This function builds trace plot for the Metropolis-Hastings draws. % -% INPUTS +% INPUTS % % options_ [structure] Dynare structure. % M_ [structure] Dynare structure (related to model definition). @@ -11,11 +11,11 @@ function trace_plot(options_,M_,estim_params_,type,blck,name1,name2) % or 'PosteriorDensity (for posterior density)' % blck [integer] Number of the mh chain. % name1 [string] Object name. -% name2 [string] Object name. -% -% OUTPUTS +% name2 [string] Object name. +% +% OUTPUTS % None -% +% % SPECIAL REQUIREMENTS % Copyright (C) 2003-2015 Dynare Team @@ -40,7 +40,7 @@ if strcmpi(type,'PosteriorDensity') column=0; name1=''; else - if nargin<7 + if nargin<7 column = name2index(options_, M_, estim_params_, type, name1); else column = name2index(options_, M_, estim_params_, type, name1, name2); @@ -92,7 +92,7 @@ else end if options_.mh_nblck>1 - FigureName = [ FigureName , ' (block number ' int2str(blck) ').']; + FigureName = [ FigureName , ' (block number ' int2str(blck) ').']; end hh=dyn_figure(options_,'Name',FigureName); @@ -107,7 +107,7 @@ first = N+1; last = TotalNumberOfMhDraws-N; for t=first:last - MovingAverage(t) = mean(PosteriorDraws(t-N:t+N)); + MovingAverage(t) = mean(PosteriorDraws(t-N:t+N)); end hold on @@ -129,5 +129,41 @@ if strcmpi(type,'PosteriorDensity') else plot_name=get_the_name(column,0,M_,estim_params_,options_); end + dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'TracePlot_' plot_name],options_) +if options_.TeX + fid=fopen([M_.fname,'/graphs/',M_.fname,'_TracePlot_' plot_name,'.TeX'],'w+'); + + if strcmpi(type,'DeepParameter') + tex_names=M_.param_names_tex; + base_names=M_.param_names; + elseif strcmpi(type,'StructuralShock') + tex_names=M_.exo_names_tex; + base_names=M_.exo_names; + elseif strcmpi(type,'MeasurementError') + tex_names=M_.endo_names_tex; + base_names=M_.endo_names; + end + + if strcmpi(type,'PosteriorDensity') + FigureName = ['Trace plot for ' TYPE name1]; + else + if nargin<7 + FigureName = ['Trace plot for ' TYPE '$' deblank(tex_names(strmatch(name1,base_names,'exact'),:)) '$']; + else + FigureName = ['Trace plot for ' TYPE '$' deblank(tex_names(strmatch(name1,base_names,'exact'),:)) '$ and $' deblank(tex_names(strmatch(name2,base_names,'exact'),:)) '$']; + end + end + if options_.mh_nblck>1 + FigureName = [ FigureName , ' (block number ' int2str(blck) ').']; + end + + fprintf(fid,'%-s\n','\begin{figure}[H]'); + fprintf(fid,'%-s\n','\centering'); + fprintf(fid,'%-s\n',[' \includegraphics[scale=0.5]{',[M_.fname, '/graphs/TracePlot_' plot_name],'}\\']); + fprintf(fid,'%-s\n',[' \caption{',FigureName,'}']); + fprintf(fid,'%-s\n','\end{figure}'); + fclose(fid); +end + diff --git a/matlab/variance_decomposition_mc_analysis.m b/matlab/variance_decomposition_mc_analysis.m index 1a04fea48..cfaf71c9a 100644 --- a/matlab/variance_decomposition_mc_analysis.m +++ b/matlab/variance_decomposition_mc_analysis.m @@ -61,6 +61,9 @@ if isempty(jndx) return end +var=deblank(var); +exo=deblank(exo); + name = [ var '.' exo ]; if isfield(oo_, [ TYPE 'TheoreticalMoments']) temporary_structure = oo_.([TYPE, 'TheoreticalMoments']); diff --git a/matlab/write_latex_parameter_table.m b/matlab/write_latex_parameter_table.m index 646adbe49..c2d739801 100644 --- a/matlab/write_latex_parameter_table.m +++ b/matlab/write_latex_parameter_table.m @@ -45,7 +45,7 @@ else end fprintf(fid, ['\\caption{Parameter Values}\\\\%%\n']); -fprintf(fid, '\\hline%%\n'); +fprintf(fid, '\\toprule%%\n'); fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Parameter}} &\n'); fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Value}} '); if Long_names_present==1; @@ -53,7 +53,7 @@ if Long_names_present==1; else fprintf(fid, ' \\\\%%\n'); end -fprintf(fid, '\\hline\\hline%%\n'); +fprintf(fid, '\\midrule%%\n'); fprintf(fid, '\\endfirsthead\n'); if Long_names_present==1; @@ -61,7 +61,7 @@ if Long_names_present==1; else fprintf(fid, '\\multicolumn{2}{c}{{\\tablename} \\thetable{} -- Continued}\\\\%%\n'); end -fprintf(fid, '\\hline%%\n'); +fprintf(fid, '\\midrule%%\n'); fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Parameter}} &\n'); fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Value}} '); if Long_names_present==1; @@ -69,7 +69,7 @@ if Long_names_present==1; else fprintf(fid, '\\\\%%\n'); end -fprintf(fid, '\\hline\\hline%%\n'); +fprintf(fid, '\\midrule%%\n'); fprintf(fid, '\\endhead\n'); tex = M_.param_names_tex; @@ -90,7 +90,7 @@ else M_.params(j,:)); end end -fprintf(fid, '\\hline%%\n'); +fprintf(fid, '\\bottomrule%%\n'); fprintf(fid, '\\end{longtable}\n'); fprintf(fid, '\\end{center}\n'); diff --git a/matlab/write_smoother_results.m b/matlab/write_smoother_results.m new file mode 100644 index 000000000..707251399 --- /dev/null +++ b/matlab/write_smoother_results.m @@ -0,0 +1,154 @@ +function [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_=write_smoother_results(M_,oo_,options_,bayestopt_,dataset_,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend) +% Writes the smoother results into respective fields in oo_ +% +% Inputs: +% M_ [structure] storing the model information +% oo_ [structure] storing the results +% options_ [structure] storing the options +% bayestopt_ [structure] storing information about priors +% dataset_ [structure] storing the dataset +% atT [double] (m*T) matrix, smoothed endogenous variables (a_{t|T}) +% innov [double] (r*T) matrix, smoothed structural shocks (r>n is the umber of shocks). +% measurement_error [double] (n*T) matrix, smoothed measurement errors. +% updated_variables [double] (m*T) matrix, updated (endogenous) variables (a_{t|T}) +% ys [double] (m*1) vector specifying the steady state level of each endogenous variable. +% trend_coeff [double] (n*1) vector, parameters specifying the slope of the trend associated to each observed variable. +% aK [double] (K,n,T+K) array, k (k=1,...,K) steps ahead filtered (endogenous) variables. +% P [3D array] of one-step ahead forecast error variance +% matrices +% PK [4D array] of k-step ahead forecast error variance +% matrices (meaningless for periods 1:d) +% decomp +% Trend [double] [nvarobs*T] matrix of trends in observables +% +% Outputs: +% oo_ [structure] storing the results +% yf [double] (nvarobs*T) matrix storing the smoothed observed variables +% +% Notes: first all smoothed variables are saved without trend and constant. +% Then trend and constant are added for the observed variables. +% +% 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 . + +gend=dataset_.nobs; +if nargin<16 + Trend=zeros(options_.number_of_observed_variables,gend); +end + +%% write variable steady state +oo_.Smoother.SteadyState = ys; + +%% write trend coefficients and trend +oo_.Smoother.TrendCoeffs = trend_coeff; %are in order of options_.varobs + +if ~isempty(Trend) + for var_iter=1:size(options_.varobs,2) + oo_.Smoother.Trend.(deblank(options_.varobs{1,var_iter})) = Trend(var_iter,:)'; + end +end +%% Compute constant for observables +if options_.prefilter == 1 %as mean is taken after log transformation, no distinction is needed here + constant_part=repmat(dataset_info.descriptive.mean',1,gend); +elseif options_.prefilter == 0 && options_.loglinear == 1 %logged steady state must be used + constant_part=repmat(log(ys(bayestopt_.mfys)),1,gend); +elseif options_.prefilter == 0 && options_.loglinear == 0 %unlogged steady state must be used + constant_part=repmat(ys(bayestopt_.mfys),1,gend); +end + +%% get observed variables including trend and constant +trend_constant_observables=constant_part+Trend; +yf = atT(bayestopt_.mf,:)+trend_constant_observables; + +if options_.nk > 0 + %filtered variable E_t(y_t+k) requires to shift trend by k periods + filter_steps_required=union(1,options_.filter_step_ahead); % 1 is required for standard filtered variables + for filter_iter=1:length(filter_steps_required) + filter_step=filter_steps_required(filter_iter); + trend_constant_observables_filtered.(['filter_ahead_' num2str(filter_step)])=constant_part+[Trend+repmat(filter_step*trend_coeff,1,gend)]; + end +end +%% write smoother variance +if options_.filter_covariance + oo_.Smoother.Variance = P; +end + +%get indicees of smoothed variables +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))) + %write deviations from steady state, add constant for observables later + oo_.FilteredVariablesKStepAhead = aK(options_.filter_step_ahead,i_endo,:); + if ~isempty(PK) %get K-step ahead variances + oo_.FilteredVariablesKStepAheadVariances = ... + PK(options_.filter_step_ahead,i_endo,i_endo,:); + end + if ~isempty(decomp) %get decomposition + 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)); %get indices of smoothed variables in name vector + %% Compute constant + if options_.loglinear == 1 %logged steady state must be used + constant_current_variable=repmat(log(ys(i1)),gend,1); + elseif options_.loglinear == 0 %unlogged steady state must be used + constant_current_variable=repmat((ys(i1)),gend,1); + end + oo_.SmoothedVariables.(deblank(M_.endo_names(i1,:)))=atT(i,:)'+constant_current_variable; + if ~isempty(options_.nk) && options_.nk > 0 && ~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file)) + oo_.FilteredVariables.(deblank(M_.endo_names(i1,:)))=squeeze(aK(1,i,2:end-(options_.nk-1))); + end + oo_.UpdatedVariables.(deblank(M_.endo_names(i1,:)))=updated_variables(i,:)'+constant_current_variable; +end + +%% Add trend and constant for observed variables +for pos_iter=1:length(bayestopt_.mf) + oo_.Smoother.Constant.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=constant_part(pos_iter,:); + oo_.SmoothedVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=yf(pos_iter,:)'; + if ~isempty(options_.nk) && options_.nk > 0 && ~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file)) + %filtered variable E_t(y_t+1) requires to shift trend by 1 period + oo_.FilteredVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=... + squeeze(aK(1,bayestopt_.mf(pos_iter),2:end-(options_.nk-1)))... + +trend_constant_observables_filtered.filter_ahead_1(pos_iter,:)'; + for filter_iter=1:length(options_.filter_step_ahead) + filter_step=options_.filter_step_ahead(filter_iter); + oo_.FilteredVariablesKStepAhead(filter_iter,bayestopt_.mf(pos_iter),1+filter_step:end-(max(options_.filter_step_ahead)-filter_step)) = ... + squeeze(aK(filter_step,bayestopt_.mf(pos_iter),1+filter_step:end-(max(options_.filter_step_ahead)-filter_step)))... + +trend_constant_observables_filtered.(['filter_ahead_' num2str(filter_step)])(pos_iter,:)'; + end + end + %updated variables are E_t(y_t) so no trend shift is required + oo_.UpdatedVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=... + updated_variables(bayestopt_.mf(pos_iter),:)'+trend_constant_observables(pos_iter,:)'; +end + +%% get smoothed shocks +for i=1:M_.exo_nbr + oo_.SmoothedShocks.(deblank(M_.exo_names(i,:)))=innov(i,:)'; +end + +%% Smoothed measurement errors +if ~isequal(M_.H,0) +% measurement_error_indices=find(diag(M_.H)~=0); + for meas_error_iter=1:length(options_.varobs) + oo_.SmoothedMeasurementErrors.(options_.varobs{meas_error_iter})= measurement_error(meas_error_iter,:)'; + end +end \ No newline at end of file diff --git a/matlab/writecellofchar.m b/matlab/writecellofchar.m new file mode 100644 index 000000000..be636e6f1 --- /dev/null +++ b/matlab/writecellofchar.m @@ -0,0 +1,63 @@ +function str = writecellofchar(c) + +% Writes a two dimensional cell of char in a string. +% +% INPUTS +% - c [cell] cell of char. +% +% OUTPUTS +% - str [char] +% +% EXAMPLES +% >> writecellofchar({'a', {'b'; 'c'}}) +% +% ans = +% +% {'a', {'b'; 'c'}} +% +% >> writecellofchar({'a', ['b'; 'c'], 'd'}) +% +% ans = +% +%{'a', '['b'; 'c']', 'd'} + +% 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 . + +str = '{'; +for i=1:size(c, 1) + for j=1:size(c, 2) + if iscell(c{i,j}) + str = sprintf('%s%s', str, writecellofchar(c{i, j})); + elseif ischar(c{i, j}) + if size(c{i, j}, 1)>1 + str = sprintf('%s''%s''', str, writematrixofchar(c{i, j})); + else + str = sprintf('%s''%s''', str, c{i, j}); + end + else + error('Type not implemenented!') + end + if j -% Copyright (C) 2013 Dynare Team +% Writes a matrix of char in a string. +% +% INPUTS +% - m [char] matrix of char. +% +% OUTPUTS +% - str [char] +% +% EXAMPLE +% >> writematrixofchar(['a'; 'b']) +% +% ans = +% +% ['a'; 'b'] +% +% where the returned argument is a string which can be evaluated or printed. + +% Copyright (C) 2015 Dynare Team % % This file is part of Dynare. % @@ -19,18 +34,15 @@ function rval = strjoin (c, varargin) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -assert(iscellstr(c), 'strjoin: first argument is a cell array of strings'); -assert(nargin <= 2, 'strjoin: takes one or two arguments'); -delimiter = ' '; -if nargin == 2 - delimiter = varargin{1}; - assert(ischar(delimiter), 'strjoin: second argument must be a char'); +if ~(ischar(m) && ismatrix(m)) + error('Input has to be a matrix of char!') end -rval = ''; -L = length(c); -for idx = 1:(L-1) - rval = [rval c{idx} delimiter]; -end -rval = [rval c{L}]; +str = '['; +for i=1:size(m, 1) + str = sprintf('%s''%s''', str, m(i,:)); + if i Unknown exogenous variable # %d", variable_num); break; case eParameter: - if (variable_num < nb_param) + if (variable_num <= nb_param) { for (unsigned int i = 0; i < param_name_length; i++) if (P_param_names[CHAR_LENGTH*(variable_num+i*nb_param)] != ' ') diff --git a/mex/sources/bytecode/Interpreter.cc b/mex/sources/bytecode/Interpreter.cc index b72272da5..f85c9e709 100644 --- a/mex/sources/bytecode/Interpreter.cc +++ b/mex/sources/bytecode/Interpreter.cc @@ -77,7 +77,7 @@ Interpreter::Interpreter(double *params_arg, double *y_arg, double *ya_arg, doub GlobalTemporaryTerms = GlobalTemporaryTerms_arg; print_error = print_error_arg; //steady_state = steady_state_arg; - //print_it = print_it_arg; + print_it = print_it_arg; } @@ -850,16 +850,18 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate, int endo_name_length_l = endo_name_length; for (int j = 0; j < col_x* nb_row_x; j++) - x_save[j] = x[j]; + { + x_save[j] = x[j]; + x[j] = 0; + } + for (int j = 0; j < col_x; j++) + x[y_kmin + j * nb_row_x] = x_save[1 + y_kmin + j * nb_row_x]; for (int i = 0; i < (y_size*(periods + y_kmax + y_kmin)); i++) y_save[i] = y[i]; if (endo_name_length_l < 8) endo_name_length_l = 8; - //mexPrintf("endo_name_length = %d\n",endo_name_length_l); + bool old_print_it = print_it; print_it = false; - //print_it = true; - mexPrintf("\nExtended Path simulation:\n"); - mexPrintf("-------------------------\n"); ostringstream res1; res1 << std::scientific << 2.54656875434865131; int real_max_length = res1.str().length(); @@ -868,16 +870,24 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate, string line; line.insert(line.begin(),table_length,'-'); line.insert(line.length(),"\n"); - mexPrintf(line.c_str()); - string title = "|" + elastic("date",date_length+2, false) + "|" + elastic("variable",endo_name_length_l+2, false) + "|" + elastic("max. value",real_max_length+2, false) + "| iter. |" + elastic("cvg",5, false) + "|\n"; - mexPrintf(title.c_str()); - mexPrintf(line.c_str()); + if (old_print_it) + { + mexPrintf("\nExtended Path simulation:\n"); + mexPrintf("-------------------------\n"); + mexPrintf(line.c_str()); + string title = "|" + elastic("date",date_length+2, false) + "|" + elastic("variable",endo_name_length_l+2, false) + "|" + elastic("max. value",real_max_length+2, false) + "| iter. |" + elastic("cvg",5, false) + "|\n"; + mexPrintf(title.c_str()); + mexPrintf(line.c_str()); + } for (int t = 0; t < nb_periods; t++) { nb_blocks = 0; previous_block_exogenous.clear(); - mexPrintf("|%s|",elastic(dates[t], date_length+2, false).c_str()); - mexEvalString("drawnow;"); + if (old_print_it) + { + mexPrintf("|%s|",elastic(dates[t], date_length+2, false).c_str()); + mexEvalString("drawnow;"); + } for (vector::const_iterator it = sextended_path.begin(); it != sextended_path.end(); it++) x[y_kmin + (it->exo_num - 1) * (periods + y_kmax + y_kmin)] = it->value[t]; it_code = Init_Code; @@ -897,18 +907,22 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate, for (int j = 0; j < col_x; j++) { x_save[t + y_kmin + j * nb_row_x] = x[y_kmin + j * nb_row_x]; - x[y_kmin + j * nb_row_x] = 0; + x[y_kmin + j * nb_row_x] = x_save[t + 1 + y_kmin + j * nb_row_x]; } - ostringstream res, res1; - for (unsigned int i = 0; i < endo_name_length; i++) - if (P_endo_names[CHAR_LENGTH*(max_res_idx+i*y_size)] != ' ') - res << P_endo_names[CHAR_LENGTH*(max_res_idx+i*y_size)]; - res1 << std::scientific << max_res; - mexPrintf("%s|%s| %4d | x |\n",elastic(res.str(),endo_name_length_l+2, true).c_str(), elastic(res1.str(), real_max_length+2, false).c_str(), iter); - mexPrintf(line.c_str()); - mexEvalString("drawnow;"); + if (old_print_it) + { + ostringstream res, res1; + for (unsigned int i = 0; i < endo_name_length; i++) + if (P_endo_names[CHAR_LENGTH*(max_res_idx+i*y_size)] != ' ') + res << P_endo_names[CHAR_LENGTH*(max_res_idx+i*y_size)]; + res1 << std::scientific << max_res; + mexPrintf("%s|%s| %4d | x |\n",elastic(res.str(),endo_name_length_l+2, true).c_str(), elastic(res1.str(), real_max_length+2, false).c_str(), iter); + mexPrintf(line.c_str()); + mexEvalString("drawnow;"); + } } + print_it = old_print_it; for (int j = 0; j < y_size; j++) { for(int k = nb_periods; k < periods; k++) diff --git a/mex/sources/bytecode/SparseMatrix.cc b/mex/sources/bytecode/SparseMatrix.cc index 37fadb663..840f302a6 100644 --- a/mex/sources/bytecode/SparseMatrix.cc +++ b/mex/sources/bytecode/SparseMatrix.cc @@ -985,7 +985,10 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si { int t, eq, var, lag, ti_y_kmin, ti_y_kmax; double* jacob_exo ; - int row_x, col_x; + int row_x; +#ifdef DEBUG + int col_x; +#endif int n = periods * Size; *b = (double*)mxMalloc(n * sizeof(double)); if (!(*b)) @@ -1040,9 +1043,13 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si { jacob_exo = mxGetPr(jacobian_exo_block[block_num]); row_x = mxGetM(jacobian_exo_block[block_num]); +#ifdef DEBUG col_x = mxGetN(jacobian_exo_block[block_num]); +#endif } +#ifdef DEBUG int local_index; +#endif bool fliped = false; bool fliped_exogenous_derivatives_updated = false; @@ -1097,7 +1104,9 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si if ((t == 0) && (var < (periods+y_kmax)*Size) && (lag == 0) && (vector_table_conditional_local.size())) { flip_exo = vector_table_conditional_local[var].var_exo; +#ifdef DEBUG local_index = eq; +#endif if (!fliped_exogenous_derivatives_updated) { fliped_exogenous_derivatives_updated = true; @@ -1193,7 +1202,6 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si throw FatalExceptionHandling(tmp.str()); } #endif - double prev_b = (*b)[eq - lag * Size]; (*b)[eq - lag * Size] += u[index] * y[index_vara[var+Size*(y_kmin+t/*+lag*/)]]; } @@ -3340,7 +3348,6 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do int flip_exo = vector_table_conditional_local[i].var_exo; double yy = -(res[i] + x[y_kmin + flip_exo*/*row_x*/nb_row_x]); direction[eq] = 0; - double mem_x = x[flip_exo*/*row_x*/nb_row_x + y_kmin]; x[flip_exo*/*row_x*/nb_row_x + y_kmin] += slowc_l * yy; } else diff --git a/mex/sources/bytecode/bytecode.cc b/mex/sources/bytecode/bytecode.cc index b9ed325ba..25260c82b 100644 --- a/mex/sources/bytecode/bytecode.cc +++ b/mex/sources/bytecode/bytecode.cc @@ -21,6 +21,38 @@ #include "ErrorHandling.hh" #include #include +#ifdef DYN_MEX_FUNC_ERR_MSG_TXT + #undef DYN_MEX_FUNC_ERR_MSG_TXT +#endif // DYN_MEX_FUNC_ERR_MSG_TXT + +#define DYN_MEX_FUNC_ERR_MSG_TXT(str) \ + do { \ + mexPrintf("%s\n", str); \ + if (nlhs > 0) \ + { \ + plhs[0] = mxCreateDoubleScalar(1); \ + if (nlhs > 1) \ + { \ + double *pind; \ + plhs[1] = mxCreateDoubleMatrix(int(row_y), int(col_y), mxREAL); \ + pind = mxGetPr(plhs[1]); \ + if (evaluate ) \ + { \ + for (unsigned int i = 0; i < row_y*col_y; i++) \ + pind[i] = 0; \ + } \ + else \ + { \ + for (unsigned int i = 0; i < row_y*col_y; i++) \ + pind[i] = yd[i]; \ + } \ + for (int i = 2; i < nlhs; i++) \ + plhs[i] = mxCreateDoubleScalar(1); \ + } \ + } \ + return; \ + } while (0) + #ifdef DEBUG_EX @@ -935,16 +967,20 @@ main(int nrhs, const char *prhs[]) if (field >= 0) temporaryfield = mxGetFieldByNumber(options_, 0, field); else - if (!steady_state) - DYN_MEX_FUNC_ERR_MSG_TXT("simul is not a field of options_"); - else - DYN_MEX_FUNC_ERR_MSG_TXT("steady is not a field of options_"); + { + if (!steady_state) + DYN_MEX_FUNC_ERR_MSG_TXT("simul is not a field of options_"); + else + DYN_MEX_FUNC_ERR_MSG_TXT("steady is not a field of options_"); + } field = mxGetFieldNumber(temporaryfield, "maxit"); if (field<0) - if (!steady_state) - DYN_MEX_FUNC_ERR_MSG_TXT("maxit is not a field of options_.simul"); - else - DYN_MEX_FUNC_ERR_MSG_TXT("maxit is not a field of options_.steady"); + { + if (!steady_state) + DYN_MEX_FUNC_ERR_MSG_TXT("maxit is not a field of options_.simul"); + else + DYN_MEX_FUNC_ERR_MSG_TXT("maxit is not a field of options_.steady"); + } int maxit_ = int (floor(*(mxGetPr(mxGetFieldByNumber(temporaryfield, 0, field))))); field = mxGetFieldNumber(options_, "slowc"); if (field < 0) diff --git a/preprocessor/CodeInterpreter.hh b/preprocessor/CodeInterpreter.hh index 2a4e755f7..cdd6f2781 100644 --- a/preprocessor/CodeInterpreter.hh +++ b/preprocessor/CodeInterpreter.hh @@ -252,6 +252,19 @@ enum PriorDistributions eWeibull = 8 }; +enum NodeTreeReference + { + eResiduals = 0, + eFirstDeriv = 1, + eSecondDeriv = 2, + eThirdDeriv = 3, + eResidualsParamsDeriv = 4, + eJacobianParamsDeriv = 5, + eResidualsParamsSecondDeriv = 6, + eJacobianParamsSecondDeriv = 7, + eHessianParamsDeriv = 8 + }; + struct Block_contain_type { int Equation, Variable, Own_Derivative; diff --git a/preprocessor/ComputingTasks.cc b/preprocessor/ComputingTasks.cc index bd62e036c..cffa58621 100644 --- a/preprocessor/ComputingTasks.cc +++ b/preprocessor/ComputingTasks.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2015 Dynare Team + * Copyright (C) 2003-2016 Dynare Team * * This file is part of Dynare. * @@ -239,7 +239,7 @@ ForecastStatement::writeOutput(ostream &output, const string &basename, bool min { options_list.writeOutput(output); symbol_list.writeOutput("var_list_", output); - output << "info = dyn_forecast(var_list_,'simul');" << endl; + output << "[oo_.forecast,info] = dyn_forecast(var_list_,M_,options_,oo_,'simul');" << endl; } RamseyModelStatement::RamseyModelStatement(const SymbolList &symbol_list_arg, @@ -559,13 +559,6 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli it = options_list.num_options.find("dsge_var"); if (it != options_list.num_options.end()) - // Ensure that irf_shocks & dsge_var have not both been passed - if (options_list.symbol_list_options.find("irf_shocks") != options_list.symbol_list_options.end()) - { - cerr << "The irf_shocks and dsge_var options may not both be passed to estimation." << endl; - exit(EXIT_FAILURE); - } - else // Fill in mod_file_struct.dsge_var_calibrated mod_file_struct.dsge_var_calibrated = it->second; @@ -1021,7 +1014,7 @@ ObservationTrendsStatement::ObservationTrendsStatement(const trend_elements_t &t void ObservationTrendsStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const { - output << "options_.trend_coeff_ = {};" << endl; + output << "options_.trend_coeff = {};" << endl; trend_elements_t::const_iterator it; @@ -3166,8 +3159,7 @@ ExtendedPathStatement::writeOutput(ostream &output, const string &basename, bool output << "options_." << it->first << " = " << it->second << ";" << endl; output << "extended_path([], " << options_list.num_options.find("periods")->second - << ");" << endl - << "oo_.exo_simul = oo_.ep.shocks;" << endl; + << ");" << endl; } ModelDiagnosticsStatement::ModelDiagnosticsStatement() diff --git a/preprocessor/DynamicModel.cc b/preprocessor/DynamicModel.cc index cdc8f22d6..11ff41f0e 100644 --- a/preprocessor/DynamicModel.cc +++ b/preprocessor/DynamicModel.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2015 Dynare Team + * Copyright (C) 2003-2016 Dynare Team * * This file is part of Dynare. * @@ -2112,26 +2112,34 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri void DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia) const { - ostringstream model_output; // Used for storing model - ostringstream model_eq_output; // Used for storing model equations - ostringstream jacobian_output; // Used for storing jacobian equations - ostringstream hessian_output; // Used for storing Hessian equations - ostringstream third_derivatives_output; + ostringstream model_local_vars_output; // Used for storing model local vars + ostringstream model_output; // Used for storing model temp vars and equations + ostringstream jacobian_output; // Used for storing jacobian equations + ostringstream hessian_output; // Used for storing Hessian equations + ostringstream third_derivatives_output; // Used for storing third order derivatives equations ExprNodeOutputType output_type = (use_dll ? oCDynamicModel : julia ? oJuliaDynamicModel : oMatlabDynamicModel); deriv_node_temp_terms_t tef_terms; - writeModelLocalVariables(model_output, output_type, tef_terms); + temporary_terms_t temp_term_union = temporary_terms_res; - writeTemporaryTerms(temporary_terms, model_output, output_type, tef_terms); + writeModelLocalVariables(model_local_vars_output, output_type, tef_terms); - writeModelEquations(model_eq_output, output_type); + writeTemporaryTerms(temporary_terms_res, model_output, output_type, tef_terms); + + writeModelEquations(model_output, output_type); int nrows = equations.size(); int hessianColsNbr = dynJacobianColsNbr * dynJacobianColsNbr; // Writing Jacobian + temp_term_union.insert(temporary_terms_g1.begin(), temporary_terms_g1.end()); + if (!first_derivatives.empty()) + if (julia) + writeTemporaryTerms(temp_term_union, jacobian_output, output_type, tef_terms); + else + writeTemporaryTerms(temporary_terms_g1, jacobian_output, output_type, tef_terms); for (first_derivatives_t::const_iterator it = first_derivatives.begin(); it != first_derivatives.end(); it++) { @@ -2141,11 +2149,17 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia jacobianHelper(jacobian_output, eq, getDynJacobianCol(var), output_type); jacobian_output << "="; - d1->writeOutput(jacobian_output, output_type, temporary_terms, tef_terms); + d1->writeOutput(jacobian_output, output_type, temp_term_union, tef_terms); jacobian_output << ";" << endl; } // Writing Hessian + temp_term_union.insert(temporary_terms_g2.begin(), temporary_terms_g2.end()); + if (!second_derivatives.empty()) + if (julia) + writeTemporaryTerms(temp_term_union, hessian_output, output_type, tef_terms); + else + writeTemporaryTerms(temporary_terms_g2, hessian_output, output_type, tef_terms); int k = 0; // Keep the line of a 2nd derivative in v2 for (second_derivatives_t::const_iterator it = second_derivatives.begin(); it != second_derivatives.end(); it++) @@ -2166,7 +2180,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia { for_sym << "g2[" << eq + 1 << "," << col_nb + 1 << "]"; hessian_output << " @inbounds " << for_sym.str() << " = "; - d2->writeOutput(hessian_output, output_type, temporary_terms, tef_terms); + d2->writeOutput(hessian_output, output_type, temp_term_union, tef_terms); hessian_output << endl; } else @@ -2179,7 +2193,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia sparseHelper(2, hessian_output, k, 2, output_type); hessian_output << "="; - d2->writeOutput(hessian_output, output_type, temporary_terms, tef_terms); + d2->writeOutput(hessian_output, output_type, temp_term_union, tef_terms); hessian_output << ";" << endl; k++; @@ -2208,6 +2222,12 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia } // Writing third derivatives + temp_term_union.insert(temporary_terms_g3.begin(), temporary_terms_g3.end()); + if (!third_derivatives.empty()) + if (julia) + writeTemporaryTerms(temp_term_union, third_derivatives_output, output_type, tef_terms); + else + writeTemporaryTerms(temporary_terms_g3, third_derivatives_output, output_type, tef_terms); k = 0; // Keep the line of a 3rd derivative in v3 for (third_derivatives_t::const_iterator it = third_derivatives.begin(); it != third_derivatives.end(); it++) @@ -2230,7 +2250,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia { for_sym << "g3[" << eq + 1 << "," << ref_col + 1 << "]"; third_derivatives_output << " @inbounds " << for_sym.str() << " = "; - d3->writeOutput(third_derivatives_output, output_type, temporary_terms, tef_terms); + d3->writeOutput(third_derivatives_output, output_type, temp_term_union, tef_terms); third_derivatives_output << endl; } else @@ -2243,7 +2263,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia sparseHelper(3, third_derivatives_output, k, 2, output_type); third_derivatives_output << "="; - d3->writeOutput(third_derivatives_output, output_type, temporary_terms, tef_terms); + d3->writeOutput(third_derivatives_output, output_type, temp_term_union, tef_terms); third_derivatives_output << ";" << endl; } @@ -2287,8 +2307,8 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia << "%" << endl << endl << "residual = zeros(" << nrows << ", 1);" << endl + << model_local_vars_output.str() << model_output.str() - << model_eq_output.str() // Writing initialization instruction for matrix g1 << "if nargout >= 2," << endl << " g1 = zeros(" << nrows << ", " << dynJacobianColsNbr << ");" << endl @@ -2298,10 +2318,10 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia << " %" << endl << endl << jacobian_output.str() - << "end" << endl; + << endl // Initialize g2 matrix - DynamicOutput << "if nargout >= 3," << endl + << "if nargout >= 3," << endl << " %" << endl << " % Hessian matrix" << endl << " %" << endl @@ -2312,7 +2332,6 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia << " g2 = sparse(v2(:,1),v2(:,2),v2(:,3)," << nrows << "," << hessianColsNbr << ");" << endl; else // Either hessian is all zero, or we didn't compute it DynamicOutput << " g2 = sparse([],[],[]," << nrows << "," << hessianColsNbr << ");" << endl; - DynamicOutput << "end" << endl; // Initialize g3 matrix DynamicOutput << "if nargout >= 4," << endl @@ -2328,7 +2347,9 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia else // Either 3rd derivatives is all zero, or we didn't compute it DynamicOutput << " g3 = sparse([],[],[]," << nrows << "," << ncols << ");" << endl; - DynamicOutput << "end" << endl; + DynamicOutput << "end" << endl + << "end" << endl + << "end" << endl; } else if (output_type == oCDynamicModel) { @@ -2337,33 +2358,30 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia << " double lhs, rhs;" << endl << endl << " /* Residual equations */" << endl + << model_local_vars_output.str() << model_output.str() - << model_eq_output.str() << " /* Jacobian */" << endl << " if (g1 == NULL)" << endl << " return;" << endl - << " else" << endl - << " {" << endl + << endl << jacobian_output.str() - << " }" << endl; + << endl; if (second_derivatives.size()) DynamicOutput << " /* Hessian for endogenous and exogenous variables */" << endl << " if (v2 == NULL)" << endl << " return;" << endl - << " else" << endl - << " {" << endl + << endl << hessian_output.str() - << " }" << endl; + << endl; if (third_derivatives.size()) DynamicOutput << " /* Third derivatives for endogenous and exogenous variables */" << endl << " if (v3 == NULL)" << endl << " return;" << endl - << " else" << endl - << " {" << endl + << endl << third_derivatives_output.str() - << " }" << endl; + << endl; DynamicOutput << "}" << endl << endl; } @@ -2396,8 +2414,8 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia << " #" << endl << " # Model equations" << endl << " #" << endl + << model_local_vars_output.str() << model_output.str() - << model_eq_output.str() << "end" << endl << endl << "function dynamic!(y::Vector{Float64}, x::Matrix{Float64}, " << "params::Vector{Float64}," << endl @@ -2413,7 +2431,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia << " @assert size(g1) == (" << nrows << ", " << dynJacobianColsNbr << ")" << endl << " fill!(g1, 0.0)" << endl << " dynamic!(y, x, params, steady_state, it_, residual)" << endl - << model_output.str() + << model_local_vars_output.str() << " #" << endl << " # Jacobian matrix" << endl << " #" << endl @@ -2433,7 +2451,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia << " @assert size(g2) == (" << nrows << ", " << hessianColsNbr << ")" << endl << " dynamic!(y, x, params, steady_state, it_, residual, g1)" << endl; if (second_derivatives.size()) - DynamicOutput << model_output.str() + DynamicOutput << model_local_vars_output.str() << " #" << endl << " # Hessian matrix" << endl << " #" << endl @@ -2456,7 +2474,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia << " @assert size(g3) == (" << nrows << ", " << ncols << ")" << endl << " dynamic!(y, x, params, steady_state, it_, residual, g1, g2)" << endl; if (third_derivatives.size()) - DynamicOutput << model_output.str() + DynamicOutput << model_local_vars_output.str() << " #" << endl << " # Third order derivatives" << endl << " #" << endl @@ -2466,7 +2484,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia } void -DynamicModel::writeOutput(ostream &output, const string &basename, bool block_decomposition, bool byte_code, bool use_dll, int order, bool estimation_present, bool julia) const +DynamicModel::writeOutput(ostream &output, const string &basename, bool block_decomposition, bool byte_code, bool use_dll, int order, bool estimation_present, bool compute_xrefs, bool julia) const { /* Writing initialisation for M_.lead_lag_incidence matrix M_.lead_lag_incidence is a matrix with as many columns as there are @@ -3049,6 +3067,9 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << modstruct << "params = " << (julia ? "fill(NaN, " : "NaN(") << symbol_table.param_nbr() << ", 1);" << endl; + if (compute_xrefs) + writeXrefs(output); + // Write number of non-zero derivatives // Use -1 if the derivatives have not been computed output << modstruct << (julia ? "nnzderivatives" : "NNZDerivatives") @@ -3092,7 +3113,8 @@ DynamicModel::runTrendTest(const eval_context_t &eval_context) void DynamicModel::computingPass(bool jacobianExo, bool hessian, bool thirdDerivatives, bool paramsDerivatives, - const eval_context_t &eval_context, bool no_tmp_terms, bool block, bool use_dll, bool bytecode) + const eval_context_t &eval_context, bool no_tmp_terms, bool block, bool use_dll, + bool bytecode, bool compute_xrefs) { assert(jacobianExo || !(hessian || thirdDerivatives || paramsDerivatives)); @@ -3200,6 +3222,9 @@ DynamicModel::computingPass(bool jacobianExo, bool hessian, bool thirdDerivative if (bytecode) computeTemporaryTermsMapping(); } + + if (compute_xrefs) + computeXrefs(); } map >, pair >, int> @@ -4237,6 +4262,40 @@ DynamicModel::substituteLeadLagInternal(aux_var_t type, bool deterministic_model equations[i] = substeq; } + + // Substitute in aux_equations + // Without this loop, the auxiliary equations in equations + // will diverge from those in aux_equations + for (int i = 0; i < (int) aux_equations.size(); i++) + { + expr_t subst; + switch (type) + { + case avEndoLead: + subst = aux_equations[i]->substituteEndoLeadGreaterThanTwo(subst_table, + neweqs, deterministic_model); + break; + case avEndoLag: + subst = aux_equations[i]->substituteEndoLagGreaterThanTwo(subst_table, neweqs); + break; + case avExoLead: + subst = aux_equations[i]->substituteExoLead(subst_table, neweqs, deterministic_model); + break; + case avExoLag: + subst = aux_equations[i]->substituteExoLag(subst_table, neweqs); + break; + case avDiffForward: + subst = aux_equations[i]->differentiateForwardVars(subset, subst_table, neweqs); + break; + default: + cerr << "DynamicModel::substituteLeadLagInternal: impossible case" << endl; + exit(EXIT_FAILURE); + } + BinaryOpNode *substeq = dynamic_cast(subst); + assert(substeq != NULL); + aux_equations[i] = substeq; + } + // Add new equations for (int i = 0; i < (int) neweqs.size(); i++) addEquation(neweqs[i], -1); diff --git a/preprocessor/DynamicModel.hh b/preprocessor/DynamicModel.hh index fbb18b222..13f181926 100644 --- a/preprocessor/DynamicModel.hh +++ b/preprocessor/DynamicModel.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2015 Dynare Team + * Copyright (C) 2003-2016 Dynare Team * * This file is part of Dynare. * @@ -213,9 +213,9 @@ public: \param no_tmp_terms if true, no temporary terms will be computed in the dynamic files */ void computingPass(bool jacobianExo, bool hessian, bool thirdDerivatives, bool paramsDerivatives, - const eval_context_t &eval_context, bool no_tmp_terms, bool block, bool use_dll, bool bytecode); + const eval_context_t &eval_context, bool no_tmp_terms, bool block, bool use_dll, bool bytecode, bool compute_xrefs); //! Writes model initialization and lead/lag incidence matrix to output - void writeOutput(ostream &output, const string &basename, bool block, bool byte_code, bool use_dll, int order, bool estimation_present, bool julia) const; + void writeOutput(ostream &output, const string &basename, bool block, bool byte_code, bool use_dll, int order, bool estimation_present, bool compute_xrefs, bool julia) const; //! Adds informations for simulation in a binary file void Write_Inf_To_Bin_File_Block(const string &dynamic_basename, const string &bin_basename, diff --git a/preprocessor/DynareBison.yy b/preprocessor/DynareBison.yy index 714079921..dbf7ae6f2 100644 --- a/preprocessor/DynareBison.yy +++ b/preprocessor/DynareBison.yy @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2015 Dynare Team + * Copyright (C) 2003-2016 Dynare Team * * This file is part of Dynare. * @@ -52,6 +52,7 @@ class ParsingDriver; SymbolType symbol_type_val; vector *vector_string_val; vector *vector_int_val; + pair *string_pair_val; PriorDistributions prior_distributions_val; }; @@ -101,7 +102,7 @@ class ParsingDriver; %token IDENTIFICATION INF_CONSTANT INITVAL INITVAL_FILE BOUNDS JSCALE INIT INFILE INVARS %token INT_NUMBER %token INV_GAMMA_PDF INV_GAMMA1_PDF INV_GAMMA2_PDF IRF IRF_SHOCKS IRF_PLOT_THRESHOLD IRF_CALIBRATION -%token KALMAN_ALGO KALMAN_TOL DIFFUSE_KALMAN_TOL SUBSAMPLES OPTIONS TOLF +%token FAST_KALMAN_FILTER KALMAN_ALGO KALMAN_TOL DIFFUSE_KALMAN_TOL SUBSAMPLES OPTIONS TOLF %token LAPLACE LIK_ALGO LIK_INIT LINEAR LOAD_IDENT_FILES LOAD_MH_FILE LOAD_PARAMS_AND_STEADY_STATE LOGLINEAR LOGDATA LYAPUNOV LINEAR_APPROXIMATION %token LYAPUNOV_FIXED_POINT_TOL LYAPUNOV_DOUBLING_TOL LYAPUNOV_SQUARE_ROOT_SOLVER_TOL LOG_DEFLATOR LOG_TREND_VAR LOG_GROWTH_FACTOR MARKOWITZ MARGINAL_DENSITY MAX MAXIT %token MFS MH_CONF_SIG MH_DROP MH_INIT_SCALE MH_JSCALE MH_MODE MH_NBLOCKS MH_REPLIC MH_RECOVER POSTERIOR_MAX_SUBSAMPLE_DRAWS MIN MINIMAL_SOLVING_PERIODS @@ -127,7 +128,7 @@ class ParsingDriver; %token UNIFORM_PDF UNIT_ROOT_VARS USE_DLL USEAUTOCORR GSA_SAMPLE_FILE USE_UNIVARIATE_FILTERS_IF_SINGULARITY_IS_DETECTED %token VALUES VAR VAREXO VAREXO_DET VAROBS PREDETERMINED_VARIABLES %token WRITE_LATEX_DYNAMIC_MODEL WRITE_LATEX_STATIC_MODEL WRITE_LATEX_ORIGINAL_MODEL -%token XLS_SHEET XLS_RANGE LONG_NAME LMMCP OCCBIN BANDPASS_FILTER +%token XLS_SHEET XLS_RANGE LMMCP OCCBIN BANDPASS_FILTER %left COMMA %left EQUAL_EQUAL EXCLAMATION_EQUAL %left LESS GREATER LESS_EQUAL GREATER_EQUAL @@ -178,8 +179,9 @@ class ParsingDriver; %type non_negative_number signed_number signed_integer date_str %type filename symbol vec_of_vec_value vec_value_list date_expr %type vec_value_1 vec_value signed_inf signed_number_w_inf -%type range vec_value_w_inf vec_value_1_w_inf named_var +%type range vec_value_w_inf vec_value_1_w_inf %type integer_range signed_integer_range +%type named_var %type change_type_arg %type change_type_var_list subsamples_eq_opt prior_eq_opt options_eq_opt calibration_range %type vec_int_elem vec_int_1 vec_int vec_int_number @@ -370,8 +372,11 @@ predetermined_variables : PREDETERMINED_VARIABLES predetermined_variables_list ' parameters : PARAMETERS parameter_list ';'; -named_var : '(' LONG_NAME EQUAL QUOTED_STRING ')' - { $$ = $4; } +named_var : '(' symbol EQUAL QUOTED_STRING ')' + { + pair *pr = new pair($2, $4); + $$ = pr; + } ; var_list : var_list symbol @@ -1698,6 +1703,7 @@ estimation_options : o_datafile | o_moments_varendo | o_contemporaneous_correlation | o_filtered_vars + | o_fast_kalman_filter | o_kalman_algo | o_kalman_tol | o_diffuse_kalman_tol @@ -2475,6 +2481,7 @@ calib_smoother_option : o_filtered_vars | o_prefilter | o_loglinear | o_first_obs + | o_filter_decomposition ; extended_path : EXTENDED_PATH ';' @@ -2746,6 +2753,7 @@ o_moments_varendo : MOMENTS_VARENDO { driver.option_num("moments_varendo", "1"); o_contemporaneous_correlation : CONTEMPORANEOUS_CORRELATION { driver.option_num("contemporaneous_correlation", "1"); }; o_filtered_vars : FILTERED_VARS { driver.option_num("filtered_vars", "1"); }; o_relative_irf : RELATIVE_IRF { driver.option_num("relative_irf", "1"); }; +o_fast_kalman_filter : FAST_KALMAN_FILTER { driver.option_num("fast_kalman_filter", "1"); }; o_kalman_algo : KALMAN_ALGO EQUAL INT_NUMBER { driver.option_num("kalman_algo", $3); }; o_kalman_tol : KALMAN_TOL EQUAL non_negative_number { driver.option_num("kalman_tol", $3); }; o_diffuse_kalman_tol : DIFFUSE_KALMAN_TOL EQUAL non_negative_number { driver.option_num("diffuse_kalman_tol", $3); }; @@ -3085,7 +3093,6 @@ o_outvars : OUTVARS EQUAL '(' symbol_list ')' { driver.option_symbol_list("outva o_lmmcp : LMMCP {driver.option_num("lmmcp", "1"); }; o_occbin : OCCBIN {driver.option_num("occbin", "1"); }; o_function : FUNCTION EQUAL filename { driver.option_str("function", $3); }; -o_prior : PRIOR { driver.option_num("prior", "1"); }; o_sampling_draws : SAMPLING_DRAWS EQUAL INT_NUMBER { driver.option_num("sampling_draws",$3); }; range : symbol ':' symbol diff --git a/preprocessor/DynareFlex.ll b/preprocessor/DynareFlex.ll index 0686500d2..dedf87dca 100644 --- a/preprocessor/DynareFlex.ll +++ b/preprocessor/DynareFlex.ll @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2015 Dynare Team + * Copyright (C) 2003-2016 Dynare Team * * This file is part of Dynare. * @@ -238,7 +238,13 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2 unput('d'); free( yycopy ); } -${DATE} { yylloc->step(); *yyout << yytext + 1; } +${DATE} { yylloc->step(); +#if (YY_FLEX_MAJOR_VERSION > 2) || (YY_FLEX_MAJOR_VERSION == 2 && YY_FLEX_MINOR_VERSION >= 6) + yyout << yytext + 1; +#else + *yyout << yytext + 1; +#endif + } dates {dates_parens_nb=0; BEGIN DATES_STATEMENT; yylval->string_val = new string("dates");} file {return token::FILE;} datafile {return token::DATAFILE;} @@ -295,6 +301,7 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2 logdata {return token::LOGDATA;} nodiagnostic {return token::NODIAGNOSTIC;} kalman_algo {return token::KALMAN_ALGO;} +fast_kalman_filter {return token::FAST_KALMAN_FILTER;} kalman_tol {return token::KALMAN_TOL;} diffuse_kalman_tol {return token::DIFFUSE_KALMAN_TOL;} forecast {return token::FORECAST;} @@ -571,7 +578,6 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2 analytic_derivation {return token::ANALYTIC_DERIVATION;} solver_periods {return token::SOLVER_PERIODS;} endogenous_prior {return token::ENDOGENOUS_PRIOR;} -long_name {return token::LONG_NAME;} consider_all_endogenous {return token::CONSIDER_ALL_ENDOGENOUS;} consider_only_observed {return token::CONSIDER_ONLY_OBSERVED;} infile {return token::INFILE;} @@ -787,7 +793,7 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2 max_dim_cova_group {return token::MAX_DIM_COVA_GROUP;} gsa_sample_file {return token::GSA_SAMPLE_FILE;} -[A-Za-z_\x80-\xf3][A-Za-z0-9_\x80-\xf3]* { +[A-Za-z_][A-Za-z0-9_]* { yylval->string_val = new string(yytext); return token::NAME; } @@ -849,7 +855,7 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2 element in initval (in which case Dynare recognizes the matrix name as an external function symbol), and may want to modify the matrix later with Matlab statements. */ -[A-Za-z_\x80-\xf3][A-Za-z0-9_\x80-\xf3]* { +[A-Za-z_][A-Za-z0-9_]* { if (driver.symbol_exists_and_is_not_modfile_local_or_external_function(yytext)) { BEGIN DYNARE_STATEMENT; @@ -867,7 +873,7 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2 /* For joint prior statement, match [symbol, symbol, ...] If no match, begin native and push everything back on stack */ -\[([[:space:]]*[A-Za-z_\x80-\xf3][A-Za-z0-9_\x80-\xf3]*[[:space:]]*,{1}[[:space:]]*)*([[:space:]]*[A-Za-z_\x80-\xf3][A-Za-z0-9_\x80-\xf3]*[[:space:]]*){1}\] { +\[([[:space:]]*[A-Za-z_][A-Za-z0-9_]*[[:space:]]*,{1}[[:space:]]*)*([[:space:]]*[A-Za-z_][A-Za-z0-9_]*[[:space:]]*){1}\] { string yytextcpy = string(yytext); yytextcpy.erase(remove(yytextcpy.begin(), yytextcpy.end(), '['), yytextcpy.end()); yytextcpy.erase(remove(yytextcpy.begin(), yytextcpy.end(), ']'), yytextcpy.end()); diff --git a/preprocessor/DynareMain.cc b/preprocessor/DynareMain.cc index 56456f815..ead3b74a8 100644 --- a/preprocessor/DynareMain.cc +++ b/preprocessor/DynareMain.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2015 Dynare Team + * Copyright (C) 2003-2016 Dynare Team * * This file is part of Dynare. * @@ -40,7 +40,8 @@ void main2(stringstream &in, string &basename, bool debug, bool clear_all, bool bool no_tmp_terms, bool no_log, bool no_warn, bool warn_uninit, bool console, bool nograph, bool nointeractive, bool parallel, ConfigFile &config_file, WarningConsolidation &warnings_arg, bool nostrict, bool check_model_changes, - bool minimal_workspace, FileOutputType output_mode, LanguageOutputType lang + bool minimal_workspace, bool compute_xrefs, FileOutputType output_mode, + LanguageOutputType lang #if defined(_WIN32) || defined(__CYGWIN32__) , bool cygwin, bool msvc #endif @@ -55,7 +56,7 @@ usage() { cerr << "Dynare usage: dynare mod_file [debug] [noclearall] [onlyclearglobals] [savemacro[=macro_file]] [onlymacro] [nolinemacro] [notmpterms] [nolog] [warn_uninit]" << " [console] [nograph] [nointeractive] [parallel[=cluster_name]] [conffile=parallel_config_path_and_filename] [parallel_slave_open_mode] [parallel_test]" - << " [-D[=]] [-I/path] [nostrict] [fast] [minimal_workspace] [output=dynamic|first|second|third] [language=C|C++|julia]" + << " [-D[=]] [-I/path] [nostrict] [fast] [minimal_workspace] [compute_xrefs] [output=dynamic|first|second|third] [language=C|C++|julia]" #if defined(_WIN32) || defined(__CYGWIN32__) << " [cygwin] [msvc]" #endif @@ -105,6 +106,7 @@ main(int argc, char **argv) bool nostrict = false; bool check_model_changes = false; bool minimal_workspace = false; + bool compute_xrefs = false; map defines; vector path; FileOutputType output_mode = none; @@ -178,6 +180,8 @@ main(int argc, char **argv) check_model_changes = true; else if (!strcmp(argv[arg], "minimal_workspace")) minimal_workspace = true; + else if (!strcmp(argv[arg], "compute_xrefs")) + compute_xrefs = true; else if (strlen(argv[arg]) >= 8 && !strncmp(argv[arg], "parallel", 8)) { parallel = true; @@ -314,7 +318,7 @@ main(int argc, char **argv) main2(macro_output, basename, debug, clear_all, clear_global, no_tmp_terms, no_log, no_warn, warn_uninit, console, nograph, nointeractive, parallel, config_file, warnings, nostrict, check_model_changes, minimal_workspace, - output_mode, language + compute_xrefs, output_mode, language #if defined(_WIN32) || defined(__CYGWIN32__) , cygwin, msvc #endif diff --git a/preprocessor/DynareMain2.cc b/preprocessor/DynareMain2.cc index 0b335b119..4bead8354 100644 --- a/preprocessor/DynareMain2.cc +++ b/preprocessor/DynareMain2.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2015 Dynare Team + * Copyright (C) 2008-2016 Dynare Team * * This file is part of Dynare. * @@ -29,7 +29,8 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear bool no_tmp_terms, bool no_log, bool no_warn, bool warn_uninit, bool console, bool nograph, bool nointeractive, bool parallel, ConfigFile &config_file, WarningConsolidation &warnings, bool nostrict, bool check_model_changes, - bool minimal_workspace, FileOutputType output_mode, LanguageOutputType language + bool minimal_workspace, bool compute_xrefs, FileOutputType output_mode, + LanguageOutputType language #if defined(_WIN32) || defined(__CYGWIN32__) , bool cygwin, bool msvc #endif @@ -50,14 +51,14 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear mod_file->evalAllExpressions(warn_uninit); // Do computations - mod_file->computingPass(no_tmp_terms, output_mode); + mod_file->computingPass(no_tmp_terms, output_mode, compute_xrefs); // Write outputs if (output_mode != none) mod_file->writeExternalFiles(basename, output_mode, language); else mod_file->writeOutputFiles(basename, clear_all, clear_global, no_log, no_warn, console, nograph, - nointeractive, config_file, check_model_changes, minimal_workspace + nointeractive, config_file, check_model_changes, minimal_workspace, compute_xrefs #if defined(_WIN32) || defined(__CYGWIN32__) , cygwin, msvc #endif diff --git a/preprocessor/ExprNode.cc b/preprocessor/ExprNode.cc index 9fd0c0ebd..057b780cc 100644 --- a/preprocessor/ExprNode.cc +++ b/preprocessor/ExprNode.cc @@ -74,7 +74,21 @@ ExprNode::precedence(ExprNodeOutputType output_type, const temporary_terms_t &te } int -ExprNode::cost(const temporary_terms_t &temporary_terms, bool is_matlab) const +ExprNode::cost(int cost, bool is_matlab) const +{ + // For a terminal node, the cost is null + return 0; +} + +int +ExprNode::cost(const temporary_terms_t &temp_terms_map, bool is_matlab) const +{ + // For a terminal node, the cost is null + return 0; +} + +int +ExprNode::cost(const map &temp_terms_map, bool is_matlab) const { // For a terminal node, the cost is null return 0; @@ -110,9 +124,9 @@ ExprNode::collectExogenous(set > &result) const } void -ExprNode::computeTemporaryTerms(map &reference_count, - temporary_terms_t &temporary_terms, - bool is_matlab) const +ExprNode::computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const { // Nothing to do for a terminal node } @@ -354,6 +368,11 @@ NumConstNode::toStatic(DataTree &static_datatree) const return static_datatree.AddNonNegativeConstant(datatree.num_constants.get(id)); } +void +NumConstNode::computeXrefs(EquationInfo &ei) const +{ +} + expr_t NumConstNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -1015,6 +1034,34 @@ VariableNode::toStatic(DataTree &static_datatree) const return static_datatree.AddVariable(symb_id); } +void +VariableNode::computeXrefs(EquationInfo &ei) const +{ + switch (type) + { + case eEndogenous: + ei.endo.insert(symb_id); + break; + case eExogenous: + ei.exo.insert(symb_id); + break; + case eExogenousDet: + ei.exo_det.insert(symb_id); + break; + case eParameter: + ei.param.insert(symb_id); + break; + case eTrend: + case eLogTrend: + case eModelLocalVariable: + case eModFileLocalVariable: + case eStatementDeclaredVariable: + case eUnusedEndogenous: + case eExternalFunction: + break; + } +} + expr_t VariableNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -1588,16 +1635,31 @@ UnaryOpNode::computeDerivative(int deriv_id) return composeDerivatives(darg, deriv_id); } +int +UnaryOpNode::cost(const map &temp_terms_map, bool is_matlab) const +{ + // For a temporary term, the cost is null + for (map::const_iterator it = temp_terms_map.begin(); + it != temp_terms_map.end(); it++) + if (it->second.find(const_cast(this)) != it->second.end()) + return 0; + + return cost(arg->cost(temp_terms_map, is_matlab), is_matlab); +} + int UnaryOpNode::cost(const temporary_terms_t &temporary_terms, bool is_matlab) const { // For a temporary term, the cost is null - temporary_terms_t::const_iterator it = temporary_terms.find(const_cast(this)); - if (it != temporary_terms.end()) + if (temporary_terms.find(const_cast(this)) != temporary_terms.end()) return 0; - int cost = arg->cost(temporary_terms, is_matlab); + return cost(arg->cost(temporary_terms, is_matlab), is_matlab); +} +int +UnaryOpNode::cost(int cost, bool is_matlab) const +{ if (is_matlab) // Cost for Matlab files switch (op_code) @@ -1685,28 +1747,27 @@ UnaryOpNode::cost(const temporary_terms_t &temporary_terms, bool is_matlab) cons case oExpectation: return cost; } - // Suppress GCC warning exit(EXIT_FAILURE); } void -UnaryOpNode::computeTemporaryTerms(map &reference_count, - temporary_terms_t &temporary_terms, - bool is_matlab) const +UnaryOpNode::computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const { expr_t this2 = const_cast(this); - map::iterator it = reference_count.find(this2); + map >::iterator it = reference_count.find(this2); if (it == reference_count.end()) { - reference_count[this2] = 1; - arg->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + reference_count[this2] = make_pair(1, tr); + arg->computeTemporaryTerms(reference_count, temp_terms_map, is_matlab, tr); } else { - reference_count[this2]++; - if (reference_count[this2] * cost(temporary_terms, is_matlab) > MIN_COST(is_matlab)) - temporary_terms.insert(this2); + reference_count[this2] = make_pair(it->second.first + 1, it->second.second); + if (reference_count[this2].first * cost(temp_terms_map, is_matlab) > MIN_COST(is_matlab)) + temp_terms_map[reference_count[this2].second].insert(this2); } } @@ -2269,6 +2330,12 @@ UnaryOpNode::toStatic(DataTree &static_datatree) const return buildSimilarUnaryOpNode(sarg, static_datatree); } +void +UnaryOpNode::computeXrefs(EquationInfo &ei) const +{ + arg->computeXrefs(ei); +} + expr_t UnaryOpNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -2691,17 +2758,35 @@ BinaryOpNode::precedence(ExprNodeOutputType output_type, const temporary_terms_t exit(EXIT_FAILURE); } +int +BinaryOpNode::cost(const map &temp_terms_map, bool is_matlab) const +{ + // For a temporary term, the cost is null + for (map::const_iterator it = temp_terms_map.begin(); + it != temp_terms_map.end(); it++) + if (it->second.find(const_cast(this)) != it->second.end()) + return 0; + + int arg_cost = arg1->cost(temp_terms_map, is_matlab) + arg2->cost(temp_terms_map, is_matlab); + + return cost(arg_cost, is_matlab); +} + int BinaryOpNode::cost(const temporary_terms_t &temporary_terms, bool is_matlab) const { - temporary_terms_t::const_iterator it = temporary_terms.find(const_cast(this)); // For a temporary term, the cost is null - if (it != temporary_terms.end()) + if (temporary_terms.find(const_cast(this)) != temporary_terms.end()) return 0; - int cost = arg1->cost(temporary_terms, is_matlab); - cost += arg2->cost(temporary_terms, is_matlab); + int arg_cost = arg1->cost(temporary_terms, is_matlab) + arg2->cost(temporary_terms, is_matlab); + return cost(arg_cost, is_matlab); +} + +int +BinaryOpNode::cost(int cost, bool is_matlab) const +{ if (is_matlab) // Cost for Matlab files switch (op_code) @@ -2724,7 +2809,7 @@ BinaryOpNode::cost(const temporary_terms_t &temporary_terms, bool is_matlab) con return cost + 990; case oPower: case oPowerDeriv: - return cost + 1160; + return cost + (MIN_COST_MATLAB/2+1); case oEqual: return cost; } @@ -2749,8 +2834,9 @@ BinaryOpNode::cost(const temporary_terms_t &temporary_terms, bool is_matlab) con case oDivide: return cost + 15; case oPower: - case oPowerDeriv: return cost + 520; + case oPowerDeriv: + return cost + (MIN_COST_C/2+1);; case oEqual: return cost; } @@ -2759,29 +2845,29 @@ BinaryOpNode::cost(const temporary_terms_t &temporary_terms, bool is_matlab) con } void -BinaryOpNode::computeTemporaryTerms(map &reference_count, - temporary_terms_t &temporary_terms, - bool is_matlab) const +BinaryOpNode::computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const { expr_t this2 = const_cast(this); - map::iterator it = reference_count.find(this2); + map >::iterator it = reference_count.find(this2); if (it == reference_count.end()) { // If this node has never been encountered, set its ref count to one, // and travel through its children - reference_count[this2] = 1; - arg1->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); - arg2->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + reference_count[this2] = make_pair(1, tr); + arg1->computeTemporaryTerms(reference_count, temp_terms_map, is_matlab, tr); + arg2->computeTemporaryTerms(reference_count, temp_terms_map, is_matlab, tr); } else { /* If the node has already been encountered, increment its ref count and declare it as a temporary term if it is too costly (except if it is an equal node: we don't want them as temporary terms) */ - reference_count[this2]++; - if (reference_count[this2] * cost(temporary_terms, is_matlab) > MIN_COST(is_matlab) + reference_count[this2] = make_pair(it->second.first + 1, it->second.second);; + if (reference_count[this2].first * cost(temp_terms_map, is_matlab) > MIN_COST(is_matlab) && op_code != oEqual) - temporary_terms.insert(this2); + temp_terms_map[reference_count[this2].second].insert(this2); } } @@ -3496,6 +3582,13 @@ BinaryOpNode::toStatic(DataTree &static_datatree) const return buildSimilarBinaryOpNode(sarg1, sarg2, static_datatree); } +void +BinaryOpNode::computeXrefs(EquationInfo &ei) const +{ + arg1->computeXrefs(ei); + arg2->computeXrefs(ei); +} + expr_t BinaryOpNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -3860,18 +3953,39 @@ TrinaryOpNode::precedence(ExprNodeOutputType output_type, const temporary_terms_ exit(EXIT_FAILURE); } +int +TrinaryOpNode::cost(const map &temp_terms_map, bool is_matlab) const +{ + // For a temporary term, the cost is null + for (map::const_iterator it = temp_terms_map.begin(); + it != temp_terms_map.end(); it++) + if (it->second.find(const_cast(this)) != it->second.end()) + return 0; + + int arg_cost = arg1->cost(temp_terms_map, is_matlab) + + arg2->cost(temp_terms_map, is_matlab) + + arg3->cost(temp_terms_map, is_matlab); + + return cost(arg_cost, is_matlab); +} + int TrinaryOpNode::cost(const temporary_terms_t &temporary_terms, bool is_matlab) const { - temporary_terms_t::const_iterator it = temporary_terms.find(const_cast(this)); // For a temporary term, the cost is null - if (it != temporary_terms.end()) + if (temporary_terms.find(const_cast(this)) != temporary_terms.end()) return 0; - int cost = arg1->cost(temporary_terms, is_matlab); - cost += arg2->cost(temporary_terms, is_matlab); - cost += arg3->cost(temporary_terms, is_matlab); + int arg_cost = arg1->cost(temporary_terms, is_matlab) + + arg2->cost(temporary_terms, is_matlab) + + arg3->cost(temporary_terms, is_matlab); + return cost(arg_cost, is_matlab); +} + +int +TrinaryOpNode::cost(int cost, bool is_matlab) const +{ if (is_matlab) // Cost for Matlab files switch (op_code) @@ -3893,28 +4007,28 @@ TrinaryOpNode::cost(const temporary_terms_t &temporary_terms, bool is_matlab) co } void -TrinaryOpNode::computeTemporaryTerms(map &reference_count, - temporary_terms_t &temporary_terms, - bool is_matlab) const +TrinaryOpNode::computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const { expr_t this2 = const_cast(this); - map::iterator it = reference_count.find(this2); + map >::iterator it = reference_count.find(this2); if (it == reference_count.end()) { // If this node has never been encountered, set its ref count to one, // and travel through its children - reference_count[this2] = 1; - arg1->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); - arg2->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); - arg3->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + reference_count[this2] = make_pair(1, tr); + arg1->computeTemporaryTerms(reference_count, temp_terms_map, is_matlab, tr); + arg2->computeTemporaryTerms(reference_count, temp_terms_map, is_matlab, tr); + arg3->computeTemporaryTerms(reference_count, temp_terms_map, is_matlab, tr); } else { // If the node has already been encountered, increment its ref count // and declare it as a temporary term if it is too costly - reference_count[this2]++; - if (reference_count[this2] * cost(temporary_terms, is_matlab) > MIN_COST(is_matlab)) - temporary_terms.insert(this2); + reference_count[this2] = make_pair(it->second.first + 1, it->second.second);; + if (reference_count[this2].first * cost(temp_terms_map, is_matlab) > MIN_COST(is_matlab)) + temp_terms_map[reference_count[this2].second].insert(this2); } } @@ -4172,6 +4286,14 @@ TrinaryOpNode::toStatic(DataTree &static_datatree) const return buildSimilarTrinaryOpNode(sarg1, sarg2, sarg3, static_datatree); } +void +TrinaryOpNode::computeXrefs(EquationInfo &ei) const +{ + arg1->computeXrefs(ei); + arg2->computeXrefs(ei); + arg3->computeXrefs(ei); +} + expr_t TrinaryOpNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -4717,11 +4839,11 @@ ExternalFunctionNode::composeDerivatives(const vector &dargs) } void -ExternalFunctionNode::computeTemporaryTerms(map &reference_count, - temporary_terms_t &temporary_terms, - bool is_matlab) const +ExternalFunctionNode::computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const { - temporary_terms.insert(const_cast(this)); + temp_terms_map[tr].insert(const_cast(this)); } void @@ -4944,6 +5066,15 @@ ExternalFunctionNode::toStatic(DataTree &static_datatree) const return static_datatree.AddExternalFunction(symb_id, static_arguments); } +void +ExternalFunctionNode::computeXrefs(EquationInfo &ei) const +{ + vector dynamic_arguments; + for (vector::const_iterator it = arguments.begin(); + it != arguments.end(); it++) + (*it)->computeXrefs(ei); +} + expr_t ExternalFunctionNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -4972,11 +5103,11 @@ FirstDerivExternalFunctionNode::FirstDerivExternalFunctionNode(DataTree &datatre } void -FirstDerivExternalFunctionNode::computeTemporaryTerms(map &reference_count, - temporary_terms_t &temporary_terms, - bool is_matlab) const +FirstDerivExternalFunctionNode::computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const { - temporary_terms.insert(const_cast(this)); + temp_terms_map[tr].insert(const_cast(this)); } void @@ -5266,6 +5397,15 @@ FirstDerivExternalFunctionNode::toStatic(DataTree &static_datatree) const inputIndex); } +void +FirstDerivExternalFunctionNode::computeXrefs(EquationInfo &ei) const +{ + vector dynamic_arguments; + for (vector::const_iterator it = arguments.begin(); + it != arguments.end(); it++) + (*it)->computeXrefs(ei); +} + SecondDerivExternalFunctionNode::SecondDerivExternalFunctionNode(DataTree &datatree_arg, int top_level_symb_id_arg, const vector &arguments_arg, @@ -5280,11 +5420,11 @@ SecondDerivExternalFunctionNode::SecondDerivExternalFunctionNode(DataTree &datat } void -SecondDerivExternalFunctionNode::computeTemporaryTerms(map &reference_count, - temporary_terms_t &temporary_terms, - bool is_matlab) const +SecondDerivExternalFunctionNode::computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const { - temporary_terms.insert(const_cast(this)); + temp_terms_map[tr].insert(const_cast(this)); } void @@ -5501,6 +5641,15 @@ SecondDerivExternalFunctionNode::toStatic(DataTree &static_datatree) const inputIndex1, inputIndex2); } +void +SecondDerivExternalFunctionNode::computeXrefs(EquationInfo &ei) const +{ + vector dynamic_arguments; + for (vector::const_iterator it = arguments.begin(); + it != arguments.end(); it++) + (*it)->computeXrefs(ei); +} + void SecondDerivExternalFunctionNode::compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, diff --git a/preprocessor/ExprNode.hh b/preprocessor/ExprNode.hh index a8f48e306..e46f567e4 100644 --- a/preprocessor/ExprNode.hh +++ b/preprocessor/ExprNode.hh @@ -37,8 +37,6 @@ class BinaryOpNode; typedef class ExprNode *expr_t; -struct Model_Block; - struct ExprNodeLess; //! Type for set of temporary terms @@ -159,7 +157,18 @@ protected: //! Cost of computing current node /*! Nodes included in temporary_terms are considered having a null cost */ + virtual int cost(int cost, bool is_matlab) const; virtual int cost(const temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual int cost(const map &temp_terms_map, bool is_matlab) const; + + //! For creating equation cross references + struct EquationInfo + { + set param; + set endo; + set exo; + set exo_det; + }; public: ExprNode(DataTree &datatree_arg); @@ -186,7 +195,9 @@ public: //! Fills temporary_terms set, using reference counts /*! A node will be marked as a temporary term if it is referenced at least two times (i.e. has at least two parents), and has a computing cost (multiplied by reference count) greater to datatree.min_cost */ - virtual void computeTemporaryTerms(map &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual void computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const; //! Writes output of node, using a Txxx notation for nodes in temporary_terms, and specifiying the set of already written external functions /*! @@ -281,6 +292,12 @@ public: adds the result in the static_datatree argument (and not in the original datatree), and returns it. */ virtual expr_t toStatic(DataTree &static_datatree) const = 0; + + /*! + Compute cross references for equations + */ + // virtual void computeXrefs(set ¶m, set &endo, set &exo, set &exo_det) const = 0; + virtual void computeXrefs(EquationInfo &ei) const = 0; //! Try to normalize an equation linear in its endogenous variable virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const = 0; @@ -460,6 +477,7 @@ public: virtual double eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException); virtual void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; + virtual void computeXrefs(EquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -502,7 +520,7 @@ public: virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void collectDynamicVariables(SymbolType type_arg, set > &result) const; - virtual void computeTemporaryTerms(map &reference_count, + virtual void computeTemporaryTerms(map &reference_count, temporary_terms_t &temporary_terms, map > &first_occurence, int Curr_block, @@ -512,6 +530,7 @@ public: virtual double eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException); virtual void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; + virtual void computeXrefs(EquationInfo &ei) const; SymbolType get_type() const { @@ -559,13 +578,17 @@ private: const int param1_symb_id, param2_symb_id; const UnaryOpcode op_code; virtual expr_t computeDerivative(int deriv_id); + virtual int cost(int cost, bool is_matlab) const; virtual int cost(const temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual int cost(const map &temp_terms_map, bool is_matlab) const; //! Returns the derivative of this node if darg is the derivative of the argument expr_t composeDerivatives(expr_t darg, int deriv_id); public: UnaryOpNode(DataTree &datatree_arg, UnaryOpcode op_code_arg, const expr_t arg_arg, int expectation_information_set_arg, int param1_symb_id_arg, int param2_symb_id_arg); virtual void prepareForDerivation(); - virtual void computeTemporaryTerms(map &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual void computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, @@ -599,6 +622,7 @@ public: return (op_code); }; virtual expr_t toStatic(DataTree &static_datatree) const; + virtual void computeXrefs(EquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -633,7 +657,9 @@ private: const expr_t arg1, arg2; const BinaryOpcode op_code; virtual expr_t computeDerivative(int deriv_id); + virtual int cost(int cost, bool is_matlab) const; virtual int cost(const temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual int cost(const map &temp_terms_map, bool is_matlab) const; //! Returns the derivative of this node if darg1 and darg2 are the derivatives of the arguments expr_t composeDerivatives(expr_t darg1, expr_t darg2); const int powerDerivOrder; @@ -644,7 +670,9 @@ public: BinaryOpcode op_code_arg, const expr_t arg2_arg, int powerDerivOrder); virtual void prepareForDerivation(); virtual int precedence(ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms) const; - virtual void computeTemporaryTerms(map &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual void computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, @@ -690,6 +718,7 @@ public: return powerDerivOrder; } virtual expr_t toStatic(DataTree &static_datatree) const; + virtual void computeXrefs(EquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -731,7 +760,9 @@ private: const expr_t arg1, arg2, arg3; const TrinaryOpcode op_code; virtual expr_t computeDerivative(int deriv_id); + virtual int cost(int cost, bool is_matlab) const; virtual int cost(const temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual int cost(const map &temp_terms_map, bool is_matlab) const; //! Returns the derivative of this node if darg1, darg2 and darg3 are the derivatives of the arguments expr_t composeDerivatives(expr_t darg1, expr_t darg2, expr_t darg3); public: @@ -739,7 +770,9 @@ public: TrinaryOpcode op_code_arg, const expr_t arg2_arg, const expr_t arg3_arg); virtual void prepareForDerivation(); virtual int precedence(ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms) const; - virtual void computeTemporaryTerms(map &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual void computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, @@ -761,6 +794,7 @@ public: virtual double eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException); virtual void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; + virtual void computeXrefs(EquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -811,7 +845,9 @@ public: AbstractExternalFunctionNode(DataTree &datatree_arg, int symb_id_arg, const vector &arguments_arg); virtual void prepareForDerivation(); - virtual void computeTemporaryTerms(map &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const = 0; + virtual void computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const = 0; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, @@ -837,6 +873,7 @@ public: virtual void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, deriv_node_temp_terms_t &tef_terms) const = 0; virtual expr_t toStatic(DataTree &static_datatree) const = 0; + virtual void computeXrefs(EquationInfo &ei) const = 0; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -871,7 +908,9 @@ private: public: ExternalFunctionNode(DataTree &datatree_arg, int symb_id_arg, const vector &arguments_arg); - virtual void computeTemporaryTerms(map &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual void computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -888,6 +927,7 @@ public: int equation) const; virtual void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; + virtual void computeXrefs(EquationInfo &ei) const; virtual expr_t buildSimilarExternalFunctionNode(vector &alt_args, DataTree &alt_datatree) const; virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const; }; @@ -902,7 +942,9 @@ public: int top_level_symb_id_arg, const vector &arguments_arg, int inputIndex_arg); - virtual void computeTemporaryTerms(map &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual void computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const; virtual void computeTemporaryTerms(map &reference_count, temporary_terms_t &temporary_terms, map > &first_occurence, @@ -922,6 +964,7 @@ public: const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; + virtual void computeXrefs(EquationInfo &ei) const; virtual expr_t buildSimilarExternalFunctionNode(vector &alt_args, DataTree &alt_datatree) const; virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const; }; @@ -938,7 +981,9 @@ public: const vector &arguments_arg, int inputIndex1_arg, int inputIndex2_arg); - virtual void computeTemporaryTerms(map &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual void computeTemporaryTerms(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const; virtual void computeTemporaryTerms(map &reference_count, temporary_terms_t &temporary_terms, map > &first_occurence, @@ -958,6 +1003,7 @@ public: const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; + virtual void computeXrefs(EquationInfo &ei) const; virtual expr_t buildSimilarExternalFunctionNode(vector &alt_args, DataTree &alt_datatree) const; virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const; }; diff --git a/preprocessor/Makefile.am b/preprocessor/Makefile.am index 9fd67c4fa..731487b09 100644 --- a/preprocessor/Makefile.am +++ b/preprocessor/Makefile.am @@ -63,7 +63,7 @@ dynare_m_LDFLAGS = $(BOOST_LDFLAGS) dynare_m_LDADD = macro/libmacro.a DynareFlex.cc FlexLexer.h: DynareFlex.ll - $(LEX) -oDynareFlex.cc DynareFlex.ll + $(LEX) -o DynareFlex.cc DynareFlex.ll cp $(LEXINC)/FlexLexer.h . DynareBison.cc DynareBison.hh location.hh stack.hh position.hh: DynareBison.yy diff --git a/preprocessor/ModFile.cc b/preprocessor/ModFile.cc index abf093e1b..00eb9c375 100644 --- a/preprocessor/ModFile.cc +++ b/preprocessor/ModFile.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006-2015 Dynare Team + * Copyright (C) 2006-2016 Dynare Team * * This file is part of Dynare. * @@ -470,7 +470,7 @@ ModFile::transformPass(bool nostrict) } void -ModFile::computingPass(bool no_tmp_terms, FileOutputType output) +ModFile::computingPass(bool no_tmp_terms, FileOutputType output, bool compute_xrefs) { // Mod file may have no equation (for example in a standalone BVAR estimation) if (dynamic_model.equation_number() > 0) @@ -503,7 +503,7 @@ ModFile::computingPass(bool no_tmp_terms, FileOutputType output) || mod_file_struct.calib_smoother_present) { if (mod_file_struct.perfect_foresight_solver_present) - dynamic_model.computingPass(true, false, false, false, global_eval_context, no_tmp_terms, block, use_dll, byte_code); + dynamic_model.computingPass(true, false, false, false, global_eval_context, no_tmp_terms, block, use_dll, byte_code, compute_xrefs); else { if (mod_file_struct.stoch_simul_present @@ -525,11 +525,11 @@ ModFile::computingPass(bool no_tmp_terms, FileOutputType output) || mod_file_struct.estimation_analytic_derivation || output == third; bool paramsDerivatives = mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation; - dynamic_model.computingPass(true, hessian, thirdDerivatives, paramsDerivatives, global_eval_context, no_tmp_terms, block, use_dll, byte_code); + dynamic_model.computingPass(true, hessian, thirdDerivatives, paramsDerivatives, global_eval_context, no_tmp_terms, block, use_dll, byte_code, compute_xrefs); } } else // No computing task requested, compute derivatives up to 2nd order by default - dynamic_model.computingPass(true, true, false, false, global_eval_context, no_tmp_terms, block, use_dll, byte_code); + dynamic_model.computingPass(true, true, false, false, global_eval_context, no_tmp_terms, block, use_dll, byte_code, compute_xrefs); } for (vector::iterator it = statements.begin(); @@ -540,7 +540,7 @@ ModFile::computingPass(bool no_tmp_terms, FileOutputType output) void ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_global, bool no_log, bool no_warn, bool console, bool nograph, bool nointeractive, const ConfigFile &config_file, - bool check_model_changes, bool minimal_workspace + bool check_model_changes, bool minimal_workspace, bool compute_xrefs #if defined(_WIN32) || defined(__CYGWIN32__) , bool cygwin, bool msvc #endif @@ -579,7 +579,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo << " clear all" << endl << "else" << endl << " clearvars -global" << endl - << " clear_persistent_variables(fileparts(which('dynare')))" << endl + << " clear_persistent_variables(fileparts(which('dynare')), false)" << endl << "end" << endl; else if (clear_global) mOutputFile << "clear M_ options_ oo_ estim_params_ bayestopt_ dataset_ dataset_info estimation_info ys0_ ex0_;" << endl; @@ -754,7 +754,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo if (dynamic_model.equation_number() > 0) { - dynamic_model.writeOutput(mOutputFile, basename, block, byte_code, use_dll, mod_file_struct.order_option, mod_file_struct.estimation_present, false); + dynamic_model.writeOutput(mOutputFile, basename, block, byte_code, use_dll, mod_file_struct.order_option, mod_file_struct.estimation_present, compute_xrefs, false); if (!no_static) static_model.writeOutput(mOutputFile, block); } @@ -798,6 +798,8 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo << " save('" << basename << "_results.mat', 'dataset_', '-append');" << endl << "end" << endl << "if exist('estimation_info', 'var') == 1" << endl << " save('" << basename << "_results.mat', 'estimation_info', '-append');" << endl << "end" << endl + << "if exist('dataset_info', 'var') == 1" << endl + << " save('" << basename << "_results.mat', 'dataset_info', '-append');" << endl << "end" << endl << "if exist('oo_recursive_', 'var') == 1" << endl << " save('" << basename << "_results.mat', 'oo_recursive_', '-append');" << endl << "end" << endl; @@ -1153,7 +1155,7 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output) { dynamic_model.writeOutput(jlOutputFile, basename, false, false, false, mod_file_struct.order_option, - mod_file_struct.estimation_present, true); + mod_file_struct.estimation_present, false, true); if (!no_static) { static_model.writeStaticFile(basename, false, false, false, true); diff --git a/preprocessor/ModFile.hh b/preprocessor/ModFile.hh index b53cca5ec..66c9fb6b9 100644 --- a/preprocessor/ModFile.hh +++ b/preprocessor/ModFile.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006-2015 Dynare Team + * Copyright (C) 2006-2016 Dynare Team * * This file is part of Dynare. * @@ -137,7 +137,8 @@ public: void transformPass(bool nostrict); //! Execute computations /*! \param no_tmp_terms if true, no temporary terms will be computed in the static and dynamic files */ - void computingPass(bool no_tmp_terms, FileOutputType output); + /*! \param compute_xrefs if true, equation cross references will be computed */ + void computingPass(bool no_tmp_terms, FileOutputType output, bool compute_xrefs); //! Writes Matlab/Octave output files /*! \param basename The base name used for writing output files. Should be the name of the mod file without its extension @@ -147,10 +148,11 @@ public: \param nointeractive Should Dynare request user input? \param cygwin Should the MEX command of use_dll be adapted for Cygwin? \param msvc Should the MEX command of use_dll be adapted for MSVC? + \param compute_xrefs if true, equation cross references will be computed */ void writeOutputFiles(const string &basename, bool clear_all, bool clear_global, bool no_log, bool no_warn, bool console, bool nograph, bool nointeractive, const ConfigFile &config_file, - bool check_model_changes, bool minimal_workspace + bool check_model_changes, bool minimal_workspace, bool compute_xrefs #if defined(_WIN32) || defined(__CYGWIN32__) , bool cygwin, bool msvc #endif diff --git a/preprocessor/ModelTree.cc b/preprocessor/ModelTree.cc index 21c2d509e..2a34ddc4f 100644 --- a/preprocessor/ModelTree.cc +++ b/preprocessor/ModelTree.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2015 Dynare Team + * Copyright (C) 2003-2016 Dynare Team * * This file is part of Dynare. * @@ -229,6 +229,103 @@ ModelTree::computeNonSingularNormalization(jacob_map_t &contemporaneous_jacobian } } +void +ModelTree::computeXrefs() +{ + int i = 0; + for (vector::iterator it = equations.begin(); + it != equations.end(); it++) + { + ExprNode::EquationInfo ei; + (*it)->computeXrefs(ei); + xrefs[i++] = ei; + } + + i = 0; + for (map::const_iterator it = xrefs.begin(); + it != xrefs.end(); it++, i++) + { + computeRevXref(xref_param, it->second.param, i); + computeRevXref(xref_endo, it->second.endo, i); + computeRevXref(xref_exo, it->second.exo, i); + computeRevXref(xref_exo_det, it->second.exo_det, i); + } +} + +void +ModelTree::computeRevXref(map > &xrefset, const set &eiref, int eqn) +{ + for (set::const_iterator it1 = eiref.begin(); + it1 != eiref.end(); it1++) + { + set eq; + if (xrefset.find(symbol_table.getTypeSpecificID(*it1)) != xrefset.end()) + eq = xrefset[symbol_table.getTypeSpecificID(*it1)]; + eq.insert(eqn); + xrefset[symbol_table.getTypeSpecificID(*it1)] = eq; + } +} + +void +ModelTree::writeXrefs(ostream &output) const +{ + output << "M_.xref1.param = cell(1, M_.eq_nbr);" << endl + << "M_.xref1.endo = cell(1, M_.eq_nbr);" << endl + << "M_.xref1.exo = cell(1, M_.eq_nbr);" << endl + << "M_.xref1.exo_det = cell(1, M_.eq_nbr);" << endl + << "M_.xref2.param = cell(1, M_.eq_nbr);" << endl + << "M_.xref2.endo = cell(1, M_.eq_nbr);" << endl + << "M_.xref2.exo = cell(1, M_.eq_nbr);" << endl + << "M_.xref2.exo_det = cell(1, M_.eq_nbr);" << endl; + int i = 1; + for (map::const_iterator it = xrefs.begin(); + it != xrefs.end(); it++, i++) + { + output << "M_.xref1.param{" << i << "} = [ "; + for (set::const_iterator it1 = it->second.param.begin(); + it1 != it->second.param.end(); it1++) + output << symbol_table.getTypeSpecificID(*it1) + 1 << " "; + output << "];" << endl; + + output << "M_.xref1.endo{" << i << "} = [ "; + for (set::const_iterator it1 = it->second.endo.begin(); + it1 != it->second.endo.end(); it1++) + output << symbol_table.getTypeSpecificID(*it1) + 1 << " "; + output << "];" << endl; + + output << "M_.xref1.exo{" << i << "} = [ "; + for (set::const_iterator it1 = it->second.exo.begin(); + it1 != it->second.exo.end(); it1++) + output << symbol_table.getTypeSpecificID(*it1) + 1 << " "; + output << "];" << endl; + + output << "M_.xref1.exo_det{" << i << "} = [ "; + for (set::const_iterator it1 = it->second.exo_det.begin(); + it1 != it->second.exo_det.end(); it1++) + output << symbol_table.getTypeSpecificID(*it1) + 1 << " "; + output << "];" << endl; + } + + writeRevXrefs(output, xref_param, "param"); + writeRevXrefs(output, xref_endo, "endo"); + writeRevXrefs(output, xref_exo, "exo"); + writeRevXrefs(output, xref_exo_det, "exo_det"); +} + +void +ModelTree::writeRevXrefs(ostream &output, const map > &xrefmap, const string &type) const +{ + for (map >::const_iterator it = xrefmap.begin(); + it != xrefmap.end(); it++) + { + output << "M_.xref2." << type << "{" << it->first + 1 << "} = [ "; + for (set::const_iterator it1 = it->second.begin(); + it1 != it->second.end(); it1++) + output << *it1 + 1 << " "; + output << "];" << endl; + } +} + void ModelTree::computeNormalizedEquations(multimap &endo2eqs) const { @@ -1092,24 +1189,50 @@ ModelTree::computeThirdDerivatives(const set &vars) void ModelTree::computeTemporaryTerms(bool is_matlab) { - map reference_count; + map > reference_count; temporary_terms.clear(); + temporary_terms_res.clear(); + temporary_terms_g1.clear(); + temporary_terms_g2.clear(); + temporary_terms_g3.clear(); + map temp_terms_map; + temp_terms_map[eResiduals]=temporary_terms_res; + temp_terms_map[eFirstDeriv]=temporary_terms_g1; + temp_terms_map[eSecondDeriv]=temporary_terms_g2; + temp_terms_map[eThirdDeriv]=temporary_terms_g3; for (vector::iterator it = equations.begin(); it != equations.end(); it++) - (*it)->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + (*it)->computeTemporaryTerms(reference_count, + temp_terms_map, + is_matlab, eResiduals); for (first_derivatives_t::iterator it = first_derivatives.begin(); it != first_derivatives.end(); it++) - it->second->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + it->second->computeTemporaryTerms(reference_count, + temp_terms_map, + is_matlab, eFirstDeriv); for (second_derivatives_t::iterator it = second_derivatives.begin(); it != second_derivatives.end(); it++) - it->second->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + it->second->computeTemporaryTerms(reference_count, + temp_terms_map, + is_matlab, eSecondDeriv); for (third_derivatives_t::iterator it = third_derivatives.begin(); it != third_derivatives.end(); it++) - it->second->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + it->second->computeTemporaryTerms(reference_count, + temp_terms_map, + is_matlab, eThirdDeriv); + + for (map::const_iterator it = temp_terms_map.begin(); + it != temp_terms_map.end(); it++) + temporary_terms.insert(it->second.begin(), it->second.end()); + + temporary_terms_res = temp_terms_map[eResiduals]; + temporary_terms_g1 = temp_terms_map[eFirstDeriv]; + temporary_terms_g2 = temp_terms_map[eSecondDeriv]; + temporary_terms_g3 = temp_terms_map[eThirdDeriv]; } void @@ -1118,7 +1241,6 @@ ModelTree::writeTemporaryTerms(const temporary_terms_t &tt, ostream &output, { // Local var used to keep track of temp nodes already written temporary_terms_t tt2; - for (temporary_terms_t::const_iterator it = tt.begin(); it != tt.end(); it++) { @@ -1213,6 +1335,12 @@ ModelTree::writeModelLocalVariables(ostream &output, ExprNodeOutputType output_t void ModelTree::writeModelEquations(ostream &output, ExprNodeOutputType output_type) const { + temporary_terms_t temp_terms; + if (IS_JULIA(output_type)) + temp_terms = temporary_terms_res; + else + temp_terms = temporary_terms; + for (int eq = 0; eq < (int) equations.size(); eq++) { BinaryOpNode *eq_node = equations[eq]; @@ -1234,13 +1362,13 @@ ModelTree::writeModelEquations(ostream &output, ExprNodeOutputType output_type) if (IS_JULIA(output_type)) output << " @inbounds "; output << "lhs ="; - lhs->writeOutput(output, output_type, temporary_terms); + lhs->writeOutput(output, output_type, temp_terms); output << ";" << endl; if (IS_JULIA(output_type)) output << " @inbounds "; output << "rhs ="; - rhs->writeOutput(output, output_type, temporary_terms); + rhs->writeOutput(output, output_type, temp_terms); output << ";" << endl; if (IS_JULIA(output_type)) @@ -1258,7 +1386,7 @@ ModelTree::writeModelEquations(ostream &output, ExprNodeOutputType output_type) << eq + ARRAY_SUBSCRIPT_OFFSET(output_type) << RIGHT_ARRAY_SUBSCRIPT(output_type) << " = "; - lhs->writeOutput(output, output_type, temporary_terms); + lhs->writeOutput(output, output_type, temp_terms); output << ";" << endl; } } @@ -1580,28 +1708,54 @@ ModelTree::computeParamsDerivatives() void ModelTree::computeParamsDerivativesTemporaryTerms() { - map reference_count; + map > reference_count; params_derivs_temporary_terms.clear(); + map temp_terms_map; + temp_terms_map[eResidualsParamsDeriv]=params_derivs_temporary_terms_res; + temp_terms_map[eJacobianParamsDeriv]=params_derivs_temporary_terms_g1; + temp_terms_map[eResidualsParamsSecondDeriv]=params_derivs_temporary_terms_res2; + temp_terms_map[eJacobianParamsSecondDeriv]=params_derivs_temporary_terms_g12; + temp_terms_map[eHessianParamsDeriv]=params_derivs_temporary_terms_g2; for (first_derivatives_t::iterator it = residuals_params_derivatives.begin(); it != residuals_params_derivatives.end(); it++) - it->second->computeTemporaryTerms(reference_count, params_derivs_temporary_terms, true); + it->second->computeTemporaryTerms(reference_count, + temp_terms_map, + true, eResidualsParamsDeriv); for (second_derivatives_t::iterator it = jacobian_params_derivatives.begin(); it != jacobian_params_derivatives.end(); it++) - it->second->computeTemporaryTerms(reference_count, params_derivs_temporary_terms, true); + it->second->computeTemporaryTerms(reference_count, + temp_terms_map, + true, eJacobianParamsDeriv); for (second_derivatives_t::const_iterator it = residuals_params_second_derivatives.begin(); it != residuals_params_second_derivatives.end(); ++it) - it->second->computeTemporaryTerms(reference_count, params_derivs_temporary_terms, true); + it->second->computeTemporaryTerms(reference_count, + temp_terms_map, + true, eResidualsParamsSecondDeriv); for (third_derivatives_t::const_iterator it = jacobian_params_second_derivatives.begin(); it != jacobian_params_second_derivatives.end(); ++it) - it->second->computeTemporaryTerms(reference_count, params_derivs_temporary_terms, true); + it->second->computeTemporaryTerms(reference_count, + temp_terms_map, + true, eJacobianParamsSecondDeriv); for (third_derivatives_t::const_iterator it = hessian_params_derivatives.begin(); it != hessian_params_derivatives.end(); ++it) - it->second->computeTemporaryTerms(reference_count, params_derivs_temporary_terms, true); + it->second->computeTemporaryTerms(reference_count, + temp_terms_map, + true, eHessianParamsDeriv); + + for (map::const_iterator it = temp_terms_map.begin(); + it != temp_terms_map.end(); it++) + params_derivs_temporary_terms.insert(it->second.begin(), it->second.end()); + + params_derivs_temporary_terms_res = temp_terms_map[eResidualsParamsDeriv]; + params_derivs_temporary_terms_g1 = temp_terms_map[eJacobianParamsDeriv]; + params_derivs_temporary_terms_res2 = temp_terms_map[eResidualsParamsSecondDeriv]; + params_derivs_temporary_terms_g12 = temp_terms_map[eJacobianParamsSecondDeriv]; + params_derivs_temporary_terms_g2 = temp_terms_map[eHessianParamsDeriv]; } bool ModelTree::isNonstationary(int symb_id) const diff --git a/preprocessor/ModelTree.hh b/preprocessor/ModelTree.hh index ea799585c..259c3962a 100644 --- a/preprocessor/ModelTree.hh +++ b/preprocessor/ModelTree.hh @@ -99,6 +99,13 @@ protected: */ first_derivatives_t residuals_params_derivatives; + //! Cross reference information + map xrefs; + map > xref_param; + map > xref_endo; + map > xref_exo; + map > xref_exo_det; + //! Second derivatives of the residuals w.r. to parameters /*! First index is equation number, second and third indeces are parameters. Only non-null derivatives are stored in the map. @@ -130,9 +137,18 @@ protected: //! Temporary terms for the static/dynamic file (those which will be noted Txxxx) temporary_terms_t temporary_terms; + temporary_terms_t temporary_terms_res; + temporary_terms_t temporary_terms_g1; + temporary_terms_t temporary_terms_g2; + temporary_terms_t temporary_terms_g3; //! Temporary terms for the file containing parameters derivatives temporary_terms_t params_derivs_temporary_terms; + temporary_terms_t params_derivs_temporary_terms_res; + temporary_terms_t params_derivs_temporary_terms_g1; + temporary_terms_t params_derivs_temporary_terms_res2; + temporary_terms_t params_derivs_temporary_terms_g12; + temporary_terms_t params_derivs_temporary_terms_g2; //! Trend variables and their growth factors @@ -220,6 +236,14 @@ protected: //! Try to normalized each unnormalized equation (matched endogenous variable only on the LHS) void computeNormalizedEquations(multimap &endo2eqs) const; + //! Compute cross references + void computeXrefs(); + //! Help computeXrefs to compute the reverse references (i.e. param->eqs, endo->eqs, etc) + void computeRevXref(map > &xrefset, const set &eiref, int eqn); + //! Write cross references + void writeXrefs(ostream &output) const; + //! Write reverse cross references + void writeRevXrefs(ostream &output, const map > &xrefmap, const string &type) const; //! Evaluate the jacobian and suppress all the elements below the cutoff void evaluateAndReduceJacobian(const eval_context_t &eval_context, jacob_map_t &contemporaneous_jacobian, jacob_map_t &static_jacobian, dynamic_jacob_map_t &dynamic_jacobian, double cutoff, bool verbose); //! Search the equations and variables belonging to the prologue and the epilogue of the model @@ -319,7 +343,6 @@ public: /*! If order=2, writes either v2(i+1,j+1) or v2[i+j*NNZDerivatives[1]] If order=3, writes either v3(i+1,j+1) or v3[i+j*NNZDerivatives[2]] */ void sparseHelper(int order, ostream &output, int row_nb, int col_nb, ExprNodeOutputType output_type) const; - inline static std::string c_Equation_Type(int type) { diff --git a/preprocessor/ParsingDriver.cc b/preprocessor/ParsingDriver.cc index ab9ff2004..15194cb18 100644 --- a/preprocessor/ParsingDriver.cc +++ b/preprocessor/ParsingDriver.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2015 Dynare Team + * Copyright (C) 2003-2016 Dynare Team * * This file is part of Dynare. * @@ -131,19 +131,19 @@ ParsingDriver::warning(const string &m) } void -ParsingDriver::declare_symbol(const string *name, SymbolType type, const string *tex_name, const string *long_name) +ParsingDriver::declare_symbol(const string *name, SymbolType type, const string *tex_name, const pair *partition_value) { try { - if (tex_name == NULL && long_name == NULL) + if (tex_name == NULL && partition_value == NULL) mod_file->symbol_table.addSymbol(*name, type); else if (tex_name == NULL) - mod_file->symbol_table.addSymbol(*name, type, "", *long_name); - else if (long_name == NULL) - mod_file->symbol_table.addSymbol(*name, type, *tex_name, ""); + mod_file->symbol_table.addSymbol(*name, type, "", partition_value); + else if (partition_value == NULL) + mod_file->symbol_table.addSymbol(*name, type, *tex_name, NULL); else - mod_file->symbol_table.addSymbol(*name, type, *tex_name, *long_name); + mod_file->symbol_table.addSymbol(*name, type, *tex_name, partition_value); } catch (SymbolTable::AlreadyDeclaredException &e) { @@ -155,47 +155,63 @@ ParsingDriver::declare_symbol(const string *name, SymbolType type, const string } void -ParsingDriver::declare_endogenous(string *name, string *tex_name, string *long_name) +ParsingDriver::declare_endogenous(string *name, string *tex_name, pair *partition_value) { - declare_symbol(name, eEndogenous, tex_name, long_name); + declare_symbol(name, eEndogenous, tex_name, partition_value); delete name; if (tex_name != NULL) delete tex_name; - if (long_name != NULL) - delete long_name; + if (partition_value != NULL) + { + delete partition_value->first; + delete partition_value->second; + delete partition_value; + } } void -ParsingDriver::declare_exogenous(string *name, string *tex_name, string *long_name) +ParsingDriver::declare_exogenous(string *name, string *tex_name, pair *partition_value) { - declare_symbol(name, eExogenous, tex_name, long_name); + declare_symbol(name, eExogenous, tex_name, partition_value); delete name; if (tex_name != NULL) delete tex_name; - if (long_name != NULL) - delete long_name; + if (partition_value != NULL) + { + delete partition_value->first; + delete partition_value->second; + delete partition_value; + } } void -ParsingDriver::declare_exogenous_det(string *name, string *tex_name, string *long_name) +ParsingDriver::declare_exogenous_det(string *name, string *tex_name, pair *partition_value) { - declare_symbol(name, eExogenousDet, tex_name, long_name); + declare_symbol(name, eExogenousDet, tex_name, partition_value); delete name; if (tex_name != NULL) delete tex_name; - if (long_name != NULL) - delete long_name; + if (partition_value != NULL) + { + delete partition_value->first; + delete partition_value->second; + delete partition_value; + } } void -ParsingDriver::declare_parameter(string *name, string *tex_name, string *long_name) +ParsingDriver::declare_parameter(string *name, string *tex_name, pair *partition_value) { - declare_symbol(name, eParameter, tex_name, long_name); + declare_symbol(name, eParameter, tex_name, partition_value); delete name; if (tex_name != NULL) delete tex_name; - if (long_name != NULL) - delete long_name; + if (partition_value != NULL) + { + delete partition_value->first; + delete partition_value->second; + delete partition_value; + } } void @@ -213,8 +229,6 @@ ParsingDriver::declare_optimal_policy_discount_factor_parameter(expr_t exprnode) { string *optimalParName_declare = new string("optimal_policy_discount_factor"); string *optimalParName_init = new string("optimal_policy_discount_factor"); - if (mod_file->symbol_table.exists(*optimalParName_declare)) - error("Symbol optimal_policy_discount_factor is needed by Dynare when using a ramsey_model, a ramsey_policy or a discretionary_policy statement"); declare_parameter(optimalParName_declare, NULL); init_param(optimalParName_init, exprnode); } @@ -356,25 +370,29 @@ ParsingDriver::add_expression_variable(string *name) } void -ParsingDriver::declare_nonstationary_var(string *name, string *tex_name, string *long_name) +ParsingDriver::declare_nonstationary_var(string *name, string *tex_name, pair *partition_value) { - if (tex_name == NULL && long_name == NULL) + if (tex_name == NULL && partition_value == NULL) declare_endogenous(new string(*name)); else if (tex_name == NULL) - declare_endogenous(new string(*name), NULL, new string(*long_name)); - else if (long_name == NULL) + declare_endogenous(new string(*name), NULL, new pair(*partition_value)); + else if (partition_value == NULL) declare_endogenous(new string(*name), new string(*tex_name)); else - declare_endogenous(new string(*name), new string(*tex_name), new string(*long_name)); + declare_endogenous(new string(*name), new string(*tex_name), new pair(*partition_value)); declared_nonstationary_vars.push_back(mod_file->symbol_table.getID(*name)); mod_file->nonstationary_variables = true; delete name; if (tex_name != NULL) delete tex_name; - if (long_name != NULL) - delete long_name; + if (partition_value != NULL) + { + delete partition_value->first; + delete partition_value->second; + delete partition_value; + } } void diff --git a/preprocessor/ParsingDriver.hh b/preprocessor/ParsingDriver.hh index 4da740fea..0885f5a69 100644 --- a/preprocessor/ParsingDriver.hh +++ b/preprocessor/ParsingDriver.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2015 Dynare Team + * Copyright (C) 2003-2016 Dynare Team * * This file is part of Dynare. * @@ -94,7 +94,7 @@ private: void check_symbol_is_endogenous_or_exogenous(string *name); //! Helper to add a symbol declaration - void declare_symbol(const string *name, SymbolType type, const string *tex_name, const string *long_name); + void declare_symbol(const string *name, SymbolType type, const string *tex_name, const pair *partition_value); //! Creates option "optim_opt" in OptionsList if it doesn't exist, else add a comma, and adds the option name void optim_options_helper(const string &name); @@ -268,13 +268,13 @@ public: //! Sets the FILENAME for the initial value in initval void initval_file(string *filename); //! Declares an endogenous variable - void declare_endogenous(string *name, string *tex_name = NULL, string *long_name = NULL); + void declare_endogenous(string *name, string *tex_name = NULL, pair *partition_value = NULL); //! Declares an exogenous variable - void declare_exogenous(string *name, string *tex_name = NULL, string *long_name = NULL); + void declare_exogenous(string *name, string *tex_name = NULL, pair *partition_value = NULL); //! Declares an exogenous deterministic variable - void declare_exogenous_det(string *name, string *tex_name = NULL, string *long_name = NULL); + void declare_exogenous_det(string *name, string *tex_name = NULL, pair *partition_value = NULL); //! Declares a parameter - void declare_parameter(string *name, string *tex_name = NULL, string *long_name = NULL); + void declare_parameter(string *name, string *tex_name = NULL, pair *partition_value = NULL); //! Declares a statement local variable void declare_statement_local_variable(string *name); //! Completes a subsample statement @@ -679,7 +679,7 @@ public: //! Ends declaration of trend variable void end_trend_var(expr_t growth_factor); //! Declares a nonstationary variable with its deflator - void declare_nonstationary_var(string *name, string *tex_name = NULL, string *long_name = NULL); + void declare_nonstationary_var(string *name, string *tex_name = NULL, pair *partition_value = NULL); //! Ends declaration of nonstationary variable void end_nonstationary_var(bool log_deflator, expr_t deflator); //! Add a graph format to the list of formats requested diff --git a/preprocessor/StaticModel.cc b/preprocessor/StaticModel.cc index 4fea0335e..92aa43f64 100644 --- a/preprocessor/StaticModel.cc +++ b/preprocessor/StaticModel.cc @@ -1183,27 +1183,35 @@ StaticModel::writeStaticMFile(const string &func_name) const void StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) const { - ostringstream model_output; // Used for storing model - ostringstream model_eq_output; // Used for storing model equations - ostringstream jacobian_output; // Used for storing jacobian equations - ostringstream hessian_output; // Used for storing Hessian equations + ostringstream model_local_vars_output; // Used for storing model local vars + ostringstream model_output; // Used for storing model + ostringstream jacobian_output; // Used for storing jacobian equations + ostringstream hessian_output; // Used for storing Hessian equations ostringstream third_derivatives_output; // Used for storing third order derivatives equations ostringstream for_sym; ExprNodeOutputType output_type = (use_dll ? oCStaticModel : julia ? oJuliaStaticModel : oMatlabStaticModel); deriv_node_temp_terms_t tef_terms; - writeModelLocalVariables(model_output, output_type, tef_terms); + temporary_terms_t temp_term_union = temporary_terms_res; - writeTemporaryTerms(temporary_terms, model_output, output_type, tef_terms); + writeModelLocalVariables(model_local_vars_output, output_type, tef_terms); - writeModelEquations(model_eq_output, output_type); + writeTemporaryTerms(temporary_terms_res, model_output, output_type, tef_terms); + + writeModelEquations(model_output, output_type); int nrows = equations.size(); int JacobianColsNbr = symbol_table.endo_nbr(); int hessianColsNbr = JacobianColsNbr*JacobianColsNbr; // Write Jacobian w.r. to endogenous only + temp_term_union.insert(temporary_terms_g1.begin(), temporary_terms_g1.end()); + if (!first_derivatives.empty()) + if (julia) + writeTemporaryTerms(temp_term_union, jacobian_output, output_type, tef_terms); + else + writeTemporaryTerms(temporary_terms_g1, jacobian_output, output_type, tef_terms); for (first_derivatives_t::const_iterator it = first_derivatives.begin(); it != first_derivatives.end(); it++) { @@ -1213,12 +1221,18 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c jacobianHelper(jacobian_output, eq, symbol_table.getTypeSpecificID(symb_id), output_type); jacobian_output << "="; - d1->writeOutput(jacobian_output, output_type, temporary_terms, tef_terms); + d1->writeOutput(jacobian_output, output_type, temp_term_union, tef_terms); jacobian_output << ";" << endl; } int g2ncols = symbol_table.endo_nbr() * symbol_table.endo_nbr(); // Write Hessian w.r. to endogenous only (only if 2nd order derivatives have been computed) + temp_term_union.insert(temporary_terms_g2.begin(), temporary_terms_g2.end()); + if (!second_derivatives.empty()) + if (julia) + writeTemporaryTerms(temp_term_union, hessian_output, output_type, tef_terms); + else + writeTemporaryTerms(temporary_terms_g2, hessian_output, output_type, tef_terms); int k = 0; // Keep the line of a 2nd derivative in v2 for (second_derivatives_t::const_iterator it = second_derivatives.begin(); it != second_derivatives.end(); it++) @@ -1238,7 +1252,7 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c { for_sym << "g2[" << eq + 1 << "," << col_nb + 1 << "]"; hessian_output << " @inbounds " << for_sym.str() << " = "; - d2->writeOutput(hessian_output, output_type, temporary_terms, tef_terms); + d2->writeOutput(hessian_output, output_type, temp_term_union, tef_terms); hessian_output << endl; } else @@ -1251,7 +1265,7 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c sparseHelper(2, hessian_output, k, 2, output_type); hessian_output << "="; - d2->writeOutput(hessian_output, output_type, temporary_terms, tef_terms); + d2->writeOutput(hessian_output, output_type, temp_term_union, tef_terms); hessian_output << ";" << endl; k++; @@ -1280,6 +1294,12 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c } // Writing third derivatives + temp_term_union.insert(temporary_terms_g3.begin(), temporary_terms_g3.end()); + if (!third_derivatives.empty()) + if (julia) + writeTemporaryTerms(temp_term_union, third_derivatives_output, output_type, tef_terms); + else + writeTemporaryTerms(temporary_terms_g3, third_derivatives_output, output_type, tef_terms); k = 0; // Keep the line of a 3rd derivative in v3 for (third_derivatives_t::const_iterator it = third_derivatives.begin(); it != third_derivatives.end(); it++) @@ -1302,7 +1322,7 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c { for_sym << "g3[" << eq + 1 << "," << ref_col + 1 << "]"; third_derivatives_output << " @inbounds " << for_sym.str() << " = "; - d3->writeOutput(third_derivatives_output, output_type, temporary_terms, tef_terms); + d3->writeOutput(third_derivatives_output, output_type, temp_term_union, tef_terms); third_derivatives_output << endl; } else @@ -1315,7 +1335,7 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c sparseHelper(3, third_derivatives_output, k, 2, output_type); third_derivatives_output << "="; - d3->writeOutput(third_derivatives_output, output_type, temporary_terms, tef_terms); + d3->writeOutput(third_derivatives_output, output_type, temp_term_union, tef_terms); third_derivatives_output << ";" << endl; } @@ -1358,8 +1378,8 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c << "%" << endl << "% Model equations" << endl << "%" << endl << endl + << model_local_vars_output.str() << model_output.str() - << model_eq_output.str() << "if ~isreal(residual)" << endl << " residual = real(residual)+imag(residual).^2;" << endl << "end" << endl @@ -1372,7 +1392,6 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c << " if ~isreal(g1)" << endl << " g1 = real(g1)+2*imag(g1);" << endl << " end" << endl - << "end" << endl << "if nargout >= 3," << endl << " %" << endl << " % Hessian matrix" << endl @@ -1385,7 +1404,7 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c << " g2 = sparse(v2(:,1),v2(:,2),v2(:,3)," << equations.size() << "," << g2ncols << ");" << endl; else StaticOutput << " g2 = sparse([],[],[]," << equations.size() << "," << g2ncols << ");" << endl; - StaticOutput << "end" << endl; + // Initialize g3 matrix StaticOutput << "if nargout >= 4," << endl << " %" << endl @@ -1399,6 +1418,9 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c << " g3 = sparse(v3(:,1),v3(:,2),v3(:,3)," << nrows << "," << ncols << ");" << endl; else // Either 3rd derivatives is all zero, or we didn't compute it StaticOutput << " g3 = sparse([],[],[]," << nrows << "," << ncols << ");" << endl; + StaticOutput << "end" << endl + << "end" << endl + << "end" << endl; } else if (output_type == oCStaticModel) { @@ -1407,32 +1429,29 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c << " double lhs, rhs;" << endl << endl << " /* Residual equations */" << endl + << model_local_vars_output.str() << model_output.str() - << model_eq_output.str() << " /* Jacobian */" << endl << " if (g1 == NULL)" << endl << " return;" << endl - << " else" << endl - << " {" << endl + << endl << jacobian_output.str() - << " }" << endl; + << endl; if (second_derivatives.size()) StaticOutput << " /* Hessian for endogenous and exogenous variables */" << endl << " if (v2 == NULL)" << endl << " return;" << endl - << " else" << endl - << " {" << endl + << endl << hessian_output.str() - << " }" << endl; + << endl; if (third_derivatives.size()) StaticOutput << " /* Third derivatives for endogenous and exogenous variables */" << endl - << " if (v3 == NULL)" << endl - << " return;" << endl - << " else" << endl - << " {" << endl - << third_derivatives_output.str() - << " }" << endl; + << " if (v3 == NULL)" << endl + << " return;" << endl + << endl + << third_derivatives_output.str() + << endl; } else { @@ -1460,8 +1479,8 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c << " #" << endl << " # Model equations" << endl << " #" << endl + << model_local_vars_output.str() << model_output.str() - << model_eq_output.str() << "if ~isreal(residual)" << endl << " residual = real(residual)+imag(residual).^2;" << endl << "end" << endl @@ -1479,7 +1498,7 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c << ")" << endl << " fill!(g1, 0.0)" << endl << " static!(y, x, params, residual)" << endl - << model_output.str() + << model_local_vars_output.str() << " #" << endl << " # Jacobian matrix" << endl << " #" << endl @@ -1501,7 +1520,7 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c << " @assert size(g2) == (" << equations.size() << ", " << g2ncols << ")" << endl << " static!(y, x, params, residual, g1)" << endl; if (second_derivatives.size()) - StaticOutput << model_output.str() + StaticOutput << model_local_vars_output.str() << " #" << endl << " # Hessian matrix" << endl << " #" << endl @@ -1524,7 +1543,7 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c << " @assert size(g3) == (" << nrows << ", " << ncols << ")" << endl << " static!(y, x, params, residual, g1, g2)" << endl; if (third_derivatives.size()) - StaticOutput << model_output.str() + StaticOutput << model_local_vars_output.str() << " #" << endl << " # Third order derivatives" << endl << " #" << endl diff --git a/preprocessor/SteadyStateModel.cc b/preprocessor/SteadyStateModel.cc index c94590cf1..4533c41f2 100644 --- a/preprocessor/SteadyStateModel.cc +++ b/preprocessor/SteadyStateModel.cc @@ -22,8 +22,8 @@ #include "SteadyStateModel.hh" -SteadyStateModel::SteadyStateModel(SymbolTable &symbol_table_arg, NumericalConstants &num_constants, ExternalFunctionsTable &external_functions_table_arg, const StaticModel &static_model_arg) : - DataTree(symbol_table_arg, num_constants, external_functions_table), static_model(static_model_arg) +SteadyStateModel::SteadyStateModel(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg, ExternalFunctionsTable &external_functions_table_arg, const StaticModel &static_model_arg) : + DataTree(symbol_table_arg, num_constants_arg, external_functions_table_arg), static_model(static_model_arg) { } diff --git a/preprocessor/SteadyStateModel.hh b/preprocessor/SteadyStateModel.hh index f79b358f5..a7e0a5424 100644 --- a/preprocessor/SteadyStateModel.hh +++ b/preprocessor/SteadyStateModel.hh @@ -34,7 +34,7 @@ private: const StaticModel &static_model; public: - SteadyStateModel(SymbolTable &symbol_table_arg, NumericalConstants &num_constants, ExternalFunctionsTable &external_functions_table_arg, const StaticModel &static_model_arg); + SteadyStateModel(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg, ExternalFunctionsTable &external_functions_table_arg, const StaticModel &static_model_arg); //! Add an expression of the form "var = expr;" void addDefinition(int symb_id, expr_t expr); //! Add an expression of the form "[ var1, var2, ... ] = expr;" diff --git a/preprocessor/SymbolTable.cc b/preprocessor/SymbolTable.cc index 5599482eb..73433ae9e 100644 --- a/preprocessor/SymbolTable.cc +++ b/preprocessor/SymbolTable.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2015 Dynare Team + * Copyright (C) 2003-2016 Dynare Team * * This file is part of Dynare. * @@ -42,7 +42,7 @@ SymbolTable::SymbolTable() : frozen(false), size(0) } int -SymbolTable::addSymbol(const string &name, SymbolType type, const string &tex_name, const string &long_name) throw (AlreadyDeclaredException, FrozenException) +SymbolTable::addSymbol(const string &name, SymbolType type, const string &tex_name, const pair *partition_value) throw (AlreadyDeclaredException, FrozenException) { if (frozen) throw FrozenException(); @@ -67,9 +67,11 @@ SymbolTable::addSymbol(const string &name, SymbolType type, const string &tex_na } } - string final_long_name = long_name; - if (final_long_name.empty()) - final_long_name = name; + string final_long_name; + if (partition_value == NULL || *(partition_value->first) != "long_name") + final_long_name = name; + else + final_long_name = *(partition_value->second); int id = size++; @@ -78,14 +80,16 @@ SymbolTable::addSymbol(const string &name, SymbolType type, const string &tex_na name_table.push_back(name); tex_name_table.push_back(final_tex_name); long_name_table.push_back(final_long_name); - + if (partition_value && *(partition_value->first) != "long_name") + partition_value_map[id] = pair(new string(partition_value->first->c_str()), + new string(partition_value->second->c_str())); return id; } int SymbolTable::addSymbol(const string &name, SymbolType type) throw (AlreadyDeclaredException, FrozenException) { - return addSymbol(name, type, "", ""); + return addSymbol(name, type, "", NULL); } void @@ -170,6 +174,23 @@ SymbolTable::getID(SymbolType type, int tsid) const throw (UnknownTypeSpecificID } } +bool +SymbolTable::isFirstOfPartitionForType(int id) const throw (UnknownSymbolIDException) +{ + if (id < 0 || id >= size || !hasPartition(id)) + throw UnknownSymbolIDException(id); + + string partition_name = getPartition(id); + SymbolType st = getType(id); + for (map >::const_iterator it = partition_value_map.begin(); + it != partition_value_map.end(); it++) + if (st == getType(it->first) && + it->first < id && + partition_name == *(it->second.first)) + return false; + return true; +} + void SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException) { @@ -181,42 +202,83 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException) output << "M_.exo_names = '" << getName(exo_ids[0]) << "';" << endl; output << "M_.exo_names_tex = '" << getTeXName(exo_ids[0]) << "';" << endl; output << "M_.exo_names_long = '" << getLongName(exo_ids[0]) << "';" << endl; + if (hasPartition(exo_ids[0])) + output << "M_.exo_" << getPartition(exo_ids[0]) << " = '" + << getPartitionValue(exo_ids[0]) << "';" << endl; for (int id = 1; id < exo_nbr(); id++) { output << "M_.exo_names = char(M_.exo_names, '" << getName(exo_ids[id]) << "');" << endl << "M_.exo_names_tex = char(M_.exo_names_tex, '" << getTeXName(exo_ids[id]) << "');" << endl << "M_.exo_names_long = char(M_.exo_names_long, '" << getLongName(exo_ids[id]) << "');" << endl; + if (hasPartition(exo_ids[id])) + if (isFirstOfPartitionForType(exo_ids[id])) + output << "M_.exo_" << getPartition(exo_ids[id]) << " = '" + << getPartitionValue(exo_ids[id]) << "';" << endl; + else + output << "M_.exo_" << getPartition(exo_ids[id]) << " = " + << "char(M_.exo_" << getPartition(exo_ids[id]) << ", '" + << getPartitionValue(exo_ids[id]) << "');" << endl; } } + if (exo_det_nbr() > 0) { output << "M_.exo_det_names = '" << getName(exo_det_ids[0]) << "';" << endl; output << "M_.exo_det_names_tex = '" << getTeXName(exo_det_ids[0]) << "';" << endl; output << "M_.exo_det_names_long = '" << getLongName(exo_det_ids[0]) << "';" << endl; + if (hasPartition(exo_det_ids[0])) + output << "M_.exo_det_" << getPartition(exo_det_ids[0]) << " = '" + << getPartitionValue(exo_det_ids[0]) << "';" << endl; for (int id = 1; id < exo_det_nbr(); id++) { output << "M_.exo_det_names = char(M_.exo_det_names, '" << getName(exo_det_ids[id]) << "');" << endl << "M_.exo_det_names_tex = char(M_.exo_det_names_tex, '" << getTeXName(exo_det_ids[id]) << "');" << endl << "M_.exo_det_names_long = char(M_.exo_det_names_long, '" << getLongName(exo_det_ids[id]) << "');" << endl; + if (hasPartition(exo_det_ids[id])) + if (isFirstOfPartitionForType(exo_det_ids[id])) + output << "M_.exo_det_" << getPartition(exo_det_ids[id]) << " = '" + << getPartitionValue(exo_det_ids[id]) << "';" << endl; + else + output << "M_.exo_det_" << getPartition(exo_det_ids[id]) << " = " + << "char(M_.exo_det_" << getPartition(exo_det_ids[id]) << ", '" + << getPartitionValue(exo_det_ids[id]) << "');" << endl; } } + if (endo_nbr() > 0) { output << "M_.endo_names = '" << getName(endo_ids[0]) << "';" << endl; output << "M_.endo_names_tex = '" << getTeXName(endo_ids[0]) << "';" << endl; output << "M_.endo_names_long = '" << getLongName(endo_ids[0]) << "';" << endl; + if (hasPartition(endo_ids[0])) + output << "M_.endo_" << getPartition(endo_ids[0]) << " = '" + << getPartitionValue(endo_ids[0]) << "';" << endl; + for (int id = 1; id < endo_nbr(); id++) { output << "M_.endo_names = char(M_.endo_names, '" << getName(endo_ids[id]) << "');" << endl << "M_.endo_names_tex = char(M_.endo_names_tex, '" << getTeXName(endo_ids[id]) << "');" << endl << "M_.endo_names_long = char(M_.endo_names_long, '" << getLongName(endo_ids[id]) << "');" << endl; + if (hasPartition(endo_ids[id])) + if (isFirstOfPartitionForType(endo_ids[id])) + output << "M_.endo_" << getPartition(endo_ids[id]) << " = '" + << getPartitionValue(endo_ids[id]) << "';" << endl; + else + output << "M_.endo_" << getPartition(endo_ids[id]) << " = " + << "char(M_.endo_" << getPartition(endo_ids[id]) << ", '" + << getPartitionValue(endo_ids[id]) << "');" << endl; } } + if (param_nbr() > 0) { output << "M_.param_names = '" << getName(param_ids[0]) << "';" << endl; output << "M_.param_names_tex = '" << getTeXName(param_ids[0]) << "';" << endl; output << "M_.param_names_long = '" << getLongName(param_ids[0]) << "';" << endl; + if (hasPartition(param_ids[0])) + output << "M_.param_" << getPartition(param_ids[0]) << " = '" + << getPartitionValue(param_ids[0]) << "';" << endl; + for (int id = 1; id < param_nbr(); id++) { output << "M_.param_names = char(M_.param_names, '" << getName(param_ids[id]) << "');" << endl @@ -225,6 +287,15 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException) if (getName(param_ids[id]) == "dsge_prior_weight") output << "options_.dsge_var = 1;" << endl; + + if (hasPartition(param_ids[id])) + if (isFirstOfPartitionForType(param_ids[id])) + output << "M_.param_" << getPartition(param_ids[id]) << " = '" + << getPartitionValue(param_ids[id]) << "';" << endl; + else + output << "M_.param_" << getPartition(param_ids[id]) << " = " + << "char(M_.param_" << getPartition(param_ids[id]) << ", '" + << getPartitionValue(param_ids[id]) << "');" << endl; } } diff --git a/preprocessor/SymbolTable.hh b/preprocessor/SymbolTable.hh index b93e1b3fe..f212953f4 100644 --- a/preprocessor/SymbolTable.hh +++ b/preprocessor/SymbolTable.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2015 Dynare Team + * Copyright (C) 2003-2016 Dynare Team * * This file is part of Dynare. * @@ -96,6 +96,8 @@ private: vector tex_name_table; //! Maps IDs to string names of variables vector long_name_table; + //! Maps IDs to a pair containing the partition and the partition value + map > partition_value_map; //! Maps IDs to types vector type_table; @@ -191,7 +193,7 @@ private: public: //! Add a symbol /*! Returns the symbol ID */ - int addSymbol(const string &name, SymbolType type, const string &tex_name, const string &long_name) throw (AlreadyDeclaredException, FrozenException); + int addSymbol(const string &name, SymbolType type, const string &tex_name, const pair *partition_value) throw (AlreadyDeclaredException, FrozenException); //! Add a symbol without its TeX name (will be equal to its name) /*! Returns the symbol ID */ int addSymbol(const string &name, SymbolType type) throw (AlreadyDeclaredException, FrozenException); @@ -253,6 +255,14 @@ public: inline string getTeXName(int id) const throw (UnknownSymbolIDException); //! Get long name inline string getLongName(int id) const throw (UnknownSymbolIDException); + //! Has partition + inline bool hasPartition(int id) const throw (UnknownSymbolIDException); + //! Returns true if the partition name is the first encountered for the type of variable represented by id + bool isFirstOfPartitionForType(int id) const throw (UnknownSymbolIDException); + //! Get partition + inline string getPartition(int id) const throw (UnknownSymbolIDException); + //! Get partition value + inline string getPartitionValue(int id) const throw (UnknownSymbolIDException); //! Get type (by ID) inline SymbolType getType(int id) const throw (UnknownSymbolIDException); //! Get type (by name) @@ -348,6 +358,33 @@ SymbolTable::getLongName(int id) const throw (UnknownSymbolIDException) return long_name_table[id]; } +inline bool +SymbolTable::hasPartition(int id) const throw (UnknownSymbolIDException) +{ + if (id < 0 || id >= size) + throw UnknownSymbolIDException(id); + else + return partition_value_map.find(id) != partition_value_map.end(); +} + +inline string +SymbolTable::getPartition(int id) const throw (UnknownSymbolIDException) +{ + if (id < 0 || id >= size || !hasPartition(id)) + throw UnknownSymbolIDException(id); + else + return *(partition_value_map.at(id).first); +} + +inline string +SymbolTable::getPartitionValue(int id) const throw (UnknownSymbolIDException) +{ + if (id < 0 || id >= size || !hasPartition(id)) + throw UnknownSymbolIDException(id); + else + return *(partition_value_map.at(id).second); +} + inline SymbolType SymbolTable::getType(int id) const throw (UnknownSymbolIDException) { diff --git a/preprocessor/macro/MacroFlex.ll b/preprocessor/macro/MacroFlex.ll index 9229b049d..9c9bc66f7 100644 --- a/preprocessor/macro/MacroFlex.ll +++ b/preprocessor/macro/MacroFlex.ll @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2015 Dynare Team + * Copyright (C) 2008-2016 Dynare Team * * This file is part of Dynare. * @@ -188,7 +188,11 @@ CONT \\\\ } else { +#if (YY_FLEX_MAJOR_VERSION > 2) || (YY_FLEX_MAJOR_VERSION == 2 && YY_FLEX_MINOR_VERSION >= 6) + yyout << endl; +#else *yyout << endl; +#endif BEGIN(INITIAL); } return token::EOL; @@ -245,7 +249,7 @@ CONT \\\\ echo { return token::ECHO_DIR; } error { return token::ERROR; } -[A-Za-z_\x80-\xf3][A-Za-z0-9_\x80-\xf3]* { +[A-Za-z_][A-Za-z0-9_]* { yylval->string_val = new string(yytext); return token::NAME; } @@ -383,7 +387,13 @@ CONT \\\\ } /* We don't use echo, because under Cygwin it will add an extra \r */ -{EOL} { yylloc->lines(1); yylloc->step(); *yyout << endl; } +{EOL} { yylloc->lines(1); yylloc->step(); +#if (YY_FLEX_MAJOR_VERSION > 2) || (YY_FLEX_MAJOR_VERSION == 2 && YY_FLEX_MINOR_VERSION >= 6) + yyout << endl; +#else + *yyout << endl; +#endif + } /* Copy everything else to output */ . { yylloc->step(); ECHO; } @@ -401,8 +411,13 @@ void MacroFlex::output_line(Macro::parser::location_type *yylloc) const { if (!no_line_macro) - *yyout << endl << "@#line \"" << *yylloc->begin.filename << "\" " - << yylloc->begin.line << endl; +#if (YY_FLEX_MAJOR_VERSION > 2) || (YY_FLEX_MAJOR_VERSION == 2 && YY_FLEX_MINOR_VERSION >= 6) + const_cast(yyout) +#else + *yyout +#endif + << endl << "@#line \"" << *yylloc->begin.filename << "\" " + << yylloc->begin.line << endl; } void diff --git a/preprocessor/macro/Makefile.am b/preprocessor/macro/Makefile.am index 5397f60cc..08a93d583 100644 --- a/preprocessor/macro/Makefile.am +++ b/preprocessor/macro/Makefile.am @@ -17,7 +17,7 @@ EXTRA_DIST = $(BUILT_SOURCES) libmacro_a_CPPFLAGS = $(BOOST_CPPFLAGS) -I.. MacroFlex.cc: MacroFlex.ll - $(LEX) -oMacroFlex.cc MacroFlex.ll + $(LEX) -o MacroFlex.cc MacroFlex.ll MacroBison.cc MacroBison.hh location.hh stack.hh position.hh: MacroBison.yy $(YACC) -o MacroBison.cc MacroBison.yy diff --git a/tests/Makefile.am b/tests/Makefile.am index ef9170389..42c67ae12 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -1,10 +1,15 @@ MODFILES = \ estimation/fs2000.mod \ + estimation/fs2000_with_weibull_prior.mod \ estimation/fs2000_MCMC_jumping_covariance.mod \ estimation/fs2000_initialize_from_calib.mod \ estimation/fs2000_calibrated_covariance.mod \ estimation/fs2000_model_comparison.mod \ + estimation/fs2000_fast.mod \ estimation/MH_recover/fs2000_recover.mod \ + estimation/MH_recover/fs2000_recover_2.mod \ + estimation/MH_recover/fs2000_recover_3.mod \ + estimation/MH_recover/fs2000_recover_tarb.mod \ estimation/t_proposal/fs2000_student.mod \ estimation/TaRB/fs2000_tarb.mod \ moments/example1_var_decomp.mod \ @@ -194,6 +199,11 @@ MODFILES = \ kalman/likelihood_from_dynare/fs2000_uncorr_ME.mod \ kalman/likelihood_from_dynare/fs2000_uncorr_ME_missing.mod \ second_order/burnside_1.mod \ + kalman_filter_smoother/compare_results_simulation/fs2000_ML.mod \ + kalman_filter_smoother/compare_results_simulation/fs2000_ML_loglinear.mod \ + kalman_filter_smoother/compare_results_simulation/fs2000.mod \ + kalman_filter_smoother/compare_results_simulation/fs2000_loglinear.mod \ + second_order/burnside_1.mod \ second_order/ds1.mod \ second_order/ds2.mod \ ep/rbc.mod \ @@ -261,7 +271,31 @@ MODFILES = \ optimizers/fs2000_w.mod \ differentiate_forward_vars/RBC_differentiate_forward.mod \ TeX/fs2000_corr_ME.mod \ - prior_posterior_function/fs2000_prior_posterior_function.mod \ + prior_posterior_function/fs2000_prior_posterior_function.mod + observation_trends_and_prefiltering/MCMC/Trend_loglin_no_prefilt_first_obs_MC.mod \ + observation_trends_and_prefiltering/MCMC/Trend_loglin_prefilt_first_obs_MC.mod \ + observation_trends_and_prefiltering/MCMC/Trend_loglinear_no_prefilter_MC.mod \ + observation_trends_and_prefiltering/MCMC/Trend_loglinear_prefilter_MC.mod \ + observation_trends_and_prefiltering/MCMC/Trend_no_prefilter_first_obs_MC.mod \ + observation_trends_and_prefiltering/MCMC/Trend_no_prefilter_MC.mod \ + observation_trends_and_prefiltering/MCMC/Trend_prefilter_first_obs_MC.mod \ + observation_trends_and_prefiltering/MCMC/Trend_prefilter_MC.mod \ + observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter.mod \ + observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter_first_obs.mod \ + observation_trends_and_prefiltering/ML/Trend_loglinear_prefilter.mod \ + observation_trends_and_prefiltering/ML/Trend_loglinear_prefilter_first_obs.mod \ + observation_trends_and_prefiltering/ML/Trend_no_prefilter.mod \ + observation_trends_and_prefiltering/ML/Trend_no_prefilter_first_obs.mod \ + observation_trends_and_prefiltering/ML/Trend_prefilter.mod \ + observation_trends_and_prefiltering/ML/Trend_prefilter_first_obs.mod \ + observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilter_calib_smoother.mod \ + observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilt_first_obs_cal_smooth.mod \ + observation_trends_and_prefiltering/calib_smoother/Tr_prefilter_calib_smoother.mod \ + observation_trends_and_prefiltering/calib_smoother/Tr_prefilt_first_obs_cal_smooth.mod \ + observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilter_loglin_calib_smoother.mod \ + observation_trends_and_prefiltering/calib_smoother/Tr_no_prefil_f_obs_loglin_cal_smoother.mod \ + observation_trends_and_prefiltering/calib_smoother/Tr_prefilter_loglin_calib_smoother.mod \ + observation_trends_and_prefiltering/calib_smoother/Tr_prefil_f_obs_loglin_cal_smoother.mod \ reporting/example1.mod XFAIL_MODFILES = ramst_xfail.mod \ @@ -460,6 +494,7 @@ EXTRA_DIST = \ kalman/likelihood_from_dynare/fsdat_simul_uncorr_ME_missing.m \ kalman/lik_init/fs2000_common.inc \ kalman/lik_init/fs2000_ns_common.inc \ + kalman_filter_smoother/compare_results_simulation/fsdat_simul_logged.m \ identification/kim/kim2_steadystate.m \ identification/as2007/as2007_steadystate.m \ estimation/fsdat_simul.m \ @@ -471,8 +506,22 @@ EXTRA_DIST = \ smoother2histval/fsdat_simul.m \ optimal_policy/Ramsey/find_c.m \ optimal_policy/Ramsey/oo_ramsey_policy_initval.mat \ + observation_trends_and_prefiltering/Trend_diagnostics_MCMC_common.inc \ + observation_trends_and_prefiltering/Trend_diagnostics_calib_common.inc \ + observation_trends_and_prefiltering/Trend_diagnostics_ML_common.inc \ + observation_trends_and_prefiltering/Trend_exp_model_prefilter_common.inc \ + observation_trends_and_prefiltering/Trend_exp_model_no_prefilter_common.inc \ + observation_trends_and_prefiltering/Trend_model_prefilter_common.inc \ + observation_trends_and_prefiltering/Trend_model_no_prefilter_common.inc \ + observation_trends_and_prefiltering/Trend_exp_model_calib_prefilter_common.inc \ + observation_trends_and_prefiltering/Trend_exp_model_calib_no_prefilter_common.inc \ + observation_trends_and_prefiltering/Trend_model_calib_prefilter_common.inc \ + observation_trends_and_prefiltering/Trend_model_calib_no_prefilter_common.inc \ + observation_trends_and_prefiltering/Trend_load_data_common.inc + optimal_policy/Ramsey/oo_ramsey_policy_initval.mat \ optimizers/optimizer_function_wrapper.m \ optimizers/fs2000.common.inc \ + estimation/MH_recover/fs2000.common.inc \ prior_posterior_function/posterior_function_demo.m diff --git a/tests/TeX/fs2000_corr_ME.mod b/tests/TeX/fs2000_corr_ME.mod index dc7a6a277..c9d3b3f08 100644 --- a/tests/TeX/fs2000_corr_ME.mod +++ b/tests/TeX/fs2000_corr_ME.mod @@ -156,11 +156,15 @@ stderr e_a, inv_gamma_pdf, 0.035449, inf; stderr e_m, inv_gamma_pdf, 0.008862, inf; corr e_m, e_a, normal_pdf, 0, 0.2; stderr gp_obs, inv_gamma_pdf, 0.001, inf; -//stderr gy_obs, inv_gamma_pdf, 0.001, inf; -//corr gp_obs, gy_obs,normal_pdf, 0, 0.2; +stderr gy_obs, inv_gamma_pdf, 0.001, inf; +corr gp_obs, gy_obs,normal_pdf, 0, 0.2; end; -estimation(mode_compute=9,order=1,datafile='../fs2000/fsdat_simul',mode_check,smoother,filter_decomposition,mh_replic=2002, mh_nblocks=2, mh_jscale=0.8,forecast = 8,bayesian_irf,filtered_vars,filter_step_ahead=[1,3],irf=20,moments_varendo,contemporaneous_correlation) m P c e W R k d y; +estimation(mode_compute=9,order=1,datafile='../fs2000/fsdat_simul',mode_check,smoother,filter_decomposition,mh_replic=4000, mh_nblocks=1, mh_jscale=0.8,forecast = 8,bayesian_irf,filtered_vars,filter_step_ahead=[1,3],irf=20,moments_varendo,contemporaneous_correlation) m P c e W R k d y; + +trace_plot(options_,M_,estim_params_,'PosteriorDensity',1); +trace_plot(options_,M_,estim_params_,'StructuralShock',1,'eps_a') + shock_decomposition y W R; collect_LaTeX_Files(M_); diff --git a/tests/deterministic_simulations/initialization.mod b/tests/deterministic_simulations/initialization.mod new file mode 100644 index 000000000..3523cfc22 --- /dev/null +++ b/tests/deterministic_simulations/initialization.mod @@ -0,0 +1,22 @@ +%% CODE TO SIMULATE LOGISTIC MAP +%% DECLARATION OF ENDOGENOUS VARIABLES +var x; +parameters r s; + +r=3.8; +s=0; + +model; +x = r*x(-1)*(1 - x(-1)) + s*x(+1); +end; + +initval; +x = 0; +end; + +check; + +%% DETERMINISTIC SIMULATION +simul(periods = 40, stack_solve_algo=0, maxit=100); +dsample 40; +rplot x; \ No newline at end of file diff --git a/tests/estimation/MH_recover/fs2000.common.inc b/tests/estimation/MH_recover/fs2000.common.inc new file mode 100644 index 000000000..bbcc293f9 --- /dev/null +++ b/tests/estimation/MH_recover/fs2000.common.inc @@ -0,0 +1,116 @@ +/* + * This file replicates the estimation of the cash in advance model described + * Frank Schorfheide (2000): "Loss function-based evaluation of DSGE models", + * Journal of Applied Econometrics, 15(6), 645-670. + * + * The data are in file "fsdat_simul.m", and have been artificially generated. + * They are therefore different from the original dataset used by Schorfheide. + * + * The equations are taken from J. Nason and T. Cogley (1994): "Testing the + * implications of long-run neutrality for monetary business cycle models", + * Journal of Applied Econometrics, 9, S37-S70. + * Note that there is an initial minus sign missing in equation (A1), p. S63. + * + * This implementation was written by Michel Juillard. Please note that the + * following copyright notice only applies to this Dynare implementation of the + * model. + */ + +/* + * Copyright (C) 2004-2010 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 . + */ + +var m P c e W R k d n l gy_obs gp_obs y dA; +varexo e_a e_m; + +parameters alp bet gam mst rho psi del; + +alp = 0.33; +bet = 0.99; +gam = 0.003; +mst = 1.011; +rho = 0.7; +psi = 0.787; +del = 0.02; + +model; +dA = exp(gam+e_a); +log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m; +-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0; +W = l/n; +-(psi/(1-psi))*(c*P/(1-n))+l/n = 0; +R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W; +1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0; +c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1); +P*c = m; +m-1+d = l; +e = exp(e_a); +y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a)); +gy_obs = dA*y/y(-1); +gp_obs = (P/P(-1))*m(-1)/dA; +end; + +shocks; +var e_a; stderr 0.014; +var e_m; stderr 0.005; +end; + +steady_state_model; + dA = exp(gam); + gst = 1/dA; + m = mst; + khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1)); + xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1); + nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp ); + n = xist/(nust+xist); + P = xist + nust; + k = khst*n; + + l = psi*mst*n/( (1-psi)*(1-n) ); + c = mst/P; + d = l - mst + 1; + y = k^alp*n^(1-alp)*gst^alp; + R = mst/bet; + W = l/n; + ist = y-c; + q = 1 - d; + + e = 1; + + gp_obs = m/dA; + gy_obs = dA; +end; + +steady; + +check; + +estimated_params; +alp, beta_pdf, 0.356, 0.02; +bet, beta_pdf, 0.993, 0.002; +gam, normal_pdf, 0.0085, 0.003; +mst, normal_pdf, 1.0002, 0.007; +rho, beta_pdf, 0.129, 0.223; +psi, beta_pdf, 0.65, 0.05; +del, beta_pdf, 0.01, 0.005; +stderr e_a, inv_gamma_pdf, 0.035449, inf; +stderr e_m, inv_gamma_pdf, 0.008862, inf; +end; + +varobs gp_obs gy_obs; +options_.plot_priors=0; \ No newline at end of file diff --git a/tests/estimation/MH_recover/fs2000_recover.mod b/tests/estimation/MH_recover/fs2000_recover.mod index 52c5664ac..3f421a8ee 100644 --- a/tests/estimation/MH_recover/fs2000_recover.mod +++ b/tests/estimation/MH_recover/fs2000_recover.mod @@ -1,139 +1,35 @@ -/* - * This file replicates the estimation of the cash in advance model described - * Frank Schorfheide (2000): "Loss function-based evaluation of DSGE models", - * Journal of Applied Econometrics, 15(6), 645-670. - * - * The data are in file "fsdat_simul.m", and have been artificially generated. - * They are therefore different from the original dataset used by Schorfheide. - * - * The equations are taken from J. Nason and T. Cogley (1994): "Testing the - * implications of long-run neutrality for monetary business cycle models", - * Journal of Applied Econometrics, 9, S37-S70. - * Note that there is an initial minus sign missing in equation (A1), p. S63. - * - * This implementation was written by Michel Juillard. Please note that the - * following copyright notice only applies to this Dynare implementation of the - * model. - */ +//Test mh_recover function for RW-MH -/* - * Copyright (C) 2004-2010 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 . - */ +@#include "fs2000.common.inc" -var m P c e W R k d n l gy_obs gp_obs y dA; -varexo e_a e_m; - -parameters alp bet gam mst rho psi del; - -alp = 0.33; -bet = 0.99; -gam = 0.003; -mst = 1.011; -rho = 0.7; -psi = 0.787; -del = 0.02; - -model; -dA = exp(gam+e_a); -log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m; --P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0; -W = l/n; --(psi/(1-psi))*(c*P/(1-n))+l/n = 0; -R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W; -1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0; -c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1); -P*c = m; -m-1+d = l; -e = exp(e_a); -y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a)); -gy_obs = dA*y/y(-1); -gp_obs = (P/P(-1))*m(-1)/dA; -end; - -shocks; -var e_a; stderr 0.014; -var e_m; stderr 0.005; -end; - -steady_state_model; - dA = exp(gam); - gst = 1/dA; - m = mst; - khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1)); - xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1); - nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp ); - n = xist/(nust+xist); - P = xist + nust; - k = khst*n; - - l = psi*mst*n/( (1-psi)*(1-n) ); - c = mst/P; - d = l - mst + 1; - y = k^alp*n^(1-alp)*gst^alp; - R = mst/bet; - W = l/n; - ist = y-c; - q = 1 - d; - - e = 1; - - gp_obs = m/dA; - gy_obs = dA; -end; - -steady; - -check; - -estimated_params; -alp, beta_pdf, 0.356, 0.02; -bet, beta_pdf, 0.993, 0.002; -gam, normal_pdf, 0.0085, 0.003; -mst, normal_pdf, 1.0002, 0.007; -rho, beta_pdf, 0.129, 0.223; -psi, beta_pdf, 0.65, 0.05; -del, beta_pdf, 0.01, 0.005; -stderr e_a, inv_gamma_pdf, 0.035449, inf; -stderr e_m, inv_gamma_pdf, 0.008862, inf; -end; - -varobs gp_obs gy_obs; - -options_.MaxNumberOfBytes=2000*11*8/4; -estimation(order=1, datafile='../fsdat_simul',nobs=192, loglinear, mh_replic=2000, mh_nblocks=2, mh_jscale=0.8); -copyfile([M_.dname filesep 'metropolis' filesep 'fs2000_recover_mh1_blck1.mat'],'fs2000_mh1_blck1.mat') -copyfile([M_.dname filesep 'metropolis' filesep 'fs2000_recover_mh3_blck2.mat'],'fs2000_mh3_blck2.mat') -delete([M_.dname filesep 'metropolis' filesep 'fs2000_recover_mh4_blck2.mat']) +options_.MaxNumberOfBytes=1000*11*8/2; +estimation(order=1, datafile='../fsdat_simul',nobs=192, loglinear, mh_replic=1000, mh_nblocks=2, mh_jscale=0.8); +copyfile([M_.dname filesep 'metropolis' filesep M_.dname '_mh1_blck1.mat'],[M_.dname '_mh1_blck1.mat']) +copyfile([M_.dname filesep 'metropolis' filesep M_.dname '_mh2_blck2.mat'],[M_.dname '_mh2_blck2.mat']) +delete([M_.dname filesep 'metropolis' filesep M_.dname '_mh2_blck2.mat']) estimation(order=1, datafile='../fsdat_simul',mode_compute=0,mode_file=fs2000_recover_mode, nobs=192, loglinear, mh_replic=2000, mh_nblocks=2, mh_jscale=0.8,mh_recover); %check first unaffected chain -temp1=load('fs2000_mh1_blck1.mat'); -temp2=load([M_.dname filesep 'metropolis' filesep 'fs2000_recover_mh1_blck1.mat']); +temp1=load([M_.dname '_mh1_blck1.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh1_blck1.mat']); -if max(max(temp1.x2-temp2.x2))>1e-10 +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 error('Draws of unaffected chain are not the same') end %check second, affected chain with last unaffected file -temp1=load('fs2000_mh3_blck2.mat'); -temp2=load([M_.dname filesep 'metropolis' filesep 'fs2000_recover_mh3_blck2.mat']); +temp1=load([M_.dname '_mh1_blck1.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh1_blck1.mat']); -if max(max(temp1.x2-temp2.x2))>1e-10 +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 error('Draws of affected chain''s unaffected files are not the same') end + +%check second, affected chain with affected file +temp1=load([M_.dname '_mh2_blck2.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh2_blck2.mat']); + +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 + error('Draws of affected chain''s affected files are not the same') +end \ No newline at end of file diff --git a/tests/estimation/MH_recover/fs2000_recover_2.mod b/tests/estimation/MH_recover/fs2000_recover_2.mod new file mode 100644 index 000000000..1d503de7c --- /dev/null +++ b/tests/estimation/MH_recover/fs2000_recover_2.mod @@ -0,0 +1,49 @@ +//Test mh_recover function for RW-MH when load_mh_file was also used +//Previous chain did not fill last mh_file so mh_recover needs to fill that file + +@#include "fs2000.common.inc" + +options_.MaxNumberOfBytes=2000*11*8/4; +estimation(order=1, datafile='../fsdat_simul',nobs=192, loglinear, mh_replic=999, mh_nblocks=2, mh_jscale=0.8); +estimation(order=1,mode_compute=0,mode_file=fs2000_recover_2_mode, datafile='../fsdat_simul',nobs=192, loglinear, load_mh_file,mh_replic=1002, mh_nblocks=2, mh_jscale=0.8); +copyfile([M_.dname filesep 'metropolis' filesep M_.dname '_mh1_blck1.mat'],[M_.dname '_mh1_blck1.mat']) +copyfile([M_.dname filesep 'metropolis' filesep M_.dname '_mh3_blck2.mat'],[M_.dname '_mh3_blck2.mat']) +copyfile([M_.dname filesep 'metropolis' filesep M_.dname '_mh4_blck2.mat'],[M_.dname '_mh4_blck2.mat']) +copyfile([M_.dname filesep 'metropolis' filesep M_.dname '_mh5_blck2.mat'],[M_.dname '_mh5_blck2.mat']) +delete([M_.dname filesep 'metropolis' filesep M_.dname '_mh3_blck2.mat']) +delete([M_.dname filesep 'metropolis' filesep M_.dname '_mh4_blck2.mat']) +delete([M_.dname filesep 'metropolis' filesep M_.dname '_mh5_blck2.mat']) + +estimation(order=1, datafile='../fsdat_simul',mode_compute=0,mode_file=fs2000_recover_2_mode, nobs=192, loglinear, mh_replic=2000, mh_nblocks=2, mh_jscale=0.8,mh_recover); + +%check first unaffected chain +temp1=load([M_.dname '_mh1_blck1.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh1_blck1.mat']); + +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 + error('Draws of unaffected chain are not the same') +end + +%check second, affected chain with last unaffected file +temp1=load([M_.dname '_mh3_blck2.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh3_blck2.mat']); + +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 + error('Draws of affected chain''s unaffected files are not the same') +end + +%check second, affected chain with affected file +temp1=load([M_.dname '_mh4_blck2.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh4_blck2.mat']); + +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 + error('Draws of affected chain''s affected files are not the same') +end + +%check second, affected chain with affected file +temp1=load([M_.dname '_mh5_blck2.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh5_blck2.mat']); + +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 + error('Draws of affected chain''s affected files are not the same') +end \ No newline at end of file diff --git a/tests/estimation/MH_recover/fs2000_recover_3.mod b/tests/estimation/MH_recover/fs2000_recover_3.mod new file mode 100644 index 000000000..3f7b920ec --- /dev/null +++ b/tests/estimation/MH_recover/fs2000_recover_3.mod @@ -0,0 +1,39 @@ +//Test mh_recover function for RW-MH when load_mh_file was also used +//Previous chain did fill last mh_file so mh_recover does not need to fill that file + +@#include "fs2000.common.inc" + +options_.MaxNumberOfBytes=2000*11*8/4; +estimation(order=1, datafile='../fsdat_simul',nobs=192, loglinear, mh_replic=1000, mh_nblocks=2, mh_jscale=0.8); +estimation(order=1,mode_compute=0,mode_file=fs2000_recover_3_mode, datafile='../fsdat_simul',nobs=192, loglinear, load_mh_file,mh_replic=1000, mh_nblocks=2, mh_jscale=0.8); +copyfile([M_.dname filesep 'metropolis' filesep M_.dname '_mh1_blck1.mat'],[M_.dname '_mh1_blck1.mat']) +copyfile([M_.dname filesep 'metropolis' filesep M_.dname '_mh3_blck2.mat'],[M_.dname '_mh3_blck2.mat']) +copyfile([M_.dname filesep 'metropolis' filesep M_.dname '_mh4_blck2.mat'],[M_.dname '_mh4_blck2.mat']) +delete([M_.dname filesep 'metropolis' filesep M_.dname '_mh3_blck2.mat']) +delete([M_.dname filesep 'metropolis' filesep M_.dname '_mh4_blck2.mat']) + +estimation(order=1, datafile='../fsdat_simul',mode_compute=0,mode_file=fs2000_recover_3_mode, nobs=192, loglinear, mh_replic=2000, mh_nblocks=2, mh_jscale=0.8,mh_recover); + +%check first unaffected chain +temp1=load([M_.dname '_mh1_blck1.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh1_blck1.mat']); + +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 + error('Draws of unaffected chain are not the same') +end + +%check second, affected chain with last unaffected file +temp1=load([M_.dname '_mh3_blck2.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh3_blck2.mat']); + +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 + error('Draws of affected chain''s unaffected files are not the same') +end + +%check second, affected chain with affected file +temp1=load([M_.dname '_mh4_blck2.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh4_blck2.mat']); + +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 + error('Draws of affected chain''s affected files are not the same') +end \ No newline at end of file diff --git a/tests/estimation/MH_recover/fs2000_recover_tarb.mod b/tests/estimation/MH_recover/fs2000_recover_tarb.mod new file mode 100644 index 000000000..9c4fca92a --- /dev/null +++ b/tests/estimation/MH_recover/fs2000_recover_tarb.mod @@ -0,0 +1,35 @@ +//Test mh_recover function for RW-MH when use_tarb was also used + +@#include "fs2000.common.inc" + +options_.MaxNumberOfBytes=10*11*8/2; +estimation(use_tarb,order=1, datafile='../fsdat_simul',nobs=192, loglinear, mh_replic=10, mh_nblocks=2, mh_jscale=0.8); +copyfile([M_.dname filesep 'metropolis' filesep M_.dname '_mh1_blck1.mat'],[M_.dname '_mh1_blck1.mat']) +copyfile([M_.dname filesep 'metropolis' filesep M_.dname '_mh2_blck2.mat'],[M_.dname '_mh2_blck2.mat']) +delete([M_.dname filesep 'metropolis' filesep M_.dname '_mh2_blck2.mat']) + +estimation(use_tarb,order=1, datafile='../fsdat_simul',mode_compute=0,mode_file=fs2000_recover_mode, nobs=192, loglinear, mh_replic=2000, mh_nblocks=2, mh_jscale=0.8,mh_recover); + +%check first unaffected chain +temp1=load([M_.dname '_mh1_blck1.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh1_blck1.mat']); + +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 + error('Draws of unaffected chain are not the same') +end + +%check second, affected chain with last unaffected file +temp1=load([M_.dname '_mh1_blck1.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh1_blck1.mat']); + +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 + error('Draws of affected chain''s unaffected files are not the same') +end + +%check second, affected chain with affected file +temp1=load([M_.dname '_mh2_blck2.mat']); +temp2=load([M_.dname filesep 'metropolis' filesep M_.dname '_mh2_blck2.mat']); + +if max(max(abs(temp1.x2-temp2.x2)))>1e-10 + error('Draws of affected chain''s affected files are not the same') +end \ No newline at end of file diff --git a/tests/estimation/fs2000_fast.mod b/tests/estimation/fs2000_fast.mod new file mode 100644 index 000000000..c9376190f --- /dev/null +++ b/tests/estimation/fs2000_fast.mod @@ -0,0 +1,88 @@ +// See fs2000.mod in the examples/ directory for details on the model + +var m P c e W R k d n l gy_obs gp_obs y dA; +varexo e_a e_m; + +parameters alp bet gam mst rho psi del; + +alp = 0.33; +bet = 0.99; +gam = 0.003; +mst = 1.011; +rho = 0.7; +psi = 0.787; +del = 0.02; + +model; +dA = exp(gam+e_a); +log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m; +-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0; +W = l/n; +-(psi/(1-psi))*(c*P/(1-n))+l/n = 0; +R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W; +1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0; +c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1); +P*c = m; +m-1+d = l; +e = exp(e_a); +y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a)); +gy_obs = dA*y/y(-1); +gp_obs = (P/P(-1))*m(-1)/dA; +end; + +steady_state_model; + dA = exp(gam); + gst = 1/dA; + m = mst; + khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1)); + xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1); + nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp ); + n = xist/(nust+xist); + P = xist + nust; + k = khst*n; + + l = psi*mst*n/( (1-psi)*(1-n) ); + c = mst/P; + d = l - mst + 1; + y = k^alp*n^(1-alp)*gst^alp; + R = mst/bet; + W = l/n; + ist = y-c; + q = 1 - d; + + e = 1; + + gp_obs = m/dA; + gy_obs = dA; +end; + + +shocks; +var e_a; stderr 0.014; +var e_m; stderr 0.005; +end; + +steady; + +check; + +estimated_params; +alp, beta_pdf, 0.356, 0.02; +bet, beta_pdf, 0.993, 0.002; +gam, normal_pdf, 0.0085, 0.003; +mst, normal_pdf, 1.0002, 0.007; +rho, beta_pdf, 0.129, 0.223; +psi, beta_pdf, 0.65, 0.05; +del, beta_pdf, 0.01, 0.005; +stderr e_a, inv_gamma_pdf, 0.035449, inf; +stderr e_m, inv_gamma_pdf, 0.008862, inf; +end; + +varobs gp_obs gy_obs; + +options_.solve_tolf = 1e-12; + +estimation(order=1,datafile=fsdat_simul,nobs=192,loglinear,mh_replic=3000, + fast_kalman_filter,mh_nblocks=2,mh_jscale=0.8,moments_varendo, + selected_variables_only,contemporaneous_correlation, + smoother,forecast=8) y m; diff --git a/tests/estimation/fs2000_model_comparison.mod b/tests/estimation/fs2000_model_comparison.mod index b350eb337..6d2476144 100644 --- a/tests/estimation/fs2000_model_comparison.mod +++ b/tests/estimation/fs2000_model_comparison.mod @@ -99,7 +99,7 @@ if oo_.Model_Comparison.fs2000.Posterior_Model_Probability < oo_.Model_Compariso end oo_laplace=oo_; model_comparison (marginal_density=modifiedharmonicmean) fs2000(0.5) fs2000_initialize_from_calib(0.75); -if abs(oo_laplace.Model_Comparison.fs2000.Log_Marginal_Density-oo_.Model_Comparison.fs2000.Log_Marginal_Density)>0.1 +if abs(oo_laplace.Model_Comparison.fs2000.Log_Marginal_Density-oo_.Model_Comparison.fs2000.Log_Marginal_Density)>0.2 error('Laplace and Harmonic Mean do not match') end model_comparison (marginal_density=modifiedharmonicmean) fs2000(0) fs2000_initialize_from_calib(1); diff --git a/tests/estimation/fs2000_with_weibull_prior.mod b/tests/estimation/fs2000_with_weibull_prior.mod new file mode 100644 index 000000000..54117b221 --- /dev/null +++ b/tests/estimation/fs2000_with_weibull_prior.mod @@ -0,0 +1,84 @@ +// See fs2000.mod in the examples/ directory for details on the model + +var m P c e W R k d n l gy_obs gp_obs y dA; +varexo e_a e_m; + +parameters alp bet gam mst rho psi del; + +alp = 0.33; +bet = 0.99; +gam = 0.003; +mst = 1.011; +rho = 0.7; +psi = 0.787; +del = 0.02; + +model; +dA = exp(gam+e_a); +log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m; +-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0; +W = l/n; +-(psi/(1-psi))*(c*P/(1-n))+l/n = 0; +R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W; +1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0; +c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1); +P*c = m; +m-1+d = l; +e = exp(e_a); +y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a)); +gy_obs = dA*y/y(-1); +gp_obs = (P/P(-1))*m(-1)/dA; +end; + +steady_state_model; + dA = exp(gam); + gst = 1/dA; + m = mst; + khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1)); + xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1); + nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp ); + n = xist/(nust+xist); + P = xist + nust; + k = khst*n; + + l = psi*mst*n/( (1-psi)*(1-n) ); + c = mst/P; + d = l - mst + 1; + y = k^alp*n^(1-alp)*gst^alp; + R = mst/bet; + W = l/n; + ist = y-c; + q = 1 - d; + + e = 1; + + gp_obs = m/dA; + gy_obs = dA; +end; + +shocks; +var e_a; stderr 0.014; +var e_m; stderr 0.005; +end; + +steady; + +check; + +estimated_params; +alp, beta_pdf, 0.356, 0.02; +bet, beta_pdf, 0.993, 0.002; +gam, normal_pdf, 0.0085, 0.003; +mst, normal_pdf, 1.0002, 0.007; +rho, beta_pdf, 0.129, 0.223; +psi, beta_pdf, 0.65, 0.05; +del, beta_pdf, 0.01, 0.005; +stderr e_a, weibull_pdf, 0.035449, 25; +stderr e_m, inv_gamma_pdf, 0.008862, Inf; +end; + +varobs gp_obs gy_obs; + +options_.solve_tolf = 1e-12; + +estimation(order=1,datafile=fsdat_simul,nobs=192,loglinear,mh_replic=2000,mh_nblocks=2,mh_jscale=0.8,moments_varendo,consider_only_observed); diff --git a/tests/gsa/ls2003.mod b/tests/gsa/ls2003.mod index 6cf6410b0..4a8e169e6 100644 --- a/tests/gsa/ls2003.mod +++ b/tests/gsa/ls2003.mod @@ -61,7 +61,7 @@ stderr e_ys,inv_gamma_pdf,1.2533,0.6551; stderr e_pies,inv_gamma_pdf,1.88,0.9827; end; - +options_.TeX=1; disp(' '); disp('NOW I DO STABILITY MAPPING and prepare sample for Reduced form Mapping'); disp(' '); @@ -217,3 +217,7 @@ dynare_sensitivity(nodisplay, stab=0, // no need for stability analysis since th datafile='data_ca1.m',first_obs=8,nobs=79,prefilter=1, rmse=1,ppost=1); +collect_LaTeX_Files(M_); +if system(['pdflatex -halt-on-error ' M_.fname '_TeX_binder.TeX']) + error('TeX-File did not compile.') +end \ No newline at end of file diff --git a/tests/identification/as2007/as2007.mod b/tests/identification/as2007/as2007.mod index f2b813e12..7e6f0313c 100644 --- a/tests/identification/as2007/as2007.mod +++ b/tests/identification/as2007/as2007.mod @@ -59,7 +59,12 @@ stderr 1; var e_z; stderr 1; end; - +options_.TeX=1; identification; identification(advanced=1,max_dim_cova_group=3,prior_mc=250); + +collect_LaTeX_Files(M_); +if system(['pdflatex -halt-on-error ' M_.fname '_TeX_binder.TeX']) + error('TeX-File did not compile.') +end \ No newline at end of file diff --git a/tests/kalman_filter_smoother/compare_results_simulation/fs2000.mod b/tests/kalman_filter_smoother/compare_results_simulation/fs2000.mod new file mode 100644 index 000000000..d2410c55b --- /dev/null +++ b/tests/kalman_filter_smoother/compare_results_simulation/fs2000.mod @@ -0,0 +1,158 @@ +/* + * This file replicates the estimation of the cash in advance model described + * Frank Schorfheide (2000): "Loss function-based evaluation of DSGE models", + * Journal of Applied Econometrics, 15(6), 645-670. + * + * The data are in file "fsdat_simul.m", and have been artificially generated. + * They are therefore different from the original dataset used by Schorfheide. + * + * The equations are taken from J. Nason and T. Cogley (1994): "Testing the + * implications of long-run neutrality for monetary business cycle models", + * Journal of Applied Econometrics, 9, S37-S70. + * Note that there is an initial minus sign missing in equation (A1), p. S63. + * + * This implementation was written by Michel Juillard. Please note that the + * following copyright notice only applies to this Dynare implementation of the + * model. + */ + +/* + * Copyright (C) 2004-2010 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 . + */ + +var m P c e W R k d n l gy_obs gp_obs y dA; +varexo e_a e_m; + +parameters alp bet gam mst rho psi del; + +alp = 0.33; +bet = 0.99; +gam = 0.003; +mst = 1.011; +rho = 0.7; +psi = 0.787; +del = 0.02; + +model; +dA = exp(gam+e_a); +log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m; +-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+1)*P(+1)*m(+1))=0; +W = l/n; +-(psi/(1-psi))*(c*P/(1-n))+l/n = 0; +R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W; +1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0; +c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1); +P*c = m; +m-1+d = l; +e = exp(e_a); +y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a)); +exp(gy_obs) = dA*y/y(-1); +exp(gp_obs) = (P/P(-1))*m(-1)/dA; +end; + +shocks; +var e_a; stderr 0.014; +var e_m; stderr 0.005; +end; + +steady_state_model; + dA = exp(gam); + gst = 1/dA; + m = mst; + khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1)); + xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1); + nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp ); + n = xist/(nust+xist); + P = xist + nust; + k = khst*n; + + l = psi*mst*n/( (1-psi)*(1-n) ); + c = mst/P; + d = l - mst + 1; + y = k^alp*n^(1-alp)*gst^alp; + R = mst/bet; + W = l/n; + ist = y-c; + q = 1 - d; + + e = 1; + + gp_obs = log(m/dA); + gy_obs = log(dA); +end; + +steady; + +check; + +estimated_params; +alp, beta_pdf, 0.356, 0.02; +bet, beta_pdf, 0.993, 0.002; +gam, normal_pdf, 0.0085, 0.003; +mst, normal_pdf, 1.0002, 0.007; +rho, beta_pdf, 0.129, 0.223; +psi, beta_pdf, 0.65, 0.05; +del, beta_pdf, 0.01, 0.005; +stderr e_a, inv_gamma_pdf, 0.035449, inf; +stderr e_m, inv_gamma_pdf, 0.008862, inf; +end; + +varobs gp_obs gy_obs; + +estimation(order=1,datafile=fsdat_simul_logged,consider_all_endogenous,nobs=192,mh_replic=2000, mh_nblocks=1,smoother, mh_jscale=0.8); + +ex_=[]; +for shock_iter=1:M_.exo_nbr +ex_=[ex_ oo_.SmoothedShocks.Mean.(deblank(M_.exo_names(shock_iter,:)))]; +end + +ex_ = ex_(2:end,:); +% ex_ = zeros(size(ex_)); +y0=[]; +for endo_iter=1:M_.endo_nbr +y0 = [y0; +oo_.SmoothedVariables.Mean.(deblank(M_.endo_names(endo_iter,:)))(1)]; +end; + +%make sure decision rules were updated +[oo_.dr,info,M_,options_] = resol(0,M_,options_,oo_); + +dr = oo_.dr; +iorder=1; +y_=simult_(y0,dr,ex_,iorder); + +fsdat_simul_logged; + +%Needs bigger tolerance than ML, because transformation from parameters to steady states is not linear and steady state at mean parameters is not mean of steady states +if mean(abs(y_(strmatch('gy_obs',M_.endo_names,'exact'),:)'-(gy_obs(1:options_.nobs))))>1e-3 ||... + mean(abs(y_(strmatch('gy_obs',M_.endo_names,'exact'),:)'-oo_.SmoothedVariables.Mean.gy_obs))>1e-3 ||... + mean(abs(y_(strmatch('gp_obs',M_.endo_names,'exact'),:)'-(gp_obs(1:options_.nobs))))>1e-1 ||... + mean(abs(y_(strmatch('gp_obs',M_.endo_names,'exact'),:)'-oo_.SmoothedVariables.Mean.gp_obs))>1e-2 +error('Smoother is wrong') +end + + +% figure +% plot((gy_obs)) +% hold on +% plot(y_(strmatch('gy_obs',M_.endo_names,'exact'),:),'r--') +% +% figure +% plot((gp_obs)) +% hold on +% plot(y_(strmatch('gp_obs',M_.endo_names,'exact'),:),'r--') \ No newline at end of file diff --git a/tests/kalman_filter_smoother/compare_results_simulation/fs2000_ML.mod b/tests/kalman_filter_smoother/compare_results_simulation/fs2000_ML.mod new file mode 100644 index 000000000..388d2b7a3 --- /dev/null +++ b/tests/kalman_filter_smoother/compare_results_simulation/fs2000_ML.mod @@ -0,0 +1,163 @@ +/* + * This file replicates the estimation of the cash in advance model described + * Frank Schorfheide (2000): "Loss function-based evaluation of DSGE models", + * Journal of Applied Econometrics, 15(6), 645-670. + * + * The data are in file "fsdat_simul.m", and have been artificially generated. + * They are therefore different from the original dataset used by Schorfheide. + * + * The equations are taken from J. Nason and T. Cogley (1994): "Testing the + * implications of long-run neutrality for monetary business cycle models", + * Journal of Applied Econometrics, 9, S37-S70. + * Note that there is an initial minus sign missing in equation (A1), p. S63. + * + * This implementation was written by Michel Juillard. Please note that the + * following copyright notice only applies to this Dynare implementation of the + * model. + */ + +/* + * Copyright (C) 2004-2010 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 . + */ + +var m P c e W R k d n l gy_obs gp_obs y dA; +varexo e_a e_m; + +parameters alp bet gam mst rho psi del theta; + +alp = 0.33; +bet = 0.99; +gam = 0.003; +mst = 1.011; +rho = 0.7; +psi = 0.787; +del = 0.02; +theta=0; + +model; +dA = exp(gam+e_a); +log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m; +-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0; +W = l/n; +-(psi/(1-psi))*(c*P/(1-n))+l/n = 0; +R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W; +1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0; +c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1); +P*c = m; +m-1+d = l; +e = exp(e_a); +y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a)); +exp(gy_obs) = dA*y/y(-1); +exp(gp_obs) = (P/P(-1))*m(-1)/dA; +end; + +steady_state_model; + dA = exp(gam); + gst = 1/dA; + m = mst; + khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1)); + xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1); + nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp ); + n = xist/(nust+xist); + P = xist + nust; + k = khst*n; + + l = psi*mst*n/( (1-psi)*(1-n) ); + c = mst/P; + d = l - mst + 1; + y = k^alp*n^(1-alp)*gst^alp; + R = mst/bet; + W = l/n; + ist = y-c; + q = 1 - d; + + e = 1; + + gp_obs = log(m/dA); + gy_obs = log(dA); +end; + + +shocks; +var e_a; stderr 0.014; +var e_m; stderr 0.005; +end; + +varobs gp_obs gy_obs; + +steady; +check; + +estimated_params; +alp, 0.356; +gam, 0.0085; +mst, 1.0002; +rho, 0.129; +psi, 0.65; +del, 0.02; +stderr e_a, 0.035449; +stderr e_m, 0.008862; +end; + +estimation(order=1,datafile='fsdat_simul_logged', nobs=192, forecast=8,smoother,filtered_vars,filter_step_ahead=[1,2,4],filter_decomposition,selected_variables_only) m P c e W R k d y gy_obs; + +% write shock matrix +ex_=[]; +for shock_iter=1:M_.exo_nbr +ex_=[ex_ oo_.SmoothedShocks.(deblank(M_.exo_names(shock_iter,:)))]; +end + +%select shocks happening after initial period +ex_ = ex_(2:end,:); + +%get state variables at t=0 +y0=[]; +for endo_iter=1:M_.endo_nbr +y0 = [y0; +oo_.SmoothedVariables.(deblank(M_.endo_names(endo_iter,:)))(1)]; +end; + +%make sure decision rules were updated +[oo_.dr,info,M_,options_] = resol(0,M_,options_,oo_); + +dr = oo_.dr; +iorder=1; +%run simulation +y_=simult_(y0,dr,ex_,iorder); + +fsdat_simul_logged; + +if max(abs(y_(strmatch('gy_obs',M_.endo_names,'exact'),:)'-gy_obs(1:options_.nobs)))>1e-10 ||... + max(abs(y_(strmatch('gy_obs',M_.endo_names,'exact'),:)'-oo_.SmoothedVariables.gy_obs))>1e-10 ||... + max(abs(y_(strmatch('gp_obs',M_.endo_names,'exact'),:)'-gp_obs(1:options_.nobs)))>1e-10 ||... + max(abs(y_(strmatch('gp_obs',M_.endo_names,'exact'),:)'-oo_.SmoothedVariables.gp_obs))>1e-10 +error('Smoother is wrong') +end + +% figure +% subplot(2,1,1) +% plot(log(gy_obs)) +% hold on +% plot(y_(strmatch('gy_obs',M_.endo_names,'exact'),:),'r--') +% +% figure +% subplot(2,1,2) +% plot(log(gp_obs)) +% hold on +% plot(y_(strmatch('gp_obs',M_.endo_names,'exact'),:),'r--') + diff --git a/tests/kalman_filter_smoother/compare_results_simulation/fs2000_ML_loglinear.mod b/tests/kalman_filter_smoother/compare_results_simulation/fs2000_ML_loglinear.mod new file mode 100644 index 000000000..0c4045651 --- /dev/null +++ b/tests/kalman_filter_smoother/compare_results_simulation/fs2000_ML_loglinear.mod @@ -0,0 +1,150 @@ +/* + * This file replicates the estimation of the cash in advance model described + * Frank Schorfheide (2000): "Loss function-based evaluation of DSGE models", + * Journal of Applied Econometrics, 15(6), 645-670. + * + * The data are in file "fsdat_simul.m", and have been artificially generated. + * They are therefore different from the original dataset used by Schorfheide. + * + * The equations are taken from J. Nason and T. Cogley (1994): "Testing the + * implications of long-run neutrality for monetary business cycle models", + * Journal of Applied Econometrics, 9, S37-S70. + * Note that there is an initial minus sign missing in equation (A1), p. S63. + * + * This implementation was written by Michel Juillard. Please note that the + * following copyright notice only applies to this Dynare implementation of the + * model. + */ + +/* + * Copyright (C) 2004-2010 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 . + */ + +var m P c e W R k d n l gy_obs gp_obs y dA; +varexo e_a e_m; + +parameters alp bet gam mst rho psi del theta; + +alp = 0.33; +bet = 0.99; +gam = 0.003; +mst = 1.011; +rho = 0.7; +psi = 0.787; +del = 0.02; +theta=0; + +model; +dA = exp(gam+e_a); +log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m; +-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0; +W = l/n; +-(psi/(1-psi))*(c*P/(1-n))+l/n = 0; +R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W; +1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0; +c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1); +P*c = m; +m-1+d = l; +e = exp(e_a); +y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a)); +gy_obs = dA*y/y(-1); +gp_obs = (P/P(-1))*m(-1)/dA; +end; + +steady_state_model; + dA = exp(gam); + gst = 1/dA; + m = mst; + khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1)); + xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1); + nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp ); + n = xist/(nust+xist); + P = xist + nust; + k = khst*n; + + l = psi*mst*n/( (1-psi)*(1-n) ); + c = mst/P; + d = l - mst + 1; + y = k^alp*n^(1-alp)*gst^alp; + R = mst/bet; + W = l/n; + ist = y-c; + q = 1 - d; + + e = 1; + + gp_obs = m/dA; + gy_obs = dA; +end; + + +shocks; +var e_a; stderr 0.014; +var e_m; stderr 0.005; +end; + +varobs gp_obs gy_obs; + +steady; +check; + +estimated_params; +alp, 0.356; +gam, 0.0085; +mst, 1.0002; +rho, 0.129; +psi, 0.65; +del, 0.02; +stderr e_a, 0.035449; +stderr e_m, 0.008862; +end; + +estimation(order=1,datafile='../fsdat_simul',loglinear, nobs=192, forecast=8,smoother,filtered_vars,filter_step_ahead=[1,2,4],filter_decomposition,selected_variables_only) m P c e W R k d y gy_obs; + +% write shock matrix +ex_=[]; +for shock_iter=1:M_.exo_nbr +ex_=[ex_ oo_.SmoothedShocks.(deblank(M_.exo_names(shock_iter,:)))]; +end + +%select shocks happening after initial period +ex_ = ex_(2:end,:); + +%get state variables at t=0 +y0=[]; +for endo_iter=1:M_.endo_nbr +y0 = [y0; +oo_.SmoothedVariables.(deblank(M_.endo_names(endo_iter,:)))(1)]; +end; + +%make sure decision rules were updated +[oo_.dr,info,M_,options_] = resol(0,M_,options_,oo_); + +dr = oo_.dr; +iorder=1; +%run simulation +y_=simult_(y0,dr,ex_,iorder); + +fsdat_simul_logged; + +if max(abs(y_(strmatch('gy_obs',M_.endo_names,'exact'),:)'-gy_obs(1:options_.nobs)))>1e-10 ||... + max(abs(y_(strmatch('gy_obs',M_.endo_names,'exact'),:)'-oo_.SmoothedVariables.gy_obs))>1e-10 ||... + max(abs(y_(strmatch('gp_obs',M_.endo_names,'exact'),:)'-gp_obs(1:options_.nobs)))>1e-10 ||... + max(abs(y_(strmatch('gp_obs',M_.endo_names,'exact'),:)'-oo_.SmoothedVariables.gp_obs))>1e-10 +error('Smoother is wrong') +end \ No newline at end of file diff --git a/tests/kalman_filter_smoother/compare_results_simulation/fs2000_loglinear.mod b/tests/kalman_filter_smoother/compare_results_simulation/fs2000_loglinear.mod new file mode 100644 index 000000000..88150b060 --- /dev/null +++ b/tests/kalman_filter_smoother/compare_results_simulation/fs2000_loglinear.mod @@ -0,0 +1,176 @@ +/* + * This file replicates the estimation of the cash in advance model described + * Frank Schorfheide (2000): "Loss function-based evaluation of DSGE models", + * Journal of Applied Econometrics, 15(6), 645-670. + * + * The data are in file "fsdat_simul.m", and have been artificially generated. + * They are therefore different from the original dataset used by Schorfheide. + * + * The equations are taken from J. Nason and T. Cogley (1994): "Testing the + * implications of long-run neutrality for monetary business cycle models", + * Journal of Applied Econometrics, 9, S37-S70. + * Note that there is an initial minus sign missing in equation (A1), p. S63. + * + * This implementation was written by Michel Juillard. Please note that the + * following copyright notice only applies to this Dynare implementation of the + * model. + */ + +/* + * Copyright (C) 2004-2010 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 . + */ + +var m P c e W R k d n l gy_obs gp_obs y dA; +varexo e_a e_m; + +parameters alp bet gam mst rho psi del; + +alp = 0.33; +bet = 0.99; +gam = 0.003; +mst = 1.011; +rho = 0.7; +psi = 0.787; +del = 0.02; + +model; +dA = exp(gam+e_a); +log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m; +-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+1)*P(+1)*m(+1))=0; +W = l/n; +-(psi/(1-psi))*(c*P/(1-n))+l/n = 0; +R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W; +1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0; +c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1); +P*c = m; +m-1+d = l; +e = exp(e_a); +y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a)); +gy_obs = dA*y/y(-1); +gp_obs = (P/P(-1))*m(-1)/dA; +end; + +initval; +k = 6; +m = mst; +P = 2.25; +c = 0.45; +e = 1; +W = 4; +R = 1.02; +d = 0.85; +n = 0.19; +l = 0.86; +y = 0.6; +gy_obs = exp(gam); +gp_obs = exp(-gam); +dA = exp(gam); +end; + +shocks; +var e_a; stderr 0.014; +var e_m; stderr 0.005; +end; + +steady_state_model; + dA = exp(gam); + gst = 1/dA; + m = mst; + khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1)); + xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1); + nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp ); + n = xist/(nust+xist); + P = xist + nust; + k = khst*n; + + l = psi*mst*n/( (1-psi)*(1-n) ); + c = mst/P; + d = l - mst + 1; + y = k^alp*n^(1-alp)*gst^alp; + R = mst/bet; + W = l/n; + ist = y-c; + q = 1 - d; + + e = 1; + + gp_obs = m/dA; + gy_obs = dA; +end; + +steady; + +check; + +estimated_params; +alp, beta_pdf, 0.356, 0.02; +bet, beta_pdf, 0.993, 0.002; +gam, normal_pdf, 0.0085, 0.003; +mst, normal_pdf, 1.0002, 0.007; +rho, beta_pdf, 0.129, 0.223; +psi, beta_pdf, 0.65, 0.05; +del, beta_pdf, 0.01, 0.005; +stderr e_a, inv_gamma_pdf, 0.035449, inf; +stderr e_m, inv_gamma_pdf, 0.008862, inf; +end; + +varobs gp_obs gy_obs; + +estimation(order=1, datafile='../fsdat_simul', nobs=192, loglinear, mh_replic=2000, mh_nblocks=1,smoother, mh_jscale=0.8,consider_all_endogenous); + +ex_=[]; +for shock_iter=1:M_.exo_nbr +ex_=[ex_ oo_.SmoothedShocks.Mean.(deblank(M_.exo_names(shock_iter,:)))]; +end + +ex_ = ex_(2:end,:); +% ex_ = zeros(size(ex_)); +y0=[]; +for endo_iter=1:M_.endo_nbr +y0 = [y0; +oo_.SmoothedVariables.Mean.(deblank(M_.endo_names(endo_iter,:)))(1)]; +end; + +%make sure decision rules were updated +[oo_.dr,info,M_,options_] = resol(0,M_,options_,oo_); + +dr = oo_.dr; +iorder=1; +% if options_.loglinear +% y0=exp(y0); +% end +y_=simult_(y0,dr,ex_,iorder); + +fsdat_simul_logged; + +if mean(abs(y_(strmatch('gy_obs',M_.endo_names,'exact'),:)'-gy_obs(1:options_.nobs)))>1e-3 ||... + mean(abs(y_(strmatch('gy_obs',M_.endo_names,'exact'),:)'-oo_.SmoothedVariables.Mean.gy_obs))>1e-3 ||... + mean(abs(y_(strmatch('gp_obs',M_.endo_names,'exact'),:)'-gp_obs(1:options_.nobs)))>1e-3 ||... + mean(abs(y_(strmatch('gp_obs',M_.endo_names,'exact'),:)'-oo_.SmoothedVariables.Mean.gp_obs))>1e-3 +error('Smoother is wrong') +end + +% figure +% plot(log(gy_obs)) +% hold on +% plot(y_(strmatch('gy_obs',M_.endo_names,'exact'),:),'r--') +% +% figure +% plot(log(gp_obs)) +% hold on +% plot(y_(strmatch('gp_obs',M_.endo_names,'exact'),:),'r--') \ No newline at end of file diff --git a/tests/kalman_filter_smoother/compare_results_simulation/fsdat_simul_logged.m b/tests/kalman_filter_smoother/compare_results_simulation/fsdat_simul_logged.m new file mode 100644 index 000000000..3e442115c --- /dev/null +++ b/tests/kalman_filter_smoother/compare_results_simulation/fsdat_simul_logged.m @@ -0,0 +1,832 @@ +gy_obs =[ + 1.0030045 + 0.99990934 + 1.0172778 + 0.99464043 + 1.0253423 + 1.0150215 + 0.97772557 + 0.97832186 + 1.0159561 + 1.0085937 + 1.0102649 + 1.0007604 + 1.0112596 + 1.0163279 + 1.0173204 + 1.0103896 + 1.0006493 + 0.99447124 + 1.0196405 + 1.0089304 + 0.99650737 + 1.0139707 + 0.97865842 + 1.0192225 + 0.99139628 + 1.0141362 + 1.0196612 + 0.97483476 + 0.99686151 + 0.99594464 + 1.0000642 + 1.0172243 + 1.0025773 + 0.97199728 + 1.0217815 + 1.0219949 + 0.99490252 + 1.0190728 + 1.0111337 + 1.0003792 + 0.98969164 + 1.010438 + 1.0216309 + 1.0016671 + 1.0357588 + 0.98803787 + 1.0093457 + 1.0177035 + 0.98548204 + 1.0274294 + 1.0141377 + 1.0091174 + 0.96427632 + 1.0083272 + 1.0007882 + 0.99038262 + 1.0031336 + 0.99500213 + 0.98203716 + 0.9889452 + 1.011632 + 0.99451949 + 0.97291047 + 0.98750871 + 0.99992418 + 0.97657318 + 0.99930448 + 1.0008515 + 1.0044064 + 0.98133792 + 1.0091702 + 1.0087023 + 1.0119876 + 1.0143019 + 1.0311061 + 0.99340471 + 1.0057428 + 0.99197259 + 1.0071019 + 0.99448853 + 1.0061819 + 1.0070088 + 0.9950913 + 1.0302318 + 0.9817693 + 1.0072885 + 0.97355282 + 0.98782586 + 1.0136674 + 0.99863956 + 1.0205668 + 0.99611384 + 1.0073805 + 0.99691529 + 1.0089194 + 1.0030467 + 1.0112006 + 1.0260523 + 0.97803331 + 0.99423374 + 1.0043727 + 1.0140173 + 1.0111473 + 0.99524348 + 0.99775943 + 0.9958619 + 0.9982344 + 1.0210212 + 1.0022288 + 1.0014801 + 1.011456 + 1.0124871 + 0.99843599 + 0.99324886 + 0.99912838 + 1.003327 + 1.0072071 + 1.0115223 + 1.009266 + 1.0070554 + 1.0129916 + 1.0053413 + 1.0051638 + 0.99212952 + 1.0214422 + 0.98716707 + 0.99905788 + 0.98877357 + 0.98568476 + 0.99767393 + 1.0061791 + 0.98423439 + 0.99492949 + 0.98786999 + 0.99754239 + 1.0168619 + 0.99472384 + 1.0041658 + 0.98123181 + 1.0112882 + 0.99245422 + 1.0010255 + 1.0017799 + 1.0089968 + 1.0072824 + 0.99768475 + 1.0044726 + 1.0118678 + 1.0056385 + 1.0276965 + 1.0025122 + 1.0065161 + 1.0234338 + 0.99760167 + 0.98922272 + 1.0101918 + 1.011615 + 1.0085286 + 1.0074455 + 0.98866757 + 0.99959012 + 1.0129881 + 0.99127881 + 0.97971901 + 1.0185314 + 1.020054 + 1.0132605 + 0.98063643 + 0.99490253 + 1.0101531 + 1.0004526 + 1.0059109 + 0.98974491 + 1.0062391 + 1.0216488 + 0.99398446 + 0.97786609 + 1.0019274 + 0.99587153 + 1.0095881 + 1.0111887 + 0.99457649 + 0.97896734 + 1.000172 + 1.0142951 + 1.0034224 + 1.0037242 + 1.0016059 + 1.016556 + 0.99687023 + 1.0117844 + 1.0059212 + 0.98083159 + 0.98638851 + 1.0128713 + 1.0096232 + 1.0115891 + 1.0011213 + 1.0147105 + 1.0066344 + 1.0164429 + 0.99825038 + 0.99403411 + +]; + +gp_obs =[ + 1.0079715 + 1.0074573 + 1.0153107 + 1.0152677 + 1.0011653 + 0.99950061 + 1.0328311 + 1.0192317 + 1.009827 + 0.99588916 + 1.007474 + 1.0113061 + 0.98696624 + 0.99978663 + 0.98240542 + 0.98861723 + 0.99008763 + 1.0185076 + 1.0052452 + 0.99447194 + 1.0092685 + 1.01208 + 1.0105237 + 0.98513875 + 1.0165628 + 0.99485934 + 1.0050255 + 1.0140756 + 1.0093128 + 1.0155868 + 1.0107023 + 0.99212762 + 1.0095465 + 1.0028435 + 1.0069437 + 1.0070473 + 1.0145902 + 1.0186922 + 1.0059917 + 1.0113072 + 1.0107386 + 0.99769196 + 0.99793444 + 1.0050791 + 0.98307821 + 1.0107594 + 0.99689982 + 0.98667064 + 0.9991662 + 0.98274722 + 0.98422032 + 0.99393016 + 1.0118567 + 0.99912781 + 1.0023744 + 1.0086662 + 1.0164773 + 1.0169327 + 1.0372478 + 1.0314242 + 1.0004256 + 1.0110541 + 1.0076575 + 1.0119851 + 1.0055188 + 1.0213959 + 1.0234416 + 1.0264917 + 1.0292725 + 1.0385184 + 1.0200999 + 1.0107697 + 1.008583 + 1.0200332 + 1.0030413 + 1.0108659 + 1.0185145 + 1.0168619 + 1.0180462 + 1.0239657 + 1.0205509 + 1.0189973 + 1.0246446 + 1.0135089 + 1.0352973 + 1.0099289 + 1.0266474 + 1.0279829 + 1.0101653 + 1.041216 + 1.0103861 + 1.0114727 + 1.0054605 + 1.0190722 + 1.0114837 + 1.0179213 + 1.006082 + 1.0049696 + 1.0143629 + 0.9971036 + 1.0005602 + 1.0078403 + 1.0240222 + 1.0195063 + 1.0355136 + 1.0218743 + 1.0171331 + 1.0049817 + 1.0140974 + 1.0168431 + 1.0049966 + 1.0045568 + 1.0156414 + 1.0273055 + 1.0197653 + 1.0030624 + 1.0154993 + 0.99782084 + 0.99711648 + 1.014408 + 1.0057417 + 0.99936837 + 1.0096934 + 1.0095138 + 1.0057734 + 1.0114497 + 1.0059784 + 1.0328889 + 1.0098032 + 1.0041114 + 1.0101247 + 1.0181588 + 1.0115712 + 1.0227509 + 1.0065104 + 1.0110902 + 1.0298169 + 1.0089532 + 1.0368733 + 1.0123033 + 1.0060763 + 1.0150937 + 1.0239325 + 0.99555536 + 0.99861271 + 1.0076201 + 0.99941535 + 1.0119522 + 1.0129183 + 0.99288924 + 1.0260784 + 1.0144982 + 1.0121985 + 1.0234916 + 1.02215 + 1.0190118 + 1.0172679 + 1.0118398 + 1.0002123 + 1.0092124 + 1.0071943 + 0.99508468 + 1.0019303 + 1.0030733 + 0.9964198 + 1.0027298 + 0.99797614 + 1.006942 + 0.99793928 + 1.0083214 + 1.0283732 + 1.0111102 + 1.016936 + 1.0229061 + 0.98846454 + 1.0015387 + 1.0201769 + 1.0079822 + 1.0064007 + 1.0095543 + 1.0092207 + 1.0135485 + 1.0198974 + 1.0140252 + 1.0128686 + 1.0092903 + 1.0141974 + 1.0023492 + 0.99731455 + 1.0026598 + 0.99303643 + 1.0036469 + 1.0160975 + 1.0368378 + 1.0139625 + 1.01493 + 1.0113531 + 1.0114548 + 0.99833441 + 0.99648401 + 0.97645361 + 1.0154053 + 1.01703 + +]; + +Y_obs =[ + 1 + 0.99690484 + 1.0111781 + 1.0028141 + 1.0251518 + 1.0371688 + 1.0118899 + 0.98720726 + 1.0001589 + 1.0057481 + 1.0130085 + 1.0107643 + 1.0190194 + 1.0323428 + 1.0466587 + 1.0540438 + 1.0516886 + 1.0431553 + 1.0597913 + 1.0657172 + 1.0592201 + 1.0701863 + 1.0458402 + 1.0620582 + 1.0504499 + 1.0615817 + 1.0782384 + 1.0500687 + 1.0439257 + 1.0368658 + 1.0339255 + 1.0481453 + 1.0477181 + 1.0167109 + 1.0354878 + 1.0544782 + 1.0463762 + 1.0624445 + 1.0705737 + 1.0679484 + 1.0546356 + 1.0620691 + 1.0806955 + 1.0793581 + 1.1121124 + 1.0971458 + 1.1034869 + 1.1181859 + 1.1006634 + 1.1250883 + 1.1362214 + 1.1423343 + 1.1036061 + 1.1089288 + 1.1067125 + 1.0940906 + 1.0942197 + 1.0862174 + 1.06525 + 1.0511907 + 1.0598182 + 1.0513331 + 1.0212391 + 1.0057433 + 1.002663 + 0.97623167 + 0.97253165 + 0.97037865 + 0.97178055 + 0.95011397 + 0.95627969 + 0.96197747 + 0.97096053 + 0.98225794 + 1.0103595 + 1.0007597 + 1.003498 + 0.99246608 + 0.99656347 + 0.98804749 + 0.99122491 + 0.99522926 + 0.98731605 + 1.0145434 + 0.99330816 + 0.99759216 + 0.96814048 + 0.95296183 + 0.96362471 + 0.95925977 + 0.97682205 + 0.96993138 + 0.9743074 + 0.96821818 + 0.97413308 + 0.9741753 + 0.98237142 + 1.0054193 + 0.98044807 + 0.9716773 + 0.9730455 + 0.98405828 + 0.99220103 + 0.98444001 + 0.97919493 + 0.97205233 + 0.96728223 + 0.98529893 + 0.98452324 + 0.98299888 + 0.99145042 + 1.000933 + 0.99636447 + 0.98660883 + 0.98273271 + 0.98305518 + 0.98725774 + 0.99577549 + 1.002037 + 1.0060879 + 1.016075 + 1.0184118 + 1.0205711 + 1.0096961 + 1.0281337 + 1.0122963 + 1.0083497 + 0.99411874 + 0.976799 + 0.97146842 + 0.97464304 + 0.95587292 + 0.94779791 + 0.93266339 + 0.92720128 + 0.94105864 + 0.93277798 + 0.93393927 + 0.91216657 + 0.92045028 + 0.9099 + 0.90792098 + 0.90669634 + 0.91268867 + 0.91696661 + 0.91164685 + 0.91311495 + 0.92197825 + 0.92461222 + 0.94930422 + 0.9488119 + 0.95232353 + 0.97275278 + 0.96734995 + 0.95356817 + 0.96075548 + 0.96936594 + 0.97489002 + 0.97933106 + 0.96499412 + 0.96157973 + 0.97156334 + 0.95983765 + 0.93655215 + 0.95207909 + 0.96912862 + 0.97938462 + 0.95701655 + 0.94891457 + 0.95606317 + 0.95351125 + 0.95641767 + 0.94315807 + 0.94639265 + 0.96503697 + 0.95601693 + 0.93087851 + 0.92980141 + 0.92266844 + 0.92925206 + 0.93743628 + 0.92900826 + 0.9049711 + 0.90213859 + 0.91342916 + 0.91384707 + 0.91456681 + 0.91316822 + 0.92671976 + 0.92058549 + 0.92936541 + 0.93228212 + 0.91010921 + 0.89349322 + 0.90336005 + 0.90997873 + 0.91856328 + 0.91668007 + 0.92838606 + 0.932016 + 0.94545438 + 0.94070026 + 0.93172987 + +]; + +P_obs =[ + 1 + 0.99948573 + 1.0068249 + 1.0141211 + 1.0073149 + 0.99884398 + 1.0237035 + 1.0349636 + 1.036819 + 1.0247366 + 1.0242391 + 1.0275737 + 1.0065684 + 0.99838346 + 0.97281734 + 0.95346302 + 0.9355791 + 0.9461152 + 0.94338882 + 0.92988921 + 0.9311862 + 0.93529467 + 0.93784681 + 0.91501401 + 0.92360522 + 0.91049302 + 0.90754698 + 0.91365103 + 0.91499228 + 0.92260749 + 0.92533824 + 0.90949431 + 0.91106924 + 0.90594116 + 0.90491334 + 0.9039891 + 0.91060772 + 0.92132842 + 0.91934854 + 0.92268418 + 0.92545127 + 0.91517169 + 0.90513459 + 0.90224212 + 0.87734878 + 0.88013667 + 0.86906494 + 0.84776403 + 0.83895869 + 0.81373437 + 0.78998314 + 0.77594176 + 0.77982695 + 0.77098321 + 0.76538611 + 0.76608075 + 0.77458654 + 0.78354767 + 0.81282389 + 0.83627649 + 0.82873051 + 0.83181309 + 0.83149903 + 0.83551261 + 0.83305985 + 0.84648418 + 0.86195421 + 0.88047436 + 0.90177533 + 0.93232215 + 0.94445051 + 0.9472487 + 0.94786015 + 0.95992178 + 0.95499149 + 0.95788581 + 0.9684288 + 0.97731917 + 0.98739379 + 1.0033879 + 1.0159673 + 1.0269931 + 1.0436661 + 1.0492034 + 1.0765292 + 1.0784865 + 1.0971624 + 1.1171737 + 1.1193675 + 1.1526119 + 1.1550265 + 1.1585277 + 1.1560166 + 1.1671172 + 1.1706294 + 1.1805791 + 1.1786896 + 1.1756876 + 1.1820789 + 1.171211 + 1.1637997 + 1.1636684 + 1.179719 + 1.1912538 + 1.2187959 + 1.2326986 + 1.2418602 + 1.2388704 + 1.2449963 + 1.2538678 + 1.2508929 + 1.2474781 + 1.255148 + 1.274482 + 1.2862757 + 1.2813665 + 1.2888943 + 1.2787436 + 1.2678886 + 1.274325 + 1.2720952 + 1.263492 + 1.2652139 + 1.2667561 + 1.264558 + 1.2680362 + 1.2660431 + 1.2909605 + 1.2927921 + 1.288932 + 1.2910852 + 1.3012725 + 1.3048721 + 1.3196515 + 1.3181903 + 1.321309 + 1.3431543 + 1.344136 + 1.3730377 + 1.3773695 + 1.3754742 + 1.3825964 + 1.3985574 + 1.3861412 + 1.3767823 + 1.3764309 + 1.3678747 + 1.3718554 + 1.3768022 + 1.3617199 + 1.3798267 + 1.3863533 + 1.3905803 + 1.4061004 + 1.4202788 + 1.4313191 + 1.4406155 + 1.4444837 + 1.4367244 + 1.4379653 + 1.4371881 + 1.4243012 + 1.41826 + 1.4133617 + 1.40181 + 1.3965683 + 1.3865729 + 1.3855433 + 1.3755111 + 1.3758609 + 1.3962625 + 1.3994012 + 1.4083656 + 1.4233002 + 1.4037932 + 1.3973604 + 1.4095657 + 1.4095764 + 1.4080055 + 1.4095882 + 1.4108374 + 1.4164143 + 1.4283402 + 1.4343939 + 1.4392909 + 1.4406097 + 1.4468355 + 1.4412132 + 1.4305562 + 1.4252445 + 1.4103094 + 1.4059847 + 1.4141106 + 1.4429769 + 1.4489679 + 1.4559263 + 1.4593079 + 1.4627911 + 1.453154 + 1.4416665 + 1.4101485 + 1.4175823 + 1.4266407 + +]; + +gp_obs=log(gp_obs); +gy_obs=log(gy_obs); +P_obs=log(P_obs); +Y_obs=log(Y_obs); \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/MCMC/Trend_loglin_no_prefilt_first_obs_MC.mod b/tests/observation_trends_and_prefiltering/MCMC/Trend_loglin_no_prefilt_first_obs_MC.mod new file mode 100644 index 000000000..640630ff8 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/MCMC/Trend_loglin_no_prefilt_first_obs_MC.mod @@ -0,0 +1,19 @@ +@#include "../Trend_exp_model_no_prefilter_common.inc" + +estimation(order=1,datafile='../Exp_AR1_trend_data_with_constant',mh_replic=2000, + mode_compute=4,first_obs=1000,loglinear,smoother,forecast=100,prefilter=0, + mcmc_jumping_covariance='MCMC_jump_covar', + filtered_vars, filter_step_ahead = [1,2,4], + mh_nblocks=1,mh_jscale=0.3) P_obs Y_obs junk2; +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameter estimates do not match') +end + +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',loaded_par.param_names,'exact')); +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',loaded_par.param_names,'exact')); + +@#include "../Trend_diagnostics_MCMC_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/MCMC/Trend_loglin_prefilt_first_obs_MC.mod b/tests/observation_trends_and_prefiltering/MCMC/Trend_loglin_prefilt_first_obs_MC.mod new file mode 100644 index 000000000..037704634 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/MCMC/Trend_loglin_prefilt_first_obs_MC.mod @@ -0,0 +1,21 @@ +@#include "../Trend_exp_model_prefilter_common.inc" + +estimation(order=1,datafile='../Exp_AR1_trend_data_with_constant',mh_replic=2000, + mode_compute=4,first_obs=1000,loglinear,smoother,forecast=100,prefilter=1, + mcmc_jumping_covariance='MCMC_jump_covar_prefilter', + filtered_vars, filter_step_ahead = [1,2,4], + mh_nblocks=1,mh_jscale=1e-4) P_obs Y_obs junk2; + +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params_prefilter'); + +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameter estimates do not match') +end +loaded_par_full=load('../orig_params'); +y_forecast_100_periods=loaded_par_full.orig_params(strmatch('const_y',loaded_par_full.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par_full.orig_params(strmatch('g_y',loaded_par_full.param_names,'exact')); +p_forecast_100_periods=loaded_par_full.orig_params(strmatch('const_p',loaded_par_full.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par_full.orig_params(strmatch('g_p',loaded_par_full.param_names,'exact')); + +@#include "../Trend_diagnostics_MCMC_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/MCMC/Trend_loglinear_no_prefilter_MC.mod b/tests/observation_trends_and_prefiltering/MCMC/Trend_loglinear_no_prefilter_MC.mod new file mode 100644 index 000000000..e39d4cf03 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/MCMC/Trend_loglinear_no_prefilter_MC.mod @@ -0,0 +1,18 @@ +@#include "../Trend_exp_model_no_prefilter_common.inc" + +estimation(order=1,datafile='../Exp_AR1_trend_data_with_constant',mh_replic=2000, + mode_compute=4,first_obs=1,loglinear,diffuse_filter,smoother,forecast=100,prefilter=0, + mcmc_jumping_covariance='MCMC_jump_covar', + filtered_vars, filter_step_ahead = [1,2,4], + mh_nblocks=1,mh_jscale=0.3) P_obs Y_obs junk2; +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameter estimates do not match') +end +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',loaded_par.param_names,'exact')); +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',loaded_par.param_names,'exact')); + +@#include "../Trend_diagnostics_MCMC_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/MCMC/Trend_loglinear_prefilter_MC.mod b/tests/observation_trends_and_prefiltering/MCMC/Trend_loglinear_prefilter_MC.mod new file mode 100644 index 000000000..b6e0931d6 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/MCMC/Trend_loglinear_prefilter_MC.mod @@ -0,0 +1,21 @@ +@#include "../Trend_exp_model_prefilter_common.inc" + +estimation(order=1,datafile='../Exp_AR1_trend_data_with_constant',mh_replic=2000, + mode_compute=4,first_obs=1,loglinear,smoother,forecast=100,prefilter=1, + mcmc_jumping_covariance='MCMC_jump_covar_prefilter', + filtered_vars, filter_step_ahead = [1,2,4], + mh_nblocks=1,mh_jscale=1e-4) P_obs Y_obs junk2; + +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params_prefilter'); + +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameter estimates do not match') +end +loaded_par_full=load('../orig_params'); +y_forecast_100_periods=loaded_par_full.orig_params(strmatch('const_y',loaded_par_full.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par_full.orig_params(strmatch('g_y',loaded_par_full.param_names,'exact')); +p_forecast_100_periods=loaded_par_full.orig_params(strmatch('const_p',loaded_par_full.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par_full.orig_params(strmatch('g_p',loaded_par_full.param_names,'exact')); + +@#include "../Trend_diagnostics_MCMC_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/MCMC/Trend_no_prefilter_MC.mod b/tests/observation_trends_and_prefiltering/MCMC/Trend_no_prefilter_MC.mod new file mode 100644 index 000000000..7eefa594d --- /dev/null +++ b/tests/observation_trends_and_prefiltering/MCMC/Trend_no_prefilter_MC.mod @@ -0,0 +1,18 @@ +@#include "../Trend_model_no_prefilter_common.inc" + +estimation(order=1,datafile='../AR1_trend_data_with_constant',mh_replic=2000, + mode_compute=4,first_obs=1,smoother,mh_nblocks=1,mh_jscale=0.3, + filtered_vars, filter_step_ahead = [1,2,4], + mcmc_jumping_covariance='MCMC_jump_covar',forecast=100,prefilter=0) P_obs Y_obs junk2; + +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameter estimates do not match') +end +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',loaded_par.param_names,'exact')); +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',loaded_par.param_names,'exact')); + +@#include "../Trend_diagnostics_MCMC_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/MCMC/Trend_no_prefilter_first_obs_MC.mod b/tests/observation_trends_and_prefiltering/MCMC/Trend_no_prefilter_first_obs_MC.mod new file mode 100644 index 000000000..0038ef3fe --- /dev/null +++ b/tests/observation_trends_and_prefiltering/MCMC/Trend_no_prefilter_first_obs_MC.mod @@ -0,0 +1,19 @@ +@#include "../Trend_model_no_prefilter_common.inc" + +estimation(order=1,datafile='../AR1_trend_data_with_constant', + mh_replic=2000,mode_compute=4,first_obs=1000,smoother,forecast=100,prefilter=0, + mcmc_jumping_covariance='MCMC_jump_covar', + filtered_vars, filter_step_ahead = [1,2,4], + mh_nblocks=1,mh_jscale=0.3) P_obs Y_obs junk2; + +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameter estimates do not match') +end +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',loaded_par.param_names,'exact')); +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',loaded_par.param_names,'exact')); + +@#include "../Trend_diagnostics_MCMC_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/MCMC/Trend_prefilter_MC.mod b/tests/observation_trends_and_prefiltering/MCMC/Trend_prefilter_MC.mod new file mode 100644 index 000000000..6b8259c2e --- /dev/null +++ b/tests/observation_trends_and_prefiltering/MCMC/Trend_prefilter_MC.mod @@ -0,0 +1,21 @@ +@#include "../Trend_model_prefilter_common.inc" + +estimation(order=1,datafile='../AR1_trend_data_with_constant',mh_replic=2000,mode_compute=4, + first_obs=1,smoother,prefilter=1, + mh_nblocks=1,mh_jscale=1e-4, + filtered_vars, filter_step_ahead = [1,2,4], + mcmc_jumping_covariance='MCMC_jump_covar_prefilter',forecast=100) P_obs Y_obs junk2; + +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params_prefilter'); + +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameter estimates do not match') +end +loaded_par_full=load('../orig_params'); +y_forecast_100_periods=loaded_par_full.orig_params(strmatch('const_y',loaded_par_full.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par_full.orig_params(strmatch('g_y',loaded_par_full.param_names,'exact')); +p_forecast_100_periods=loaded_par_full.orig_params(strmatch('const_p',loaded_par_full.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par_full.orig_params(strmatch('g_p',loaded_par_full.param_names,'exact')); + +@#include "../Trend_diagnostics_MCMC_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/MCMC/Trend_prefilter_first_obs_MC.mod b/tests/observation_trends_and_prefiltering/MCMC/Trend_prefilter_first_obs_MC.mod new file mode 100644 index 000000000..191655a99 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/MCMC/Trend_prefilter_first_obs_MC.mod @@ -0,0 +1,21 @@ +@#include "../Trend_model_prefilter_common.inc" + +estimation(order=1,datafile='../AR1_trend_data_with_constant',mh_replic=2000,mode_compute=4, + first_obs=1000,smoother,prefilter=1, + mh_nblocks=1,mh_jscale=1e-4, + filtered_vars, filter_step_ahead = [1,2,4], + mcmc_jumping_covariance='MCMC_jump_covar_prefilter',forecast=100) P_obs Y_obs junk2; + +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params_prefilter'); + +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameter estimates do not match') +end +loaded_par_full=load('../orig_params'); +y_forecast_100_periods=loaded_par_full.orig_params(strmatch('const_y',loaded_par_full.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par_full.orig_params(strmatch('g_y',loaded_par_full.param_names,'exact')); +p_forecast_100_periods=loaded_par_full.orig_params(strmatch('const_p',loaded_par_full.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par_full.orig_params(strmatch('g_p',loaded_par_full.param_names,'exact')); + +@#include "../Trend_diagnostics_MCMC_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter.mod b/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter.mod new file mode 100644 index 000000000..aa659e989 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter.mod @@ -0,0 +1,19 @@ +@#include "../Trend_exp_model_no_prefilter_common.inc" + +estimation(order=1,datafile='../Exp_AR1_trend_data_with_constant',mh_replic=0, + mode_compute=4,first_obs=1, + filtered_vars, filter_step_ahead = [1,2,4], + loglinear,smoother,forecast=100,prefilter=0) P_obs Y_obs junk2; + +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameter estimates do not match') +end + +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',M_.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',M_.param_names,'exact')); +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',M_.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',M_.param_names,'exact')); + +@#include "../Trend_diagnostics_ML_common.inc" diff --git a/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter_first_obs.mod b/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter_first_obs.mod new file mode 100644 index 000000000..be50874d7 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter_first_obs.mod @@ -0,0 +1,19 @@ +@#include "../Trend_exp_model_no_prefilter_common.inc" + +estimation(order=1,datafile='../Exp_AR1_trend_data_with_constant',mh_replic=0, + mode_compute=4,first_obs=1000, + filtered_vars, filter_step_ahead = [1,2,4], + loglinear,smoother,forecast=100,prefilter=0) P_obs Y_obs junk2; + +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameter estimates do not match') +end + +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',M_.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',M_.param_names,'exact')); +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',M_.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',M_.param_names,'exact')); + +@#include "../Trend_diagnostics_ML_common.inc" diff --git a/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_prefilter.mod b/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_prefilter.mod new file mode 100644 index 000000000..43eefe0e6 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_prefilter.mod @@ -0,0 +1,20 @@ +@#include "../Trend_exp_model_prefilter_common.inc" + +estimation(order=1,datafile='../Exp_AR1_trend_data_with_constant',mh_replic=0,mode_compute=4, + first_obs=1,smoother,loglinear, + filtered_vars, filter_step_ahead = [1,2,4], + forecast=100,prefilter=1) P_obs Y_obs junk2; + +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); + +if max(abs((M_.params-loaded_par.orig_params([1:4,7:8]))./loaded_par.orig_params([1:4,7:8])))>0.03 + error('Parameter estimates do not match') +end + +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',loaded_par.param_names,'exact')); +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',loaded_par.param_names,'exact')); + +@#include "../Trend_diagnostics_ML_common.inc" diff --git a/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_prefilter_first_obs.mod b/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_prefilter_first_obs.mod new file mode 100644 index 000000000..2019dd046 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/ML/Trend_loglinear_prefilter_first_obs.mod @@ -0,0 +1,20 @@ +@#include "../Trend_exp_model_prefilter_common.inc" + +estimation(order=1,datafile='../Exp_AR1_trend_data_with_constant',mh_replic=0,mode_compute=4, + first_obs=1000,smoother,loglinear, + filtered_vars, filter_step_ahead = [1,2,4], + forecast=100,prefilter=1) P_obs Y_obs junk2; + +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); + +if max(abs((M_.params-loaded_par.orig_params([1:4,7:8]))./loaded_par.orig_params([1:4,7:8])))>0.03 + error('Parameter estimates do not match') +end + +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',loaded_par.param_names,'exact')); +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',loaded_par.param_names,'exact')); + +@#include "../Trend_diagnostics_ML_common.inc" diff --git a/tests/observation_trends_and_prefiltering/ML/Trend_no_prefilter.mod b/tests/observation_trends_and_prefiltering/ML/Trend_no_prefilter.mod new file mode 100644 index 000000000..68b963112 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/ML/Trend_no_prefilter.mod @@ -0,0 +1,18 @@ +@#include "../Trend_model_no_prefilter_common.inc" + +estimation(order=1,datafile='../AR1_trend_data_with_constant',mh_replic=0, + mode_compute=4,first_obs=1, + filtered_vars, filter_step_ahead = [1,2,4], + diffuse_filter,smoother,forecast=100,prefilter=0) P_obs Y_obs junk2; +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameter estimates do not match') +end + +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',M_.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',M_.param_names,'exact')) +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',M_.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',M_.param_names,'exact')) + +@#include "../Trend_diagnostics_ML_common.inc" diff --git a/tests/observation_trends_and_prefiltering/ML/Trend_no_prefilter_first_obs.mod b/tests/observation_trends_and_prefiltering/ML/Trend_no_prefilter_first_obs.mod new file mode 100644 index 000000000..4b926f1cf --- /dev/null +++ b/tests/observation_trends_and_prefiltering/ML/Trend_no_prefilter_first_obs.mod @@ -0,0 +1,19 @@ +@#include "../Trend_model_no_prefilter_common.inc" + +estimation(order=1,datafile='../AR1_trend_data_with_constant',mh_replic=0, + mode_compute=4,first_obs=1000, + filtered_vars, filter_step_ahead = [1,2,4], + smoother,forecast=100,prefilter=0) P_obs Y_obs junk2; + +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs(M_.params-loaded_par.orig_params)./loaded_par.orig_params)>0.03 + error('Parameter estimates do not match') +end + +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',M_.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',M_.param_names,'exact')); +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',M_.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',M_.param_names,'exact')); + +@#include "../Trend_diagnostics_ML_common.inc" diff --git a/tests/observation_trends_and_prefiltering/ML/Trend_prefilter.mod b/tests/observation_trends_and_prefiltering/ML/Trend_prefilter.mod new file mode 100644 index 000000000..6dec6a3dd --- /dev/null +++ b/tests/observation_trends_and_prefiltering/ML/Trend_prefilter.mod @@ -0,0 +1,20 @@ +@#include "../Trend_model_prefilter_common.inc" + +estimation(order=1,datafile='../AR1_trend_data_with_constant',mh_replic=0,mode_compute=4, + first_obs=1, + filtered_vars, filter_step_ahead = [1,2,4], + smoother,forecast=100,prefilter=1) P_obs Y_obs junk2; + +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); + +if max(abs((M_.params-loaded_par.orig_params([1:4,7:8]))./loaded_par.orig_params([1:4,7:8])))>0.03 + error('Parameter estimates do not match') +end + +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',loaded_par.param_names,'exact')) +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',loaded_par.param_names,'exact')) + +@#include "../Trend_diagnostics_ML_common.inc" diff --git a/tests/observation_trends_and_prefiltering/ML/Trend_prefilter_first_obs.mod b/tests/observation_trends_and_prefiltering/ML/Trend_prefilter_first_obs.mod new file mode 100644 index 000000000..d5f45ce2e --- /dev/null +++ b/tests/observation_trends_and_prefiltering/ML/Trend_prefilter_first_obs.mod @@ -0,0 +1,21 @@ +@#include "../Trend_model_prefilter_common.inc" + +estimation(order=1,datafile='../AR1_trend_data_with_constant', + mh_replic=0,mode_compute=4, + filtered_vars, filter_step_ahead = [1,2,4], + first_obs=1000,diffuse_filter,smoother,forecast=100,prefilter=1) P_obs Y_obs junk2; + +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + + +loaded_par=load('../orig_params'); + +if max(abs((M_.params-loaded_par.orig_params([1:4,7:8]))./loaded_par.orig_params([1:4,7:8])))>0.03 + error('Parameter estimates do not match') +end + +y_forecast_100_periods=loaded_par.orig_params(strmatch('const_y',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_y',loaded_par.param_names,'exact')) +p_forecast_100_periods=loaded_par.orig_params(strmatch('const_p',loaded_par.param_names,'exact'))+(options_.first_obs+options_.nobs-1+options_.forecast)*loaded_par.orig_params(strmatch('g_p',loaded_par.param_names,'exact')) + +@#include "../Trend_diagnostics_ML_common.inc" diff --git a/tests/observation_trends_and_prefiltering/Trend_diagnostics_MCMC_common.inc b/tests/observation_trends_and_prefiltering/Trend_diagnostics_MCMC_common.inc new file mode 100644 index 000000000..8c6b30c81 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_diagnostics_MCMC_common.inc @@ -0,0 +1,50 @@ + +if max(abs(oo_.SmoothedVariables.Mean.Y_obs-Y_obs'))>1e-5 ||... + max(abs(oo_.SmoothedVariables.Mean.P_obs-P_obs'))>1e-5 || ... + max(abs(oo_.SmoothedVariables.Mean.junk2-junk2'))>1e-5 + error('Smoothed Variables are wrong') +end + +if max(abs(oo_.UpdatedVariables.Mean.Y_obs-Y_obs'))>1e-5 ||... + max(abs(oo_.UpdatedVariables.Mean.P_obs-P_obs'))>1e-5 || ... + max(abs(oo_.UpdatedVariables.Mean.junk2-junk2'))>1e-5 + error('Updated Variables are wrong') +end + +if mean(abs(oo_.FilteredVariables.Mean.Y_obs(1:end-1)-Y_obs(2:end)'))>1e-3 ||... + mean(abs(oo_.FilteredVariables.Mean.P_obs(1:end-1)-P_obs(2:end)'))>1e-3 + error('Filtered Variables are wrong') +end + +if abs(corr(oo_.FilteredVariables.Mean.Y_obs(2:end-1)-Y_obs(3:end)',oo_.FilteredVariables.Mean.Y_obs(1:end-2)-Y_obs(2:end-1)'))>2e-2 ||... + abs(corr(oo_.FilteredVariables.Mean.P_obs(2:end-1)-P_obs(3:end)',oo_.FilteredVariables.Mean.P_obs(1:end-2)-P_obs(2:end-1)'))>2e-2 ||... + abs(corr(oo_.FilteredVariables.Mean.junk2(2:end-1)-junk2(3:end)',oo_.FilteredVariables.Mean.junk2(1:end-2)-junk2(2:end-1)'))>2e-2 + error('Filtered Variables are wrong') +end + +if max(abs(squeeze(oo_.FilteredVariablesKStepAhead(1,1,2:end-(options_.nk-1)))-oo_.FilteredVariables.Mean.P_obs))>1e-5 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(1,2,2:end-(options_.nk-1)))-oo_.FilteredVariables.Mean.Y_obs))>1e-5 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(1,3,2:end-(options_.nk-1)))-oo_.FilteredVariables.Mean.junk2))>1e-5 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(2,1,3:end-options_.nk))-oo_.FilteredVariables.Mean.P_obs(3:end)))>1e-2 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(2,2,3:end-options_.nk))-oo_.FilteredVariables.Mean.Y_obs(3:end)))>1e-2 ||... + mean(squeeze(oo_.FilteredVariablesKStepAhead(2,3,3:end-options_.nk)))>1e-1 + error('FilteredVariablesKStepAhead is wrong') +end + +if abs(oo_.PointForecast.Mean.Y_obs(end)- y_forecast_100_periods)>2e-4 || abs(oo_.PointForecast.Mean.P_obs(end)- p_forecast_100_periods)>2e-4 + error('Mean Point Forecasts do not match') +end +if abs(oo_.PointForecast.Median.Y_obs(end)- y_forecast_100_periods)>2e-4 || abs(oo_.PointForecast.Median.P_obs(end)- p_forecast_100_periods)>2e-4 + error('Median Point Forecasts do not match') +end + +if abs(oo_.MeanForecast.Mean.Y_obs(end)- y_forecast_100_periods)>2e-4 || abs(oo_.MeanForecast.Mean.P_obs(end)- p_forecast_100_periods)>2e-4 + error('Mean Mean Forecasts do not match') +end +if abs(oo_.MeanForecast.Median.Y_obs(end)- y_forecast_100_periods)>2e-4 || abs(oo_.MeanForecast.Median.P_obs(end)- p_forecast_100_periods)>1e-3 + error('Median Mean Forecasts do not match') +end + +if abs(mean(oo_.SmoothedShocks.Mean.e_y))>1e-2 || abs(mean(oo_.SmoothedShocks.Mean.e_p))>1e-2 || abs(mean(oo_.SmoothedShocks.Median.e_y))>1e-2 || abs(mean(oo_.SmoothedShocks.Median.e_p))>1e-2 + error('Residuals are not mean 0') +end \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/Trend_diagnostics_ML_common.inc b/tests/observation_trends_and_prefiltering/Trend_diagnostics_ML_common.inc new file mode 100644 index 000000000..dca528e27 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_diagnostics_ML_common.inc @@ -0,0 +1,40 @@ +if abs(oo_.forecast.Mean.Y_obs(end)- y_forecast_100_periods)>1e-4 || abs(oo_.forecast.Mean.P_obs(end)- p_forecast_100_periods)>1e-4 + error('Forecasts do not match') +end + +if max(abs(oo_.SmoothedVariables.Y_obs-Y_obs'))>1e-5 ||... + max(abs(oo_.SmoothedVariables.P_obs-P_obs'))>1e-5 || ... + max(abs(oo_.SmoothedVariables.junk2-junk2'))>1e-5 + error('Smoothed Variables are wrong') +end + +if max(abs(oo_.UpdatedVariables.Y_obs-Y_obs'))>1e-5 ||... + max(abs(oo_.UpdatedVariables.P_obs-P_obs'))>1e-5 || ... + max(abs(oo_.UpdatedVariables.junk2-junk2'))>1e-5 + error('Updated Variables are wrong') +end + +if mean(abs(oo_.FilteredVariables.Y_obs(1:end-1)-Y_obs(2:end)'))>1e-3 ||... + mean(abs(oo_.FilteredVariables.P_obs(1:end-1)-P_obs(2:end)'))>1e-3 + error('Smoothed Variables are wrong') +end + +if abs(corr(oo_.FilteredVariables.Y_obs(2:end-1)-Y_obs(3:end)',oo_.FilteredVariables.Y_obs(1:end-2)-Y_obs(2:end-1)'))>2e-2 ||... + abs(corr(oo_.FilteredVariables.P_obs(2:end-1)-P_obs(3:end)',oo_.FilteredVariables.P_obs(1:end-2)-P_obs(2:end-1)'))>2e-1 ||... + abs(corr(oo_.FilteredVariables.junk2(2:end-1)-junk2(3:end)',oo_.FilteredVariables.junk2(1:end-2)-junk2(2:end-1)'))>2e-2 + error('Filtered Variables are wrong') +end + +if max(abs(squeeze(oo_.FilteredVariablesKStepAhead(1,1,2:end-(options_.nk-1)))-oo_.FilteredVariables.Y_obs))>1e-5 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(1,2,2:end-(options_.nk-1)))-oo_.FilteredVariables.P_obs))>1e-5 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(1,3,2:end-(options_.nk-1)))-oo_.FilteredVariables.junk2))>1e-5 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(2,1,3:end-options_.nk))-oo_.FilteredVariables.Y_obs(3:end)))>1e-2 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(2,2,3:end-options_.nk))-oo_.FilteredVariables.P_obs(3:end)))>1e-2 ||... + mean(squeeze(oo_.FilteredVariablesKStepAhead(2,3,3:end-options_.nk)))>1e-1 ||... + mean(squeeze(oo_.FilteredVariablesKStepAhead(2,4,3:end-options_.nk)))>1e-1 + error('FilteredVariablesKStepAhead is wrong') +end + +if abs(mean(oo_.SmoothedShocks.e_y))>1e-1 || abs(mean(oo_.SmoothedShocks.e_p))>1e-1 + error('Residuals are not mean 0') +end \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/Trend_diagnostics_calib_common.inc b/tests/observation_trends_and_prefiltering/Trend_diagnostics_calib_common.inc new file mode 100644 index 000000000..2a7af6878 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_diagnostics_calib_common.inc @@ -0,0 +1,36 @@ +if max(abs(oo_.SmoothedVariables.Y_obs-Y_obs'))>1e-5 ||... + max(abs(oo_.SmoothedVariables.P_obs-P_obs'))>1e-5 || ... + max(abs(oo_.SmoothedVariables.junk2-junk2'))>1e-5 + error('Smoothed Variables are wrong') +end + +if max(abs(oo_.UpdatedVariables.Y_obs-Y_obs'))>1e-5 ||... + max(abs(oo_.UpdatedVariables.P_obs-P_obs'))>1e-5 || ... + max(abs(oo_.UpdatedVariables.junk2-junk2'))>1e-5 + error('Updated Variables are wrong') +end + +if mean(abs(oo_.FilteredVariables.Y_obs(1:end-1)-Y_obs(2:end)'))>1e-3 ||... + mean(abs(oo_.FilteredVariables.P_obs(1:end-1)-P_obs(2:end)'))>1e-3 + error('Smoothed Variables are wrong') +end + +if abs(corr(oo_.FilteredVariables.Y_obs(2:end-1)-Y_obs(3:end)',oo_.FilteredVariables.Y_obs(1:end-2)-Y_obs(2:end-1)'))>2e-2 ||... + abs(corr(oo_.FilteredVariables.P_obs(2:end-1)-P_obs(3:end)',oo_.FilteredVariables.P_obs(1:end-2)-P_obs(2:end-1)'))>2e-1 ||... + abs(corr(oo_.FilteredVariables.junk2(2:end-1)-junk2(3:end)',oo_.FilteredVariables.junk2(1:end-2)-junk2(2:end-1)'))>2e-2 + error('Filtered Variables are wrong') +end + +if max(abs(squeeze(oo_.FilteredVariablesKStepAhead(1,1,2:end-(options_.nk-1)))-oo_.FilteredVariables.Y_obs))>1e-5 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(1,2,2:end-(options_.nk-1)))-oo_.FilteredVariables.P_obs))>1e-5 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(1,3,2:end-(options_.nk-1)))-oo_.FilteredVariables.junk2))>1e-5 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(2,1,3:end-options_.nk))-oo_.FilteredVariables.Y_obs(3:end)))>1e-2 ||... + max(abs(squeeze(oo_.FilteredVariablesKStepAhead(2,2,3:end-options_.nk))-oo_.FilteredVariables.P_obs(3:end)))>1e-2 ||... + mean(squeeze(oo_.FilteredVariablesKStepAhead(2,3,3:end-options_.nk)))>1e-1 ||... + mean(squeeze(oo_.FilteredVariablesKStepAhead(2,4,3:end-options_.nk)))>1e-1 + error('FilteredVariablesKStepAhead is wrong') +end + +if abs(mean(oo_.SmoothedShocks.e_y))>0.05 || abs(mean(oo_.SmoothedShocks.e_p))>0.05 + error('Residuals are not mean 0') +end \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/Trend_exp_model_calib_no_prefilter_common.inc b/tests/observation_trends_and_prefiltering/Trend_exp_model_calib_no_prefilter_common.inc new file mode 100644 index 000000000..9deccb509 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_exp_model_calib_no_prefilter_common.inc @@ -0,0 +1,43 @@ +var Y_obs P_obs junk1 junk2; +varexo e_y e_p eps_junk; + +parameters rho_y rho_p g_y g_p const_y const_p sigma_y sigma_p; + +rho_y=0.5; +rho_p=0.5; +g_y=0.0001; +g_p=-0.0001; +const_y=2; +const_p=2; +sigma_y=0.001; +sigma_p=0.001; + +model; +Y_obs = exp(const_y)^(1-rho_y)*Y_obs(-1)^rho_y*exp(sigma_y*e_y); +P_obs = exp(const_p)^(1-rho_p)*P_obs(-1)^rho_p*exp(sigma_p*e_p); +junk1 = (junk1(+1))^0.9; +junk2 = (junk2(-1))^0.9*exp(eps_junk); +end; + +steady_state_model; +Y_obs = exp(const_y); +P_obs = exp(const_p); +junk1=1; +junk2=1; +end; + +shocks; +var e_p; stderr 1; +var e_y; stderr 1; +var eps_junk; stderr 1; +end; + +steady(nocheck); +check; + +varobs P_obs Y_obs junk2; + +observation_trends; +P_obs (g_p); +Y_obs (g_y); +end; diff --git a/tests/observation_trends_and_prefiltering/Trend_exp_model_calib_prefilter_common.inc b/tests/observation_trends_and_prefiltering/Trend_exp_model_calib_prefilter_common.inc new file mode 100644 index 000000000..cb7cd7c6c --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_exp_model_calib_prefilter_common.inc @@ -0,0 +1,41 @@ +var Y_obs P_obs junk1 junk2; +varexo e_y e_p eps_junk; + +parameters rho_y rho_p g_y g_p sigma_y sigma_p; + +rho_y=0.5; +rho_p=0.5; +g_y=0.0001; +g_p=-0.0001; +sigma_y=0.001; +sigma_p=0.001; + +model; +Y_obs = Y_obs(-1)^rho_y*exp(sigma_y*e_y); +P_obs = P_obs(-1)^rho_p*exp(sigma_p*e_p); +junk1 = (junk1(+1))^0.9; +junk2 = (junk2(-1))^0.9*exp(eps_junk); +end; + +steady_state_model; +Y_obs = 1; +P_obs = 1; +junk1=1; +junk2=1; +end; + +shocks; +var e_p; stderr 1; +var e_y; stderr 1; +var eps_junk; stderr 1; +end; + +steady(nocheck); +check; + +varobs P_obs Y_obs junk2; + +observation_trends; +P_obs (g_p); +Y_obs (g_y); +end; diff --git a/tests/observation_trends_and_prefiltering/Trend_exp_model_no_prefilter_common.inc b/tests/observation_trends_and_prefiltering/Trend_exp_model_no_prefilter_common.inc new file mode 100644 index 000000000..0b00f643e --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_exp_model_no_prefilter_common.inc @@ -0,0 +1,62 @@ +var Y_obs P_obs junk1 junk2; +varexo e_y e_p eps_junk; + +parameters rho_y rho_p g_y g_p const_y const_p sigma_y sigma_p; + +rho_y=0.5; +rho_p=0.5; +g_y=0.0001; +g_p=-0.0001; +const_y=2; +const_p=2; +sigma_y=0.001; +sigma_p=0.001; + +model; +Y_obs = exp(const_y)^(1-rho_y)*Y_obs(-1)^rho_y*exp(sigma_y*e_y); +P_obs = exp(const_p)^(1-rho_p)*P_obs(-1)^rho_p*exp(sigma_p*e_p); +junk1 = (junk1(+1))^0.9; +junk2 = (junk2(-1))^0.9*exp(eps_junk); +end; + +steady_state_model; +Y_obs = exp(const_y); +P_obs = exp(const_p); +junk1=1; +junk2=1; +end; + +shocks; +var e_p; stderr 1; +var e_y; stderr 1; +var eps_junk; stderr 1; +end; + +steady(nocheck); +check; + +estimated_params; +const_y, normal_pdf, 2, 1; +const_p, normal_pdf, 2, 1; +g_y, normal_pdf, 0.0001, 1; +g_p, normal_pdf, -0.0001, 1; +rho_y, normal_pdf, 0.5, 1; +rho_p, normal_pdf, 0.5, 1; +sigma_y, inv_gamma_pdf, 0.001, inf; +sigma_p, inv_gamma_pdf, 0.001, inf; +end; + +estimated_params_init(use_calibration); +end; + +varobs P_obs Y_obs junk2; + +observation_trends; +P_obs (g_p); +Y_obs (g_y); +end; + +// estimated_params_init(use_calibration); +// end; + +options_.plot_priors=0; diff --git a/tests/observation_trends_and_prefiltering/Trend_exp_model_prefilter_common.inc b/tests/observation_trends_and_prefiltering/Trend_exp_model_prefilter_common.inc new file mode 100644 index 000000000..d90cd6c2e --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_exp_model_prefilter_common.inc @@ -0,0 +1,59 @@ +var Y_obs P_obs junk1 junk2; +varexo e_y e_p eps_junk; + +parameters rho_y rho_p g_y g_p sigma_y sigma_p; + +rho_y=0.5; +rho_p=0.5; +g_y=0.0001; +g_p=-0.0001; +sigma_y=0.001; +sigma_p=0.001; + + +model; +Y_obs = Y_obs(-1)^rho_y*exp(sigma_y*e_y); +P_obs = P_obs(-1)^rho_p*exp(sigma_p*e_p); +junk1 = (junk1(+1))^0.9; +junk2 = (junk2(-1))^0.9*exp(eps_junk); +end; + +steady_state_model; +Y_obs = 1; +P_obs = 1; +junk1=1; +junk2=1; +end; + +shocks; +var e_p; stderr 1; +var e_y; stderr 1; +var eps_junk; stderr 1; +end; + +steady(nocheck); +check; + +estimated_params; +g_y, normal_pdf, 0.0001, 1; +g_p, normal_pdf, -0.0001, 1; +rho_y, normal_pdf, 0.5, 1; +rho_p, normal_pdf, 0.5, 1; +sigma_y, inv_gamma_pdf, 0.001, inf; +sigma_p, inv_gamma_pdf, 0.001, inf; +end; + +estimated_params_init(use_calibration); +end; + +varobs P_obs Y_obs junk2; + +observation_trends; +P_obs (g_p); +Y_obs (g_y); +end; + +// estimated_params_init(use_calibration); +// end; + +options_.plot_priors=0; diff --git a/tests/observation_trends_and_prefiltering/Trend_load_data_common.inc b/tests/observation_trends_and_prefiltering/Trend_load_data_common.inc new file mode 100644 index 000000000..b327d53b3 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_load_data_common.inc @@ -0,0 +1,11 @@ +verbatim; +if options_.loglinear +Y_obs=log(Y_obs(options_.first_obs:end)); +P_obs=log(P_obs(options_.first_obs:end)); +junk2=log(junk2(options_.first_obs:end)); +else +Y_obs=Y_obs(options_.first_obs:end); +P_obs=P_obs(options_.first_obs:end); +junk2=junk2(options_.first_obs:end); +end +end; diff --git a/tests/observation_trends_and_prefiltering/Trend_model_calib_no_prefilter_common.inc b/tests/observation_trends_and_prefiltering/Trend_model_calib_no_prefilter_common.inc new file mode 100644 index 000000000..423266e64 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_model_calib_no_prefilter_common.inc @@ -0,0 +1,43 @@ +var Y_obs P_obs junk1 junk2; +varexo e_y e_p eps_junk; + +parameters rho_y rho_p g_y g_p const_y const_p sigma_y sigma_p; + +rho_y=0.5; +rho_p=0.5; +g_y=0.0001; +g_p=-0.0001; +const_y=2; +const_p=2; +sigma_y=0.001; +sigma_p=0.001; + + +model; +Y_obs = (1-rho_y)*const_y + rho_y*Y_obs(-1)+sigma_y*e_y; +P_obs = (1-rho_p)*const_p + rho_p*P_obs(-1)+sigma_p*e_p; +junk1 = 0.9*junk1(+1); +junk2 = 0.9*junk2(-1)+eps_junk; +end; + +steady_state_model; +Y_obs = const_y; +P_obs = const_p; +junk1=0; +junk2=0; +end; + +shocks; +var e_p; stderr 1; +var e_y; stderr 1; +var eps_junk; stderr 1; +end; + +steady; + +varobs P_obs Y_obs junk2; + +observation_trends; +P_obs (g_p); +Y_obs (g_y); +end; diff --git a/tests/observation_trends_and_prefiltering/Trend_model_calib_prefilter_common.inc b/tests/observation_trends_and_prefiltering/Trend_model_calib_prefilter_common.inc new file mode 100644 index 000000000..e2365c28a --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_model_calib_prefilter_common.inc @@ -0,0 +1,43 @@ +var Y_obs P_obs junk1 junk2; +varexo e_y e_p eps_junk; + +parameters rho_y rho_p g_y g_p sigma_y sigma_p; + +rho_y=0.5; +rho_p=0.5; +g_y=0.0001; +g_p=-0.0001; +sigma_y=0.001; +sigma_p=0.001; + + +model; +Y_obs = rho_y*Y_obs(-1)+sigma_y*e_y; +P_obs = rho_p*P_obs(-1)+sigma_p*e_p; +junk1 = 0.9*junk1(+1); +junk2 = 0.9*junk2(-1)+eps_junk; + +end; + +steady_state_model; +Y_obs = 0; +P_obs = 0; +junk1=0; +junk2=0; +end; + + +shocks; +var e_p; stderr 1; +var e_y; stderr 1; +var eps_junk; stderr 1; +end; + +steady; + +varobs P_obs Y_obs junk2; + +observation_trends; +P_obs (g_p); +Y_obs (g_y); +end; diff --git a/tests/observation_trends_and_prefiltering/Trend_model_no_prefilter_common.inc b/tests/observation_trends_and_prefiltering/Trend_model_no_prefilter_common.inc new file mode 100644 index 000000000..6f7e8c609 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_model_no_prefilter_common.inc @@ -0,0 +1,58 @@ +var Y_obs P_obs junk1 junk2; +varexo e_y e_p eps_junk; +parameters rho_y rho_p g_y g_p const_y const_p sigma_y sigma_p; + +rho_y=0.5; +rho_p=0.5; +g_y=0.0001; +g_p=-0.0001; +const_y=2; +const_p=2; +sigma_y=0.001; +sigma_p=0.001; + + +model; +Y_obs = (1-rho_y)*const_y + rho_y*Y_obs(-1)+sigma_y*e_y; +P_obs = (1-rho_p)*const_p + rho_p*P_obs(-1)+sigma_p*e_p; +junk1 = 0.9*junk1(+1); +junk2 = 0.9*junk2(-1)+eps_junk; +end; + +steady_state_model; +Y_obs = const_y; +P_obs = const_p; +junk1=0; +junk2=0; +end; + +shocks; +var e_p; stderr 1; +var e_y; stderr 1; +var eps_junk; stderr 1; +end; + +steady; + +estimated_params; +const_y, normal_pdf, 2, 1; +const_p, normal_pdf, 2, 1; +g_y, normal_pdf, 0.0001, 1; +g_p, normal_pdf, -0.0001, 1; +rho_y, normal_pdf, 0.5, 1; +rho_p, normal_pdf, 0.5, 1; +sigma_y, inv_gamma_pdf, 0.001, inf; +sigma_p, inv_gamma_pdf, 0.001, inf; +end; + +varobs P_obs Y_obs junk2; + +observation_trends; +Y_obs (g_y); +P_obs (g_p); +end; + +estimated_params_init(use_calibration); +end; + +options_.plot_priors=0; diff --git a/tests/observation_trends_and_prefiltering/Trend_model_prefilter_common.inc b/tests/observation_trends_and_prefiltering/Trend_model_prefilter_common.inc new file mode 100644 index 000000000..124e6279e --- /dev/null +++ b/tests/observation_trends_and_prefiltering/Trend_model_prefilter_common.inc @@ -0,0 +1,60 @@ +var Y_obs P_obs junk1 junk2; +varexo e_y e_p eps_junk; + +parameters rho_y rho_p g_y g_p sigma_y sigma_p; + +rho_y=0.5; +rho_p=0.5; +g_y=0.0001; +g_p=-0.0001; +sigma_y=0.001; +sigma_p=0.001; + + +model; +Y_obs = rho_y*Y_obs(-1)+sigma_y*e_y; +P_obs = rho_p*P_obs(-1)+sigma_p*e_p; +junk1 = 0.9*junk1(+1); +junk2 = 0.9*junk2(-1)+eps_junk; + +end; + +steady_state_model; +Y_obs = 0; +P_obs = 0; +junk1=0; +junk2=0; +end; + +shocks; +var e_p; stderr 1; +var e_y; stderr 1; +var eps_junk; stderr 1; +end; + +steady(nocheck); +check; + +estimated_params; +g_y, normal_pdf, 0.0001, 1; +g_p, normal_pdf, -0.0001, 1; +rho_y, normal_pdf, 0.5, 1; +rho_p, normal_pdf, 0.5, 1; +sigma_y, inv_gamma_pdf, 0.001, inf; +sigma_p, inv_gamma_pdf, 0.001, inf; +end; + +estimated_params_init(use_calibration); +end; + +varobs P_obs Y_obs junk2; + +observation_trends; +P_obs (g_p); +Y_obs (g_y); +end; + +// estimated_params_init(use_calibration); +// end; + +options_.plot_priors=0; diff --git a/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefil_f_obs_loglin_cal_smoother.mod b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefil_f_obs_loglin_cal_smoother.mod new file mode 100644 index 000000000..121b6c3a9 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefil_f_obs_loglin_cal_smoother.mod @@ -0,0 +1,15 @@ +@#include "../Trend_exp_model_calib_no_prefilter_common.inc" +options_.filter_decomposition=1; + +calib_smoother(datafile='../Exp_AR1_trend_data_with_constant',prefilter=0,loglinear,first_obs=1000, +// filter_decomposition, + filtered_vars, filter_step_ahead = [1,2,4]) P_obs Y_obs junk2; +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameters do not match') +end + +@#include "../Trend_diagnostics_calib_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilt_first_obs_cal_smooth.mod b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilt_first_obs_cal_smooth.mod new file mode 100644 index 000000000..12ca5bcdd --- /dev/null +++ b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilt_first_obs_cal_smooth.mod @@ -0,0 +1,16 @@ +@#include "../Trend_model_calib_no_prefilter_common.inc" +options_.filter_decomposition=1; + +calib_smoother(datafile='../AR1_trend_data_with_constant',prefilter=0,first_obs=1000, +// filter_decomposition, + filtered_vars, filter_step_ahead = [1,2,4]) P_obs Y_obs; + +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameters do not match') +end + +@#include "../Trend_diagnostics_calib_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilter_calib_smoother.mod b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilter_calib_smoother.mod new file mode 100644 index 000000000..261f20476 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilter_calib_smoother.mod @@ -0,0 +1,14 @@ +@#include "../Trend_model_calib_no_prefilter_common.inc" +options_.filter_decomposition=1; +calib_smoother(datafile='../AR1_trend_data_with_constant',prefilter=0, +// filter_decomposition, + filtered_vars, filter_step_ahead = [1,2,4]) P_obs Y_obs; +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameters do not match') +end + +@#include "../Trend_diagnostics_calib_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilter_loglin_calib_smoother.mod b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilter_loglin_calib_smoother.mod new file mode 100644 index 000000000..db0f43279 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_no_prefilter_loglin_calib_smoother.mod @@ -0,0 +1,16 @@ +@#include "../Trend_exp_model_calib_no_prefilter_common.inc" +options_.filter_decomposition=1; + +calib_smoother(datafile='../Exp_AR1_trend_data_with_constant',prefilter=0,loglinear, +// filter_decomposition, + filtered_vars, filter_step_ahead = [1,2,4]) P_obs Y_obs junk2; +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params)./loaded_par.orig_params))>0.03 + error('Parameters do not match') +end + +@#include "../Trend_diagnostics_calib_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefil_f_obs_loglin_cal_smoother.mod b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefil_f_obs_loglin_cal_smoother.mod new file mode 100644 index 000000000..eb6ae5e1c --- /dev/null +++ b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefil_f_obs_loglin_cal_smoother.mod @@ -0,0 +1,15 @@ +@#include "../Trend_exp_model_calib_prefilter_common.inc" +options_.filter_decomposition=1; + +calib_smoother(datafile='../Exp_AR1_trend_data_with_constant',prefilter=1,loglinear,first_obs=1000, +// filter_decomposition, + filtered_vars, filter_step_ahead = [1,2,4]) P_obs Y_obs junk2; +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params([1:4,7:8]))./loaded_par.orig_params([1:4,7:8])))>0.03 + error('Parameters do not match') +end + +@#include "../Trend_diagnostics_calib_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefilt_first_obs_cal_smooth.mod b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefilt_first_obs_cal_smooth.mod new file mode 100644 index 000000000..3444502d5 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefilt_first_obs_cal_smooth.mod @@ -0,0 +1,15 @@ +@#include "../Trend_model_calib_prefilter_common.inc" +options_.filter_decomposition=1; + +calib_smoother(datafile='../AR1_trend_data_with_constant',prefilter=1,first_obs=1000, +// filter_decomposition, + filtered_vars, filter_step_ahead = [1,2,4]) P_obs Y_obs; +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params([1:4,7:8]))./loaded_par.orig_params([1:4,7:8])))>0.03 + error('Parameters do not match') +end + +@#include "../Trend_diagnostics_calib_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefilter_calib_smoother.mod b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefilter_calib_smoother.mod new file mode 100644 index 000000000..46a2d0310 --- /dev/null +++ b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefilter_calib_smoother.mod @@ -0,0 +1,15 @@ +@#include "../Trend_model_calib_prefilter_common.inc" +options_.filter_decomposition=1; + +calib_smoother(datafile='../AR1_trend_data_with_constant',prefilter=1, +// filter_decomposition, + filtered_vars, filter_step_ahead = [1,2,4]) P_obs Y_obs; +load('../AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params([1:4,7:8]))./loaded_par.orig_params([1:4,7:8])))>0.03 + error('Parameters do not match') +end + +@#include "../Trend_diagnostics_calib_common.inc" \ No newline at end of file diff --git a/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefilter_loglin_calib_smoother.mod b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefilter_loglin_calib_smoother.mod new file mode 100644 index 000000000..6ff184f5b --- /dev/null +++ b/tests/observation_trends_and_prefiltering/calib_smoother/Tr_prefilter_loglin_calib_smoother.mod @@ -0,0 +1,15 @@ +@#include "../Trend_exp_model_calib_prefilter_common.inc" +options_.filter_decomposition=1; + +calib_smoother(datafile='../Exp_AR1_trend_data_with_constant',prefilter=1,loglinear, +// filter_decomposition, + filtered_vars, filter_step_ahead = [1,2,4]) P_obs Y_obs junk2; +load('../Exp_AR1_trend_data_with_constant'); +@#include "../Trend_load_data_common.inc" + +loaded_par=load('../orig_params'); +if max(abs((M_.params-loaded_par.orig_params([1:4,7:8]))./loaded_par.orig_params([1:4,7:8])))>0.03 + error('Parameters do not match') +end + +@#include "../Trend_diagnostics_calib_common.inc" \ No newline at end of file diff --git a/windows/dynare.nsi b/windows/dynare.nsi index 7d59808e6..0e1d628c6 100644 --- a/windows/dynare.nsi +++ b/windows/dynare.nsi @@ -88,9 +88,9 @@ SectionEnd SectionGroup "MEX files for MATLAB" -Section "MEX files for MATLAB 32-bit, version 7.5 to 8.5 (R2007b to R2015a)" - SetOutPath $INSTDIR\mex\matlab\win32-7.5-8.5 - File ..\mex\matlab\win32-7.5-8.5\*.mexw32 +Section "MEX files for MATLAB 32-bit, version 7.5 to 8.6 (R2007b to R2015b)" + SetOutPath $INSTDIR\mex\matlab\win32-7.5-8.6 + File ..\mex\matlab\win32-7.5-8.6\*.mexw32 SectionEnd Section "MEX files for MATLAB 64-bit, version 7.5 to 7.7 (R2007b to R2008b)" @@ -98,9 +98,9 @@ Section "MEX files for MATLAB 64-bit, version 7.5 to 7.7 (R2007b to R2008b)" File ..\mex\matlab\win64-7.5-7.7\*.mexw64 SectionEnd -Section "MEX files for MATLAB 64-bit, version 7.8 to 8.5 (R2009a to R2015a)" - SetOutPath $INSTDIR\mex\matlab\win64-7.8-8.5 - File ..\mex\matlab\win64-7.8-8.5\*.mexw64 +Section "MEX files for MATLAB 64-bit, version 7.8 to 8.6 (R2009a to R2015b)" + SetOutPath $INSTDIR\mex\matlab\win64-7.8-8.6 + File ..\mex\matlab\win64-7.8-8.6\*.mexw64 SectionEnd SectionGroupEnd