Merge branch 'master' into new_ep

time-shift
Michel Juillard 2015-07-21 09:30:58 +02:00
commit 9b8077fc28
282 changed files with 11073 additions and 6573 deletions

3
.gitignore vendored
View File

@ -33,6 +33,9 @@ install-sh
ylwrap
ar-lib
# checksum associated with fast option
checksum
# Make Check Rules
*.trs

7
.gitmodules vendored
View File

@ -13,14 +13,17 @@
[submodule "matlab/utilities/tests"]
path = matlab/utilities/tests
url = https://github.com/DynareTeam/m-unit-tests.git
[submodule "matlab/particles"]
path = matlab/particles
url = https://github.com/DynareTeam/particles.git
[submodule "matlab/modules/dates"]
path = matlab/modules/dates
url = https://github.com/DynareTeam/dates.git
branch = old-oop-syntax
branch = old-oop-style
[submodule "matlab/modules/dseries"]
path = matlab/modules/dseries
url = https://github.com/DynareTeam/dseries.git
branch = old-oop-style
[submodule "matlab/modules/reporting"]
path = matlab/modules/reporting
url = https://github.com/DynareTeam/reporting.git
url = https://github.com/DynareTeam/reporting.git

114
README.md
View File

@ -176,110 +176,28 @@ Alternatively, if you want to build everything, manually install the following p
## Windows
The following instructions are compatible with MATLAB or with Octave/MinGW (as downloadable [here](http://www.dynare.org/download/octave)).
### Setting up the Compilation Environment
- First, you need to setup a Cygwin environment, following the instructions at <http://www.cygwin.com>. You can install either the 32-bit or the 64-bit version. If you opt for the latter, you need to replace `c:\cygwin` by `c:\cygwin64` in the following.
- Install the following packages:
- `make`
- `bison`
- `flex`
- `git`, `gettext`
- `autoconf`
- `automake`
- `texi2html`
- `texlive`, `texlive-collection-latexextra`, `texlive-collection-formatsextra`, `texlive-collection-publishers`, `texlive-collection-fontsrecommended`, `texlive-collection-fontsextra`, `texlive-collection-bibtexextra`, `texlive-collection-genericrecommended`, `texlive-collection-mathextra`, `texlive-collection-binextra`
- `texinfo`
- `doxygen`
- `mingw64-i686-gcc-core`, `mingw64-i686-gcc-g++`, `mingw64-i686-gcc-fortran` (if you have Octave/MinGW or if you have MATLAB 32-bit)
- `mingw64-x86_64-gcc-core`, `mingw64-x86_64-gcc-g++`, `mingw64-x86_64-gcc-fortran` (if you have MATLAB 64-bit)
- Second, install precompiled librairies for BLAS, LAPACK, Boost and GSL:
- If you have Octave or MATLAB 32-bit, download [dynare-mingw32-libs.zip](http://www.dynare.org/build/dynare-mingw32-libs.zip), and uncompress it in `c:\cygwin\usr\local\lib\mingw32`
- If you have MATLAB 64-bit, download [dynare-mingw64-libs.zip](http://www.dynare.org/build/dynare-mingw64-libs.zip), and uncompress it in `c:\cygwin\usr\local\lib\mingw64`
*Remark*: You need to make sure that Cygwins git is used and not a potentially installed msysgit. The latter typically happens when one installs msysgit and allows it to set a system path. This will result in wrong line endings and cryptic error messages à la "syntax error near unexpected token `fi'". In that case it might be necessary to uninstall msysgit and reinstall it without setting a system path.
### Compiling the preprocessor, Dynare++, the MEX for MATLAB and the documentation
Install the Dynare source tree, lets say in `c:\cygwin\home\user\dynare` (by either uncompressing a source archive, or by cloning the git repository with `git clone --recursive http://github.com/DynareTeam/dynare.git`).
Launch a Cygwin shell, and enter the Dynare source tree:
```
cd dynare
```
If you retrieved the source from Git, don't forget to do:
```
autoreconf -i -s
```
Then, configure the package.
- If your MATLAB is 32-bit, let's say version R2008b installed in `c:\Program Files\MATLAB\R2008b`
```
./configure --host=i686-w64-mingw32 --with-boost=/usr/local/lib/mingw32/boost --with-blas=/usr/local/lib/mingw32/blas/libopenblas.a --with-lapack=/usr/local/lib/mingw32/lapack/liblapack.a --with-gsl=/usr/local/lib/mingw32/gsl --with-matio=/usr/local/lib/mingw32/matio --with-slicot=/usr/local/lib/mingw32/slicot --with-matlab=/cygdrive/c/Progra~1/MATLAB/R2008b MATLAB_VERSION=R2008b --disable-octave
```
- If your MATLAB is 64-bit:
```
./configure --host=x86_64-w64-mingw32 --with-boost=/usr/local/lib/mingw64/boost --with-blas=/usr/local/lib/mingw64/blas/libopenblas.a --with-lapack=/usr/local/lib/mingw64/lapack/liblapack.a --with-gsl=/usr/local/lib/mingw64/gsl --with-matio=/usr/local/lib/mingw64/matio --with-slicot=/usr/local/lib/mingw64/slicot --with-matlab=/cygdrive/c/Progra~1/MATLAB/R2008b MATLAB_VERSION=R2008b --disable-octave
```
A few remarks:
- Note that here we use `Progra~1` (the 8.3 filename) instead of `Program Files`. This is because spaces in filenames confuse the configuration scripts.
- If you dont have MATLAB, then drop the `--with-matlab` and `MATLAB_VERSION` options
- If your MATLAB is 32-bit and your Windows is 64-bit, you need to explicitly give the MEX extension, with `MEXEXT=mexw32`
Then compile everything with:
```
make all pdf html
```
This should build:
- Dynare preprocessor
- Dynare MEX files for MATLAB (provided you gave the MATLAB path to configure)
- Dynare++
- Part of the documentation
### Compiling the MEX for Octave (MinGW package)
Launch a Cygwin shell, and enter the Dynare source tree for Octave MEX:
cd dynare/mex/build/octave
Configure and make:
./configure MKOCTFILE=/usr/local/lib/mingw32/mkoctfile-win --with-boost=/usr/local/lib/mingw32/boost --with-gsl=/usr/local/lib/mingw32/gsl --with-matio=/usr/local/lib/mingw32/matio --with-slicot=/usr/local/lib/mingw32/slicot-underscore
make
We no longer support compilation on Windows. To use the unstable version of Dynare on a Windows system, please download it from the [Dynare website](http://www.dynare.org/download/dynare-unstable).
## Mac OS X
- Install the Xcode Command Line Tools:
- Download "Command Line Tools (OS X 10.X) for Xcode," where 10.X corresponds to your OS X version, from https://developer.apple.com/downloads/index.action
- Install the latest version of [MacTeX](http://www.tug.org/mactex/)
- Install [Homebrew](http://mxcl.github.io/homebrew/) by following the instructions on the website
- Tap [Homebrew Science](https://github.com/Homebrew/homebrew-science) by opening Terminal and typing:
- ```brew tap homebrew/science```
- Install the following brews:
- ```brew install gcc```
- ```brew install automake```
- ```brew install gsl```
- ```brew install bison```
- ```brew install boost```
- ```brew install libmatio --with-hdf5```
- ```brew install slicot --with-default-integer-8```
- Force link ```flex``` and ```bison```
- ```brew link --force flex```
- ```brew link --force bison```
- ```brew tap homebrew/science```
- **(Optional)** To compile Dynare mex files for use on Octave:
- ```brew install octave```
- **(Optional)** To compile Dynare's documentation, first install the latest version of [MacTeX](http://www.tug.org/mactex/). Then install `doxygen`, `latex2html` and `texi2html` via Homebrew with the following commands:
- ```brew install doxygen```
- ```brew install texinfo```
- ```brew install latex2html```
- ```brew install texi2html```
- **(On OS X 10.7 Only)** Copy [FlexLexer.h](http://www.dynare.org/build/FlexLexer.h) into the `preprocessor` directory (there was an error in the `FlexLexer.h` file distributed with 10.7)
- Ensure `/usr/local/bin` is at the beginning of your path:
- ```PATH=/usr/local/bin:$PATH```
- Finally, switch to the root dynare directory and compile dynare
- `autoreconf -si`
- `./configure --with-matlab=/Applications/MATLAB_R2014b.app MATLAB_VERSION=8.4`
- `make`
- `make pdf TEXI2DVI=/usr/local/Cellar/texinfo/5.2/bin/texi2dvi`, where you replace everything after the equal sign with the path to the `texi2dvi` installed by homebrew when you installed `texinfo`.
- To see the available options for compiling Dynare, type:
- ```brew info dynare```
- Install Dynare via a command of the form:
- (basic) ```brew install dynare --HEAD --without-check```
- (with Matlab mex) ```brew install dynare --HEAD --without-check --with-matlab=/Applications/MATLAB_R2015a.app --with-matlab-version=8.5```
- **NB**: If compiling Dynare documentation, add ```--with-doc``` to the installation command
- **NB**: If not compiling Dynare mex files for Octave, add ```--without-octave``` to the installation command
- **NB**: To compile the latest stable version of dynare, follow the same instructions as above, omitting the ```--HEAD``` argument
- **NB**: To update a ```--HEAD``` install of dynare you need to uninstall it then install it again: ```brew uninstall dynare; brew install dynare --HEAD```.
- **NB**: If you want to maintain a separate git directory of dynare, you can do a ```--HEAD``` install of dynare, then uninstall it. This will have the effect of bringing in all the dependencies you will need to then compile dynare from your git directory. Then, change to the git directory and type:
- ```autoreconf -si; ./configure --with-matlab=/Applications/MATLAB_R2015a.app MATLAB_VERSION=R2015a```, adjusting the Matlab path and version to accord with your version
- Once compilation is done, open Matlab and type the last line shown when you type ```brew info dynare``` in the Terminal window. With the typical Homebrew setup, this is:
- ```addpath /usr/local/opt/dynare/lib/dynare/matlab```

View File

@ -24,7 +24,7 @@
{
\begin{frame}
\frametitle{Outline}
\tableofcontents[currentsection]
\tableofcontents[currentsection, hideothersubsections]
\end{frame}
}
@ -34,7 +34,7 @@
\title{Dynare Time Series \& Reporting}
\author[Houtan Bastani]{Houtan Bastani\newline\href{mailto:houtan@dynare.org}{houtan@dynare.org}}
\institute{CEPREMAP}
\date{13 June 2014}
\date{11 June 2015}
\newcommand{\myitem}{\item[$\bullet$]}
@ -70,7 +70,8 @@
\myitem Windows, Mac OS X, Linux
\myitem Matlab 7.5 (R2007b) or later, Octave
\end{itemize}
\myitem NB: More complete information is included in the Dynare manual
\myitem Must run \texttt{dynare} or \texttt{dynare\_config} at least once in the current Matlab/Octave session before use
\myitem More complete information is included in the Dynare manual
\end{itemize}
\end{frame}
@ -85,8 +86,8 @@
\myitem A class is a template for defining objects, defining their member
variables and methods.
\begin{itemize}
\myitem \textit{e.g.,} The \texttt{dates} class defines 3 member
variables--\texttt{ndat}, \texttt{freq}, and \texttt{time}--and many
\myitem \textit{e.g.,} The \texttt{dates} class defines 2 member
variables--\texttt{freq} and \texttt{time}--and many
methods (analogous to functions)
\end{itemize}
\myitem An object is an instance of a specific class. For exemplary
@ -167,14 +168,13 @@ X =
\begin{frame}[fragile,t]
\frametitle{\texttt{dates} Syntax}
\begin{itemize}
\myitem The \texttt{dates} command creates an object that represents at least one date at a given frequency
\myitem The \texttt{dates} command creates an object that represents zero or more dates at a given frequency
\myitem A \texttt{dates} object contains 3 members (fields):
\begin{itemize}
\myitem{\textbf{\texttt{freq}}}: 1, `y' (Annual); 4, `q' (Quarterly); 12, `m' (Monthly); 52, `w' (Weekly)
\myitem{\textbf{\texttt{ndat}}}: The number of dates
\myitem{\textbf{\texttt{time}}}: An \texttt{ndat$\times$2} matrix; the 1\textsuperscript{st} col is the year and the 2\textsuperscript{nd} col is the period
\myitem{\textbf{\texttt{time}}}: A \texttt{<<No of dates>>$\times$2} matrix; the 1\textsuperscript{st} col is the year and the 2\textsuperscript{nd} col is the period
\end{itemize}
\myitem \texttt{dseries} members cannot be modified. Thus, this is not allowed:
\myitem \texttt{dates} members cannot be modified. Thus, this is not allowed
\begin{alltt}
>> dd.freq = 12;
\end{alltt}
@ -239,9 +239,9 @@ would be transformed into
\begin{alltt}
disp(`In dates(`1999q1'), ...')
\end{alltt}
\myitem To fix this, simply escape any date that you don't want transformed by the preprocessor with a `\texttt{\$}'
\myitem To fix this, simply prefix any date that you don't want transformed by the preprocessor with a `\texttt{\$}': \texttt{disp(`In \$1999q1, ...')}
\begin{alltt}
disp(`In $1999q1, ...')
\(\Rightarrow\) disp(`In 1999q1, ...')
\end{alltt}
\end{itemize}
@ -334,7 +334,7 @@ would be transformed into
\myitem \texttt{setdiff}: returns dates present in first arg but not in second
\begin{alltt}
>> setdiff(a, b)
ans = <dates: 1900Y>
ans = <dates: 1990Q1, 1990Q2>
\end{alltt}
\myitem \texttt{union}: returns the union of two sets (repititions removed)
\begin{alltt}
@ -354,7 +354,7 @@ would be transformed into
\begin{frame}[fragile,t]
\frametitle{Misc \texttt{dates} operations}
\begin{itemize}
\myitem Can index a \texttt{dates} object.
\myitem Can index a \texttt{dates} object
\begin{alltt}
>> a = dates(`2000y'):dates(`2009y');
>> a(1)
@ -386,7 +386,7 @@ would be transformed into
\begin{frame}[fragile,t]
\frametitle{\texttt{dseries} Syntax}
\begin{itemize}
\myitem A \texttt{dseries} is composed of one or more individual time series
\myitem A \texttt{dseries} is composed of zero or more individual time series
\myitem All time series in a \texttt{dseries} must have the same frequency
\myitem A \texttt{dseries} runs from the earliest date to the latest date,
with \texttt{NaN}'s inserted to pad the shorter series
@ -435,11 +435,11 @@ would be transformed into
\begin{alltt}
>> ts = dseries(FILENAME);
\end{alltt}
\myitem File format (\texttt{.csv, .xls}): dates in first column (using the standard format:
199Q1 for quarterly data, 1990Y for annual data, \dots) and (optional)
variable names in the first row
\myitem File format (\texttt{.m, .mat}): must define the variables \texttt{INIT\_\_},
\texttt{NAMES\_\_}, and, optionally, \texttt{TEX\_\_}. More info in the
\myitem File format (\texttt{.csv, .xls}): dates (optional) in first column (using the
standard format: 1990Q1 for quarterly data, 1990Y for annual data, \dots) and variable
names (optional) in the first row
\myitem File format (\texttt{.m, .mat}): variables \texttt{INIT\_\_},
\texttt{NAMES\_\_}, and \texttt{TEX\_\_} are optional. More info in the
manual. Data are vectors.
\begin{alltt}
INIT__ = `1999q1';
@ -447,10 +447,10 @@ would be transformed into
cons = randn(100,1);
\end{alltt}
\end{itemize}
Create an empty time series. Usefull for programatically creating a series.
Create an empty time series. Useful for renaming dseries.
\begin{itemize}
\myitem \texttt{ts=dseries();}
\myitem \texttt{ts=dseries(dates(`1999y'));}
\myitem \texttt{tseries = dseries();}
\myitem \texttt{ts = tseries(randn(3,2));}
\end{itemize}
\end{frame}
@ -459,8 +459,11 @@ would be transformed into
\begin{frame}[fragile,t]
\frametitle{Creating subsamples from a \texttt{dseries}}
\begin{itemize}
\myitem Let \texttt{ts} be a \texttt{dseries} with $N$ variables and 5
\myitem Let \texttt{ts} be a \texttt{dseries} with $3$ variables and 5
observations from \texttt{2000Y} to \texttt{2004Y}
\begin{alltt}
ts=dseries(randn(5,3), `2000y')
\end{alltt}
\myitem To obtain a subsample from \texttt{2001Y} to \texttt{2003Y}
\begin{alltt}
ts(2001Y:2003Y)
@ -874,8 +877,8 @@ shocke = dseries();
shocku = dseries();
@#define endovars=["y", "c", "k", "a", "h", "b"]
@#for var in endovars
shocke = [shocke dseries(@{var}_e, 2014q3, '@{var}')];
shocku = [shocku dseries(@{var}_u, 2014q3, '@{var}')];
shocke = [shocke dseries(@{var}_e, 2014q3, `@{var}')];
shocku = [shocku dseries(@{var}_u, 2014q3, `@{var}')];
@#endfor
\end{verbatim}
\end{block}

View File

@ -859,6 +859,12 @@ and the equations haven't changed. We use a 32 bit checksum, stored in
@code{<model filename>/checksum}. There is a very small probability that
the preprocessor misses a change in the model. In case of doubt, re-run
without the @code{fast} option.
@item minimal_workspace
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.
@end table
@outputhead
@ -1910,12 +1916,15 @@ equations using the @code{write_latex_static_model} command.
@descriptionhead
This command creates a @LaTeX{} file containing the model, as defined
in the model block.
This command creates two @LaTeX{} files: one containing the model as
defined in the model block and one containing the @LaTeX{} document
header information.
If your @file{.mod} file is @file{@var{FILENAME}.mod}, then Dynare
will create a file called @file{@var{FILENAME}_dynamic.tex},
containing the list of all the dynamic model equations.
will create a file called @file{@var{FILENAME}_original.tex}, which
includes a file called @file{@var{FILENAME}_original_content.tex}
(also created by Dynare) containing the list of all the original model
equations.
If @LaTeX{} names were given for variables and parameters
(@pxref{Variable declarations}), then those will be used; otherwise,
@ -1924,6 +1933,9 @@ the plain text names will be used.
Time subscripts (@code{t}, @code{t+1}, @code{t-1}, @dots{}) will be
appended to the variable names, as @LaTeX{} subscripts.
Compiling the @TeX{} file requires the following @LaTeX{} packages:
@code{geometry}, @code{fullpage}, @code{breqn}.
@end deffn
@anchor{write_latex_dynamic_model}
@ -1932,11 +1944,14 @@ appended to the variable names, as @LaTeX{} subscripts.
@descriptionhead
This command creates a @LaTeX{} file containing the (dynamic) model.
This command creates two @LaTeX{} files: one containing the dynamic
model and one containing the @LaTeX{} document header information.
If your @file{.mod} file is @file{@var{FILENAME}.mod}, then Dynare
will create a file called @file{@var{FILENAME}_dynamic.tex},
containing the list of all the dynamic model equations.
will create a file called @file{@var{FILENAME}_dynamic.tex}, which
includes a file called @file{@var{FILENAME}_dynamic_content.tex}
(also created by Dynare) containing the list of all the dynamic model
equations.
If @LaTeX{} names were given for variables and parameters
(@pxref{Variable declarations}), then those will be used; otherwise,
@ -1970,8 +1985,7 @@ for a stochastic model, exogenous variables with leads or lags will
also have been replaced by new auxiliary variables and equations.
@end itemize
Compiling the @TeX{} file requires the following @LaTeX{} packages:
@code{geometry}, @code{fullpage}, @code{breqn}.
For the required @LaTeX{} packages, @pxref{write_latex_original_model}.
@end deffn
@ -1979,11 +1993,14 @@ Compiling the @TeX{} file requires the following @LaTeX{} packages:
@descriptionhead
This command creates a @LaTeX{} file containing the static model.
This command creates two @LaTeX{} files: one containing the static
model and one containing the @LaTeX{} document header information.
If your @file{.mod} file is @file{@var{FILENAME}.mod}, then Dynare
will create a file called @file{@var{FILENAME}_static.tex}, containing
the list of all the equations of the steady state model.
will create a file called @file{@var{FILENAME}_static.tex}, which
includes a file called @file{@var{FILENAME}_static_content.tex} (also
created by Dynare) containing the list of all the steady state model
equations.
If @LaTeX{} names were given for variables and parameters
(@pxref{Variable declarations}), then those will be used; otherwise,
@ -1998,8 +2015,7 @@ optional @code{steady_state_model} block (@pxref{steady_state_model});
it will rather output a static version (@i{i.e.} without leads and
lags) of the dynamic model declared in the @code{model} block.
Compiling the @TeX{} file requires the following @LaTeX{} packages:
@code{geometry}, @code{fullpage}, @code{breqn}.
For the required @LaTeX{} packages, @pxref{write_latex_original_model}.
@end deffn
@ -2154,20 +2170,25 @@ commands (@code{stoch_simul}, @code{estimation}@dots{}).
It is not necessary to declare @code{0} as initial value for exogenous
stochastic variables, since it is the only possible value.
This steady state will be used as the initial condition at all the
periods preceeding the first simulation period for the two possible
types of simulations in stochastic mode:
The subsequently computed steady state (not the initial values, use
@ref{histval} or this) will be used as the initial condition at all
the periods preceeding the first simulation period for the three
possible types of simulations in stochastic mode:
@itemize
@item
in @code{stoch_simul}, if the @code{periods} options is specified
@ref{stoch_simul}, if the @code{periods} options is specified
@item
in @code{forecast} (in this case, note that it is still possible to
modify some of these initial values with @code{histval})
@ref{forecast} as the initial point at which the forecasts are computed
@item
@ref{conditional_forecast} as the initial point at which the conditional forecasts are computed
@end itemize
To start simulations at a particular set of starting values that are not a computed steady state, use @ref{histval}.
@optionshead
@table @code
@ -2380,16 +2401,30 @@ before (except when a @code{steady} command doesn't follow an
@customhead{In a stochastic simulation context}
In the context of stochastic simulations, @code{histval} allows setting
the starting point of those simulations in the state space (it does not
affect the starting point for impulse response functions). As for the case of
the starting point of those simulations in the state space. As for the case of
perfect foresight simulations, all not explicitly specified variables are set to 0.
Moreover, as only states enter the recursive policy functions, all values specified for control variables will be ignored.
Moreover, as only states enter the recursive policy functions, all values specified for control variables will be ignored. This can be used
For @ref{Ramsey} policy, it also specifies the values of the endogenous states at
@itemize
@item
in @ref{stoch_simul}, if the @code{periods} options is specified. Note that this only affects the starting point for the simulation, but not for the impulse response functions.
@item
in @ref{forecast} as the initial point at which the forecasts are computed
@item
in @ref{conditional_forecast} as the initial point at which the conditional forecasts are computed
@item
in @ref{Ramsey} policy, where it also specifies the values of the endogenous states at
which the objective function of the planner is computed. Note that the initial values
of the Lagrange multipliers associated with the planner's problem cannot be set
(@pxref{planner_objective_value}).
@end itemize
@examplehead
@example
@ -3474,7 +3509,8 @@ options).
By default, the perfect foresight solver uses a homotopy technique if it cannot
solve the problem. Concretely, it divides the problem into smaller steps by
diminishing the size of shocks and increasing them progressively until the
problem converges. This option tells Dynare to disable that behavior.
problem converges. This option tells Dynare to disable that behavior. Note that
the homotopy is not implemented for purely forward or backward models.
@item markowitz = @var{DOUBLE}
Value of the Markowitz criterion, used to select the pivot. Only used
@ -3496,6 +3532,9 @@ errors are more important with this mixed strategy (user should check
the reported value of the maximum absolute error). Only available with
option @code{stack_solve_algo==0}.
@item linear_approximation
Solves the linearized version of the perfect foresight model. The model must be stationary. Only available with option @code{stack_solve_algo==0}.
@end table
@outputhead
@ -3581,7 +3620,7 @@ solution is computed using the @code{extended_path} command.
@deffn Command stoch_simul [@var{VARIABLE_NAME}@dots{}];
@deffnx Command stoch_simul (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];
@anchor{stoch_simul}
@descriptionhead
@code{stoch_simul} solves a stochastic (@i{i.e.} rational
@ -3656,8 +3695,12 @@ suppresses the plotting of IRFs. Default: @code{40}.
The exogenous variables for which to compute IRFs. Default: all.
@item relative_irf
Requests the computation of normalized IRFs in percentage of the
standard error of each shock.
@anchor{relative_irf}
Requests the computation of normalized IRFs. At first order, the normal shock vector of size one standard deviation is divided by the standard deviation of the current shock and multiplied by 100. The impulse responses are hence the responses to a unit shock of size 1 (as opposed to the regular shock size of one standard deviation), multiplied by 100. Thus, for a loglinearized model where the variables are measured in percent, the IRFs have the interpretation of the percent responses to a 100 percent shock. For example, a response of 400 of output to a TFP shock shows that output increases by 400 percent after a 100 percent TFP shock (you will see that TFP increases by 100 on impact). Given linearity at @code{ordeR=1}, it is straightforward to rescale the IRFs stored in @code{oo_.irfs} to any desired size.
At higher order, the interpretation is different. The @code{relative_irf} option then triggers the generation of IRFs as the response to a 0.01 unit shock (corresponding to 1 percent for shocks measured in percent) and no multiplication with 100 is performed. That is, the normal shock vector of size one standard deviation is divided by the standard deviation of the current shock and divided by 100.
For example, a response of 0.04 of log output (thus measured in percent of the steady state output level) to a TFP shock also measured in percent then shows that output increases by 4 percent after a 1 percent TFP shock (you will see that TFP increases by 0.01 on impact).
@item irf_plot_threshold = @var{DOUBLE}
@anchor{irf_plot_threshold}
@ -3861,6 +3904,16 @@ steady states. @code{stoch_simul} will display the moments, decision rules,
and impulse responses for the log-linearized variables. The decision rules saved
in @code{oo_.dr} and the simulated variables will also be the ones for the log-linear variables.
@item tex
@anchor{tex} Requests the printing of results and graphs in @TeX{}
tables and graphics that can be later directly included in @LaTeX{}
files.
@item dr_display_tol = @var{DOUBLE}
Tolerance for the suppression of small terms in the display of decision rules. Rows where all terms are
smaller than @code{dr_display_tol} are not displayed.
Default value: @code{1e-6}.
@end table
@outputhead
@ -4694,8 +4747,8 @@ The range with the data in an Excel file. For example, @code{xls_range=B2:D200}
@item nobs = @var{INTEGER}
@anchor{nobs}
The number of observations to be used. Default: all observations in
the file
The number of observations following @ref{first_obs} to be used. Default: all observations in
the file after @code{first_obs}
@item nobs = [@var{INTEGER1}:@var{INTEGER2}]
@anchor{nobs1}
@ -4706,7 +4759,8 @@ also be specified. The forecasts are stored in the
@item first_obs = @var{INTEGER}
@anchor{first_obs}
The number of the first observation to be used. Default: @code{1}
The number of the first observation to be used. In case of estimating a DSGE-VAR,
@code{first_obs} needs to be larger than the number of lags. Default: @code{1}
@item prefilter = @var{INTEGER}
@anchor{prefilter}
@ -4715,14 +4769,16 @@ each data series by its empirical mean. Default: @code{0}, @i{i.e.} no prefilter
@item presample = @var{INTEGER}
@anchor{presample}
The number of observations to be skipped before evaluating the
likelihood. These first observations are used as a training sample. Default: @code{0}
The number of observations after @ref{first_obs} to be skipped before evaluating the
likelihood. These presample observations do not enter the likelihood, but are used as a
training sample for starting the Kalman filter iterations. This option is incompatible with
estimating a DSGE-VAR. Default: @code{0}
@item loglinear
@anchor{loglinear}
Computes a log-linear approximation of the model instead of a linear
approximation. As always in the context of estimation, the data must correspond to the definition of the
variables used in the model (see @cite{Pfeifer 2013} for more details on how to correctly specify observation equations linking model variables and the data). If you specify the loglinear option, Dynare will take the logarithm of both your model variables and of your data as it assumes the data to correspond to the original non-logged model variables. The displayed posterior results like impulse responses, smoothed variables, and moments will be for the logged variables, not the original un-logged ones. Default: computes a linear approximation
variables used in the model (see @cite{Pfeifer (2013)} for more details on how to correctly specify observation equations linking model variables and the data). If you specify the loglinear option, Dynare will take the logarithm of both your model variables and of your data as it assumes the data to correspond to the original non-logged model variables. The displayed posterior results like impulse responses, smoothed variables, and moments will be for the logged variables, not the original un-logged ones. Default: computes a linear approximation
@item logdata
@anchor{logdata}
@ -4785,7 +4841,7 @@ Default value is @code{1}. For advanced use only.
For internal use and testing only.
@item conf_sig = @var{DOUBLE}
Confidence interval used for classical forecasting after estimation. See @xref{conf_sig}.
Confidence interval used for classical forecasting after estimation. @xref{conf_sig}.
@item mh_conf_sig = @var{DOUBLE}
@anchor{mh_conf_sig}
@ -4917,6 +4973,9 @@ Uses the CMA-ES (Covariance Matrix Adaptation Evolution Strategy) algorithm of
Uses the simpsa algorithm, based on the combination of the non-linear simplex and simulated annealing algorithms and proposed by
@cite{Cardoso, Salcedo and Feyo de Azevedo (1996)}.
@item 11
This is not strictly speaking an optimization algorithm. The (estimated) parameters are treated as state variables and estimated jointly with the original state variables of the model using a nonlinear filter. The algorithm implemented in Dynare is described in @cite{Liu and West (2001)}.
@item 101
Uses the SolveOpt algorithm for local nonlinear optimization problems proposed by
@cite{Kuntsevich and Kappel (1997)}.
@ -4934,6 +4993,11 @@ value of that function as the posterior mode.
@noindent
Default value is @code{4}.
@item silent_optimizer
@anchor{silent_optimizer}
Instructs Dynare to run mode computing/optimization silently without displaying results or
saving files in between. Useful when running loops.
@item mcmc_jumping_covariance = hessian|prior_variance|identity_matrix|@var{FILENAME}
Tells Dynare which covariance to use for the proposal density of the MCMC sampler. @code{mcmc_jumping_covariance} can be one of the following:
@ -4957,7 +5021,10 @@ Note that the covariance matrices are still scaled with @ref{mh_jscale}. Default
@item mode_check
Tells Dynare to plot the posterior density for values around the
computed mode for each estimated parameter in turn. This is helpful to
diagnose problems with the optimizer
diagnose problems with the optimizer. Note that for @code{order}>1, the
likelihood function resulting from the particle filter is not differentiable
anymore due to random chatter introduced by selecting different particles for
different parameter values. For this reason, the @code{mode_check}-plot may look wiggly.
@item mode_check_neighbourhood_size = @var{DOUBLE}
Used in conjunction with option @code{mode_check}, gives the width of
@ -4983,6 +5050,10 @@ Number of points around the posterior mode where the posterior kernel is evaluat
density that is ignored when computing bounds for the
parameters. Default: @code{1e-32}
@item huge_number = @var{DOUBLE}
@anchor{huge_number} Value for replacing infinite values in the definition of (prior) bounds
when finite values are required for computational reasons. Default: @code{1e7}
@item load_mh_file
@anchor{load_mh_file} Tells Dynare to add to previous
Metropolis-Hastings simulations instead of starting from
@ -5055,6 +5126,12 @@ Size of the perturbation used to compute numerically the gradient of the objecti
@item 'TolFun'
Stopping criteria. Default: @code{1e-7}
@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}
@item 'SaveFiles'
Controls saving of intermediate results during optimization. Set to 0 to shut off saving. Default: @code{1}
@end table
@item 5
@ -5074,6 +5151,12 @@ Maximum number of iterations. Default: @code{1000}
@item 'TolFun'
Stopping criteria. Default: @code{1e-5} for numerical derivatives @code{1e-7} for analytic derivatives.
@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}
@item 'SaveFiles'
Controls saving of intermediate results during optimization. Set to 0 to shut off saving. Default: @code{1}
@end table
@item 6
@ -5124,6 +5207,9 @@ Tolerance parameter (w.r.t the objective function). Default: @code{1e-4}
@item 'TolX'
Tolerance parameter (w.r.t the instruments). Default: @code{1e-4}
@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}
@end table
@item 9
@ -5143,6 +5229,12 @@ Tolerance parameter (w.r.t the objective function). Default: @code{1e-7}
@item 'TolX'
Tolerance parameter (w.r.t the instruments). Default: @code{1e-7}
@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}
@item 'SaveFiles'
Controls saving of intermediate results during optimization. Set to 0 to shut off saving. Default: @code{1}
@end table
@item 10
@ -5165,6 +5257,9 @@ Tolerance parameter (w.r.t the objective function). Default: @code{1e-4}
@item 'TolX'
Tolerance parameter (w.r.t the instruments). Default: @code{1e-4}
@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}
@end table
@item 101
@ -5187,6 +5282,9 @@ Tolerance parameter (w.r.t the objective function). Default: @code{1e-6}
@item 'TolX'
Tolerance parameter (w.r.t the instruments). Default: @code{1e-6}
@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}
@end table
@item 102
@ -5210,6 +5308,9 @@ distribution of IRFs. The length of the IRFs are controlled by the
@code{irf} option. Results are stored in @code{oo_.PosteriorIRF.dsge}
(see below for a description of this variable)
@item relative_irf
@xref{relative_irf}.
@item dsge_var = @var{DOUBLE}
@anchor{dsge_var} Triggers the estimation of a DSGE-VAR model, where the
weight of the DSGE prior of the VAR model is calibrated to the value
@ -5231,6 +5332,32 @@ deprecated and will be removed in a future release of Dynare.
@anchor{dsge_varlag} The number of lags used to estimate a DSGE-VAR
model. Default: @code{4}.
@item use_tarb
Instructs Dynare to use the Tailored randomized block (TaRB) Metropolis-Hastings algorithm
proposed by @cite{Chib and Ramamurthy (2010)} instead of the standard Random-Walk Metropolis-Hastings.
In this algorithm, at each iteration the estimated parameters are randomly assigned to different
blocks. For each of these blocks a mode-finding step is conducted. The inverse Hessian at this mode
is then used as the covariance of the proposal density for a Random-Walk Metropolis-Hastings step.
If the numerical Hessian is not positive definite, the generalized Cholesky decomposition of
@cite{Schnabel and Eskow (1990)} is used, but without pivoting. The TaRB-MH algorithm massively reduces
the autocorrelation in the MH draws and thus reduces the number of draws required to
representatively sample from the posterior. However, this comes at a computational costs as the
algorithm takes more time to run.
@item tarb_new_block_probability = @var{DOUBLE}
Specifies the probability of the next parameter belonging to a new block when the random blocking in the TaRB
Metropolis-Hastings algorithm is conducted. The higher this number, the smaller is the average block size and the
more random blocks are formed during each parameter sweep. Default: @code{0.25}.
@item tarb_mode_compute = @var{INTEGER}
Specifies the mode-finder run in every iteration for every block of the
TaRB Metropolis-Hastings algorithm. @xref{mode_compute}. Default: @code{4}.
@item tarb_optim = @var{INTEGER}
Specifies the options for the mode-finder used in the TaRB
Metropolis-Hastings algorithm. @xref{optim}.
@item moments_varendo
@anchor{moments_varendo} Triggers the computation of the posterior
distribution of the theoretical moments of the endogenous
@ -5281,9 +5408,7 @@ distribution of forecasts is stored in variables
these variables.
@item tex
@anchor{tex} Requests the printing of results and graphs in @TeX{}
tables and graphics that can be later directly included in @LaTeX{}
files (not yet implemented)
@pxref{tex}.
@item kalman_algo = @var{INTEGER}
@anchor{kalman_algo}
@ -5339,6 +5464,7 @@ decomposition of the above k-step ahead filtered values. Stores results in @code
@item diffuse_filter
@anchor{diffuse_filter}
Uses the diffuse Kalman filter (as described in
@cite{Durbin and Koopman (2012)} and @cite{Koopman and Durbin
(2003)}) to estimate models with non-stationary observed variables.
@ -6227,7 +6353,7 @@ Fields are of the form:
@deffn Command conditional_forecast (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];
@anchor{conditional_forecast}
@descriptionhead
This command computes forecasts on an estimated or calibrated model for a
@ -6344,6 +6470,15 @@ Variable set by the @code{conditional_forecast} command. Stores the names of the
Variable set by the @code{conditional_forecast} command. Stores the position of the constrained endogenous variables in declaration order.
@end defvr
@defvr {MATLAB/Octave variable} forecasts.controlled_exo_variables
Variable set by the @code{conditional_forecast} command. Stores the values of the controlled exogenous
variables underlying the conditional forecasts to achieve the constrained endogenous
variables. Fields are number of constrained periods by 1 vectors and are of the form:
@example
@code{forecasts.controlled_exo_variables.@var{FORECAST_MOMENT}.@var{SHOCK_NAME}}
@end example
@end defvr
@defvr {MATLAB/Octave variable} forecasts.graphs
Variable set by the @code{conditional_forecast} command. Stores the information for generating the conditional forecast plots.
@end defvr
@ -6383,8 +6518,12 @@ Describes the path of constrained endogenous, before calling
shocks in @code{shocks}, see @code{conditional_forecast} for an
example.
The syntax of the block is the same than the deterministic shocks in
the @code{shocks} blocks (@pxref{Shocks on exogenous variables}).
The syntax of the block is the same as for the deterministic shocks in
the @code{shocks} blocks (@pxref{Shocks on exogenous variables}). Note that you need to specify the full path for all constrained endogenous
variables between the first and last specified period. If an intermediate period
is not specified, a value of 0 is assumed. That is, if you specify only
values for periods 1 and 3, the values for period 2 will be 0. Currently, it is not
possible to have uncontrolled intermediate periods.
@end deffn
@ -6646,6 +6785,13 @@ Specifies the optimizer for minimizing the objective function. The same solvers
@item optim = (@var{NAME}, @var{VALUE}, ...)
A list of @var{NAME} and @var{VALUE} pairs. Can be used to set options for the optimization routines. The set of available options depends on the selected optimization routine (i.e. on the value of option @ref{opt_algo}). @xref{optim}.
@item silent_optimizer
@pxref{silent_optimizer}
@item huge_number = @var{DOUBLE}
Value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons (@pxref{huge_number}).
Users need to make sure that the optimal parameters are not larger than this value. Default: @code{1e7}
@end table
The value of the objective is stored in the variable
@ -6798,6 +6944,24 @@ instrument.
@end deffn
@deffn Block ramsey_constraints
@anchor{ramsey_constraints}
@descriptionhead
This block lets you define constraints on the variables in the Ramsey
problem. The constraints take the form of a variable, an inequality
operator (@code{>} or @code{<}) and a constant.
@examplehead
@example
ramsey_constraints;
i > 0;
end;
@end example
@end deffn
@deffn Command ramsey_policy [@var{VARIABLE_NAME}@dots{}];
@deffnx Command ramsey_policy (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];
@anchor{ramsey_policy}
@ -7197,8 +7361,8 @@ for identification analysis. Default: @code{0}
@item ar = @var{INTEGER}
Maximum number of lags for moments in identification analysis. Default: @code{1}
@item lik_init = @var{INTEGER}
@xref{lik_init}.
@item diffuse_filter = @var{INTEGER}
@xref{diffuse_filter}.
@end table
@ -7761,9 +7925,11 @@ It completely offsets any use of the sensitivity analysis toolbox.
Given a list of variables, observed variables and a data file, Dynare
can be used to solve a Markov-switching SBVAR model according to
@cite{Sims, Waggoner and Zha (2008)}. Having done this, you can create
forecasts and compute the marginal data density, regime probabilities,
IRFs, and variance decomposition of the model.
@cite{Sims, Waggoner and Zha (2008)}.@footnote{If you want to align
the paper with the description herein, please note that @math{A} is
@math{A^0} and @math{F} is @math{A^+}.} Having done this, you can
create forecasts and compute the marginal data density, regime
probabilities, IRFs, and variance decomposition of the model.
The commands have been modularized, allowing for multiple calls to the
same command within a @code{<mod_file>.mod} file. The default is to use
@ -9185,8 +9351,26 @@ the one that is highest on the MATLAB/Octave path).
@deffn {MATLAB/Octave command} write_latex_definitions ;
Writes the names, @LaTeX{} names and long names of model variables to
tables in a file named @code{<<M_.fname>>_latex_definitions.tex}.
tables in a file named @code{<<M_.fname>>_latex_definitions.tex}. Requires the
following @LaTeX{} packages: @code{longtable}
@end deffn
@deffn {MATLAB/Octave command} write_latex_parameter_table ;
Writes the @LaTeX{} names, parameter names, and long names of model parameters to
a table in a file named @code{<<M_.fname>>_latex_parameters.tex}. The command writes the values
of the parameters currently stored. Thus, if parameters are set or changed in the steady state
computation, the command should be called after a @code{steady}-command to make sure the
parameters were correctly updated. The long names can be used to add parameter descriptions. Requires the
following @LaTeX{} packages: @code{longtable}
@end deffn
@deffn {MATLAB/Octave command} collect_LaTeX_Files(M_) ;
Writes a @LaTeX{} file named @code{<<M_.fname>>_TeX_binder.tex} that collects all @TeX{} output generated by Dynare
into a file. This file can be compiled using pdflatex and automatically tries to load all required packages.
Requires the following @LaTeX{} packages: @code{longtable}, @code{psfrag},
@code{graphicx}, @code{epstopdf}, @code{longtable}
@end deffn
@ -9322,7 +9506,7 @@ Note that creating the configuration file is not enough in order to
trigger parallelization of the computations: you also need to specify
the @code{parallel} option to the @code{dynare} command. For more
details, and for other options related to the parallelization engine,
see @pxref{Dynare invocation}.
@pxref{Dynare invocation}.
You also need to verify that the following requirements are met by
your cluster (which is composed of a master and of one or more
@ -11733,7 +11917,7 @@ used.
Below, you will see a list of methods available for the Report class and
a clarifying example.
@defmethod Report report compiler, showDate, fileName, margin, marginUnit, orientation, paper, showOutput, title
@defmethod Report report compiler, showDate, fileName, header, margin, marginUnit, orientation, paper, showOutput, title
Instantiates a @code{Report} object.
@optionshead
@table @code
@ -11754,6 +11938,10 @@ Display the date and time when the report was compiled. Default:
The file name to use when saving this report. Default:
@code{report.tex}
@item header, @var{STRING}
The @LaTeX{} code to be included in the report before
@code{\begin@{document@}}. Default: @code{empty}
@item margin, @var{DOUBLE}
The margin size. Default: @code{2.5}
@ -11780,16 +11968,29 @@ Report Title. Default: @code{none}
@end defmethod
@anchor{addPage}
@defmethod Report addPage footnote, orientation, paper, title, titleFormat, titleTruncate
@defmethod Report addPage footnote, latex, orientation, pageDirName, paper, title, titleFormat, titleTruncate
Adds a @code{Page} to the @code{Report}.
@optionshead
@table @code
@item footnote, @code{STRING}
A footnote to be included at the bottom of this page. Default: @code{none}
@anchor{latex}
@item latex, @code{STRING}
The @LaTeX{} code to be used for this page. Alows the user to create a
page to be included in the report by passing @LaTeX{} code
directly. If this option is passed, the page itself will be saved in
the @ref{pageDirName} directory in the form @code{page_X.tex} where
@code{X} refers to the page number. Default @code{empty}
@item orientation, `landscape' | `portrait'
@xref{orientation}.
@anchor{pageDirName}
@item pageDirName, @code{STRING}
The name of the folder in which to store this page. Only used when the
@ref{latex} command is passed. Default: @code{tmpRepDir}
@item paper, `a4' | `letter'
@xref{paper}.
@ -12508,6 +12709,17 @@ computational and graphical statistics}, 7, pp. 434--455
@item
Cardoso, Margarida F., R. L. Salcedo and S. Feyo de Azevedo (1996): ``The simplex simulated annealing approach to continuous non-linear optimization,'' @i{Computers chem. Engng}, 20(9), 1065-1080
@item
Chib, Siddhartha and Srikanth Ramamurthy (2010):
``Tailored randomized block MCMC methods with application to DSGE models,''
@i{Journal of Econometrics}, 155, 19--38
@item
Christiano, Lawrence J., Mathias Trabandt and Karl Walentin (2011):
``Introducing financial frictions and unemployment into a small open
economy model,'' @i{Journal of Economic Dynamics and Control}, 35(12),
1999--2041
@item
Collard, Fabrice (2001): ``Stochastic simulations with Dynare: A practical guide''
@ -12527,12 +12739,6 @@ Corona, Angelo, M. Marchesi, Claudio Martini, and Sandro Ridella (1987):
``Minimizing multimodal functions of continuous variables with the ``simulated annealing'' algorithm'',
@i{ACM Transactions on Mathematical Software}, 13(3), 262--280
@item
Christiano, Lawrence J., Mathias Trabandt and Karl Walentin (2011):
``Introducing financial frictions and unemployment into a small open
economy model,'' @i{Journal of Economic Dynamics and Control}, 35(12),
1999--2041
@item
Del Negro, Marco and Franck Schorfheide (2004): ``Priors from General Equilibrium Models for VARS'',
@i{International Economic Review}, 45(2), 643--673
@ -12633,6 +12839,9 @@ Laffargue, Jean-Pierre (1990): ``Résolution d'un modèle
macroéconomique avec anticipations rationnelles'', @i{Annales
d'Économie et Statistique}, 17, 97--119
@item
Liu, Jane and Mike West (2001): ``Combined parameter and state estimation in simulation-based filtering'', in @i{Sequential Monte Carlo Methods in Practice}, Eds. Doucet, Freitas and Gordon, Springer Verlag
@item
Lubik, Thomas and Frank Schorfheide (2007): ``Do Central Banks Respond
to Exchange Rate Movements? A Structural Investigation,'' @i{Journal
@ -12669,6 +12878,10 @@ General Equilibrium Models Using a Second-Order Approximation to the
Policy Function,'' @i{Journal of Economic Dynamics and Control},
28(4), 755--775
@item
Schnabel, Robert B. and Elizabeth Eskow (1990): ``A new modified Cholesky algorithm,''
@i{SIAM Journal of Scientific and Statistical Computing}, 11, 1136--1158
@item
Sims, Christopher A., Daniel F. Waggoner and Tao Zha (2008): ``Methods for
inference in large multiple-equation Markov-switching models,''

View File

@ -1,14 +1,19 @@
\documentclass{beamer}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{amsmath}
\usepackage[copyright]{ccicons}
\usetheme{Boadilla}
\title{The Dynare Macro-processor}
\subtitle{Dynare Summer School 2013}
\subtitle{Dynare Summer School 2015}
\author{Sébastien Villemot}
\institute{CEPREMAP}
\date{June 28, 2013}
%\pgfdeclareimage[height=0.6cm]{logo}{logo-ofce}
%\institute[OFCE]{\pgfuseimage{logo}}
\institute{OFCE}
\date{June 9, 2015}
\AtBeginSection[]
{
@ -58,7 +63,6 @@
\item conditional inclusion (\textit{if/else} structures)
\item expression substitution
\end{itemize}
\item Implemented in Dynare starting from version 4.0
\item The macro-processor transforms a MOD file with macro-commands into a MOD file without macro-commands (doing text expansions/inclusions) and then feeds it to the Dynare parser
\item The key point to understand is that the macro-processor only does \textbf{text substitution} (like the C preprocessor or the PHP language)
\end{itemize}
@ -101,13 +105,21 @@
\end{block}
\item Exactly equivalent to a copy/paste of the content of the included file
\item Note that it is possible to nest includes (\textit{i.e.} to include a file from an included file)
\item Since Dynare 4.5, the filename can be given by a macro-variable (see below).
Useful in loops.
\begin{block}{Example with variable}
\begin{verbatim}
@#define fname = "modelcomponent.mod"
@#include fname
\end{verbatim}
\end{block}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Variables}
\begin{itemize}
\item The macro processor maintains its own list of variables (distinct of model variables and of MATLAB variables)
\item The macro processor maintains its own list of variables (distinct of model variables and of MATLAB/Octave variables)
\item Macro-variables can be of four types:
\begin{itemize}
\item integer
@ -510,11 +522,11 @@ end;
\end{frame}
\begin{frame}[fragile=singleslide]
\frametitle{MATLAB loops vs macro-processor loops (1/3)}
\frametitle{MATLAB/Octave loops vs macro-processor loops (1/3)}
Suppose you have a model with a parameter $\rho$, and you want to make
simulations for three values: $\rho = 0.8, 0.9, 1$. There are
several ways of doing this:
\begin{block}{With a MATLAB loop}
\begin{block}{With a MATLAB/Octave loop}
\begin{verbatim}
rhos = [ 0.8, 0.9, 1];
for i = 1:length(rhos)
@ -525,13 +537,13 @@ end
\end{block}
\begin{itemize}
\item The loop is not unrolled
\item MATLAB manages the iterations
\item MATLAB/Octave manages the iterations
\item Interesting when there are a lot of iterations
\end{itemize}
\end{frame}
\begin{frame}[fragile=singleslide]
\frametitle{MATLAB loops vs macro-processor loops (2/3)}
\frametitle{MATLAB/Octave loops vs macro-processor loops (2/3)}
\begin{block}{With a macro-processor loop (case 1)}
\begin{verbatim}
rhos = [ 0.8, 0.9, 1];
@ -549,7 +561,7 @@ rhos = [ 0.8, 0.9, 1];
\end{frame}
\begin{frame}[fragile=singleslide]
\frametitle{MATLAB loops vs macro-processor loops (3/3)}
\frametitle{MATLAB/Octave loops vs macro-processor loops (3/3)}
\begin{block}{With a macro-processor loop (case 2)}
\begin{verbatim}
@#for rho_val in [ "0.8", "0.9", "1"]
@ -562,7 +574,7 @@ rhos = [ 0.8, 0.9, 1];
\item Advantage: shorter syntax, since list of values directly given in the loop construct
\item Note that values are given as character strings (the macro-processor does not
know floating point values)
\item Inconvenient: can not reuse an array stored in a MATLAB variable
\item Inconvenient: can not reuse an array stored in a MATLAB/Octave variable
\end{itemize}
\end{frame}
@ -578,4 +590,25 @@ rhos = [ 0.8, 0.9, 1];
% \end{itemize}
% \end{frame}
\begin{frame}
\begin{center}
\vfill {\LARGE Thanks for your attention!} \vfill
{\LARGE Questions?}
\vfill
\end{center}
\vfill
\begin{columns}[T]
\column{0.2\textwidth}
\column{0.09\textwidth}
\ccbysa
\column{0.71\textwidth}
\tiny
Copyright © 2008--2015 Dynare Team \\
Licence: \href{http://creativecommons.org/licenses/by-sa/4.0/}{Creative
Commons Attribution-ShareAlike 4.0}
\end{columns}
\end{frame}
\end{document}

View File

@ -1,7 +1,7 @@
/*
* 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.
* This file replicates the estimation of the cash in advance model (termed M1
* in the paper) described in 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.
@ -17,7 +17,7 @@
*/
/*
* Copyright (C) 2004-2010 Dynare Team
* Copyright (C) 2004-2015 Dynare Team
*
* This file is part of Dynare.
*

View File

@ -8,7 +8,7 @@
*/
/*
* Copyright (C) 2004-2010 Dynare Team
* Copyright (C) 2004-2015 Dynare Team
*
* This file is part of Dynare.
*
@ -59,18 +59,27 @@ M-M(-1)+d = l;
y = k(-1)^alp*(A*n)^(1-alp);
end;
initval;
k = 6;
gM = mst;
P = 2.25;
c = 0.45;
W = 4;
R = 1.02;
d = 0.85;
n = 0.19;
l = 0.86;
y = 0.6;
gA = exp(gam);
steady_state_model;
gA = exp(gam);
gst = 1/gA;
gM = 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;
end;
shocks;

View File

@ -146,6 +146,10 @@ Files: doc/userguide/*.tex doc/userguide/*.bib doc/userguide/*.pdf
Copyright: 2007-2013 Tommaso Mancini Griffoli
License: GFDL-NIV-1.3+
Files: doc/macroprocessor/*
Copyright: 2008-2015 Dynare Team
License: CC-BY-SA-4.0
Files: doc/dr.tex doc/bvar_a_la_sims.tex
Copyright: 2007-2011 Sébastien Villemot
License: GFDL-NIV-1.3+
@ -428,3 +432,430 @@ License: LGPL-3+
.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
License: CC-BY-SA-4.0
Attribution-ShareAlike 4.0 International
.
=======================================================================
.
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
.
Using Creative Commons Public Licenses
.
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
.
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More_considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
.
=======================================================================
.
Creative Commons Attribution-ShareAlike 4.0 International Public
License
.
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-ShareAlike 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
.
.
Section 1 -- Definitions.
.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
.
c. BY-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution and ShareAlike.
.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
.
k. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
.
l. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
.
m. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
.
.
Section 2 -- Scope.
.
a. License grant.
.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
.
a. reproduce and Share the Licensed Material, in whole or
in part; and
.
b. produce, reproduce, and Share Adapted Material.
.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
.
3. Term. The term of this Public License is specified in Section
6(a).
.
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
.
5. Downstream recipients.
.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
.
b. Other rights.
.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
.
2. Patent and trademark rights are not licensed under this
Public License.
.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
.
.
Section 3 -- License Conditions.
.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
.
a. Attribution.
.
1. If You Share the Licensed Material (including in modified
form), You must:
.
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
.
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
.
ii. a copyright notice;
.
iii. a notice that refers to this Public License;
.
iv. a notice that refers to the disclaimer of
warranties;
.
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
.
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
.
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
.
b. ShareAlike.
.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-SA Compatible License.
.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
.
.
Section 4 -- Sui Generis Database Rights.
.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
.
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
.
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
.
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
.
.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
.
.
Section 6 -- Term and Termination.
.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
.
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
.
2. upon express reinstatement by the Licensor.
.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
.
.
Section 7 -- Other Terms and Conditions.
.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
.
.
Section 8 -- Interpretation.
.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
.
.
=======================================================================
.
Creative Commons is not a party to its public licenses.
Notwithstanding, Creative Commons may elect to apply one of its public
licenses to material it publishes and in those instances will be
considered the "Licensor." Except for the limited purpose of indicating
that material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the public
licenses.
.
Creative Commons may be contacted at creativecommons.org.

View File

@ -64,7 +64,9 @@ decomp = [];
vobs = length(options_.varobs);
smpl = size(Y,2);
M_ = set_all_parameters(xparam1,estim_params_,M_);
if ~isempty(xparam1) %not calibrated model
M_ = set_all_parameters(xparam1,estim_params_,M_);
end
%------------------------------------------------------------------------------
% 2. call model setup & reduction program

View File

@ -144,7 +144,7 @@ if NumberOfDraws < Origin
return
end
if TeX
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([OutputFolder '/' ModelName '_UnivariateDiagnostics.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by McmcDiagnostics.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
@ -233,7 +233,7 @@ for i = 1:pages
end
end
dyn_saveas(h,[OutputFolder '/' ModelName '_udiag' int2str(i)],options_);
if TeX
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
for jj = 1:size(NAMES,1)
fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
@ -296,7 +296,7 @@ if reste
end
end
dyn_saveas(h,[ OutputFolder '/' ModelName '_udiag' int2str(pages+1)],options_);
if TeX
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
for jj = 1:size(NAMES,1);
fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
@ -323,7 +323,7 @@ clear UDIAG;
%
% Multivariate diagnostic.
%
if TeX
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([OutputFolder '/' ModelName '_MultivariateDiagnostics.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by McmcDiagnostics.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
@ -402,7 +402,7 @@ for crit = 1:3
end
dyn_saveas(h,[ OutputFolder '/' ModelName '_mdiag'],options_);
if TeX
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
for jj = 1:3
fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),' ');

View File

@ -49,7 +49,7 @@ nn = sqrt(MaxNumberOfPlotPerFigure);
figurename = 'Priors and posteriors';
if TeX
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by PlotPosteriorDistributions.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
@ -153,7 +153,7 @@ for i=1:npar
drawnow
if subplotnum == MaxNumberOfPlotPerFigure || i == npar;
dyn_saveas(hfig,[OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber)],options_);
if TeX
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
for j = 1:size(NAMES,1)
fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(j,:)),deblank(TeXNAMES(j,:)));

View File

@ -384,52 +384,50 @@ end
% The files .TeX are genereted in sequential way always!
if options_.TeX
% The files .TeX are generated in sequential way always!
subplotnum = 0;
tit_TeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex;
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([DirectoryName filesep M_.fname '_BayesianIRF.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by PosteriorIRF.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
titTeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex;
for i=irf_shocks_indx
NAMES = [];
TEXNAMES = [];
for ii=irf_shocks_indx
figunumber = 0;
for j=1:nvar
if max(abs(MeanIRF(:,j,i))) > options_.impulse_responses.plot_threshold
name = deblank(varlist(j,:));
texname = deblank(varlist_TeX(j,:));
if j==1
NAMES = name;
TEXNAMES = ['$' texname '$'];
else
NAMES = char(NAMES,name);
TEXNAMES = char(TEXNAMES,['$' texname '$']);
for jj=1:nvar
if max(abs(MeanIRF(:,jj,ii))) > options_.impulse_responses.plot_threshold
subplotnum = subplotnum+1;
if subplotnum == 1
fprintf(fidTeX,'\\begin{figure}[H]\n');
end
name = deblank(varlist(jj,:));
texname = deblank(varlist_TeX(jj,:));
fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],name,['$' texname '$']);
end
if subplotnum == MaxNumberOfPlotPerFigure || (jj == nvar && subplotnum> 0)
figunumber = figunumber+1;
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s/%s_Bayesian_IRF_%s_%d}\n',DirectoryName,M_.fname,deblank(tit(ii,:)),figunumber);
if options_.relative_irf
fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']);
else
fprintf(fidTeX,'\\caption{Bayesian IRF: Orthogonalized shock to $%s$.}\n',deblank(tit_TeX(ii,:)));
end
fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s}\n',deblank(tit(ii,:)));
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
subplotnum = 0;
end
end
fprintf(fidTeX,'\\begin{figure}[H]\n');
for jj = 1:size(TEXNAMES,1)
fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
end
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Bayesian_IRF_%s}\n',M_.fname,deblank(tit(i,:)));
if options_.relative_irf
fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']);
else
fprintf(fidTeX,'\\caption{Bayesian IRF.}');
end
fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s}\n',deblank(tit(i,:)));
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
end
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end
% The others file format are generated in parallel by PosteriorIRF_core2!

View File

@ -177,8 +177,12 @@ while fpar<B
irf_shocks_indx = getIrfShocksIndx();
for i=irf_shocks_indx
if SS(i,i) > 1e-13
y=irf(dr,SS(M_.exo_names_orig_ord,i), options_.irf, options_.drop,options_.replic,options_.order);
if options_.relative_irf
if options_.order>1 && options_.relative_irf % normalize shock to 0.01 before IRF generation for GIRFs; multiply with 100 later
y=irf(dr,SS(M_.exo_names_orig_ord,i)./SS(i,i)/100, options_.irf, options_.drop,options_.replic,options_.order);
else
y=irf(dr,SS(M_.exo_names_orig_ord,i), options_.irf, options_.drop,options_.replic,options_.order);
end
if options_.relative_irf && options_.order==1 %multiply with 100 for backward compatibility
y = 100*y/SS(i,i);
end
for j = 1:nvar

View File

@ -0,0 +1,293 @@
function myoutput = TaRB_metropolis_hastings_core(myinputs,fblck,nblck,whoiam, ThisMatlab)
% function myoutput = TaRB_metropolis_hastings_core(myinputs,fblck,nblck,whoiam, ThisMatlab)
% Contains the most computationally intensive portion of code in
% random_walk_metropolis_hastings (the 'for xxx = fblck:nblck' loop) using the TaRB algorithm.
% The branches in that 'for'
% cycle are completely independent to be suitable for parallel execution.
%
% INPUTS
% o myimput [struc] The mandatory variables for local/remote
% parallel computing obtained from random_walk_metropolis_hastings.m
% function.
% o fblck and nblck [integer] The Metropolis-Hastings chains.
% o whoiam [integer] In concurrent programming a modality to refer to the different threads running in parallel is needed.
% The integer whoaim is the integer that
% allows us to distinguish between them. Then it is the index number of this CPU among all CPUs in the
% cluster.
% o ThisMatlab [integer] Allows us to distinguish between the
% 'main' Matlab, the slave Matlab worker, local Matlab, remote Matlab,
% ... Then it is the index number of this slave machine in the cluster.
% OUTPUTS
% o myoutput [struc]
% If executed without parallel, this is the original output of 'for b =
% fblck:nblck'. Otherwise, it's a portion of it computed on a specific core or
% remote machine. In this case:
% record;
% irun;
% NewFile;
% OutputFileName
%
% ALGORITHM
% Portion of Tailored Randomized Block Metropolis-Hastings proposed in
% Chib/Ramamurthy (2010): Tailored randomized block MCMC methods with
% application to DSGE models, Journal of Econometrics 155, pp. 19-38
%
% This implementation differs from the originally proposed one in the
% treatment of non-positive definite Hessians. Here we
% - use the Jordan decomposition
%
% SPECIAL REQUIREMENTS.
% None.
%
% PARALLEL CONTEXT
% See the comments in the random_walk_metropolis_hastings.m funtion.
% Copyright (C) 2006-2015 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global objective_function_penalty_base;
if nargin<4,
whoiam=0;
end
% reshape 'myinputs' for local computation.
% In order to avoid confusion in the name space, the instruction struct2local(myinputs) is replaced by:
TargetFun=myinputs.TargetFun;
ProposalFun=myinputs.ProposalFun;
xparam1=myinputs.xparam1;
mh_bounds=myinputs.mh_bounds;
last_draw=myinputs.ix2;
last_posterior=myinputs.ilogpo2;
fline=myinputs.fline;
npar=myinputs.npar;
nruns=myinputs.nruns;
NewFile=myinputs.NewFile;
MAX_nruns=myinputs.MAX_nruns;
d=myinputs.d;
InitSizeArray=myinputs.InitSizeArray;
record=myinputs.record;
dataset_ = myinputs.dataset_;
dataset_info = myinputs.dataset_info;
bayestopt_ = myinputs.bayestopt_;
estim_params_ = myinputs.estim_params_;
options_ = myinputs.options_;
M_ = myinputs.M_;
oo_ = myinputs.oo_;
% Necessary only for remote computing!
if whoiam
% initialize persistent variables in priordens()
priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7, bayestopt_.p3,bayestopt_.p4,1);
end
MetropolisFolder = CheckPath('metropolis',M_.dname);
ModelName = M_.fname;
BaseName = [MetropolisFolder filesep ModelName];
options_.lik_algo = 1;
OpenOldFile = ones(nblck,1);
%
% Now I run the (nblck-fblck+1) Metropolis-Hastings chains
%
block_iter=0;
for curr_chain = fblck:nblck,
block_iter=block_iter+1;
try
% This will not work if the master uses a random number generator not
% available in the slave (different Matlab version or
% Matlab/Octave cluster). Therefore the trap.
%
% Set the random number generator type (the seed is useless but needed by the function)
set_dynare_seed(options_.DynareRandomStreams.algo, options_.DynareRandomStreams.seed);
% Set the state of the RNG
set_dynare_random_generator_state(record.InitialSeeds(curr_chain).Unifor, record.InitialSeeds(curr_chain).Normal);
catch
% If the state set by master is incompatible with the slave, we only reseed
set_dynare_seed(options_.DynareRandomStreams.seed+curr_chain);
end
if (options_.load_mh_file~=0) && (fline(curr_chain)>1) && OpenOldFile(curr_chain) %load previous draws and likelihood
load([BaseName '_mh' int2str(NewFile(curr_chain)) '_blck' int2str(curr_chain) '.mat'])
x2 = [x2;zeros(InitSizeArray(curr_chain)-fline(curr_chain)+1,npar)];
logpo2 = [logpo2;zeros(InitSizeArray(curr_chain)-fline(curr_chain)+1,1)];
OpenOldFile(curr_chain) = 0;
else
x2 = zeros(InitSizeArray(curr_chain),npar);
logpo2 = zeros(InitSizeArray(curr_chain),1);
end
%Prepare waiting bars
if whoiam
prc0=(curr_chain-fblck)/(nblck-fblck+1)*(isoctave || options_.console_mode);
hh = dyn_waitbar({prc0,whoiam,options_.parallel(ThisMatlab)},['MH (' int2str(curr_chain) '/' int2str(options_.mh_nblck) ')...']);
else
hh = dyn_waitbar(0,['Metropolis-Hastings (' int2str(curr_chain) '/' int2str(options_.mh_nblck) ')...']);
set(hh,'Name','Metropolis-Hastings');
end
accepted_draws_this_chain = 0;
accepted_draws_this_file = 0;
blocked_draws_counter_this_chain=0;
blocked_draws_counter_this_chain_this_file=0;
draw_index_current_file = fline(curr_chain); %get location of first draw in current block
draw_iter = 1;
while draw_iter <= nruns(curr_chain)
%% randomize indices for blocking in this iteration
indices=randperm(npar)';
blocks=[1; (1+cumsum((rand(length(indices)-1,1)>(1-options_.TaRB.new_block_probability))))];
nblocks=blocks(end,1); %get number of blocks this iteration
current_draw=last_draw(curr_chain,:)'; %get starting point for current draw for updating
for block_iter=1:nblocks
blocked_draws_counter_this_chain=blocked_draws_counter_this_chain+1;
blocked_draws_counter_this_chain_this_file=blocked_draws_counter_this_chain_this_file+1;
nxopt=length(indices(blocks==block_iter,1)); %get size of current block
par_start_current_block=current_draw(indices(blocks==block_iter,1));
[xopt_current_block, fval, exitflag, hess_mat_optimizer, options_, Scale] = dynare_minimize_objective(@TaRB_optimizer_wrapper,par_start_current_block,options_.TaRB.mode_compute,options_,[mh_bounds.lb(indices(blocks==block_iter,1),1) mh_bounds.ub(indices(blocks==block_iter,1),1)],bayestopt_.name,bayestopt_,[],...
current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper
dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_); %inputs for objective
objective_function_penalty_base=Inf; %reset penalty that may have been changed by optimizer
%% covariance for proposal density
hessian_mat = reshape(hessian('TaRB_optimizer_wrapper',xopt_current_block, ...
options_.gstep,...
current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper
dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_),nxopt,nxopt);
if any(any(isnan(hessian_mat))) || any(any(isinf(hessian_mat)))
inverse_hessian_mat=eye(nxopt)*1e-4; %use diagonal
else
inverse_hessian_mat=inv(hessian_mat); %get inverse Hessian
if any(any((isnan(inverse_hessian_mat)))) || any(any((isinf(inverse_hessian_mat))))
inverse_hessian_mat=eye(nxopt)*1e-4; %use diagonal
end
end
[proposal_covariance_Cholesky_decomposition_upper,negeigenvalues]=chol(inverse_hessian_mat);
%if not positive definite, use generalized Cholesky if
%Eskow/Schnabel
if negeigenvalues~=0
proposal_covariance_Cholesky_decomposition_upper=chol_SE(inverse_hessian_mat,0);
end
proposal_covariance_Cholesky_decomposition_upper=proposal_covariance_Cholesky_decomposition_upper*diag(bayestopt_.jscale(indices(blocks==block_iter,1),:));
%get proposal draw
if strcmpi(ProposalFun,'rand_multivariate_normal')
n = nxopt;
elseif strcmpi(ProposalFun,'rand_multivariate_student')
n = options_.student_degrees_of_freedom;
end
proposed_par = feval(ProposalFun, xopt_current_block', proposal_covariance_Cholesky_decomposition_upper, n);
% chech whether draw is valid and compute posterior
if all( proposed_par(:) > mh_bounds.lb(indices(blocks==block_iter,1),:) ) && all( proposed_par(:) < mh_bounds.ub(indices(blocks==block_iter,1),:) )
try
logpost = - feval('TaRB_optimizer_wrapper', proposed_par(:),...
current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper
dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
catch
logpost = -inf;
end
else
logpost = -inf;
end
%get ratio of proposal densities, required because proposal depends
%on current mode via Hessian and is thus not symmetric anymore
if strcmpi(ProposalFun,'rand_multivariate_normal')
proposal_density_proposed_move_forward=multivariate_normal_pdf(proposed_par,xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
proposal_density_proposed_move_backward=multivariate_normal_pdf(par_start_current_block',xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
elseif strcmpi(ProposalFun,'rand_multivariate_student')
proposal_density_proposed_move_forward=multivariate_student_pdf(proposed_par,xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
proposal_density_proposed_move_backward=multivariate_student_pdf(par_start_current_block',xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
end
accprob=logpost-last_posterior(curr_chain)+ log(proposal_density_proposed_move_backward)-log(proposal_density_proposed_move_forward); %Formula (6), Chib/Ramamurthy
if (logpost > -inf) && (log(rand) < accprob)
current_draw(indices(blocks==block_iter,1))=proposed_par;
last_posterior(curr_chain)=logpost;
accepted_draws_this_chain =accepted_draws_this_chain +1;
accepted_draws_this_file = accepted_draws_this_file + 1;
else %no updating
%do nothing, keep old value
end
end
%save draws and update stored last values
x2(draw_index_current_file,:) = current_draw;
last_draw(curr_chain,:) = current_draw;
%save posterior after full run through all blocks
logpo2(draw_index_current_file) = last_posterior(curr_chain);
prtfrc = draw_iter/nruns(curr_chain);
if (mod(draw_iter, 3)==0 && ~whoiam) || (mod(draw_iter,50)==0 && whoiam)
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');
fidlog = fopen([MetropolisFolder '/metropolis.log'],'a');
fprintf(fidlog,['\n']);
fprintf(fidlog,['%% Mh' int2str(NewFile(curr_chain)) 'Blck' int2str(curr_chain) ' (' datestr(now,0) ')\n']);
fprintf(fidlog,' \n');
fprintf(fidlog,[' Number of simulations.: ' int2str(length(logpo2)) '\n']);
fprintf(fidlog,[' Acceptance ratio......: ' num2str(accepted_draws_this_file /blocked_draws_counter_this_chain_this_file) '\n']);
fprintf(fidlog,[' Posterior mean........:\n']);
for i=1:length(x2(1,:))
fprintf(fidlog,[' params:' int2str(i) ': ' num2str(mean(x2(:,i))) '\n']);
end
fprintf(fidlog,[' log2po:' num2str(mean(logpo2)) '\n']);
fprintf(fidlog,[' Minimum value.........:\n']);
for i=1:length(x2(1,:))
fprintf(fidlog,[' params:' int2str(i) ': ' num2str(min(x2(:,i))) '\n']);
end
fprintf(fidlog,[' log2po:' num2str(min(logpo2)) '\n']);
fprintf(fidlog,[' Maximum value.........:\n']);
for i=1:length(x2(1,:))
fprintf(fidlog,[' params:' int2str(i) ': ' num2str(max(x2(:,i))) '\n']);
end
fprintf(fidlog,[' log2po:' num2str(max(logpo2)) '\n']);
fprintf(fidlog,' \n');
fclose(fidlog);
%reset counters;
accepted_draws_this_file = 0;
blocked_draws_counter_this_chain_this_file=0;
if draw_iter == nruns(curr_chain) % I record the last draw...
record.LastParameters(curr_chain,:) = x2(end,:);
record.LastLogPost(curr_chain) = logpo2(end);
end
% size of next file in chain curr_chain
InitSizeArray(curr_chain) = min(nruns(curr_chain)-draw_iter,MAX_nruns);
% initialization of next file if necessary
if InitSizeArray(curr_chain)
x2 = zeros(InitSizeArray(curr_chain),npar);
logpo2 = zeros(InitSizeArray(curr_chain),1);
NewFile(curr_chain) = NewFile(curr_chain) + 1;
draw_index_current_file = 0;
end
end
draw_iter=draw_iter+1;
draw_index_current_file = draw_index_current_file + 1;
end% End of the simulations for one mh-block.
record.AcceptanceRatio(curr_chain) = accepted_draws_this_chain/blocked_draws_counter_this_chain;
dyn_waitbar_close(hh);
[record.LastSeeds(curr_chain).Unifor, record.LastSeeds(curr_chain).Normal] = get_dynare_random_generator_state();
OutputFileName(block_iter,:) = {[MetropolisFolder,filesep], [ModelName '_mh*_blck' int2str(curr_chain) '.mat']};
end% End of the loop over the mh-blocks.
myoutput.record = record;
myoutput.irun = draw_index_current_file;
myoutput.NewFile = NewFile;
myoutput.OutputFileName = OutputFileName;

View File

@ -0,0 +1,40 @@
function [fval,DLIK,Hess,exit_flag] = TaRB_optimizer_wrapper(optpar,par_vector,parameterindices,TargetFun,varargin)
% function [fval,DLIK,Hess,exit_flag] = TaRB_optimizer_wrapper(optpar,par_vector,parameterindices,TargetFun,varargin)
% Wrapper function for target function used in TaRB algorithm; reassembles
% full parameter vector before calling target function
%
% INPUTS
% o optpar [double] (p_opt*1) vector of subset of parameters to be considered
% o par_vector [double] (p*1) full vector of parameters
% o parameterindices [double] (p_opt*1) index of optpar entries in
% par_vector
% o TargetFun [char] string specifying the name of the objective
% function (posterior kernel).
% o varargin [structure] other inputs of target function
%
% OUTPUTS
% o fval [scalar] value of (minus) the likelihood.
% o DLIK [double] (p*1) score vector of the likelihood.
% o Hess [double] (p*p) asymptotic Hessian matrix.
% o exit_flag [scalar] equal to zero if the routine return with a penalty (one otherwise).
%
% Copyright (C) 2015 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
par_vector(parameterindices,:)=optpar; %reassemble parameter
[fval,DLIK,Hess,exit_flag] = feval(TargetFun,par_vector,varargin{:}); %call target function

View File

@ -21,7 +21,7 @@ if nargin<2
modifypath = true;
end
if isoctave
if exist('OCTAVE_VERSION')
mexpath = {[dynareroot '../mex/octave/']};
if modifypath
addpath(mexpath{1});

View File

@ -116,13 +116,9 @@ for shock=1:ny
figure('Name',['Posterior BVAR Impulse Responses (shock in equation ' int2str(shock) ').']);
for variable=1:ny
subplot(number_of_rows,number_of_columns,variable);
h1 = area(1:options_.irf,squeeze(posterior_up_conf_irfs(shock,variable,:)));
set(h1,'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))]))
set(h1,'FaceColor',[.9 .9 .9])
h1 = area(1:options_.irf,squeeze(posterior_up_conf_irfs(shock,variable,:)),'FaceColor',[.9 .9 .9],'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))]));
hold on
h2 = area(1:options_.irf,squeeze(posterior_down_conf_irfs(shock,variable,:)));
set(h2,'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))]))
set(h2,'FaceColor',[1 1 1])
h2 = area(1:options_.irf,squeeze(posterior_down_conf_irfs(shock,variable,:)),'FaceColor',[1 1 1],'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))]));
plot(1:options_.irf,squeeze(posterior_median_irfs(shock,variable,:)),'-k','linewidth',2)
axis tight
hold off

View File

@ -1,30 +0,0 @@
function b = check_file_extension(file,type)
% Copyright (C) 2012 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% AUTHOR(S) stephane DOT adjemian AT univ DASH lemans DOT fr
% Clean-up path
file = strrep(file, '../', '');
file = strrep(file, './', '');
remain = file;
while ~isempty(remain)
[ext, remain] = strtok(remain,'.');
end
b = strcmp(ext,type);

View File

@ -65,7 +65,7 @@ elseif isempty(varlist) && ~isempty(options_.endo_vars_for_moment_computations_i
if strcmp(options_.endo_vars_for_moment_computations_in_estimation,'all_endogenous_variables')
varlist = M_.endo_names(1:M_.orig_endo_nbr, :);
elseif strcmp(options_.endo_vars_for_moment_computations_in_estimation,'only_observed_variables')
varlist = options_.varobs;
varlist = char(options_.varobs');
else
error('Unknown option')
end

309
matlab/chol_SE.m Normal file
View File

@ -0,0 +1,309 @@
function [R,indef, E, P]=chol_SE(A,pivoting)
% [R,indef, E, P]=chol_SE(A,pivoting)
% Performs a (modified) Cholesky factorization of the form
%
% P'*A*P + E = R'*R
%
% As detailed in Schnabel/Eskow (1990), the factorization has 2 phases:
% Phase 1: While A can still be positive definite, pivot on the maximum diagonal element.
% Check that the standard Cholesky update would result in a positive diagonal
% at the current iteration. If so, continue with the normal Cholesky update.
% Otherwise switch to phase 2.
% If A is safely positive definite, stage 1 is never left, resulting in
% the standard Cholesky decomposition.
%
% Phase 2: Pivot on the minimum of the negatives of the lower Gershgorin bound
% estimates. To prevent negative diagonals, compute the amount to add to the
% pivot element and add this. Then, do the Cholesky update and update the estimates of the
% Gershgorin bounds.
%
% Notes:
% - During factorization, L=R' is stored in the lower triangle of the original matrix A,
% miminizing the memory requirements
% - Conforming with the original Schnabel/Eskow (1990) algorithm:
% - at each iteration the updated Gershgorin bounds are estimated instead of recomputed,
% reducing the computational requirements from o(n^3) to o (n^2)
% - For the last 2 by 2 submatrix, an eigenvalue-based decomposition is used
% - While pivoting is not necessary, it improves the size of E, the add-on on to the diagonal. But this comes at
% the cost of introduding a permutation.
%
%
% Inputs
% A [n*n] Matrix to be factorized
% pivoting [scalar] dummy whether pivoting is used
%
% Outputs
% R [n*n] originally stored in lower triangular portion of A, including the main diagonal
%
% E [n*1] Elements added to the diagonal of A
% P [n*1] record of how the rows and columns of the matrix were permuted while
% performing the decomposition
%
% REFERENCES:
% This implementation is based on
%
% Robert B. Schnabel and Elizabeth Eskow. 1990. "A New Modified Cholesky
% Factorization," SIAM Journal of Scientific Statistical Computating,
% 11, 6: 1136-58.
%
% Elizabeth Eskow and Robert B. Schnabel 1991. "Algorithm 695 - Software for a New Modified Cholesky
% Factorization," ACM Transactions on Mathematical Software, Vol 17, No 3: 306-312
%
%
% Author: Johannes Pfeifer based on Eskow/Schnabel (1991)
%
% Copyright (C) 2015 Johannes Pfeifer
% Copyright (C) 2015 Dynare Team
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if sum(sum(abs(A-A'))) > 0
error('A is not symmetric')
end
if nargin==1
pivoting=0;
end
n=size(A,1);
tau1=eps^(1/3); %tolerance parameter for determining when to switch phase 2
tau2=eps^(1/3); %tolerance used for determining the maximum condition number of the final 2X2 submatrix.
phase1 = 1;
delta = 0;
P=1:n;
g=zeros(n,1);
E=zeros(n,1);
% Find the maximum magnitude of the diagonal elements. If any diagonal element is negative, then phase1 is false.
gammma=max(diag(A));
if any(diag(A)) < 0
phase1 = 0;
end
taugam = tau1*gammma;
% If not in phase1, then calculate the initial Gershgorin bounds needed for the start of phase2.
if ~phase1
g=gersh_nested(A,1,n);
end
% check for n=1
if n==1
delta = tau2*abs(A(1,1)) - A(1,1);
if delta > 0
E(1) = delta;
end
if A(1,1) == 0
E(1) = tau2;
end
A(1,1)=sqrt(A(1,1)+E(1));
end
for j = 1:n-1
% PHASE 1
if phase1
if pivoting==1
% Find index of maximum diagonal element A(i,i) where i>=j
[tmp,imaxd] = max(diag(A(j:n,j:n)));
imaxd=imaxd+j-1;
% Pivot to the top the row and column with the max diag
if (imaxd ~= j)
% Swap row j with row of max diag
for ii = 1:j-1
temp = A(j,ii);
A(j,ii) = A(imaxd,ii);
A(imaxd,ii) = temp;
end
% Swap colj and row maxdiag between j and maxdiag
for ii = j+1:imaxd-1
temp = A(ii,j);
A(ii,j) = A(imaxd,ii);
A(imaxd,ii) = temp;
end
% Swap column j with column of max diag
for ii = imaxd+1:n
temp = A(ii,j);
A(ii,j) = A(ii,imaxd);
A(ii,imaxd) = temp;
end
% Swap diag elements
temp = A(j,j);
A(j,j) = A(imaxd,imaxd);
A(imaxd,imaxd) = temp;
% Swap elements of the permutation vector
itemp = P(j);
P(j) = P(imaxd);
P(imaxd) = itemp;
end
end
% check to see whether the normal Cholesky update for this
% iteration would result in a positive diagonal,
% and if not then switch to phase 2.
jp1 = j+1;
if A(j,j)>0
if min((diag(A(j+1:n,j+1:n)) - A(j+1:n,j).^2/A(j,j))) < taugam %test whether stage 2 is required
phase1=0;
end
else
phase1 = 0;
end
if phase1
% Do the normal cholesky update if still in phase 1
A(j,j) = sqrt(A(j,j));
tempjj = A(j,j);
for ii = jp1: n
A(ii,j) = A(ii,j)/tempjj;
end
for ii=jp1:n
temp=A(ii,j);
for k = jp1:ii
A(ii,k) = A(ii,k)-(temp * A(k,j));
end
end
if j == n-1
A(n,n)=sqrt(A(n,n));
end
else
% Calculate the negatives of the lower Gershgorin bounds
g=gersh_nested(A,j,n);
end
end
% PHASE 2
if ~phase1
if j ~= n-1
if pivoting
% Find the minimum negative Gershgorin bound
[tmp,iming] = min(g(j:n));
iming=iming+j-1;
% Pivot to the top the row and column with the
% minimum negative Gershgorin bound
if iming ~= j
% Swap row j with row of min Gershgorin bound
for ii = 1:j-1
temp = A(j,ii);
A(j,ii) = A(iming,ii);
A(iming,ii) = temp;
end
% Swap col j with row iming from j to iming
for ii = j+1:iming-1
temp = A(ii,j);
A(ii,j) = A(iming,ii);
A(iming,ii) = temp;
end
% Swap column j with column of min Gershgorin bound
for ii = iming+1:n
temp = A(ii,j);
A(ii,j) = A(ii,iming);
A(ii,iming) = temp;
end
% Swap diagonal elements
temp = A(j,j);
A(j,j) = A(iming,iming);
A(iming,iming) = temp;
% Swap elements of the permutation vector
itemp = P(j);
P(j) = P(iming);
P(iming) = itemp;
% Swap elements of the negative Gershgorin bounds vector
temp = g(j);
g(j) = g(iming);
g(iming) = temp;
end
end
% Calculate delta and add to the diagonal. delta=max{0,-A(j,j) + max{normj,taugam},delta_previous}
% where normj=sum of |A(i,j)|,for i=1,n, delta_previous is the delta computed at the previous iter and taugam is tau1*gamma.
normj=sum(abs(A(j+1:n,j)));
delta = max([0;delta;-A(j,j)+normj;-A(j,j)+taugam]); % get adjustment based on formula on bottom of p. 309 of Eskow/Schnabel (1991)
E(j) = delta;
A(j,j) = A(j,j) + E(j);
% Update the Gershgorin bound estimates (note: g(i) is the negative of the Gershgorin lower bound.)
if A(j,j) ~= normj
temp = (normj/A(j,j)) - 1;
for ii = j+1:n
g(ii) = g(ii) + abs(A(ii,j)) * temp;
end
end
% Do the cholesky update
A(j,j) = sqrt(A(j,j));
tempjj = A(j,j);
for ii = j+1:n
A(ii,j) = A(ii,j) / tempjj;
end
for ii = j+1:n
temp = A(ii,j);
for k = j+1: ii
A(ii,k) = A(ii,k) - (temp * A(k,j));
end
end
else
% Find eigenvalues of final 2 by 2 submatrix
% Find delta such that:
% 1. the l2 condition number of the final 2X2 submatrix + delta*I <= tau2
% 2. delta >= previous delta,
% 3. min(eigvals) + delta >= tau2 * gamma, where min(eigvals) is the smallest eigenvalue of the final 2X2 submatrix
A(n-1,n)=A(n,n-1); %set value above diagonal for computation of eigenvalues
eigvals = eig(A(n-1:n,n-1:n));
delta = max([ 0 ; delta ; -min(eigvals)+tau2*max((max(eigvals)-min(eigvals))/(1-tau1),gammma) ]); %Formula 5.3.2 of Schnabel/Eskow (1990)
if delta > 0
A(n-1,n-1) = A(n-1,n-1) + delta;
A(n,n) = A(n,n) + delta;
E(n-1) = delta;
E(n) = delta;
end
% Final update
A(n-1,n-1) = sqrt(A(n-1,n-1));
A(n,n-1) = A(n,n-1)/A(n-1,n-1);
A(n,n) = A(n,n) - (A(n,n-1)^2);
A(n,n) = sqrt(A(n,n));
end
end
end
R=(tril(A))';
indef=~phase1;
Pprod=zeros(n,n);
Pprod(sub2ind([n,n],P,1:n))=1;
P=Pprod;
end
function g=gersh_nested(A,j,n)
g=zeros(n,1);
for ii = j:n
if ii == 1;
sum_up_to_i = 0;
else
sum_up_to_i = sum(abs(A(ii,j:(ii-1))));
end;
if ii == n;
sum_after_i = 0;
else
sum_after_i = sum(abs(A((ii+1):n,ii)));
end;
g(ii) = sum_up_to_i + sum_after_i- A(ii,ii);
end
end

View File

@ -0,0 +1,72 @@
function collect_LaTeX_Files(M_)
% function collect_LaTeX_Files(M_);
% Creates TeX-File embedding all eps-loaders created for current mod-file
%
% Inputs:
% o M_ model structure
%
% Notes:
% - The packages loaded enable pdflatex to run
% - The _dynamic and _static TeX-model files are not included as they are standalone TeX-files
% Copyright (C) 2015 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
%% Write header
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{psfrag}');
fprintf(fid,'%s \n','\usepackage{graphicx}');
fprintf(fid,'%s \n','\usepackage{epstopdf}');
fprintf(fid,'%s \n','\usepackage{longtable}');
fprintf(fid,'%s \n','\begin{document}');
%% Root directory
TeX_Files=dir([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) && ...
~strcmp(TeX_Files(ii).name,[M_.fname,'_dynamic.tex']) && ...
~strcmp(TeX_Files(ii).name,[M_.fname,'_static.tex']) && ...
~strcmp(TeX_Files(ii).name,[M_.fname,'_original.tex'])
fprintf(fid,'%s \n',['\include{',f_name,'}']);
end
end
%% Output directory
TeX_Files=dir([M_.dname filesep 'Output' 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 '/Output' '/',f_name,'}']);
end
end
%5 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);
if ~strcmp(TeX_Files(ii).name,f_name_binder)
fprintf(fid,'%s \n',['\include{', M_.dname '/graphs' '/',f_name,'}']);
end
end
%% Write footer
fprintf(fid,'%s \n','\end{document}');
fclose(fid);

View File

@ -1,128 +0,0 @@
function [n,message] = common_strings_in_cell_arrays(a,b)
%@info:
%! @deftypefn {Function File} {[@var{n}, @var{message} ] =} common_strings_in_cell_arrays (@var{a}, @var{b})
%! @anchor{common_strings_in_cell_arrays}
%! @sp 1
%! Counts the number of common strings in two cell arrays of strings @var{a} and @var{b}.
%! @sp 2
%! @strong{Inputs}
%! @sp 1
%! @table @ @var
%! @item a
%! One dimensional cell array of strings.
%! @item b
%! One dimensional cell array of strings.
%! @end table
%! @sp 2
%! @strong{Outputs}
%! @sp 1
%! @table @ @var
%! @item n
%! Scalar integer, number of common strings.
%! @item message
%! String, formatted list of common strings.
%! @end table
%! @end deftypefn
%@eod:
% Copyright (C) 2013 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
common_strings = intersect(a,b);
n = numel(common_strings);
if nargout>1
switch n
case 0
message = [];
case 1
message = common_strings{1};
case 2
message = [common_strings{1} ' and ' common_strings{2}];
otherwise
message = common_strings{1};
for i = 2:n-1
message = [message ', ' common_strings{i}];
end
message = [message ' and ' common_strings{n}];
end
end
%@test:1
%$ % Define cell arrays of strings.
%$ A = {'A1'; 'A2'; 'A3'; 'A4'};
%$ B = {'B1'; 'B2'; 'B3'; 'B4'};
%$
%$ try
%$ n = common_strings_in_cell_arrays(A,B);
%$ [m,message] = common_strings_in_cell_arrays(A,B);
%$ t(1) = 1;
%$ catch
%$ t = 0;
%$ end
%$
%$ if length(t)>1
%$ t(2) = dassert(n,m);
%$ t(3) = dassert(n,0);
%$ t(4) = dassert(isempty(message),1);
%$ end
%$ T = all(t);
%@eof:1
%@test:2
%$ % Define cell arrays of strings.
%$ A = {'A1'; 'A2'; 'A3'; 'A4'};
%$ B = {'B1'; 'A2'; 'B3'; 'A4'};
%$
%$ try
%$ n = common_strings_in_cell_arrays(A,B);
%$ [m,message] = common_strings_in_cell_arrays(A,B);
%$ t(1) = 1;
%$ catch
%$ t = 0;
%$ end
%$
%$ if length(t)>1
%$ t(2) = dassert(n,m);
%$ t(3) = dassert(n,2);
%$ t(4) = dassert(message,'A2 and A4');
%$ end
%$ T = all(t);
%@eof:2
%@test:2
%$ % Define cell arrays of strings.
%$ A = {'A1'; 'A2'; 'A3'; 'A4'; 'A5'; 'A6'};
%$ B = {'B1'; 'A2'; 'B3'; 'A4'; 'A1'};
%$
%$ try
%$ n = common_strings_in_cell_arrays(A,B);
%$ [m,message] = common_strings_in_cell_arrays(A,B);
%$ t(1) = 1;
%$ catch
%$ t = 0;
%$ end
%$
%$ if length(t)>1
%$ t(2) = dassert(n,m);
%$ t(3) = dassert(n,3);
%$ t(4) = dassert(message,'A2, A4 and A1');
%$ end
%$ T = all(t);
%@eof:3

View File

@ -58,7 +58,7 @@ if size(stationary_vars, 1) > 0
end
if ~options_.noprint %options_.nomoments == 0
if options_.order == 2
title='APROXIMATED THEORETICAL MOMENTS';
title='APPROXIMATED THEORETICAL MOMENTS';
else
title='THEORETICAL MOMENTS';
end

View File

@ -36,9 +36,13 @@ function []=display_problematic_vars_Jacobian(problemrow,problemcol,M_,x,type,ca
if nargin<6
caller_string='';
end
aux_vars_type = [M_.aux_vars.type];
aux_eq_nbr = max(find(aux_vars_type == 6));
if isempty(aux_eq_nbr)
if ~isempty(M_.aux_vars)
aux_vars_type = [M_.aux_vars.type];
aux_eq_nbr = max(find(aux_vars_type == 6));
if isempty(aux_eq_nbr)
aux_eq_nbr=0;
end
else
aux_eq_nbr=0;
end
if strcmp(type,'dynamic')
@ -84,6 +88,7 @@ if strcmp(type,'dynamic')
fprintf('\n%s The problem most often occurs, because a variable with\n',caller_string)
fprintf('%s exponent smaller than 1 has been initialized to 0. Taking the derivative\n',caller_string)
fprintf('%s and evaluating it at the steady state then results in a division by 0.\n',caller_string)
fprintf('%s If you are using model-local variables (# operator), check their values as well.\n',caller_string)
elseif strcmp(type,'static')
for ii=1:length(problemrow)
if problemcol(ii)<=M_.orig_endo_nbr
@ -119,6 +124,7 @@ elseif strcmp(type,'static')
fprintf('\n%s The problem most often occurs, because a variable with\n',caller_string)
fprintf('%s exponent smaller than 1 has been initialized to 0. Taking the derivative\n',caller_string)
fprintf('%s and evaluating it at the steady state then results in a division by 0.\n',caller_string)
fprintf('%s If you are using model-local variables (# operator), check their values as well.\n',caller_string)
else
error('Unknown Type')
end

View File

@ -352,7 +352,7 @@ if (kalman_algo == 2) || (kalman_algo == 4)
Q = blkdiag(Q,H);
R = blkdiag(R,eye(pp));
Pstar = blkdiag(Pstar,H);
Pinf = blckdiag(Pinf,zeros(pp));
Pinf = blkdiag(Pinf,zeros(pp));
H = zeros(pp,1);
mmm = mm+pp;
end
@ -395,7 +395,7 @@ switch DynareOptions.lik_init
if kalman_algo == 0
kalman_algo = 3;
elseif ~((kalman_algo == 3) || (kalman_algo == 4))
error(['diffuse filter: options_.kalman_algo can only be equal ' ...
error(['The model requires Diffuse filter, but you specified a different Kalman filter. You must set options_.kalman_algo ' ...
'to 0 (default), 3 or 4'])
end
[Z,T,R,QT,Pstar,Pinf] = schur_statespace_transformation(Z,T,R,Q,DynareOptions.qz_criterium);
@ -436,7 +436,7 @@ switch DynareOptions.lik_init
Q = blkdiag(Q,H);
R = blkdiag(R,eye(pp));
Pstar = blkdiag(Pstar,H);
Pinf = blckdiag(Pinf,zeros(pp));
Pinf = blkdiag(Pinf,zeros(pp));
H1 = zeros(pp,1);
mmm = mm+pp;
end
@ -726,7 +726,7 @@ if (kalman_algo==2) || (kalman_algo==4)
Q = blkdiag(Q,H);
R = blkdiag(R,eye(pp));
Pstar = blkdiag(Pstar,H);
Pinf = blckdiag(Pinf,zeros(pp));
Pinf = blkdiag(Pinf,zeros(pp));
H1 = zeros(pp,1);
mmm = mm+pp;
end

View File

@ -99,6 +99,7 @@ DecompFileNumber = 1;
% Compute total variances (covariances are not saved) and variances
% implied by each structural shock.
linea = 0;
only_non_stationary_vars=0;
for file = 1:NumberOfDrawsFiles
if posterior
load([M_.dname '/metropolis/' DrawsFiles(file).name ]);
@ -115,10 +116,26 @@ for file = 1:NumberOfDrawsFiles
set_parameters(pdraws{linee,1});
[dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
end
tmp = th_autocovariances(dr,ivar,M_,options_,nodecomposition);
for i=1:nvar
for j=1:nexo
Decomposition_array(linea,(i-1)*nexo+j) = tmp{2}(i,j);
if file==1 && linee==1
[tmp, stationary_vars] = th_autocovariances(dr,ivar,M_,options_,nodecomposition);
if isempty(stationary_vars)
fprintf('\ndsge_simulated_theoretical_variance_decomposition:: All requested endogenous variables have a unit root and thus infinite variance.\n')
fprintf('dsge_simulated_theoretical_variance_decomposition:: No decomposition is performed.\n')
only_non_stationary_vars=1;
end
end
if only_non_stationary_vars
for i=1:nvar
for j=1:nexo
Decomposition_array(linea,(i-1)*nexo+j) = NaN;
end
end
else
tmp = th_autocovariances(dr,ivar,M_,options_,nodecomposition);
for i=1:nvar
for j=1:nexo
Decomposition_array(linea,(i-1)*nexo+j) = tmp{2}(i,j);
end
end
end
if linea == NumberOfDecompLines

View File

@ -64,7 +64,7 @@ switch task
horizon = 5;
end
if isempty(M_.endo_histval)
y0 = repmat(oo_.steady_state,1,maximum_lag);
y0 = repmat(oo_.dr.ys,1,maximum_lag);
else
y0 = M_.endo_histval;
end
@ -136,5 +136,5 @@ for i=1:M_.exo_det_nbr
end
if options_.nograph == 0
forecast_graphs(var_list);
forecast_graphs(var_list,M_, oo_,options_)
end

View File

@ -53,8 +53,12 @@ elseif options_.steadystate_flag
%solve for instrument, using univariate solver, starting at initial value for instrument
inst_val = csolve(nl_func,ys_init(k_inst),'',options_.solve_tolf,100);
else
%solve for instrument, using multivariate solver, starting at initial value for instrument
[inst_val,info1] = dynare_solve(nl_func,ys_init(k_inst),options_);
%solve for instrument, using multivariate solver, starting at
%initial value for instrument
opt = options_;
opt.jacobian_flag = 0;
[inst_val,info1] = dynare_solve(nl_func,ys_init(k_inst), ...
opt);
end
ys_init(k_inst) = inst_val;
exo_ss = [oo.exo_steady_state oo.exo_det_steady_state];
@ -63,7 +67,9 @@ elseif options_.steadystate_flag
else
n_var = M.orig_endo_nbr;
xx = oo.steady_state(1:n_var);
[xx,check] = dynare_solve(nl_func,xx,options_);
opt = options_;
opt.jacobian_flag = 0;
[xx,check] = dynare_solve(nl_func,xx,opt);
[junk,junk,steady_state] = nl_func(xx);
end

View File

@ -55,7 +55,7 @@ addpath([dynareroot '/ms-sbvar/'])
addpath([dynareroot '/ms-sbvar/identification/'])
addpath([dynareroot '../contrib/ms-sbvar/TZcode/MatlabFiles/'])
addpath([dynareroot '/parallel/'])
addpath([dynareroot '/particle/'])
addpath([dynareroot '/particles/src'])
addpath([dynareroot '/gsa/'])
addpath([dynareroot '/ep/'])
addpath([dynareroot '/cli/'])
@ -63,7 +63,6 @@ addpath([dynareroot '/lmmcp/'])
addpath([dynareroot '/optimization/'])
addpath([dynareroot '/modules/dates/src/'])
addpath([dynareroot '/modules/dseries/src/'])
addpath([dynareroot '/modules/dseries/src/read'])
addpath([dynareroot '/utilities/doc/'])
addpath([dynareroot '/utilities/tests/src/'])
addpath([dynareroot '/utilities/dataset/'])
@ -131,7 +130,7 @@ mex_status(4,1) = {'sparse_hessian_times_B_kronecker_C'};
mex_status(4,2) = {'kronecker'};
mex_status(4,3) = {'Sparse kronecker products'};
mex_status(5,1) = {'local_state_space_iteration_2'};
mex_status(5,2) = {'particle/local_state_space_iteration'};
mex_status(5,2) = {'reduced_form_models/local_state_space_iteration_2'};
mex_status(5,3) = {'Local state space iteration (second order)'};
number_of_mex_files = size(mex_status,1);
%% Remove some directories from matlab's path. This is necessary if the user has
@ -217,8 +216,7 @@ if verbose
skipline()
end
% Save empty dates and dseries objects (necessary if a mod file is not preprocessed).
initialize_dates_toolbox;
dseries('initialize');
% Initialization of the dates and dseries classes (recursive).
initialize_dseries_toolbox;
cd(origin);

View File

@ -33,11 +33,11 @@ global M_ options_ oo_ estim_params_ bayestopt_ dataset_ dataset_info
% Set particle filter flag.
if options_.order > 1
if options_.particle.status && options_.order==2
if options_.particle.status && options_.order==2
skipline()
disp('Estimation using a non linear filter!')
skipline()
if ~options_.nointeractive && ismember(options_.mode_compute,[1,3,4]) % Known gradient-based optimizers
if ~options_.nointeractive && ismember(options_.mode_compute,[1,3,4]) && ~strcmpi(options_.particle.filter_algorithm,'gf')% Known gradient-based optimizers
disp('You are using a gradient-based mode-finder. Particle filtering introduces discontinuities in the')
disp('objective function w.r.t the parameters. Thus, should use a non-gradient based optimizer.')
fprintf('\nPlease choose a mode-finder:\n')
@ -107,29 +107,6 @@ if options_.dsge_var
end
end
%check for calibrated covariances before updating parameters
if ~isempty(estim_params_)
estim_params_=check_for_calibrated_covariances(xparam1,estim_params_,M_);
end
%%read out calibration that was set in mod-file and can be used for initialization
xparam1_calib=get_all_parameters(estim_params_,M_); %get calibrated parameters
if ~any(isnan(xparam1_calib)) %all estimated parameters are calibrated
full_calibration_detected=1;
else
full_calibration_detected=0;
end
if options_.use_calibration_initialization %set calibration as starting values
[xparam1,estim_params_]=do_parameter_initialization(estim_params_,xparam1_calib,xparam1); %get explicitly initialized parameters that have precedence to calibrated values
try
check_prior_bounds(xparam1,bounds,M_,estim_params_,options_,bayestopt_); %check whether calibration satisfies prior bounds
catch
e = lasterror();
fprintf('Cannot use parameter values from calibration as they violate the prior bounds.')
rethrow(e);
end
end
% Set sigma_e_is_diagonal flag (needed if the shocks block is not declared in the mod file).
M_.sigma_e_is_diagonal = 1;
if estim_params_.ncx || any(nnz(tril(M_.Correlation_matrix,-1))) || isfield(estim_params_,'calibrated_covariances')
@ -180,7 +157,7 @@ try
oo_ = initial_estimation_checks(objective_function,xparam1,dataset_,dataset_info,M_,estim_params_,options_,bayestopt_,bounds,oo_);
catch % if check fails, provide info on using calibration if present
e = lasterror();
if full_calibration_detected %calibrated model present and no explicit starting values
if estim_params_.full_calibration_detected %calibrated model present and no explicit starting values
skipline(1);
fprintf('ESTIMATION_CHECKS: There was an error in computing the likelihood for initial parameter values.\n')
fprintf('ESTIMATION_CHECKS: You should try using the calibrated version of the model as starting values. To do\n')
@ -314,9 +291,9 @@ if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation
end
parameter_names = bayestopt_.name;
if options_.cova_compute || options_.mode_compute==5 || options_.mode_compute==6
save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names');
save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names','fval');
else
save([M_.fname '_mode.mat'],'xparam1','parameter_names');
save([M_.fname '_mode.mat'],'xparam1','parameter_names','fval');
end
end
@ -527,7 +504,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
oo_.Smoother.TrendCoeffs = trend_coeff;
oo_.Smoother.Variance = P;
i_endo = bayestopt_.smoother_saved_var_list;
if options_.nk ~= 0
if 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')
@ -545,7 +522,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
i1 = dr.order_var(bayestopt_.smoother_var_list(i));
eval(['oo_.SmoothedVariables.' deblank(M_.endo_names(i1,:)) ' = ' ...
'atT(i,:)'';']);
if options_.nk > 0
if 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
@ -557,9 +534,9 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
end
if ~options_.nograph,
[nbplt,nr,nc,lr,lc,nstar] = pltorg(M_.exo_nbr);
if options_.TeX
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([M_.fname '_SmoothedShocks.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n');
fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
end
@ -606,7 +583,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
title(name,'Interpreter','none')
end
dyn_saveas(fh,[M_.fname '_SmoothedShocks' int2str(plt)],options_);
if options_.TeX
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
for jj = 1:nstar0
fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
@ -619,7 +596,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
fprintf(fidTeX,'\n');
end
end
if options_.TeX
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
@ -649,9 +626,9 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
end
if ~options_.nograph
[nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw);
if options_.TeX
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([M_.fname '_SmoothedObservationErrors.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n');
fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
end
@ -699,7 +676,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
title(name,'Interpreter','none')
end
dyn_saveas(fh,[M_.fname '_SmoothedObservationErrors' int2str(plt)],options_);
if options_.TeX
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
for jj = 1:nstar0
fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
@ -712,7 +689,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
fprintf(fidTeX,'\n');
end
end
if options_.TeX
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
@ -724,9 +701,9 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
%%
if ~options_.nograph
[nbplt,nr,nc,lr,lc,nstar] = pltorg(n_varobs);
if options_.TeX
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([M_.fname '_HistoricalAndSmoothedVariables.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n');
fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
end
@ -774,7 +751,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
title(name,'Interpreter','none')
end
dyn_saveas(fh,[M_.fname '_HistoricalAndSmoothedVariables' int2str(plt)],options_);
if options_.TeX
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
for jj = 1:nstar0,
fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
@ -787,7 +764,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
fprintf(fidTeX,'\n');
end
end
if options_.TeX
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);

View File

@ -65,6 +65,10 @@ else
options_.varlist = var_list_;
end
if options_.dsge_var && options_.presample~=0
error('DSGE-VAR does not support the presample option.')
end
% Set the number of observed variables.
options_.number_of_observed_variables = length(options_.varobs);
@ -281,6 +285,22 @@ if ~isempty(estim_params_) && ~isempty(options_.mode_file) && ~options_.mh_poste
skipline()
end
%check for calibrated covariances before updating parameters
if ~isempty(estim_params_)
estim_params_=check_for_calibrated_covariances(xparam1,estim_params_,M_);
end
%%read out calibration that was set in mod-file and can be used for initialization
xparam1_calib=get_all_parameters(estim_params_,M_); %get calibrated parameters
if ~any(isnan(xparam1_calib)) %all estimated parameters are calibrated
estim_params_.full_calibration_detected.full_calibration_detected=1;
else
estim_params_.full_calibration_detected.full_calibration_detected=0;
end
if options_.use_calibration_initialization %set calibration as starting values
[xparam1,estim_params_]=do_parameter_initialization(estim_params_,xparam1_calib,xparam1); %get explicitly initialized parameters that have precedence to calibrated values
end
if ~isempty(estim_params_)
if ~isempty(bayestopt_) && any(bayestopt_.pshape > 0)
% Plot prior densities.
@ -299,7 +319,17 @@ if ~isempty(estim_params_)
bounds.ub = ub;
end
% Test if initial values of the estimated parameters are all between the prior lower and upper bounds.
check_prior_bounds(xparam1,bounds,M_,estim_params_,options_,bayestopt_)
if options_.use_calibration_initialization
try
check_prior_bounds(xparam1,bounds,M_,estim_params_,options_,bayestopt_)
catch
e = lasterror();
fprintf('Cannot use parameter values from calibration as they violate the prior bounds.')
rethrow(e);
end
else
check_prior_bounds(xparam1,bounds,M_,estim_params_,options_,bayestopt_)
end
end
if isempty(estim_params_)% If estim_params_ is empty (e.g. when running the smoother on a calibrated model)
@ -453,7 +483,8 @@ if options_.analytic_derivation,
if estim_params_.np,
% check if steady state changes param values
M=M_;
M.params(estim_params_.param_vals(:,1)) = M.params(estim_params_.param_vals(:,1))*1.01;
M.params(estim_params_.param_vals(:,1)) = xparam1(estim_params_.nvx+estim_params_.ncx+estim_params_.nvn+estim_params_.ncn+1:end); %set parameters
M.params(estim_params_.param_vals(:,1)) = M.params(estim_params_.param_vals(:,1))*1.01; %vary parameters
if options_.diffuse_filter
steadystate_check_flag = 0;
else
@ -513,7 +544,13 @@ ncn = estim_params_.ncn;
if estim_params_.np
M.params(estim_params_.param_vals(:,1)) = xparam1(nvx+ncx+nvn+ncn+1:end);
end
[oo_.steady_state, params] = evaluate_steady_state(oo_.steady_state,M,options_,oo_,steadystate_check_flag);
[oo_.steady_state, params,info] = evaluate_steady_state(oo_.steady_state,M,options_,oo_,steadystate_check_flag);
if info(1)
fprintf('\ndynare_estimation_init:: The steady state at the initial parameters cannot be computed.')
print_info(info, 0, options_);
end
if all(abs(oo_.steady_state(bayestopt_.mfys))<1e-9)
options_.noconstant = 1;
else

View File

@ -59,8 +59,24 @@ options_ident = set_default_option(options_ident,'periods',300);
options_ident = set_default_option(options_ident,'replic',100);
options_ident = set_default_option(options_ident,'advanced',0);
options_ident = set_default_option(options_ident,'normalize_jacobians',1);
%Deal with non-stationary cases
if isfield(options_ident,'diffuse_filter') %set lik_init and options_
options_ident.lik_init=3; %overwrites any other lik_init set
options_.diffuse_filter=options_ident.diffuse_filter; %make options_ inherit diffuse filter; will overwrite any conflicting lik_init in dynare_estimation_init
else
if options_.diffuse_filter==1 %warning if estimation with diffuse filter was done, but not passed
warning('IDENTIFICATION:: Previously the diffuse_filter option was used, but it was not passed to the identification command. This may result in problems if your model contains unit roots.')
end
if isfield(options_ident,'lik_init')
if options_ident.lik_init==3 %user specified diffuse filter using the lik_init option
options_ident.analytic_derivation=0; %diffuse filter not compatible with analytic derivation
end
end
end
options_ident = set_default_option(options_ident,'lik_init',1);
options_ident = set_default_option(options_ident,'analytic_derivation',1);
if isfield(options_ident,'nograph'),
options_.nograph=options_ident.nograph;
end
@ -70,6 +86,9 @@ end
if isfield(options_ident,'graph_format'),
options_.graph_format=options_ident.graph_format;
end
if isfield(options_ident,'prior_trunc'),
options_.prior_trunc=options_ident.prior_trunc;
end
if options_ident.gsa_sample_file,
GSAFolder = checkpath('gsa',M_.dname);
@ -122,8 +141,7 @@ options_.prior_mc = options_ident.prior_mc;
options_.options_ident = options_ident;
options_.Schur_vec_tol = 1.e-8;
options_.nomoments=0;
options_.analytic_derivation=1;
options_ = set_default_option(options_,'analytic_derivation',1);
options_ = set_default_option(options_,'datafile','');
options_.mode_compute = 0;
options_.plot_priors = 0;

View File

@ -88,18 +88,18 @@ if options.solve_algo == 0
error('You can''t use solve_algo=0 since you don''t have MATLAB''s Optimization Toolbox')
end
end
options=optimset('fsolve');
options.MaxFunEvals = 50000;
options.MaxIter = options.steady.maxit;
options.TolFun = tolf;
options.Display = 'iter';
options4fsolve=optimset('fsolve');
options4fsolve.MaxFunEvals = 50000;
options4fsolve.MaxIter = options.steady.maxit;
options4fsolve.TolFun = tolf;
options4fsolve.Display = 'iter';
if jacobian_flag
options.Jacobian = 'on';
options4fsolve.Jacobian = 'on';
else
options.Jacobian = 'off';
options4fsolve.Jacobian = 'off';
end
if ~isoctave
[x,fval,exitval,output] = fsolve(func,x,options,varargin{:});
[x,fval,exitval,output] = fsolve(func,x,options4fsolve,varargin{:});
else
% Under Octave, use a wrapper, since fsolve() does not have a 4th arg
func2 = str2func(func);
@ -107,7 +107,7 @@ if options.solve_algo == 0
% The Octave version of fsolve does not converge when it starts from the solution
fvec = feval(func,x);
if max(abs(fvec)) >= tolf
[x,fval,exitval,output] = fsolve(func,x,options);
[x,fval,exitval,output] = fsolve(func,x,options4fsolve);
else
exitval = 3;
end;

View File

@ -74,9 +74,8 @@ elseif options.bytecode
x(M.block_structure_stat.block(b).variable) = y;
else
[chk, nulldev, nulldev1, x] = bytecode( x, exo, params, ...
x, 1, x, 'evaluate', ...
'static', ['block ' ...
'= '] int2str(b)]);
x, 1, x, 'evaluate', 'static', ...
['block = ' int2str(b)]);
if chk
info = 1;
return

View File

@ -172,7 +172,7 @@ end
% set boundaries if mcp
[lb,ub,pfm.eq_index] = get_complementarity_conditions(M_);
[lb,ub,pfm.eq_index] = get_complementarity_conditions(M_, options_.ramsey_policy);
options_.lmmcp.lb = repmat(lb,block_nbr,1);
options_.lmmcp.ub = repmat(ub,block_nbr,1);
pfm.block_nbr = block_nbr;

View File

@ -207,9 +207,16 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
disp(['STEADY: numerical initial values or parameters incompatible with the following' ...
' equations'])
disp(ii')
disp('Check whether your model in truly linear')
disp('Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n')
elseif isempty(ii) && max(abs(fvec)) > 1e-12
ys = ys_init-jacob\fvec;
resid = evaluate_static_model(ys,exo_ss,params,M,options);
if max(abs(resid)) > 1e-6
check=1;
fprintf('STEADY: No steady state for your model could be found\n')
fprintf('STEADY: Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n')
end
else
ys = ys_init;
end
@ -225,7 +232,7 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
fprintf('STEADY: Derivative of Equation %d with respect to Variable %s (initial value of %s: %g) \n',infrow(ii),deblank(M.endo_names(orig_var_index,:)),deblank(M.endo_names(orig_var_index,:)),ys_init(infcol(ii)))
end
end
disp('STEADY: Check whether your model in truly linear\n')
fprintf('Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n')
end
end
end
@ -237,7 +244,7 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
if check
info(1)= 20;
resid = evaluate_static_model(ys_init,exo_ss,params,M,options);
resid = evaluate_static_model(ys,exo_ss,params,M,options);
info(2) = resid'*resid ;
if isnan(info(2))
info(1)=22;

View File

@ -1,6 +1,14 @@
function forecast_graphs(var_list)
function forecast_graphs(var_list,M_, oo_,options_)
% function forecast_graphs(var_list)
% Plots the classical forecasts created by dyn_forecast.m
%
% Inputs:
% o var_list character array with variable names
% o M_ model structure
% o oo_ outputs structure
% o options_ options structure
% Copyright (C) 2008-2013 Dynare Team
% Copyright (C) 2008-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -17,35 +25,41 @@ function forecast_graphs(var_list)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ options_
nc = 4;
nr = 3;
exo_nbr = M_.exo_nbr;
endo_names = M_.endo_names;
fname = M_.fname;
dname = M_.dname;
yf = oo_.forecast.Mean;
hpdinf = oo_.forecast.HPDinf;
hpdsup = oo_.forecast.HPDsup;
if isempty(var_list)
varlist = 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)
tmp = strmatch(var_list(i,:),endo_names,'exact');
if isempty(tmp)
error([var_list(i,:) ' isn''t and endogenous variable'])
error([var_list(i,:) ' isn''t an endogenous variable'])
end
i_var = [i_var; tmp];
end
nvar = length(i_var);
% create subdirectory <fname>/graphs if id doesn't exist
if ~exist(fname, 'dir')
mkdir('.',fname);
% create subdirectory <dname>/graphs if id doesn't exist
if ~exist(dname, 'dir')
mkdir('.',dname);
end
if ~exist([fname '/graphs'])
mkdir(fname,'graphs');
if ~exist([dname '/graphs'],'dir')
mkdir(dname,'graphs');
end
%% write LaTeX-Header
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([M_.dname '/graphs/',fname,'_forcst.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by Dynare''s graph_decomp.m.\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
end
m = 1;
@ -53,8 +67,16 @@ n_fig = 1;
hh=dyn_figure(options_,'Name','Forecasts (I)');
for j= 1:nvar
if m > nc*nr;
dyn_saveas(hh,[ fname '/graphs/forcst' int2str(n_fig)],options_);
dyn_saveas(hh,[ dname '/graphs/forcst' int2str(n_fig)],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s/graphs/forcst%d}\n',dname,n_fig);
fprintf(fidTeX,'\\label{Fig:forcst:%d}\n',n_fig);
fprintf(fidTeX,'\\caption{Mean forecasts and %2.0f%% confidence intervals}\n',options_.conf_sig*100);
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
end
n_fig =n_fig+1;
eval(['hh=dyn_figure(options_,''Name'',''Forecasts (' int2str(n_fig) ')'');']);
m = 1;
@ -69,11 +91,11 @@ for j= 1:nvar
% $$$ hold on
% $$$ obs = 10;
% $$$ end
plot([NaN(obs,1); yf.(vn)]);
plot([NaN(obs,1); yf.(vn)],'b-');
hold on
plot([NaN(obs,1); hpdinf.(vn)]);
plot([NaN(obs,1); hpdinf.(vn)],'b-');
hold on
plot([NaN(obs,1); hpdsup.(vn)]);
plot([NaN(obs,1); hpdsup.(vn)],'b-');
title(vn,'Interpreter','none');
xlim([1 obs+length(hpdsup.(vn))])
hold off
@ -81,5 +103,21 @@ for j= 1:nvar
end
if m > 1
dyn_saveas(hh,[fname '/graphs/forcst' int2str(n_fig)],options_);
dyn_saveas(hh,[dname '/graphs/forcst' int2str(n_fig)],options_);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s/graphs/forcst%d}\n',dname,n_fig);
fprintf(fidTeX,'\\label{Fig:forcst:%d}\n',n_fig);
fprintf(fidTeX,'\\caption{Mean forecasts and %2.0f\\%% confidence intervals}\n',options_.conf_sig*100);
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
end
end
%% write LaTeX-Footer
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,' \n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end

View File

@ -52,6 +52,7 @@ else
end
i = 1;
c = zeros(n,1,p);
c1 = zeros(n,1,p);
while i < m
if t(i+1,i) == 0
if i == 1

View File

@ -19,10 +19,18 @@ function [H, dA, dOm, Hss, gp, d2A, d2Om, H2ss] = getH(A, B, M_,oo_,options_,kro
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if nargin<6 || isempty(kronflag), kronflag = 0; end
if nargin<7 || isempty(indx), indx = [1:M_.param_nbr]; end,
if nargin<8 || isempty(indexo), indexo = []; end,
if nargin<9 || isempty(iv), iv = (1:length(A))'; end,
if nargin<6 || isempty(kronflag)
kronflag = 0;
end
if nargin<7 || isempty(indx)
indx = [];
end
if nargin<8 || isempty(indexo)
indexo = [];
end
if nargin<9 || isempty(iv)
iv = (1:length(A))';
end
[I,J]=find(M_.lead_lag_incidence');
yy0=oo_.dr.ys(I);
@ -122,7 +130,7 @@ else
dyssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr);
d2yssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr,M_.param_nbr);
[residual, gg1] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params);
df = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ...
df = feval([M_.fname,'_params_derivs'],yy0, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1]), ...
M_.params, oo_.dr.ys, 1, dyssdtheta, d2yssdtheta);
dyssdtheta = -gg1\df;
if nargout>5,
@ -184,9 +192,9 @@ if nargout>5,
% g22 = get_all_2nd_derivs(gpp,m,nelem,M_.param_nbr);
% g22 = g22(:,:,indx,indx);
else
[df, gp] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ...
[df, gp] = feval([M_.fname,'_params_derivs'],yy0, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1,1]), ...
M_.params, oo_.dr.ys, 1, dyssdtheta,d2yssdtheta);
[residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
[residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1,1]), ...
M_.params, oo_.dr.ys, 1);
[nr, nc]=size(g2);
end

View File

@ -17,10 +17,18 @@ function [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, M_,oo_,options_,kronflag,
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if nargin<7 || isempty(indx), indx = [1:M_.param_nbr];, end,
if nargin<8 || isempty(indexo), indexo = [];, end,
if nargin<10 || isempty(nlags), nlags=3; end,
if nargin<11 || isempty(useautocorr), useautocorr=0; end,
if nargin<7 || isempty(indx)
% indx = [1:M_.param_nbr];
end,
if nargin<8 || isempty(indexo)
indexo = [];
end,
if nargin<10 || isempty(nlags)
nlags=3;
end
if nargin<11 || isempty(useautocorr)
useautocorr=0;
end
% if useautocorr,
warning('off','MATLAB:divideByZero')

View File

@ -1,56 +0,0 @@
function str = get_random_string(n);
%@info:
%! @deftypefn {Function File} {@var{str} =} get_random_string (@var{n})
%! @anchor{get_random_string}
%! @sp 1
%! Builds a random string (starting with a letter).
%! @sp 2
%! @strong{Inputs}
%! @sp 1
%! @table @ @var
%! @item a
%! Scalar integer, number of characters in the generated string.
%! @end table
%! @sp 1
%! @strong{Outputs}
%! @sp 1
%! @table @ @var
%! @item str
%! Generated string
%! @end table
%! @sp 2
%! @strong{This function is called by:}
%! @sp 2
%! @strong{This function calls:}
%! @ref{set_time}
%!
%! @end deftypefn
%@eod:
% Copyright (C) 2012 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
% AUTHOR(S) stephane DOT adjemian AT univ DASH lemans DOT fr
str0 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
m0 = 2*26;
m1 = m0+10;
str = str0(ceil(rand*m0)); % First character has to be a letter!
str = [str, str0(ceil(rand(1,n-1)*m1))];

View File

@ -57,7 +57,7 @@ options_.lyapunov_complex_threshold = 1e-15;
options_.solve_tolf = eps^(1/3);
options_.solve_tolx = eps^(2/3);
options_.dr_display_tol=1e-6;
options_.minimal_workspace = 0;
options_.dp.maxit = 3000;
options_.steady.maxit = 50;
options_.simul.maxit = 50;
@ -259,8 +259,8 @@ particle.proposal_approximation.cubature = 1;
particle.proposal_approximation.unscented = 0;
particle.proposal_approximation.montecarlo = 0;
% Approximation of the particle distribution
particle.distribution_approximation.cubature = 0;
particle.distribution_approximation.unscented = 1;
particle.distribution_approximation.cubature = 1;
particle.distribution_approximation.unscented = 0;
particle.distribution_approximation.montecarlo = 0;
% Number of partitions for the smoothed resampling method
particle.resampling.number_of_partitions = 200;
@ -275,6 +275,9 @@ particle.liu_west_delta = 0.99 ;
particle.liu_west_chol_sigma_bar = .01 ;
% Copy ep structure in options_ global structure
options_.particle = particle;
options_.rwgmh.init_scale = 1e-4 ;
options_.rwgmh.scale_chain = 1 ;
options_.rwgmh.scale_shock = 1e-5 ;
% TeX output
options_.TeX = 0;
@ -403,6 +406,7 @@ options_.lik_init = 1;
options_.load_mh_file = 0;
options_.logdata = 0;
options_.loglinear = 0;
options_.linear_approximation = 0;
options_.logged_steady_state = 0;
options_.mh_conf_sig = 0.90;
options_.prior_interval = 0.90;
@ -417,7 +421,14 @@ options_.recursive_estimation_restart = 0;
options_.MCMC_jumping_covariance='hessian';
options_.use_calibration_initialization = 0;
options_.endo_vars_for_moment_computations_in_estimation=[];
% Tailored Random Block Metropolis-Hastings
options_.TaRB.use_TaRB = 0;
options_.TaRB.mode_compute=4;
options_.TaRB.new_block_probability=0.25; %probability that next parameter belongs to new block
% Run optimizer silently
options_.silent_optimizer=0;
% Prior restrictions
options_.prior_restrictions.status = 0;
@ -488,6 +499,9 @@ options_.homotopy_force_continue = 0;
%csminwel optimization routine
csminwel.tolerance.f=1e-7;
csminwel.maxiter=1000;
csminwel.verbosity=1;
csminwel.Save_files=1;
options_.csminwel=csminwel;
%newrat optimization routine
@ -495,6 +509,9 @@ newrat.hess=1; % dynare numerical hessian
newrat.tolerance.f=1e-5;
newrat.tolerance.f_analytic=1e-7;
newrat.maxiter=1000;
newrat.verbosity=1;
newrat.Save_files=1;
options_.newrat=newrat;
% Simplex optimization routine (variation on Nelder Mead algorithm).

View File

@ -28,6 +28,15 @@ x = initial_period-1/freq:(1/freq):initial_period+(gend-1)/freq;
nvar = length(i_var);
%% write LaTeX-Header
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
fidTeX = fopen([DynareModel.fname '_shock_decomp.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by Dynare''s graph_decomp.m.\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
end
%%plot decomposition
for j=1:nvar
z1 = squeeze(z(i_var(j),:,:));
xmin = x(1);
@ -81,4 +90,20 @@ for j=1:nvar
dyn_saveas(fhandle,[DynareModel.fname,'_shock_decomposition_',deblank(endo_names(i_var(j),:))],DynareOptions);
hold off
end
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,['\\includegraphics[scale=0.5]{%s_shock_decomposition_%s}\n'],DynareModel.fname,deblank(endo_names(i_var(j),:)));
fprintf(fidTeX,'\\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,'\\end{figure}\n');
fprintf(fidTeX,' \n');
end
end
%% write LaTeX-Footer
if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
fprintf(fidTeX,' \n');
fprintf(fidTeX,'%% End of TeX file.\n');
fclose(fidTeX);
end

View File

@ -64,7 +64,7 @@ if opt_gsa.load_ident_files==0,
if opt_gsa.morris==2,
pdraws = dynare_identification(options_.options_ident,[lpmatx lpmat(istable,:)]);
% [pdraws, TAU, GAM] = dynare_identification(options_.options_ident,[lpmatx lpmat(istable,:)]);
if max(max(abs(pdraws-[lpmatx lpmat(istable,:)])))==0,
if ~isempty(pdraws) && max(max(abs(pdraws-[lpmatx lpmat(istable,:)])))==0,
disp(['Sample check OK ', num2str(max(max(abs(pdraws-[lpmatx lpmat(istable,:)]))))]),
clear pdraws;
end

View File

@ -20,7 +20,7 @@ function [vdec, cc, ac] = mc_moments(mm, ss, dr)
global options_ M_ estim_params_ oo_
[nr1, nc1, nsam] = size(mm);
nobs=size(options_.varobs,1);
nobs=size(options_.varobs,2);
disp('Computing theoretical moments ...')
h = dyn_waitbar(0,'Theoretical moments ...');
vdec = zeros(nobs,M_.exo_nbr,nsam);
@ -37,7 +37,7 @@ global options_ M_ estim_params_ oo_
cc(:,:,j)=triu(corr);
dum=[];
for i=1:options_.ar
dum=[dum, autocorr{i}];
dum=[dum, autocorr{i}];
end
ac(:,:,j)=dum;
dyn_waitbar(j/nsam,h)

View File

@ -42,7 +42,7 @@ function pdraw = prior_draw_gsa(init,rdraw)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global bayestopt_ options_
global bayestopt_ options_ estim_params_ M_
persistent npar pshape p6 p7 p3 p4 lbcum ubcum
if init
@ -55,7 +55,18 @@ if init
pdraw = zeros(npar,1);
lbcum = zeros(npar,1);
ubcum = ones(npar,1);
bounds = prior_bounds(bayestopt_,options_);
[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.lb = max(bounds.lb,lb);
bounds.ub = min(bounds.ub,ub);
else % estimated parameters but no declared priors
% No priors are declared so Dynare will estimate the model by
% maximum likelihood with inequality constraints for the parameters.
bounds.lb = lb;
bounds.ub = ub;
end
% set bounds for cumulative probabilities
for i = 1:npar
switch pshape(i)
@ -63,8 +74,8 @@ if init
p4(i) = min(p4(i),bounds.ub(i));
p3(i) = max(p3(i),bounds.lb(i));
case 3% Gaussian prior.
lbcum(i) = 0.5 * erfc(-(bounds.lb(i)-p6(i))/p7(i) ./ sqrt(2));;
ubcum(i) = 0.5 * erfc(-(bounds.ub(i)-p6(i))/p7(i) ./ sqrt(2));;
lbcum(i) = 0.5 * erfc(-(bounds.lb(i)-p6(i))/p7(i) ./ sqrt(2));
ubcum(i) = 0.5 * erfc(-(bounds.ub(i)-p6(i))/p7(i) ./ sqrt(2));
case 2% Gamma prior.
lbcum(i) = gamcdf(bounds.lb(i)-p3(i),p6(i),p7(i));
ubcum(i) = gamcdf(bounds.ub(i)-p3(i),p6(i),p7(i));

View File

@ -1,6 +1,8 @@
function set_shocks_param(xparam1)
% function set_shocks_param(xparam1)
% Set the structural and measurement error variances and covariances
% Copyright (C) 2012 Dynare Team
% Copyright (C) 2012-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -18,31 +20,86 @@ function set_shocks_param(xparam1)
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global estim_params_ M_
nvx = estim_params_.nvx;
ncx = estim_params_.ncx;
np = estim_params_.np;
Sigma_e = M_.Sigma_e;
offset = 0;
if nvx
offset = offset + nvx;
nvx = estim_params_.nvx;
ncx = estim_params_.ncx;
nvn = estim_params_.nvn;
ncn = estim_params_.ncn;
Sigma_e = M_.Sigma_e;
Correlation_matrix = M_.Correlation_matrix;
H = M_.H;
Correlation_matrix_ME = M_.Correlation_matrix_ME;
% setting shocks variance on the diagonal of Covariance matrix; used later
% for updating covariances
if nvx
var_exo = estim_params_.var_exo;
for i=1:nvx
k = var_exo(i,1);
Sigma_e(k,k) = xparam1(i)^2;
k =var_exo(i,1);
Sigma_e(k,k) = xparam1(i)^2;
end
end
if ncx
offset = offset + estim_params_.nvn;
end
% update offset
offset = nvx;
% setting measument error variance; on the diagonal of Covariance matrix; used later
% for updating covariances
if nvn
for i=1:nvn
k = estim_params_.nvn_observable_correspondence(i,1);
H(k,k) = xparam1(i+offset)^2;
end
end
% update offset
offset = nvx+nvn;
% setting shocks covariances
if ncx
corrx = estim_params_.corrx;
for i=1:ncx
k1 = corrx(i,1);
k2 = corrx(i,2);
Sigma_e(k1,k2) = xparam1(i+offset)*sqrt(Sigma_e_(k1,k1)*Sigma_e_(k2,k2));
Sigma_e(k2,k1) = Sigma_e_(k1,k2);
k1 = corrx(i,1);
k2 = corrx(i,2);
Correlation_matrix(k1,k2) = xparam1(i+offset);
Correlation_matrix(k2,k1) = Correlation_matrix(k1,k2);
end
end
end
%build covariance matrix from correlation matrix and variances already on
%diagonal
Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e)));
%if calibrated covariances, set them now to their stored value
if isfield(estim_params_,'calibrated_covariances')
Sigma_e(estim_params_.calibrated_covariances.position)=estim_params_.calibrated_covariances.cov_value;
end
% update offset
offset = nvx+nvn+ncx;
% setting measurement error covariances
if ncn
corrn_observable_correspondence = estim_params_.corrn_observable_correspondence;
for i=1:ncn
k1 = corrn_observable_correspondence(i,1);
k2 = corrn_observable_correspondence(i,2);
Correlation_matrix_ME(k1,k2) = xparam1(i+offset);
Correlation_matrix_ME(k2,k1) = Correlation_matrix_ME(k1,k2);
end
end
%build covariance matrix from correlation matrix and variances already on
%diagonal
H = diag(sqrt(diag(H)))*Correlation_matrix_ME*diag(sqrt(diag(H)));
%if calibrated covariances, set them now to their stored value
if isfield(estim_params_,'calibrated_covariances_ME')
H(estim_params_.calibrated_covariances_ME.position)=estim_params_.calibrated_covariances_ME.cov_value;
end
M_.Sigma_e = Sigma_e;
% updating matrices in M
if nvx || ncx
M_.Sigma_e = Sigma_e;
M_.Correlation_matrix=Correlation_matrix;
end
if nvn || ncn
M_.H = H;
M_.Correlation_matrix_ME=Correlation_matrix_ME;
end

View File

@ -87,7 +87,7 @@ nshock = estim_params_.nvx;
nshock = nshock + estim_params_.nvn;
nshock = nshock + estim_params_.ncx;
nshock = nshock + estim_params_.ncn;
lpmat0=[];
lpmat0=zeros(Nsam,0);
xparam1=[];
pshape = bayestopt_.pshape(nshock+1:end);
@ -96,7 +96,22 @@ p2 = bayestopt_.p2(nshock+1:end);
p3 = bayestopt_.p3(nshock+1:end);
p4 = bayestopt_.p4(nshock+1:end);
bounds = prior_bounds(bayestopt_,options_);
[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.lb = max(bounds.lb,lb);
bounds.ub = min(bounds.ub,ub);
else % estimated parameters but no declared priors
% No priors are declared so Dynare will estimate the model by
% maximum likelihood with inequality constraints for the parameters.
bounds.lb = lb;
bounds.ub = ub;
if opt_gsa.prior_range==0
warning('GSA:: When using ML, sampling from the prior is not possible. Setting prior_range=1')
opt_gsa.prior_range=1;
end
end
if nargin==0,
OutputDirectoryName='';
@ -143,7 +158,7 @@ if fload==0,
end
end
else %ilptau==0
%[lpmat] = rand(Nsam,np);
[lpmat] = NaN(Nsam,np);
for j=1:np,
lpmat(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube
end
@ -151,7 +166,7 @@ if fload==0,
end
end
% try
dummy=prior_draw_gsa(1);
dummy=prior_draw_gsa(1); %initialize persistent variables
% catch
% if pprior,
% if opt_gsa.prior_range==0;
@ -242,6 +257,7 @@ if fload==0,
else
d = chol(inv(hh));
lp=randn(Nsam*2,nshock+np)*d+kron(ones(Nsam*2,1),xparam1');
lnprior=zeros(1,Nsam*2);
for j=1:Nsam*2,
lnprior(j) = any(lp(j,:)'<=bounds.lb | lp(j,:)'>=bounds.ub);
end
@ -263,6 +279,7 @@ if fload==0,
iwrong=zeros(1,Nsam);
inorestriction=zeros(1,Nsam);
irestriction=zeros(1,Nsam);
infox=zeros(1,Nsam);
for j=1:Nsam,
M_ = set_all_parameters([lpmat0(j,:) lpmat(j,:)]',estim_params_,M_);
%try stoch_simul([]);
@ -273,7 +290,7 @@ if fload==0,
[Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_,'restrict');
end
infox(j,1)=info(1);
if infox(j,1)==0 && ~exist('T'),
if infox(j,1)==0 && ~exist('T','var'),
dr_=oo_.dr;
if prepSA,
try
@ -321,7 +338,7 @@ if fload==0,
% bayestopt_.restrict_columns, ...
% bayestopt_.restrict_aux);
end
if ~exist('nspred'),
if ~exist('nspred','var'),
nspred = dr_.nspred; %size(dr_.ghx,2);
nboth = dr_.nboth;
nfwrd = dr_.nfwrd;
@ -339,7 +356,7 @@ if fload==0,
istable(j)=0;
if isfield(dr_,'eigval')
egg(:,j) = sort(dr_.eigval);
if exist('nspred')
if exist('nspred','var')
if any(isnan(egg(1:nspred,j)))
iwrong(j)=j;
else
@ -349,7 +366,7 @@ if fload==0,
end
end
else
if exist('egg'),
if exist('egg','var'),
egg(:,j)=ones(size(egg,1),1).*NaN;
end
iwrong(j)=j;
@ -457,6 +474,7 @@ else
stoch_simul([]);
%T=zeros(size(dr_.ghx,1),size(dr_.ghx,2)+size(dr_.ghu,2),length(istable));
ntrans=length(istable);
yys=NaN(length(ys_),ntrans);
for j=1:ntrans,
M_.params(estim_params_.param_vals(:,1)) = lpmat(istable(j),:)';
%stoch_simul([]);
@ -465,12 +483,12 @@ else
%[Tt,Rr,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
% bayestopt_.restrict_columns,...
% bayestopt_.restrict_aux);
if ~exist('T')
if ~exist('T','var')
T=zeros(size(dr_.ghx,1),size(dr_.ghx,2)+size(dr_.ghu,2),ntrans);
end
dr_ = oo_.dr;
T(:,:,j) = [dr_.ghx dr_.ghu];
if ~exist('nspred')
if ~exist('nspred','var')
nspred = dr_.nspred; %size(dr_.ghx,2);
nboth = dr_.nboth;
nfwrd = dr_.nfwrd;

View File

@ -1,6 +1,7 @@
function [vdec, corr, autocorr, z, zz] = th_moments(dr,var_list)
% [vdec, corr, autocorr, z, zz] = th_moments(dr,var_list)
% Copyright (C) 2012 Dynare Team
% Copyright (C) 2012-2015 Dynare Team
%
% This file is part of Dynare.
%
@ -17,38 +18,38 @@ function [vdec, corr, autocorr, z, zz] = th_moments(dr,var_list)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ options_
nvar = size(var_list,1);
if nvar == 0
global M_ oo_ options_
nvar = size(var_list,2);
if nvar == 0
nvar = length(dr.order_var);
ivar = [1:nvar]';
else
else
ivar=zeros(nvar,1);
for i=1:nvar
i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact');
if isempty(i_tmp)
error (['One of the variable specified does not exist']) ;
else
ivar(i) = i_tmp;
end
i_tmp = strmatch(var_list(:,i),M_.endo_names,'exact');
if isempty(i_tmp)
error(['One of the variables specified does not exist']) ;
else
ivar(i) = i_tmp;
end
end
end
[gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_, options_);
m = dr.ys(ivar(stationary_vars));
end
[gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_, options_);
m = dr.ys(ivar(stationary_vars));
% i1 = find(abs(diag(gamma_y{1})) > 1e-12);
i1 = [1:length(ivar)];
s2 = diag(gamma_y{1});
sd = sqrt(s2);
i1 = [1:length(ivar)];
s2 = diag(gamma_y{1});
sd = sqrt(s2);
z = [ m sd s2 ];
mean = m;
var = gamma_y{1};
z = [ m sd s2 ];
mean = m;
var = gamma_y{1};
%'THEORETICAL MOMENTS';
%'MEAN','STD. DEV.','VARIANCE');
@ -56,28 +57,27 @@ z;
%'VARIANCE DECOMPOSITION (in percent)';
if M_.exo_nbr>1,
vdec = 100*gamma_y{options_.ar+2}(i1,:);
vdec = 100*gamma_y{options_.ar+2}(i1,:);
else
vdec = 100*ones(size(gamma_y{1}(i1,1)));
end
vdec = 100*ones(size(gamma_y{1}(i1,1)));
end
%'MATRIX OF CORRELATIONS';
if options_.opt_gsa.useautocorr,
corr = gamma_y{1}(i1,i1)./(sd(i1)*sd(i1)');
corr = corr-diag(diag(corr))+diag(diag(gamma_y{1}(i1,i1)));
else
corr = gamma_y{1}(i1,i1);
corr = gamma_y{1}(i1,i1);
end
if options_.ar > 0
%'COEFFICIENTS OF AUTOCORRELATION';
if options_.ar > 0
%'COEFFICIENTS OF AUTOCORRELATION';
for i=1:options_.ar
if options_.opt_gsa.useautocorr,
autocorr{i} = gamma_y{i+1}(i1,i1);
else
autocorr{i} = gamma_y{i+1}(i1,i1).*(sd(i1)*sd(i1)');
end
zz(:,i) = diag(gamma_y{i+1}(i1,i1));
if options_.opt_gsa.useautocorr,
autocorr{i} = gamma_y{i+1}(i1,i1);
else
autocorr{i} = gamma_y{i+1}(i1,i1).*(sd(i1)*sd(i1)');
end
zz(:,i) = diag(gamma_y{i+1}(i1,i1));
end
end
end

View File

@ -17,7 +17,7 @@ function histvalf(fname)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_
global M_ oo_ ex0_
if ~exist(fname)
error(['Can''t find datafile: ' fname ]);

View File

@ -75,7 +75,7 @@ if info(1)==0,
tau=[oo_.dr.ys(oo_.dr.order_var); vec(A); dyn_vech(B*M_.Sigma_e*B')];
yy0=oo_.dr.ys(I);
[residual, g1 ] = feval([M_.fname,'_dynamic'],yy0, ...
oo_.exo_steady_state', M_.params, ...
repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1]), M_.params, ...
oo_.dr.ys, 1);
vg1 = [oo_.dr.ys(oo_.dr.order_var); vec(g1)];
@ -86,7 +86,7 @@ if info(1)==0,
if init,
indJJ = (find(max(abs(JJ'),[],1)>1.e-8));
if isempty(indJJ) && any(any(isnan(JJ)))
error('There are NaN in the JJ matrix. Please check whether your model has units roots and you forgot to set lik_init~=1.' )
error('There are NaN in the JJ matrix. Please check whether your model has units roots and you forgot to set diffuse_filter=1.' )
end
while length(indJJ)<nparam && nlags<10,
disp('The number of moments with non-zero derivative is smaller than the number of parameters')
@ -97,6 +97,7 @@ if info(1)==0,
derivatives_info.DOm=dOm;
derivatives_info.DYss=dYss;
evalin('caller',['options_ident.ar=',int2str(nlags),';']);
indJJ = (find(max(abs(JJ'),[],1)>1.e-8));
end
if length(indJJ)<nparam,
disp('The number of moments with non-zero derivative is smaller than the number of parameters')
@ -119,12 +120,12 @@ if info(1)==0,
normaliz = abs(params);
if prior_exist,
if ~isempty(estim_params_.var_exo),
normaliz1 = estim_params_.var_exo(:,7); % normalize with prior standard deviation
normaliz1 = estim_params_.var_exo(:,7)'; % normalize with prior standard deviation
else
normaliz1=[];
end
if ~isempty(estim_params_.param_vals),
normaliz1 = [normaliz1; estim_params_.param_vals(:,7)]'; % normalize with prior standard deviation
normaliz1 = [normaliz1 estim_params_.param_vals(:,7)']; % normalize with prior standard deviation
end
% normaliz = max([normaliz; normaliz1]);
normaliz1(isinf(normaliz1)) = 1;

View File

@ -82,7 +82,7 @@ end
ixnoJ = 0;
if rankJ<npar || rankJJ<npar || min(1-McoJ)<1.e-10
if npar>0 && (rankJ<npar || rankJJ<npar || min(1-McoJ)<1.e-10)
% - find out which parameters are involved
% disp('Some parameters are NOT identified by the moments included in J')
% disp(' ')

View File

@ -118,8 +118,6 @@ if estimated_model
trend = trend(oo_.dr.order_var,:);
InitState(:,1) = atT(:,end);
else
InitState(:,1) = zeros(M_.endo_nbr,1);
trend = repmat(oo_.steady_state(oo_.dr.order_var),1,options_cond_fcst.periods+1);
graph_title='Calibration';
end
@ -132,13 +130,26 @@ end
if ~isdiagonal(M_.Sigma_e)
warning(sprintf('The innovations are correlated (the covariance matrix has non zero off diagonal elements), the results of the conditional forecasts will\ndepend on the ordering of the innovations (as declared after varexo) because a Cholesky decomposition is used to factorize the covariance matrix.\n\n=> It is preferable to declare the correlations in the model block (explicitly imposing the identification restrictions), unless you are satisfied\nwith the implicit identification restrictions implied by the Cholesky decomposition.'))
end
sQ = chol(M_.Sigma_e,'lower');
if ~estimated_model
if isempty(M_.endo_histval)
y0 = ys;
else
y0 = M_.endo_histval;
end
InitState(:,1) = y0(oo_.dr.order_var)-ys(oo_.dr.order_var,:); %initial state in deviations from steady state
trend = repmat(ys(oo_.dr.order_var,:),1,options_cond_fcst.periods+1); %trend needs to contain correct steady state
end
sQ = sqrt(M_.Sigma_e);
NumberOfStates = length(InitState);
FORCS1 = zeros(NumberOfStates,options_cond_fcst.periods+1,options_cond_fcst.replic);
FORCS1(:,1,:) = repmat(InitState,1,options_cond_fcst.replic);
FORCS1(:,1,:) = repmat(InitState,1,options_cond_fcst.replic); %set initial steady state to deviations from steady state in first period
EndoSize = M_.endo_nbr;
ExoSize = M_.exo_nbr;
@ -169,15 +180,19 @@ cL = size(constrained_paths,2);
constrained_paths = bsxfun(@minus,constrained_paths,trend(idx,1:cL));
FORCS1_shocks = zeros(n1,cL,options_cond_fcst.replic);
%randn('state',0);
for b=1:options_cond_fcst.replic
for b=1:options_cond_fcst.replic %conditional forecast using cL set to constrained values
shocks = sQ*randn(ExoSize,options_cond_fcst.periods);
shocks(jdx,:) = zeros(length(jdx),options_cond_fcst.periods);
FORCS1(:,:,b) = mcforecast3(cL,options_cond_fcst.periods,constrained_paths,shocks,FORCS1(:,:,b),T,R,mv, mu)+trend;
[FORCS1(:,:,b), FORCS1_shocks(:,:,b)] = mcforecast3(cL,options_cond_fcst.periods,constrained_paths,shocks,FORCS1(:,:,b),T,R,mv, mu);
FORCS1(:,:,b)=FORCS1(:,:,b)+trend; %add trend
end
mFORCS1 = mean(FORCS1,3);
mFORCS1_shocks = mean(FORCS1_shocks,3);
tt = (1-options_cond_fcst.conf_sig)/2;
t1 = round(options_cond_fcst.replic*tt);
@ -193,16 +208,21 @@ for i = 1:EndoSize
' = [tmp(t1,:)'' ,tmp(t2,:)'' ]'';']);
end
clear FORCS1;
for i = 1:n1
eval(['forecasts.controlled_exo_variables.Mean.' deblank(options_cond_fcst.controlled_varexo(i,:)) ' = mFORCS1_shocks(i,:)'';']);
tmp = sort(squeeze(FORCS1_shocks(i,:,:))');
eval(['forecasts.controlled_exo_variables.ci.' deblank(options_cond_fcst.controlled_varexo(i,:)) ...
' = [tmp(t1,:)'' ,tmp(t2,:)'' ]'';']);
end
clear FORCS1 mFORCS1_shocks;
FORCS2 = zeros(NumberOfStates,options_cond_fcst.periods+1,options_cond_fcst.replic);
for b=1:options_cond_fcst.replic
FORCS2(:,1,b) = InitState;
end
FORCS2(:,1,:) = repmat(InitState,1,options_cond_fcst.replic); %set initial steady state to deviations from steady state in first period
%randn('state',0);
for b=1:options_cond_fcst.replic
for b=1:options_cond_fcst.replic %conditional forecast using cL set to 0
shocks = sQ*randn(ExoSize,options_cond_fcst.periods);
shocks(jdx,:) = zeros(length(jdx),options_cond_fcst.periods);
FORCS2(:,:,b) = mcforecast3(0,options_cond_fcst.periods,constrained_paths,shocks,FORCS2(:,:,b),T,R,mv, mu)+trend;

View File

@ -54,6 +54,10 @@ if DynareOptions.student_degrees_of_freedom <= 0
error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
end
if DynareOptions.TaRB.use_TaRB && (DynareOptions.TaRB.new_block_probability<0 || DynareOptions.TaRB.new_block_probability>1)
error(['initial_estimation_checks:: The tarb_new_block_probability must be between 0 and 1!'])
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)
@ -111,12 +115,16 @@ end
% Evaluate the likelihood.
ana_deriv = DynareOptions.analytic_derivation;
DynareOptions.analytic_derivation=0;
if ~isequal(DynareOptions.mode_compute,11)
if ~isequal(DynareOptions.mode_compute,11) || ...
(isequal(DynareOptions.mode_compute,11) && isequal(DynareOptions.order,1))
[fval,junk1,junk2,a,b,c,d] = feval(objective_function,xparam1,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults);
else
b=0;
fval = 0;
end
if DynareOptions.debug
DynareResults.likelihood_at_initial_parameters=fval;
end
DynareOptions.analytic_derivation=ana_deriv;
if DynareOptions.dsge_var || strcmp(func2str(objective_function),'non_linear_dsge_likelihood')

View File

@ -1,66 +0,0 @@
function matrix = insert_column_vector_in_a_matrix(matrix, vector, i) % --*-- Unitary tests --*--
% Copyright (C) 2013 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if nargin<2
error('insert_column_vector_in_a_matrix: I need at least two input arguments!')
end
if ~isequal(ndims(matrix),2)
error(['insert_column_vector_in_a_matrix: First input ''' inputname(1) ''' must be a matrix!'])
end
[n,m] = size(matrix);
if nargin<3
i = m+1;
end
if ~isvector(vector) || ~isequal(numel(vector),size(vector,1)) || ~isequal(numel(vector),n)
error(['insert_column_vector_in_a_matrix: Second input argument ''' inputname(2) ''' must be a ' int2str(n) ' by 1 vector!'])
end
switch i
case m+1
matrix = [matrix, vector];
case 1
matrix = [vector, matrix];
otherwise
matrix = [matrix(:,1:i-1), vector, matrix(:,i:m)];
end
%@test:1
%$ % Define a datasets.
%$ A = rand(8,3); b = rand(8,1);
%$
%$ try
%$ A4 = insert_column_vector_in_a_matrix(A, b);
%$ A1 = insert_column_vector_in_a_matrix(A, b, 1);
%$ A2 = insert_column_vector_in_a_matrix(A, b, 2);
%$ t(1) = 1;
%$ catch
%$ t(1) = 0;
%$ end
%$
%$ if t(1)
%$ t(2) = dassert(A4,[A,b],1e-15);
%$ t(3) = dassert(A1,[b,A],1e-15);
%$ t(4) = dassert(A2,[A(:,1), b, A(:,2:end)],1e-15);
%$ end
%$ T = all(t);
%@eof:1

View File

@ -1,73 +0,0 @@
function one_dimensional_cell_array = insert_object_in_a_one_dimensional_cell_array(one_dimensional_cell_array, object, i) % --*-- Unitary tests --*--
% Copyright (C) 2013 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
if nargin<2
error('insert_object_in_a_one_dimensional_cell_array: I need at least two input arguments!')
end
if ~iscell(one_dimensional_cell_array)
error(['insert_column_vector_in_a_matrix: First input ''' inputname(1) ''' must be a cell array!'])
end
[nr, nc] = size(one_dimensional_cell_array);
if ~isequal(nr*nc,numel(one_dimensional_cell_array))
error(['insert_column_vector_in_a_matrix: First input ''' inputname(1) ''' must be a one dimensional cell array!'])
end
n = numel(one_dimensional_cell_array);
if nargin<3
i = n+1;
end
one_dimensional_cell_array = one_dimensional_cell_array(:);
switch i
case n+1
one_dimensional_cell_array = [one_dimensional_cell_array; object];
case 1
one_dimensional_cell_array = [object; one_dimensional_cell_array];
otherwise
one_dimensional_cell_array = [one_dimensional_cell_array(1:i-1); object; one_dimensional_cell_array(i:n)];
end
if nc>nr
one_dimensional_cell_array = transpose(one_dimensional_cell_array);
end
%@test:1
%$ A = {'A1'; 'A2'; 'A3'}; b = [1, pi];
%$
%$ try
%$ C4 = insert_object_in_a_one_dimensional_cell_array(A, b);
%$ C1 = insert_object_in_a_one_dimensional_cell_array(A, b, 1);
%$ C2 = insert_object_in_a_one_dimensional_cell_array(A, b, 2);
%$ t(1) = 1;
%$ catch
%$ t(1) = 0;
%$ end
%$
%$ if t(1)
%$ t(2) = dassert(C4,[A;b]);
%$ t(3) = dassert(C1,[b;A],1e-15);
%$ t(4) = dassert(C2,[A(1); b; A(2:3)]);
%$ end
%$ T = all(t);
%@eof:1

View File

@ -1,4 +1,4 @@
function [lb,ub,eq_index] = get_complementarity_conditions(M)
function [lb,ub,eq_index] = get_complementarity_conditions(M,ramsey_policy)
% Copyright (C) 2014 Dynare Team
%
@ -17,11 +17,27 @@ function [lb,ub,eq_index] = get_complementarity_conditions(M)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
etags = M.equations_tags;
ub = inf(M.endo_nbr,1);
lb = -ub;
eq_index = (1:M.endo_nbr)';
if ramsey_policy
if isfield(M,'ramsey_model_constraints')
rc = M.ramsey_model_constraints;
for i = 1:length(rc)
switch rc{i}{2}
case {'>','>='}
lb(rc{i}{1}) = eval(rc{i}{3});
case {'<','<='}
ub(rc{i}{1}) = eval(rc{i}{3});
otherwise
error('Wrong operator in get_complementarity_conditions')
end
eq_index(i) = 1;
end
end
end
etags = M.equations_tags;
for i=1:size(etags,1)
if strcmp(etags{i,2},'mcp')
str = etags{i,3};

View File

@ -1,4 +1,4 @@
function forcs = mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu)
function [forcs, e]= mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu)
% forcs = mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu)
% Computes the shock values for constrained forecasts necessary to keep
% endogenous variables at their constrained paths

View File

@ -77,7 +77,7 @@ end
[nbplt,nr,nc,lr,lc,nstar] = pltorg(length(x));
if TeX
if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
fidTeX = fopen([Model.fname '_CheckPlots.TeX'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by mode_check.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
@ -89,6 +89,8 @@ if isinf(ll),
DynareOptions.mode_check.symmetric_plots = 0;
end
mcheck = struct('cross',struct(),'emode',struct());
for plt = 1:nbplt,
if TeX
NAMES = [];
@ -149,6 +151,8 @@ for plt = 1:nbplt,
y(i,2) = (y(i,1)+lnprior-dy);
end
end
mcheck.cross = setfield(mcheck.cross, name, [transpose(z), -y]);
mcheck.emode = setfield(mcheck.emode, name, x(kk));
fighandle=plot(z,-y);
hold on
yl=get(gca,'ylim');
@ -181,7 +185,7 @@ for plt = 1:nbplt,
text(0.69,0.5,'log-lik kernel')
end
dyn_saveas(hh,[ Model.fname '_CheckPlots' int2str(plt) ],DynareOptions);
if TeX
if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
% TeX eps loader file
fprintf(fidTeX,'\\begin{figure}[H]\n');
for jj = 1:min(nstar,length(x)-(plt-1)*nstar)
@ -194,4 +198,7 @@ for plt = 1:nbplt,
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
end
end
end
OutputDirectoryName = CheckPath('modecheck',Model.dname);
save([OutputDirectoryName '/check_plot_data'],'mcheck');

View File

@ -123,6 +123,12 @@ for b=1:nb
fprintf('\nMODEL_DIAGNOSTICS: The Jacobian of the static model contains Inf or NaN. The problem arises from: \n\n')
display_problematic_vars_Jacobian(infrow,infcol,M,dr.ys,'static','MODEL_DIAGNOSTICS: ')
end
if any(any(~isreal(jacob)))
problem_dummy=1;
[imagrow,imagcol]=find(abs(imag(jacob))>1e-15);
fprintf('\nMODEL_DIAGNOSTICS: The Jacobian of the static model contains imaginary parts. The problem arises from: \n\n')
display_problematic_vars_Jacobian(imagrow,imagcol,M,dr.ys,'static','MODEL_DIAGNOSTICS: ')
end
try
rank_jacob = rank(jacob); %can sometimes fail
catch
@ -227,6 +233,12 @@ if any(any(isinf(jacobia_) | isnan(jacobia_)))
fprintf('\nMODEL_DIAGNOSTICS: The Jacobian of the dynamic model contains Inf or NaN. The problem arises from: \n\n')
display_problematic_vars_Jacobian(infrow,infcol,M,dr.ys,'dynamic','MODEL_DIAGNOSTICS: ')
end
if any(any(~isreal(jacobia_)))
problem_dummy=1;
[imagrow,imagcol]=find(abs(imag(jacobia_))>1e-15);
fprintf('\nMODEL_DIAGNOSTICS: The Jacobian of the dynamic model contains imaginary parts. The problem arises from: \n\n')
display_problematic_vars_Jacobian(imagrow,imagcol,M,dr.ys,'dynamic','MODEL_DIAGNOSTICS: ')
end
if exist('hessian1','var')
if any(any(isinf(hessian1) | isnan(hessian1)))
problem_dummy=1;

@ -1 +1 @@
Subproject commit 0ab546e6fa6f6d712cb7e8a0b536eb9e86581f67
Subproject commit cb29cec352522cf2e8b029a2febe5ae502f86859

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

@ -1 +1 @@
Subproject commit b7d5391051635207f088a493c92d7357f3bdd4e9
Subproject commit 8c32ea69951b4781dcabd763868a2c8b5e262559

View File

@ -227,32 +227,11 @@ end
% Define a vector of indices for the observed variables. Is this really usefull?...
BayesInfo.mf = BayesInfo.mf1;
% Define the deterministic linear trend of the measurement equation.
if DynareOptions.noconstant
constant = zeros(DynareDataset.vobs,1);
else
constant = SteadyState(BayesInfo.mfys);
end
% Define the deterministic linear trend of the measurement equation.
if BayesInfo.with_trend
trend_coeff = zeros(DynareDataset.vobs,1);
t = DynareOptions.trend_coeffs;
for i=1:length(t)
if ~isempty(t{i})
trend_coeff(i) = evalin('base',t{i});
end
end
trend = repmat(constant,1,DynareDataset.nobs)+trend_coeff*[1:DynareDataset.nobs];
else
trend = repmat(constant,1,DynareDataset.nobs);
end
% Get needed informations for kalman filter routines.
start = DynareOptions.presample+1;
np = size(T,1);
mf = BayesInfo.mf;
Y = transpose(DynareDataset.data)-trend;
Y = transpose(DynareDataset.data);
%------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter
@ -297,7 +276,7 @@ switch DynareOptions.particle.initialization
StateVectorMean = ReducedForm.constant(mf0);
old_DynareOptionsperiods = DynareOptions.periods;
DynareOptions.periods = 5000;
y_ = simult(oo_.steady_state, dr,Model,DynareOptions,DynareResults);
y_ = simult(DynareResults.steady_state, dr,Model,DynareOptions,DynareResults);
y_ = y_(state_variables_idx,2001:5000);
StateVectorVariance = cov(y_');
DynareOptions.periods = old_DynareOptionsperiods;
@ -316,7 +295,7 @@ ReducedForm.StateVectorVariance = StateVectorVariance;
%------------------------------------------------------------------------------
DynareOptions.warning_for_steadystate = 0;
[s1,s2] = get_dynare_random_generator_state();
LIK = feval(DynareOptions.particle.algorithm,ReducedForm,Y,start,DynareOptions);
LIK = feval(DynareOptions.particle.algorithm,ReducedForm,Y,start,DynareOptions.particle,DynareOptions.threads);
set_dynare_random_generator_state(s1,s2);
if imag(LIK)
info = 46;

View File

@ -0,0 +1,21 @@
% Solve model, generate model IRFs
[zdatalinear zdatapiecewise zdatass oobase_ Mbase_ ] = ...
solve_one_constraint(modnam,modnamstar,...
constraint, constraint_relax,...
shockssequence,irfshock,nperiods,maxiter);
% unpack the IRFs
for i=1:Mbase_.endo_nbr
eval([deblank(Mbase_.endo_names(i,:)),'_uncdifference=zdatalinear(:,i);']);
eval([deblank(Mbase_.endo_names(i,:)),'_difference=zdatapiecewise(:,i);']);
eval([deblank(Mbase_.endo_names(i,:)),'_ss=zdatass(i);']);
end
nparams = size(Mbase_.param_names,1);
for i = 1:nparams
eval([Mbase_.param_names(i,:),'= Mbase_.params(i);']);
end

View File

@ -0,0 +1,21 @@
[zdatalinear zdatapiecewise zdatass oobase_ Mbase_] = solve_two_constraints(...
modnam_00,modnam_10,modnam_01,modnam_11,...
constraint1, constraint2,...
constraint_relax1, constraint_relax2,...
scalefactormod,irfshock,nperiods,curb_retrench,maxiter);
for i=1:Mbase_.endo_nbr
eval([deblank(Mbase_.endo_names(i,:)),'_uncdifference=zdatalinear(:,i);']);
eval([deblank(Mbase_.endo_names(i,:)),'_difference=zdatapiecewise(:,i);']);
eval([deblank(Mbase_.endo_names(i,:)),'_ss=zdatass(i);']);
end
constraint1_difference = process_constraint(constraint1,'_difference',Mbase_.endo_names,0);
constraint2_difference = process_constraint(constraint2,'_difference',Mbase_.endo_names,0);
nparams = size(Mbase_.param_names,1);
for i = 1:nparams
eval([Mbase_.param_names(i,:),'= Mbase_.params(i);']);
end

83
matlab/occbin/get_deriv.m Executable file
View File

@ -0,0 +1,83 @@
function [hm1,h,hl1,j,resid] = get_deriv(M_,ys_)
iy_ = M_.lead_lag_incidence;
it_ = 1;
x = zeros(1,M_.exo_nbr);
% For most models, there are leads, lags and current values of variables
if size(iy_,1)==3
% find non-zero columns of hm1
lag_cols = find(iy_(1,:)~=0);
% find non-zero columns of h
con_cols = find(iy_(2,:));
% find non-zero columns of hl1
lea_cols = find(iy_(3,:));
% If models either lacks leads or lags, iy_ will have two rows
% In this case, we guess that the row with more nonzeros is the row with current variables
elseif size(iy_,1)==2
% if first row has more nonzero entries than the second, assume model lacks lagged variables
if length(find(iy_(1,:)))>length(find(iy_(2,:)))
warning('Model does not have lagged endogenous variables')
con_cols = find(iy_(1,:));
lea_cols = find(iy_(2,:));
lag_cols = [];
else
warning('Model does not have expected future endogenous variables')
lag_cols = find(iy_(1,:));
con_cols = find(iy_(2,:));
lea_cols = [];
end
end
% find number of entries for y vector
ny = length(find(iy_~=0));
% build steady state y
y = ys_(lag_cols);
y = [y;ys_(con_cols)];
y = [y;ys_(lea_cols)];
if ismac
eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']);
% Older versions of DYNARE for Mac did not include ys_ in the call structure
%eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, it_);']);
else
eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']);
end
hm1=zeros(M_.endo_nbr);
h = hm1;
hl1 = hm1;
j = zeros(M_.endo_nbr,M_.exo_nbr);
% build hm1
nlag_cols = length(lag_cols);
for i=1:nlag_cols
hm1(:,lag_cols(i)) = g1(:,i);
end
% build h
ncon_cols = length(con_cols);
for i=1:ncon_cols
h(:,con_cols(i)) = g1(:,i+nlag_cols);
end
% build hl1
nlea_cols = length(lea_cols);
for i=1:nlea_cols
hl1(:,lea_cols(i)) = g1(:,i+nlag_cols+ncon_cols);
end
for i = 1:M_.exo_nbr;
j(:,i) =g1(:,i+ny);
end

28
matlab/occbin/get_pq.m Executable file
View File

@ -0,0 +1,28 @@
function [p,q]=get_pq(dr_,nstatic,nfwrd);
nvars = size(dr_.ghx,1);
nshocks = size(dr_.ghu,2);
statevar_pos = (nstatic +1):(nvars-nfwrd);
p = zeros(nvars);
% interlace matrix
nnotzero = length(statevar_pos);
for i=1:nnotzero
p(:,statevar_pos(i)) = dr_.ghx(:,i);
end
% reorder p matrix according to order in lgy_
inverse_order = zeros(nvars,1);
for i=1:nvars
inverse_order(i) = find(i==dr_.order_var);
end
p_reordered = zeros(nvars);
q = zeros(nvars,nshocks);
for i=1:nvars
for j=1:nvars
p_reordered(i,j)=p(inverse_order(i),inverse_order(j));
end
q(i,:)=dr_.ghu(inverse_order(i),:);
end
p=p_reordered;

81
matlab/occbin/makechart.m Executable file
View File

@ -0,0 +1,81 @@
function makechart(titlelist,legendlist,figlabel,ylabels,zdata1,zdata2,zdata3)
figure
titlelist = char(strrep(cellstr(titlelist),'_','.'));
ndsets=3; % default, changed below as applicable
if nargin==5
zdata2=nan*zdata1;
zdata3=nan*zdata1;
ndsets =1;
elseif nargin == 6
zdata3 =nan*zdata1;
ndsets=2;
elseif ((nargin>8) | (nargin <=4))
error ('makechart takes 5 to 6 arguments')
end
nobs = size(zdata1,1);
xvalues = (1:nobs)';
nvars = size(titlelist,1);
if nvars==1
nrows=1;
ncols = 1;
elseif nvars==2
nrows =2;
ncols = 1;
elseif (nvars == 3 | nvars ==4)
nrows = 2;
ncols =2;
elseif (nvars==5 |nvars ==6)
nrows = 3;
ncols = 2;
elseif (nvars==7 | nvars==8)
nrows = 4;
ncols = 2;
elseif (nvars==9 | nvars==10)
nrows = 5;
ncols = 2;
else
error('too many variables (makechart)')
end
for i = 1:nvars
subplot(nrows,ncols,i)
h1=plot(xvalues,zdata1(:,i),'b-','linewidth',2); hold on
h1=plot(xvalues,zdata2(:,i),'r--','linewidth',2); hold on
h2=plot(xvalues,zdata3(:,i),'b-','LineWidth',3);
[x0 x1 y10 y11] = pickaxes(xvalues,zdata1(:,i));
[x0 x1 y20 y21] = pickaxes(xvalues,zdata2(:,i));
[x0 x1 y30 y31] = pickaxes(xvalues,zdata3(:,i));
y0 = min([y10,y20,y30]);
y1 = max([y11,y21,y31]);
if y0==y1
y1=y0+1;
end
axis([x0 x1 y0 y1])
set(h1);
if i==1 && isempty(legendlist)==0
legend(legendlist)
text('String',figlabel,'Units','normalized','Position',[1.2 1.24],...
'FontSize',14,'FontWeight','bold','HorizontalAlignment','center');
end
if i==nvars | i==nvars-1
xlabel('Time');
end
% set(gca,'XTick',xtick)
% set(gca,'XTickLabel',xticklabel)
title([num2str(i),'. ',titlelist(i,:)]);
ylabel(ylabels(i,:))
end
% sets printing preferences
%printpref

136
matlab/occbin/makechart9.m Executable file
View File

@ -0,0 +1,136 @@
function makechart9(titlelist,legendlist,figlabel,yearshock,ylabels,...
zdata1,zdata2,zdata3,zdata4,zdata5,zdata6,zdata7)
figure
titlelist = char(strrep(cellstr(titlelist),'_','.'));
ndsets=7; % default, changed below as applicable
if nargin==6
zdata2=nan*zdata1;
zdata3=nan*zdata1;
zdata4=nan*zdata1;
zdata5=nan*zdata1;
zdata6=nan*zdata1;
zdata7=nan*zdata1;
ndsets =1;
elseif nargin==7
zdata3=nan*zdata1;
zdata4=nan*zdata1;
zdata5=nan*zdata1;
zdata6=nan*zdata1;
zdata7=nan*zdata1;
ndsets =2;
elseif nargin == 8
zdata4 =nan*zdata1;
zdata5 =nan*zdata1;
zdata6=nan*zdata1;
zdata7=nan*zdata1;
ndsets=3;
elseif nargin == 9
zdata5 =nan*zdata1;
zdata6=nan*zdata1;
zdata7=nan*zdata1;
ndsets=4;
elseif nargin == 10
zdata6 =nan*zdata1;
zdata7=nan*zdata1;
ndsets=5;
elseif nargin == 11
zdata7=nan*zdata1;
ndsets=6;
elseif ((nargin>=13) | (nargin <=3))
error ('makechart takes 4 to 10 arguments')
end
nobs = size(zdata1,1);
if yearshock>-100
xvalues = yearshock+(0:nobs-1)'/4; % Matteo plot year on x axis
else
xvalues = (1:nobs)'; % Matteo plot year on x axis
end
nvars = size(titlelist,1);
if nvars==1
nrows=1;
ncols = 1;
elseif nvars==2
nrows =2;
ncols = 1;
elseif nvars == 3
nrows = 3;
ncols = 1;
elseif nvars==4
nrows = 2;
ncols = 2;
elseif (nvars==5 | nvars ==6)
nrows = 3;
ncols = 2;
elseif (nvars==7 | nvars==8)
nrows = 4;
ncols = 2;
elseif nvars>8 & nvars<=12;
nrows = 3;
ncols = 4;
elseif nvars>12 & nvars<=15;
nrows = 5;
ncols = 3;
else
error('too many variables (makechart)')
end
for i = 1:nvars
subplot(nrows,ncols,i)
h1=plot(xvalues,zdata1(:,i),'k',...
xvalues,zdata2(:,i),'r',...
xvalues,zdata3(:,i),'b',...
xvalues,zdata4(:,i),'g',...
xvalues,zdata5(:,i),'g',...
xvalues,zdata6(:,i),'c',...
xvalues,zdata7(:,i),'y');
[x0 x1 y10 y11] = pickaxes(xvalues,zdata1(:,i));
[x0 x1 y20 y21] = pickaxes(xvalues,zdata2(:,i));
[x0 x1 y30 y31] = pickaxes(xvalues,zdata3(:,i));
[x0 x1 y40 y41] = pickaxes(xvalues,zdata4(:,i));
[x0 x1 y50 y51] = pickaxes(xvalues,zdata5(:,i));
[x0 x1 y60 y61] = pickaxes(xvalues,zdata6(:,i));
[x0 x1 y70 y71] = pickaxes(xvalues,zdata7(:,i));
grid on
y0 = min([y10,y20,y30,y40,y50,y60,y70]);
y1 = max([y11,y21,y31,y41,y51,y61,y71]);
if y0==y1
y1=y0+1;
end
axis([x0 x1 y0 y1])
set(h1,'linewidth',2);
if i==1
if numel(strvcat(legendlist(1,:)))
h=legend(legendlist,'Location','Northwest');
set(h,'Fontsize',8)
end
end
if i==1
if nvars>3
text('String',figlabel,'Units','normalized','Position',[1.2 1.21],...
'FontSize',13,'FontWeight','bold','HorizontalAlignment','center');
else
text('String',figlabel,'Units','normalized','Position',[0.4 1.24],...
'FontSize',13,'FontWeight','bold','HorizontalAlignment','center');
end
end
%set(gca,'XTick',xtick)
%set(gca,'XTickLabel',xticklabel)
title(titlelist(i,:),'Fontsize',11);
ylabel(ylabels(i,:))
end
% sets printing preferences
%printpref

25
matlab/occbin/map_regime.m Executable file
View File

@ -0,0 +1,25 @@
function [regime regimestart]=map_regimes(violvecbool)
nperiods = length(violvecbool)-1;
% analyse violvec and isolate contiguous periods in the other regime.
regime(1) = violvecbool(1);
regimeindx = 1;
regimestart(1) = 1;
for i=2:nperiods
if violvecbool(i)~=regime(regimeindx)
regimeindx=regimeindx+1;
regime(regimeindx) = violvecbool(i);
regimestart(regimeindx)=i;
end
end
if (regime(1) == 1 & length(regimestart)==1)
warning('Increase nperiods');
end
if (regime(end)==1)
warning('Increase nperiods');
end

63
matlab/occbin/mkdata.m Executable file
View File

@ -0,0 +1,63 @@
function [zdata]=mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,scalefactormod,init)
%[nsim, ksim, ysim, isim, csim] = mkdata(nperiods,cofb,endog_)
% given decision rule
neqs = size(endog_,1);
if nargin<9
init = zeros(neqs,1);
end
if nargin<8
scalefactormod=1;
end
if nargin<7
error('Not enough inputs')
end
history = zeros(neqs,nperiods+1);
nshocks = size(irfshock,1);
for i = 1:nshocks
shockpos = strmatch(irfshock(i,:),exog_,'exact');
if ~isempty(shockpos)
irfshockpos(i) = shockpos;
else
error(['Shock ',irfshock(i,:),' is not in the model']);
end
end
% generate data
% history will contain data, the state vector at each period in time will
% be stored columnwise.
history = zeros(neqs,nperiods);
history(:,1)= init;
lengthshock = size(scalefactormod,1);
errvec = zeros(size(exog_,1),1);
for i = 2:nperiods+1
if i<=(lengthshock+1)
for j = 1:nshocks
errvec(irfshockpos(j)) = scalefactormod(i-1,j);
end
history(:,i) = decrulea * history(:,i-1)+decruleb*errvec;
else
% update endogenous variables
history(:,i) = decrulea * history(:,i-1);
end
end
% extract desired variables
nwish=size(wishlist,1);
wishpos = zeros(nwish,1);
history=history';
for i=1:nwish
wishpos(i) = strmatch(wishlist(i,:),endog_,'exact');
end
zdata = history(2:end,wishpos);

View File

@ -0,0 +1,125 @@
function [zdata]=mkdatap_anticipated(nperiods,decrulea,decruleb,...
cof,Jbarmat,cofstar,Jstarbarmat,Dstarbarmat,...
regime,regimestart,violvecbool,...
endog_,exog_,irfshock,scalefactormod,init)
nvars = size(endog_,1);
if nargin<16
init=zeros(nvars,1);
end
if nargin<15;
scalefactormod=1;
end
nshocks = size(irfshock,1);
for i = 1:nshocks
shockpos = strmatch(irfshock(i,:),exog_,'exact');
if ~isempty(shockpos)
irfshockpos(i) = shockpos;
else
error(['Shock ',irfshock(i,:),' is not in the model']);
end
end
nregimes = length(regime);
Cbarmat = cof(:,1:nvars);
Bbarmat = cof(:,nvars+1:2*nvars);
Abarmat = cof(:,2*nvars+1:3*nvars);
% cofstar contains the system for the model when the constraint binds
Cstarbarmat = cofstar(:,1:nvars);
Bstarbarmat = cofstar(:,nvars+1:2*nvars);
Astarbarmat = cofstar(:,2*nvars+1:3*nvars);
% get the time-dependent decision rules
Tmax = regimestart(nregimes)-1; % Tmax is the position of the last period
% when the constraint binds
if Tmax > 0
P = zeros(nvars,nvars,Tmax);
D = zeros(nvars,Tmax);
invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
P(:,:,Tmax) = -invmat*Cstarbarmat;
D(:,Tmax) = -invmat*Dstarbarmat;
% equivalent to pre-multiplying by the inverse above if the target
% matrix is invertible. Otherwise it yields the minimum state solution
%P(:,:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Cstarbarmat;
%D(:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Dstarbarmat;
for i = Tmax-1:-1:1
if violvecbool(i)
invmat = inv(Bstarbarmat+Astarbarmat*P(:,:,i+1));
P(:,:,i)=-invmat*Cstarbarmat;
D(:,i) = -invmat*(Astarbarmat*D(:,i+1)+Dstarbarmat);
else
invmat = inv(Bbarmat+Abarmat*P(:,:,i+1));
P(:,:,i)=-invmat*Cbarmat;
D(:,i) = -invmat*(Abarmat*D(:,i+1));
end
end
if Tmax > 1
if violvecbool(1)
E = -invmat*Jstarbarmat;
else
E = -invmat*Jbarmat;
end
else
invmat = inv(Astarbarmat*decrulea+Bstarbarmat);
E = -invmat*Jstarbarmat;
end
end
% generate data
% history will contain data, the state vector at each period in time will
% be stored columnwise.
history = zeros(nvars,nperiods+1);
history(:,1) = init;
errvec = zeros(size(exog_,1),1);
% deal with predetermined conditions
for i = 1:nshocks
errvec(irfshockpos(i)) = scalefactormod(i);
end
% deal with shocks
irfpos =1;
if irfpos <=Tmax
history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
D(:,irfpos) + E*errvec;
else
history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec;
end
% all other periods
for irfpos=2:nperiods+1
if irfpos <=Tmax
history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
D(:,irfpos);
else
history(:,irfpos+1) = decrulea*history(:,irfpos);
end
end
history=history';
zdata = history(2:end,:);

View File

@ -0,0 +1,180 @@
function [zdata]=mkdatap_anticipated_2constraints_alt(nperiods,decrulea,decruleb,...
cof,Jbarmat,...
cof10,Jbarmat10,Dbarmat10,...
cof01,Jbarmat01,Dbarmat01,...
cof11,Jbarmat11,Dbarmat11,...
regime1,regimestart1,...
regime2,regimestart2,...
violvecbool,endog_,exog_,...
irfshock,scalefactormod,init)
nvars = size(endog_,1);
if nargin<16
init=zeros(nvars,1);
end
if nargin<15;
scalefactormod=1;
end
nshocks = size(irfshock,1);
for i = 1:nshocks
shockpos = strmatch(irfshock(i,:),exog_,'exact');
if ~isempty(shockpos)
irfshockpos(i) = shockpos;
else
error(['Shock ',irfshock(i,:),' is not in the model']);
end
end
Cbarmat = cof(:,1:nvars);
Bbarmat = cof(:,nvars+1:2*nvars);
Abarmat = cof(:,2*nvars+1:3*nvars);
% cofstar contains the system for the model when the constraint binds
Cbarmat10 = cof10(:,1:nvars);
Bbarmat10 = cof10(:,nvars+1:2*nvars);
Abarmat10 = cof10(:,2*nvars+1:3*nvars);
Cbarmat01 = cof01(:,1:nvars);
Bbarmat01 = cof01(:,nvars+1:2*nvars);
Abarmat01 = cof01(:,2*nvars+1:3*nvars);
Cbarmat11 = cof11(:,1:nvars);
Bbarmat11 = cof11(:,nvars+1:2*nvars);
Abarmat11 = cof11(:,2*nvars+1:3*nvars);
% get the time-dependent decision rules
nregimes1 = length(regime1);
nregimes2 = length(regime2);
Tmax = max([regimestart1(nregimes1) regimestart2(nregimes2)])-1; % Tmax is the position of the last period
% when the constraint binds
if Tmax > 0
P = zeros(nvars,nvars,Tmax);
D = zeros(nvars,Tmax);
% invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
% P(:,:,Tmax) = -invmat*Cstarbarmat;
% D(:,Tmax) = -invmat*Dstarbarmat;
if (violvecbool(Tmax,1) & ~violvecbool(Tmax,2))
%XXX fix next three lines
invmat = inv((Abarmat10*decrulea+Bbarmat10));
P(:,:,Tmax) = -invmat*Cbarmat10;
D(:,Tmax) = -invmat*Dbarmat10;
elseif (violvecbool(Tmax,1) & violvecbool(Tmax,2))
invmat = inv((Abarmat11*decrulea+Bbarmat11));
P(:,:,Tmax) = -invmat*Cbarmat11;
D(:,Tmax) = -invmat*Dbarmat11;
else
invmat = inv((Abarmat01*decrulea+Bbarmat01));
P(:,:,Tmax) = -invmat*Cbarmat01;
D(:,Tmax) = -invmat*Dbarmat01;
end
for i = Tmax-1:-1:1
if (violvecbool(i,1) & ~violvecbool(i,2))
invmat = inv(Bbarmat10+Abarmat10*P(:,:,i+1));
P(:,:,i)=-invmat*Cbarmat10;
D(:,i) = -invmat*(Abarmat10*D(:,i+1)+Dbarmat10);
elseif (~violvecbool(i,1) & violvecbool(i,2))
invmat = inv(Bbarmat01+Abarmat01*P(:,:,i+1));
P(:,:,i)=-invmat*Cbarmat01;
D(:,i) = -invmat*(Abarmat01*D(:,i+1)+Dbarmat01);
elseif (violvecbool(i,1) & violvecbool(i,2))
invmat = inv(Bbarmat11+Abarmat11*P(:,:,i+1));
P(:,:,i)=-invmat*Cbarmat11;
D(:,i) = -invmat*(Abarmat11*D(:,i+1)+Dbarmat11);
else
invmat = inv(Bbarmat+Abarmat*P(:,:,i+1));
P(:,:,i)=-invmat*Cbarmat;
D(:,i) = -invmat*(Abarmat*D(:,i+1));
end
end
% Double check the appropriate invmat in each case
% right now -- inherited from previous loop
if Tmax > 1
if ( ~violvecbool(1,1) & violvecbool(1,2) )
E = -invmat*Jbarmat01;
elseif ( violvecbool(1,1) & ~violvecbool(1,2) )
E = -invmat*Jbarmat10;
elseif ( violvecbool(1,1) & violvecbool(1,2) )
E = -invmat*Jbarmat11;
else
E = -invmat*Jbarmat;
end
else % Tmax is equal to 1
% invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
% E = -invmat*Jstarbarmat;
if ( ~violvecbool(1,1) & violvecbool(1,2) )
invmat = inv((Abarmat01*decrulea+Bbarmat01));
E = -invmat*Jbarmat01;
elseif ( violvecbool(1,1) & violvecbool(1,2) )
invmat = inv((Abarmat11*decrulea+Bbarmat11));
E = -invmat*Jbarmat11;
else
invmat = inv((Abarmat10*decrulea+Bbarmat10));
E = -invmat*Jbarmat10;
end
end
end
% generate data
% history will contain data, the state vector at each period in time will
% be stored columnwise.
history = zeros(nvars,nperiods+1);
history(:,1) = init;
errvec = zeros(size(exog_,1),1);
for i = 1:nshocks
errvec(irfshockpos(i)) = scalefactormod(i);
end
% deal with shocks
irfpos =1;
if irfpos <=Tmax
history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
D(:,irfpos) + E*errvec;
else
history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec;
end
% all other periods
for irfpos=2:nperiods+1
if irfpos <=Tmax
history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
D(:,irfpos);
else
history(:,irfpos+1) = decrulea*history(:,irfpos);
end
end
history=history';
zdata = history(2:end,:);

16
matlab/occbin/pickaxes.m Executable file
View File

@ -0,0 +1,16 @@
function [x0,x1,y0,y1] = pickaxes(xvalues,yvalues)
x0=xvalues(1);
nobs = length(xvalues);
x1=xvalues(nobs);
maxy = max(yvalues);
miny = min(yvalues);
y0 = miny - .05*abs(miny);
if (miny>0 & y0<0)
y0 = 0;
end
y1 = maxy + .05*abs(maxy);

View File

@ -0,0 +1,38 @@
% this function looks for occurrences of the endogenous variables in
% endo_names in the input string constraint
% all occurrences of the endogenous variables are appended a suffix
% if the invert_switch is true, the direction of the inequality in the
% constraint is inverted
function constraint1 = process_constraint(constraint,suffix,endo_names,invert_switch)
% create a list of delimiters that can separate parameters and endogenoous
% variables in the string that expresses the constraint
delimiters = char(',',';','(',')','+','-','^','*','/',' ','>','<','=');
% split the string that holds the constraint into tokens
tokens = tokenize(constraint,delimiters);
ntokens = length(tokens);
% search for tokens that match the list of endogenous variables
for i=1:ntokens
if ~isempty(find(strcmp(tokens(i),endo_names)))
% when there is a match with an endogenous variable append the
% suffix
tokens(i) = cellstr([char(tokens(i)),suffix]);
end
% if the invert_switch is true
% reverse the direction of the inequality
if invert_switch
if strcmp(tokens(i),cellstr('>'))
tokens(i) = cellstr('<');
elseif strcmp(tokens(i),cellstr('<'))
tokens(i) = cellstr('>');
end
end
end
% reassemble the tokens to create a string that expresses the constraint
constraint1 = strmerge(tokens);

14
matlab/occbin/setss.m Executable file
View File

@ -0,0 +1,14 @@
% Script that retrieves parameter values once model is solved
nendog = size(Mbase_.endo_names,1);
for i=1:nendog
eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']);
end
nparams = size(Mbase_.param_names);
for i = 1:nparams
eval([Mbase_.param_names(i,:),'= M_.params(i);']);
end

View File

@ -0,0 +1,50 @@
function [zdata_, zdatass_, oobase_, Mbase_ ] = ...
solve_no_constraint(modnam,...
shockssequence,irfshock,nperiods)
global M_ oo_
errlist = [];
% solve model
eval(['dynare ',modnam,' noclearall'])
oobase_ = oo_;
Mbase_ = M_;
ys_ = oobase_.dr.ys;
nvars = numel(ys_);
zdatass_ = ys_ ;
for i=1:Mbase_.endo_nbr
eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']);
end
for i = 1:size(Mbase_.param_names)
eval([Mbase_.param_names(i,:),'= M_.params(i);']);
end
[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_);
cof = [hm1,h,hl1];
[decrulea,decruleb]=get_pq(oobase_.dr);
endog_ = M_.endo_names;
exog_ = M_.exo_names;
nvars = numel(Mbase_.endo_nbr);
nshocks = size(shockssequence,1);
init = zeros(nvars,1);
wishlist = endog_;
nwishes = size(wishlist,1);
zdata_ = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence);

View File

@ -0,0 +1,48 @@
function [zdata oobase_ Mbase_ ] = ...
solve_no_constraint_noclear(modnam,...
shockssequence,irfshock,nperiods);
global M_ oo_
errlist = [];
% solve model
eval(['dynare ',modnam,' nolog']);
oobase_ = oo_;
Mbase_ = M_;
ys_ = oobase_.dr.ys;
for i=1:Mbase_.endo_nbr
eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']);
end
for i = 1:size(Mbase_.param_names)
eval([Mbase_.param_names(i,:),'= M_.params(i);']);
end
setss
[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_);
cof = [hm1,h,hl1];
[decrulea,decruleb]=get_pq(oobase_.dr);
endog_ = M_.endo_names;
exog_ = M_.exo_names;
nvars = numel(Mbase_.endo_nbr);
nshocks = size(shockssequence,1);
init = zeros(nvars,1);
wishlist = endog_;
nwishes = size(wishlist,1);
zdata = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence);

View File

@ -0,0 +1,192 @@
% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init);
%
% Inputs:
% modnam: name of .mod file for the reference regime (excludes the .mod extension).
% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion).
% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime.
% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime.
% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks).
% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?).
% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files.
%
% Outputs:
% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide.
% Log of changes:
% 6/17/2013 -- Luca added a trailing underscore to local variables in an
% attempt to avoid conflicts with parameter names defined in the .mod files
% to be processed.
% 6/17/2013 -- Luca replaced external .m file setss.m
function [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ Mbase_ ] = ...
solve_one_constraint(modnam_,modnamstar_,...
constraint_, constraint_relax_,...
shockssequence_,irfshock_,nperiods_,maxiter_,init_)
global M_ oo_
errlist_ = [];
% solve the reference model linearly
eval(['dynare ',modnam_,' noclearall nolog '])
oobase_ = oo_;
Mbase_ = M_;
% import locally the values of parameters assigned in the reference .mod
% file
for i_indx_ = 1:Mbase_.param_nbr
eval([Mbase_.param_names(i_indx_,:),'= M_.params(i_indx_);']);
end
% Create steady state values of the variables if needed for processing the constraint
for i=1:Mbase_.endo_nbr
eval([deblank(Mbase_.endo_names(i,:)) '_ss = oobase_.dr.ys(i); ']);
end
% parse the .mod file for the alternative regime
eval(['dynare ',modnamstar_,' noclearall nolog '])
oostar_ = oo_;
Mstar_ = M_;
% check inputs
if ~strcmp(Mbase_.endo_names,Mstar_.endo_names)
error('The two .mod files need to have exactly the same endogenous variables declared in the same order')
end
if ~strcmp(Mbase_.exo_names,Mstar_.exo_names)
error('The two .mod files need to have exactly the same exogenous variables declared in the same order')
end
if ~strcmp(Mbase_.param_names,Mstar_.param_names)
warning('The parameter list does not match across .mod files')
end
% ensure that the two models have the same parameters
% use the parameters for the base model.
Mstar_.params = Mbase_.params;
nvars_ = Mbase_.endo_nbr;
zdatass_ = oobase_.dr.ys;
% get the matrices holding the first derivatives for the model
% each regime is treated separately
[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_);
cof_ = [hm1_,h_,hl1_];
[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_);
cofstar_ = [hm1_,h_,hl1_];
Dstartbarmat_ = resid_;
[decrulea_,decruleb_]=get_pq(oobase_.dr);
endog_ = M_.endo_names;
exog_ = M_.exo_names;
% processes the constraints specified in the call to this function
% uppend a suffix to each endogenous variable
constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0);
constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0);
nshocks_ = size(shockssequence_,1);
% if necessary, set default values for optional arguments
if ~exist('init_')
init_ = zeros(nvars_,1);
end
if ~exist('maxiter_')
maxiter_ = 20;
end
if ~exist('nperiods_')
nperiods_ = 100;
end
% set some initial conditions and loop through the shocks
% period by period
init_orig_ = init_;
zdatapiecewise_ = zeros(nperiods_,nvars_);
wishlist_ = endog_;
nwishes_ = size(wishlist_,1);
violvecbool_ = zeros(nperiods_+1,1);
for ishock_ = 1:nshocks_
changes_=1;
iter_ = 0;
while (changes_ & iter_<maxiter_)
iter_ = iter_ +1;
% analyze when each regime starts based on current guess
[regime regimestart]=map_regime(violvecbool_);
% get the hypothesized piece wise linear solution
[zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,...
cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,...
regime,regimestart,violvecbool_,...
endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_);
for i_indx_=1:nwishes_
eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']);
end
newviolvecbool_ = eval(constraint_difference_);
relaxconstraint_ = eval(constraint_relax_difference_);
% check if changes to the hypothesis of the duration for each
% regime
if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
changes_ = 1;
else
changes_ = 0;
end
violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_);
end
init_ = zdatalinear_(1,:);
zdatapiecewise_(ishock_,:)=init_;
init_= init_';
% reset violvecbool_ for next period's shock -- this resetting is
% consistent with expecting no additional shocks
violvecbool_=[violvecbool_(2:end);0];
end
% if necessary, fill in the rest of the path with the remainder of the
% last IRF computed.
zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
% get the linear responses
zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),...
decrulea_,decruleb_,endog_,exog_,...
wishlist_,irfshock_,shockssequence_,init_orig_);
if changes_ ==1
display('Did not converge -- increase maxiter_')
end

View File

@ -0,0 +1,200 @@
% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init);
%
% Inputs:
% modnam: name of .mod file for the reference regime (excludes the .mod extension).
% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion).
% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime.
% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime.
% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks).
% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?).
% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files.
%
% Outputs:
% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide.
% Log of changes:
% 6/17/2013 -- Luca added a trailing underscore to local variables in an
% attempt to avoid conflicts with parameter names defined in the .mod files
% to be processed.
% 6/17/2013 -- Luca replaced external .m file setss.m
function [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ Mbase_ ] = ...
solve_one_constraint(modnam_,modnamstar_,...
constraint_, constraint_relax_,...
shockssequence_,irfshock_,nperiods_,maxiter_,init_)
global M_ oo_
errlist_ = [];
% solve the reference model linearly
eval(['dynare ',modnam_,' noclearall nolog '])
oobase_ = oo_;
Mbase_ = M_;
% import locally the values of parameters assigned in the reference .mod
% file
for i_indx_ = 1:Mbase_.param_nbr
eval([Mbase_.param_names(i_indx_,:),'= M_.params(i_indx_);']);
end
% Create steady state values of the variables if needed for processing the constraint
for i=1:Mbase_.endo_nbr
eval([deblank(Mbase_.endo_names(i,:)) '_ss = oobase_.dr.ys(i); ']);
end
% parse the .mod file for the alternative regime
eval(['dynare ',modnamstar_,' noclearall nolog '])
oostar_ = oo_;
Mstar_ = M_;
% check inputs
if ~strcmp(Mbase_.endo_names,Mstar_.endo_names)
error('The two .mod files need to have exactly the same endogenous variables declared in the same order')
end
if ~strcmp(Mbase_.exo_names,Mstar_.exo_names)
error('The two .mod files need to have exactly the same exogenous variables declared in the same order')
end
if ~strcmp(Mbase_.param_names,Mstar_.param_names)
warning('The parameter list does not match across .mod files')
end
% ensure that the two models have the same parameters
% use the parameters for the base model.
Mstar_.params = Mbase_.params;
nvars_ = Mbase_.endo_nbr;
zdatass_ = oobase_.dr.ys;
% get the matrices holding the first derivatives for the model
% each regime is treated separately
[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_);
cof_ = [hm1_,h_,hl1_];
[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_);
cofstar_ = [hm1_,h_,hl1_];
Dstartbarmat_ = resid_;
if isfield(Mbase_,'nfwrd')
% the latest Dynare distributions have moved nstatic and nfwrd
[decrulea_,decruleb_]=get_pq(oobase_.dr,Mbase_.nstatic,Mbase_.nfwrd);
else
[decrulea_,decruleb_]=get_pq(oobase_.dr,oobase_.dr.nstatic,oobase_.dr.nfwrd);
end
endog_ = M_.endo_names;
exog_ = M_.exo_names;
% processes the constraints specified in the call to this function
% uppend a suffix to each endogenous variable
constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0);
constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0);
nshocks_ = size(shockssequence_,1);
% if necessary, set default values for optional arguments
if ~exist('init_')
init_ = zeros(nvars_,1);
end
if ~exist('maxiter_')
maxiter_ = 20;
end
if ~exist('nperiods_')
nperiods_ = 100;
end
% set some initial conditions and loop through the shocks
% period by period
init_orig_ = init_;
zdatapiecewise_ = zeros(nperiods_,nvars_);
wishlist_ = endog_;
nwishes_ = size(wishlist_,1);
violvecbool_ = zeros(nperiods_+1,1);
for ishock_ = 1:nshocks_
changes_=1;
iter_ = 0;
while (changes_ & iter_<maxiter_)
iter_ = iter_ +1;
% analyze when each regime starts based on current guess
[regime regimestart]=map_regime(violvecbool_);
% get the hypothesized piece wise linear solution
[zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,...
cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,...
regime,regimestart,violvecbool_,...
endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_);
for i_indx_=1:nwishes_
eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']);
end
newviolvecbool_ = eval(constraint_difference_);
relaxconstraint_ = eval(constraint_relax_difference_);
% check if changes to the hypothesis of the duration for each
% regime
if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
changes_ = 1;
else
changes_ = 0;
end
violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_);
end
init_ = zdatalinear_(1,:);
zdatapiecewise_(ishock_,:)=init_;
init_= init_';
% reset violvecbool_ for next period's shock -- this resetting is
% consistent with expecting no additional shocks
violvecbool_=[violvecbool_(2:end);0];
end
% if necessary, fill in the rest of the path with the remainder of the
% last IRF computed.
zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
% get the linear responses
zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),...
decrulea_,decruleb_,endog_,exog_,...
wishlist_,irfshock_,shockssequence_,init_orig_);
if changes_ ==1
display('Did not converge -- increase maxiter_')
end

View File

@ -0,0 +1,305 @@
% [zdatalinear zdatapiecewise zdatass oo 00 M 00] = solve two constraints(modnam 00,modnam 10,modnam 01,modnam 11,... constraint1, constraint2,... constraint relax1, constraint relax2,... shockssequence,irfshock,nperiods,curb retrench,maxiter,init);
%
% Inputs:
% modnam 00: name of the .mod file for reference regime (excludes the .mod extension). modnam10: name of the .mod file for the alternative regime governed by the first
% constraint.
% modnam01: name of the .mod file for the alternative regime governed by the second constraint.
% modnam 11: name of the .mod file for the case in which both constraints force a switch to their alternative regimes.
% constraint1: the first constraint (see notes 1 and 2 below). If constraint1 evaluates to true, then the solution switches to the alternative regime for condition 1. In thatcase, if constraint2 (described below) evaluates to false, then the model solution switches to enforcing the conditions for an equilibrium in modnam 10. Otherwise, if constraint2 also evaluates to true, then the model solution switches to enforcing the conditions for an equilibrium in modnam 11.
% constraint relax1: when the condition in constraint relax1 evaluates to true, the solution returns to the reference regime for constraint1.
% constraint2: the second constraint (see notes 1 and 2 below). constraint relax2: when the condition in constraint relax2 evaluates to true, the
% solution returns to the reference regime for constraint2. shockssequence: a sequence of unforeseen shocks under which one wants to solve the
% model
% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?)
% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
% curb retrench: a scalar equal to 0 or 1. Default is 0. When set to 0, it updates the guess based of regimes based on the previous iteration. When set to 1, it updates in a manner similar to a Gauss-Jacobi scheme, slowing the iterations down by updating the guess of regimes only one period at a time.
% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is a vector of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
%
% Outputs:
% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
% zdatass: a vector that holds the steady state values of the endogenous variables ( following the definition order in the .mod file).
% oo00 , M00 : structures produced by Dynare for the reference model ? see Dynare User Guide.
% Log of changes
% 6/17/2013 -- Luca added a trailing underscore to local variables in an
% attempt to avoid conflicts with parameter names defined in the .mod files
% to be processed.
% 6/17/2013 -- Luca replaced external .m file setss.m
function [ zdatalinear_ zdatapiecewise_ zdatass_ oo00_ M00_ ] = ...
solve_two_constraints(modnam_00_,modnam_10_,modnam_01_,modnam_11_,...
constrain1_, constrain2_,...
constraint_relax1_, constraint_relax2_,...
shockssequence_,irfshock_,nperiods_,curb_retrench_,maxiter_,init_)
global M_ oo_
% solve model
eval(['dynare ',modnam_00_,' noclearall nolog'])
oo00_ = oo_;
M00_ = M_;
for i=1:M00_.endo_nbr
eval([deblank(M00_.endo_names(i,:)) '_ss = oo00_.dr.ys(i); ']);
end
for i_indx_ = 1:M00_.param_nbr
eval([M00_.param_names(i_indx_,:),'= M00_.params(i_indx_);']);
end
eval(['dynare ',modnam_10_,' noclearall'])
oo10_ = oo_;
M10_ = M_;
eval(['dynare ',modnam_01_,' noclearall'])
oo01_ = oo_;
M01_ = M_;
eval(['dynare ',modnam_11_,' noclearall'])
oo11_ = oo_;
M11_ = M_;
% do some error checking
% check inputs
if ~strcmp(M00_.endo_names,M10_.endo_names)
error([modnam_00_,' and ',modnam_10_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
end
if ~strcmp(M00_.exo_names,M10_.exo_names)
error([modnam_00_,' and ',modnam_10_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
end
if ~strcmp(M00_.param_names,M10_.param_names)
warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_10_])
end
if ~strcmp(M00_.endo_names,M01_.endo_names)
error([modnam_00,' and ',modnam_01_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
end
if ~strcmp(M00_.exo_names,M01_.exo_names)
error([modnam_00_,' and ',modnam_01_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
end
if ~strcmp(M00_.param_names,M01_.param_names)
warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_01_])
end
if ~strcmp(M00_.endo_names,M11_.endo_names)
error([modnam_00_,' and ',modnam_11_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
end
if ~strcmp(M00_.exo_names,M11_.exo_names)
error([modnam_00_,' and ',modnam_11_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
end
if ~strcmp(M00_.param_names,M11_.param_names)
warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_11_])
end
nvars_ = M00_.endo_nbr;
zdatass_ = oo00_.dr.ys;
[hm1_,h_,hl1_,Jbarmat_] = get_deriv(M00_,zdatass_);
cof_ = [hm1_,h_,hl1_];
M10_.params = M00_.params;
[hm1_,h_,hl1_,Jbarmat10_,resid_] = get_deriv(M10_,zdatass_);
cof10_ = [hm1_,h_,hl1_];
Dbarmat10_ = resid_;
M01_.params = M00_.params;
[hm1_,h_,hl1_,Jbarmat01_,resid_] = get_deriv(M01_,zdatass_);
cof01_ = [hm1_,h_,hl1_];
Dbarmat01_ = resid_;
M11_.params = M00_.params;
[hm1_,h_,hl1_,Jbarmat11_,resid_] = get_deriv(M11_,zdatass_);
cof11_ = [hm1_,h_,hl1_];
Dbarmat11_ = resid_;
if isfield(M00_,'nfwrd') % needed for bakward compatibility with older Dynare releases
[decrulea,decruleb]=get_pq(oo00_.dr,M00_.nstatic,M00_.nfwrd);
else
[decrulea,decruleb]=get_pq(oo00_.dr,oo00_.dr.nstatic,oo00_.dr.nfwrd);
end
endog_ = M00_.endo_names;
exog_ = M00_.exo_names;
% processes the constrain so as to uppend a suffix to each
% endogenous variables
constraint1_difference_ = process_constraint(constrain1_,'_difference',M00_.endo_names,0);
% when the last argument in process_constraint is set to 1, the
% direction of the inequality in the constraint is inverted
constraint_relax1_difference_ = process_constraint(constraint_relax1_,'_difference',M00_.endo_names,0);
% processes the constrain so as to uppend a suffix to each
% endogenous variables
constraint2_difference_ = process_constraint(constrain2_,'_difference',M00_.endo_names,0);
% when the last argument in process_constraint is set to 1, the
% direction of the inequality in the constraint is inverted
constraint_relax2_difference_ = process_constraint(constraint_relax2_,'_difference',M00_.endo_names,0);
nshocks = size(shockssequence_,1);
if ~exist('init_')
init_ = zeros(nvars_,1);
end
if ~exist('maxiter_')
maxiter_ = 20;
end
if ~exist('curb_retrench_')
curb_retrench_ = 0;
end
init_orig_ = init_;
zdatapiecewise_ = zeros(nperiods_,nvars_);
violvecbool_ = zeros(nperiods_+1,2); % This sets the first guess for when
% the constraints are going to hold.
% The variable is a boolean with two
% columns. The first column refers to
% constrain1_; the second to
% constrain2_.
% Each row is a period in time.
% If the boolean is true it indicates
% the relevant constraint is expected
% to evaluate to true.
% The default initial guess is
% consistent with the base model always
% holding -- equivalent to the linear
% solution.
wishlist_ = endog_;
nwishes_ = size(wishlist_,1);
for ishock_ = 1:nshocks
changes_=1;
iter_ = 0;
while (changes_ & iter_<maxiter_)
iter_ = iter_ +1;
% analyse violvec and isolate contiguous periods in the other
% regime.
[regime1 regimestart1]=map_regime(violvecbool_(:,1));
[regime2 regimestart2]=map_regime(violvecbool_(:,2));
[zdatalinear_]=mkdatap_anticipated_2constraints(nperiods_,decrulea,decruleb,...
cof_,Jbarmat_,...
cof10_,Jbarmat10_,Dbarmat10_,...
cof01_,Jbarmat01_,Dbarmat01_,...
cof11_,Jbarmat11_,Dbarmat11_,...
regime1,regimestart1,...
regime2,regimestart2,...
violvecbool_,endog_,exog_,...
irfshock_,shockssequence_(ishock_,:),init_);
for i_indx_=1:nwishes_
eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']);
end
newviolvecbool1_ = eval(constraint1_difference_);
relaxconstraint1_ = eval(constraint_relax1_difference_);
newviolvecbool2_ = eval(constraint2_difference_);
relaxconstraint2_ = eval(constraint_relax2_difference_);
newviolvecbool_ = [newviolvecbool1_;newviolvecbool2_];
relaxconstraint_ = [relaxconstraint1_;relaxconstraint2_];
% check if changes_
if (max(newviolvecbool_(:)-violvecbool_(:)>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
changes_ = 1;
else
changes_ = 0;
end
if curb_retrench_ % apply Gauss-Sidel idea of slowing down the change in the guess
% for the constraint -- only relax one
% period at a time starting from the last
% one when each of the constraints is true.
retrench = 0*violvecbool_(:);
if ~isempty(find(relaxconstraint1_ & violvecbool_(:,1)))
retrenchpos = max(find(relaxconstraint1_ & violvecbool_(:,1)));
retrench(retrenchpos) = 1;
end
if ~isempty(find(relaxconstraint2_ & violvecbool_(:,2)))
retrenchpos = max(find(relaxconstraint2_ & violvecbool_(:,2)));
retrench(retrenchpos+nperiods_+1) = 1;
end
violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-retrench(:);
else
violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-(relaxconstraint_(:) & violvecbool_(:));
end
violvecbool_ = reshape(violvecbool_,nperiods_+1,2);
end
if changes_ ==1
display('Did not converge -- increase maxiter')
end
init_ = zdatalinear_(1,:);
zdatapiecewise_(ishock_,:)=init_;
init_= init_';
% update the guess for constraint violations for next period
% update is consistent with expecting no additional shocks next period
violvecbool_=[violvecbool_(2:end,:);zeros(1,2)];
end
zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
zdatalinear_ = mkdata(nperiods_,decrulea,decruleb,endog_,exog_,wishlist_,irfshock_,shockssequence_,init_orig_);

9
matlab/occbin/strmerge.m Executable file
View File

@ -0,0 +1,9 @@
function string = strmerge(tokens)
ntokens = length(tokens);
string = char(tokens(1));
for i=2:ntokens
string = [string,char(tokens(i))];
end

55
matlab/occbin/tokenize.m Executable file
View File

@ -0,0 +1,55 @@
function tokens = tokenize(source,delimiter)
% syntax
% tokens = tokenize(source,delimiters)
%
% source is a string to be broken into tokens
% delimiters is a character array of single character delimiters
% tokens is a cell string array containing the tokens
posdelims = [];
% assumes that delimiter cannot be in the first position or the last
% position
ndelimiters = size(delimiter,1);
for i=1:ndelimiters
newpositions = strfind(source,delimiter(i,:));
if ~isempty(newpositions)
posdelims =[posdelims, newpositions];
end
end
% reorder posdelims in ascending order
posdelims = sort(posdelims);
if isempty(posdelims)
tokens = cellstr(source);
else
ndelims = length(posdelims);
% build positions for substrings
delims = zeros(ndelims+1,2);
for i=1:ndelims+1;
if i==1
if posdelims(1) == 1
tokens = cellstr(source(1));
else
delims(i,:) = [1,posdelims(i)-1];
tokens = cellstr(source([delims(i,1):delims(i,2)]));
tokens = [tokens, source(posdelims(i))];
end
elseif i==ndelims+1
if (posdelims(i-1) < length(source))
delims(i,:) = [posdelims(i-1)+1,length(source)];
tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))];
end
else
if posdelims(i)>posdelims(i-1)+1
delims(i,:) = [posdelims(i-1)+1,posdelims(i)-1];
tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))];
end
tokens = [tokens, source(posdelims(i))];
end
end
end

View File

@ -1,13 +1,15 @@
function H = bfgsi1(H0,dg,dx)
% H = bfgsi1(H0,dg,dx)
function H = bfgsi1(H0,dg,dx,Verbose,Save_files)
% H = bfgsi1(H0,dg,dx,Verbose,Save_files)
% Update Inverse Hessian matrix
%
% Inputs:
% H0 [npar by npar] initial inverse Hessian matrix
% dg [npar by 1] previous change in gradient
% dx [npar by 1] previous change in x;
% Verbose [scalar] Indicator for silent mode
% Save_files [scalar] Indicator whether to save files
%
% 6/8/93 version that updates inverse hessian instead of hessian
% 6/8/93 version that updates inverse Hessian instead of Hessian
% itself.
%
% Original file downloaded from:
@ -42,10 +44,12 @@ dgdx = dg'*dx;
if (abs(dgdx) >1e-12)
H = H0 + (1+(dg'*Hdg)/dgdx)*(dx*dx')/dgdx - (dx*Hdg'+Hdg*dx')/dgdx;
else
disp('bfgs update failed.')
disp(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))]);
disp(['dg''*dx = ' num2str(dgdx)])
disp(['|H*dg| = ' num2str(Hdg'*Hdg)])
disp_verbose('bfgs update failed.',Verbose)
disp_verbose(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))],Verbose);
disp_verbose(['dg''*dx = ' num2str(dgdx)],Verbose)
disp_verbose(['|H*dg| = ' num2str(Hdg'*Hdg)],Verbose)
H=H0;
end
save('H.dat','H')
if Save_files
save('H.dat','H')
end

View File

@ -1,4 +1,4 @@
function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,f0,g0,badg,H0,varargin)
function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,f0,g0,badg,H0,Verbose,varargin)
% [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,f0,g0,badg,H0,varargin)
%
% Inputs:
@ -101,7 +101,7 @@ else
% toc
dxnorm = norm(dx);
if dxnorm > 1e12
disp('Near-singular H problem.')
disp_verbose('Near-singular H problem.',Verbose)
dx = dx*FCHANGE/dxnorm;
end
dfhat = dx'*g0;
@ -115,10 +115,10 @@ else
dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g;
dfhat = dx'*g;
dxnorm = norm(dx);
disp(sprintf('Correct for low angle: %g',a))
disp_verbose(sprintf('Correct for low angle: %g',a),Verbose)
end
end
disp(sprintf('Predicted improvement: %18.9f',-dfhat/2))
disp_verbose(sprintf('Predicted improvement: %18.9f',-dfhat/2),Verbose)
%
% Have OK dx, now adjust length of step (lambda) until min and
% max improvement rate criteria are met.
@ -141,7 +141,7 @@ else
%ARGLIST
%f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13);
% f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8);
disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f ))
disp_verbose(sprintf('lambda = %10.5g; f = %20.7f',lambda,f ),Verbose)
%debug
%disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda))
if f<fhat
@ -176,7 +176,11 @@ else
if abs(lambda) < MINLAMB
if (lambda > 0) && (f0 <= fhat)
% try going against gradient, which may be inaccurate
lambda = -lambda*factor^6
if Verbose
lambda = -lambda*factor^6
else
lambda = -lambda*factor^6;
end
else
if lambda < 0
retcode = 6;
@ -222,4 +226,5 @@ else
end
end
end
disp(sprintf('Norm of dx %10.5g', dxnorm))
disp_verbose(sprintf('Norm of dx %10.5g', dxnorm),Verbose)

View File

@ -1,4 +1,4 @@
function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,method,epsilon,varargin)
function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,method,epsilon,Verbose,Save_files,varargin)
%[fhat,xhat,ghat,Hhat,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,method,epsilon,varargin)
% Inputs:
% fcn: [string] string naming the objective function to be minimized
@ -65,7 +65,6 @@ fh = [];
xh = [];
[nx,no]=size(x0);
nx=max(nx,no);
Verbose=1;
NumGrad= isempty(grad);
done=0;
itct=0;
@ -87,7 +86,7 @@ retcodeh = [];
[f0,junk1,junk2,cost_flag] = feval(fcn,x0,varargin{:});
if ~cost_flag
disp('Bad initial parameter.')
disp_verbose('Bad initial parameter.',Verbose)
return
end
@ -110,15 +109,13 @@ while ~done
g1=[]; g2=[]; g3=[];
%addition fj. 7/6/94 for control
if Verbose
disp('-----------------')
disp(sprintf('f at the beginning of new iteration, %20.10f',f))
end
disp_verbose('-----------------',Verbose)
disp_verbose(sprintf('f at the beginning of new iteration, %20.10f',f),Verbose)
%-----------Comment out this line if the x vector is long----------------
% disp([sprintf('x = ') sprintf('%15.8g %15.8g %15.8g %15.8g\n',x)]);
% disp_verbose([sprintf('x = ') sprintf('%15.8g %15.8g %15.8g %15.8g\n',x)]);
%-------------------------
itct=itct+1;
[f1, x1, fc, retcode1] = csminit1(fcn,x,f,g,badg,H,varargin{:});
[f1, x1, fc, retcode1] = csminit1(fcn,x,f,g,badg,H,Verbose,varargin{:});
fcount = fcount+fc;
% erased on 8/4/94
% if (retcode == 1) || (abs(f1-f) < crit)
@ -142,7 +139,9 @@ while ~done
end
wall1=badg1;
% g1
save g1.mat g1 x1 f1 varargin;
if Save_files
save g1.mat g1 x1 f1 varargin;
end
end
if wall1 % && (~done) by Jinill
% Bad gradient or back and forth on step length. Possibly at
@ -150,10 +149,8 @@ while ~done
%
%fcliff=fh;xcliff=xh;
Hcliff=H+diag(diag(H).*rand(nx,1));
if Verbose
disp('Cliff. Perturbing search direction.')
end
[f2, x2, fc, retcode2] = csminit1(fcn,x,f,g,badg,Hcliff,varargin{:});
disp_verbose('Cliff. Perturbing search direction.',Verbose)
[f2, x2, fc, retcode2] = csminit1(fcn,x,f,g,badg,Hcliff,Verbose,varargin{:});
fcount = fcount+fc; % put by Jinill
if f2 < f
if retcode2==2 || retcode2==4
@ -169,11 +166,15 @@ while ~done
end
wall2=badg2;
% g2
badg2
save g2.mat g2 x2 f2 varargin
if Verbose
badg2
end
if Save_files
save g2.mat g2 x2 f2 varargin
end
end
if wall2
disp('Cliff again. Try traversing')
disp_verbose('Cliff again. Try traversing',Verbose)
if norm(x2-x1) < 1e-13
f3=f; x3=x; badg3=1;retcode3=101;
else
@ -181,7 +182,7 @@ while ~done
if(size(x0,2)>1)
gcliff=gcliff';
end
[f3, x3, fc, retcode3] = csminit1(fcn,x,f,gcliff,0,eye(nx),varargin{:});
[f3, x3, fc, retcode3] = csminit1(fcn,x,f,gcliff,0,eye(nx),Verbose,varargin{:});
fcount = fcount+fc; % put by Jinill
if retcode3==2 || retcode3==4
wall3=1;
@ -197,7 +198,9 @@ while ~done
end
wall3=badg3;
% g3
save g3.mat g3 x3 f3 varargin;
if Save_files
save g3.mat g3 x3 f3 varargin;
end
end
end
else
@ -225,7 +228,7 @@ while ~done
fh=f1;xh=x1;gh=g1;badgh=badg1;retcodeh=retcode1;
else
[fh,ih] = min([f1,f2,f3]);
%disp(sprintf('ih = %d',ih))
%disp_verbose(sprintf('ih = %d',ih))
%eval(['xh=x' num2str(ih) ';'])
switch ih
case 1
@ -259,18 +262,16 @@ while ~done
%end of picking
stuck = (abs(fh-f) < crit);
if (~badg) && (~badgh) && (~stuck)
H = bfgsi1(H,gh-g,xh-x);
end
if Verbose
disp('----')
disp(sprintf('Improvement on iteration %d = %18.9f',itct,f-fh))
H = bfgsi1(H,gh-g,xh-x,Verbose,Save_files);
end
disp_verbose('----',Verbose)
disp_verbose(sprintf('Improvement on iteration %d = %18.9f',itct,f-fh),Verbose)
% if Verbose
if itct > nit
disp('iteration count termination')
disp_verbose('iteration count termination',Verbose)
done = 1;
elseif stuck
disp('improvement < crit termination')
disp_verbose('improvement < crit termination',Verbose)
done = 1;
end
rc=retcodeh;
@ -278,19 +279,19 @@ while ~done
if rc ==0
%do nothing, just a normal step
elseif rc == 1
disp('zero gradient')
disp_verbose('zero gradient',Verbose)
elseif rc == 6
disp('smallest step still improving too slow, reversed gradient')
disp_verbose('smallest step still improving too slow, reversed gradient',Verbose)
elseif rc == 5
disp('largest step still improving too fast')
disp_verbose('largest step still improving too fast',Verbose)
elseif (rc == 4) || (rc==2)
disp('back and forth on step length never finished')
disp_verbose('back and forth on step length never finished',Verbose)
elseif rc == 3
disp('smallest step still improving too slow')
disp_verbose('smallest step still improving too slow',Verbose)
elseif rc == 7
disp('warning: possible inaccuracy in H matrix')
disp_verbose('warning: possible inaccuracy in H matrix',Verbose)
else
error('Unaccounted Case, please contact the developers')
error('Unaccounted Case, please contact the developers',Verbose)
end
end

View File

@ -5,7 +5,7 @@ function [opt_par_values,fval,exitflag,hessian_mat,options_,Scale]=dynare_minimi
% INPUTS
% objective_function [function handle] handle to the objective function
% start_par_value [n_params by 1] vector of doubles starting values for the parameters
% minimizer_algorithm [scalar double] code of the optimizer algorithm
% minimizer_algorithm [scalar double, or string] code of the optimizer algorithm, or string for the name of a user defined optimization routine (not shipped with dynare).
% options_ [matlab structure] Dynare options structure
% bounds [n_params by 2] vector of doubles 2 row vectors containing lower and upper bound for parameters
% parameter_names [n_params by 1] cell array strings containing the parameters names
@ -46,11 +46,7 @@ function [opt_par_values,fval,exitflag,hessian_mat,options_,Scale]=dynare_minimi
%% set bounds and parameter names if not already set
n_params=size(start_par_value,1);
if isempty(bounds)
if isnumeric(minimizer_algorithm) && minimizer_algorithm==10
error('Algorithm 10 (simpsa) requires upper and lower bounds')
else
bounds=[-Inf(n_params,1) Inf(n_params,1)];
end
bounds=[-Inf(n_params,1) Inf(n_params,1)];
end
if isempty(parameter_names)
@ -77,6 +73,9 @@ switch minimizer_algorithm
if ~isempty(options_.optim_opt)
eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
end
if options_.silent_optimizer
optim_options = optimset(optim_options,'display','off');
end
if options_.analytic_derivation,
optim_options = optimset(optim_options,'GradObj','on','TolX',1e-7);
end
@ -114,15 +113,20 @@ switch minimizer_algorithm
end
end
end
if options_.silent_optimizer
sa_options.verbosity = 0;
end
npar=length(start_par_value);
[LB, UB]=set_bounds_to_finite_values(bounds, options_.huge_number);
fprintf('\nNumber of parameters= %d, initial temperatur= %4.3f \n', npar,sa_options.initial_temperature);
fprintf('rt= %4.3f; TolFun= %4.3f; ns= %4.3f;\n',sa_options.rt,sa_options.TolFun,sa_options.ns);
fprintf('nt= %4.3f; neps= %4.3f; MaxIter= %d\n',sa_options.nt,sa_options.neps,sa_options.MaxIter);
fprintf('Initial step length(vm): %4.3f; step_length_c: %4.3f\n', sa_options.initial_step_length,sa_options.step_length_c);
fprintf('%-20s %-6s %-6s %-6s\n','Name:', 'LB;','Start;','UB;');
for pariter=1:npar
fprintf('%-20s %6.4f; %6.4f; %6.4f;\n',parameter_names{pariter}, LB(pariter),start_par_value(pariter),UB(pariter));
if sa_options.verbosity
fprintf('\nNumber of parameters= %d, initial temperatur= %4.3f \n', npar,sa_options.initial_temperature);
fprintf('rt= %4.3f; TolFun= %4.3f; ns= %4.3f;\n',sa_options.rt,sa_options.TolFun,sa_options.ns);
fprintf('nt= %4.3f; neps= %4.3f; MaxIter= %d\n',sa_options.nt,sa_options.neps,sa_options.MaxIter);
fprintf('Initial step length(vm): %4.3f; step_length_c: %4.3f\n', sa_options.initial_step_length,sa_options.step_length_c);
fprintf('%-20s %-6s %-6s %-6s\n','Name:', 'LB;','Start;','UB;');
for pariter=1:npar
fprintf('%-20s %6.4f; %6.4f; %6.4f;\n',parameter_names{pariter}, LB(pariter),start_par_value(pariter),UB(pariter));
end
end
sa_options.initial_step_length= sa_options.initial_step_length*ones(npar,1); %bring step length to correct vector size
sa_options.step_length_c= sa_options.step_length_c*ones(npar,1); %bring step_length_c to correct vector size
@ -142,6 +146,9 @@ switch minimizer_algorithm
if options_.analytic_derivation,
optim_options = optimset(optim_options,'GradObj','on');
end
if options_.silent_optimizer
optim_options = optimset(optim_options,'display','off');
end
if ~isoctave
[opt_par_values,fval,exitflag] = fminunc(objective_function,start_par_value,optim_options,varargin{:});
else
@ -156,6 +163,8 @@ switch minimizer_algorithm
nit = options_.csminwel.maxiter;
numgrad = options_.gradient_method;
epsilon = options_.gradient_epsilon;
Verbose = options_.csminwel.verbosity;
Save_files = options_.csminwel.Save_files;
% Change some options.
if ~isempty(options_.optim_opt)
options_list = read_key_value_string(options_.optim_opt);
@ -171,11 +180,19 @@ switch minimizer_algorithm
numgrad = options_list{i,2};
case 'NumgradEpsilon'
epsilon = options_list{i,2};
case 'verbosity'
Verbose = options_list{i,2};
case 'SaveFiles'
Save_files = options_list{i,2};
otherwise
warning(['csminwel: Unknown option (' options_list{i,1} ')!'])
end
end
end
if options_.silent_optimizer
Save_files = 0;
Verbose = 0;
end
% Set flag for analytical gradient.
if options_.analytic_derivation
analytic_grad=1;
@ -184,7 +201,7 @@ switch minimizer_algorithm
end
% Call csminwell.
[fval,opt_par_values,grad,inverse_hessian_mat,itct,fcount,exitflag] = ...
csminwel1(objective_function, start_par_value, H0, analytic_grad, crit, nit, numgrad, epsilon, varargin{:});
csminwel1(objective_function, start_par_value, H0, analytic_grad, crit, nit, numgrad, epsilon, Verbose, Save_files, varargin{:});
hessian_mat=inv(inverse_hessian_mat);
case 5
if options_.analytic_derivation==-1 %set outside as code for use of analytic derivation
@ -197,6 +214,8 @@ switch minimizer_algorithm
newratflag = options_.newrat.hess; %default
end
nit=options_.newrat.maxiter;
Verbose = options_.newrat.verbosity;
Save_files = options_.newrat.Save_files;
if ~isempty(options_.optim_opt)
options_list = read_key_value_string(options_.optim_opt);
for i=1:rows(options_list)
@ -212,12 +231,20 @@ switch minimizer_algorithm
end
case 'TolFun'
crit = options_list{i,2};
case 'verbosity'
Verbose = options_list{i,2};
case 'SaveFiles'
Save_files = options_list{i,2};
otherwise
warning(['newrat: Unknown option (' options_list{i,1} ')!'])
end
end
end
[opt_par_values,hessian_mat,gg,fval,invhess] = newrat(objective_function,start_par_value,analytic_grad,crit,nit,0,varargin{:});
if options_.silent_optimizer
Save_files = 0;
Verbose = 0;
end
[opt_par_values,hessian_mat,gg,fval,invhess] = newrat(objective_function,start_par_value,analytic_grad,crit,nit,0,Verbose, Save_files,varargin{:});
%hessian_mat is the plain outer product gradient Hessian
case 6
[opt_par_values, hessian_mat, Scale, fval] = gmhmaxlik(objective_function, start_par_value, ...
@ -233,6 +260,9 @@ switch minimizer_algorithm
if ~isempty(options_.optim_opt)
eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
end
if options_.silent_optimizer
optim_options = optimset(optim_options,'display','off');
end
if ~isoctave
[opt_par_values,fval,exitflag] = fminsearch(objective_function,start_par_value,optim_options,varargin{:});
else
@ -259,11 +289,16 @@ switch minimizer_algorithm
simplexOptions.maxfcallfactor = options_list{i,2};
case 'InitialSimplexSize'
simplexOptions.delta_factor = options_list{i,2};
case 'verbosity'
simplexOptions.verbose = options_list{i,2};
otherwise
warning(['simplex: Unknown option (' options_list{i,1} ')!'])
end
end
end
if options_.silent_optimizer
simplexOptions.verbose = options_list{i,2};
end
[opt_par_values,fval,exitflag] = simplex_optimization_routine(objective_function,start_par_value,simplexOptions,parameter_names,varargin{:});
case 9
% Set defaults
@ -282,11 +317,29 @@ switch minimizer_algorithm
cmaesOptions.TolX = options_list{i,2};
case 'MaxFunEvals'
cmaesOptions.MaxFunEvals = options_list{i,2};
case 'verbosity'
if options_list{i,2}==0
cmaesOptions.DispFinal = 'off'; % display messages like initial and final message';
cmaesOptions.DispModulo = '0'; % [0:Inf], disp messages after every i-th iteration';
end
case 'SaveFiles'
if options_list{i,2}==0
cmaesOptions.SaveVariables='off';
cmaesOptions.LogModulo = '0'; % [0:Inf] if >1 record data less frequently after gen=100';
cmaesOptions.LogTime = '0'; % [0:100] max. percentage of time for recording data';
end
otherwise
warning(['cmaes: Unknown option (' options_list{i,1} ')!'])
end
end
end
if options_.silent_optimizer
cmaesOptions.DispFinal = 'off'; % display messages like initial and final message';
cmaesOptions.DispModulo = '0'; % [0:Inf], disp messages after every i-th iteration';
cmaesOptions.SaveVariables='off';
cmaesOptions.LogModulo = '0'; % [0:Inf] if >1 record data less frequently after gen=100';
cmaesOptions.LogTime = '0'; % [0:100] max. percentage of time for recording data';
end
warning('off','CMAES:NonfinitenessRange');
warning('off','CMAES:InitialSigma');
[x, fval, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = cmaes(func2str(objective_function),start_par_value,H0,cmaesOptions,varargin{:});
@ -313,11 +366,20 @@ switch minimizer_algorithm
simpsaOptions.TEMP_END = options_list{i,2};
case 'MaxFunEvals'
simpsaOptions.MAX_FUN_EVALS = options_list{i,2};
case 'verbosity'
if options_list{i,2} == 0
simpsaOptions.DISPLAY = 'none';
else
simpsaOptions.DISPLAY = 'iter';
end
otherwise
warning(['simpsa: Unknown option (' options_list{i,1} ')!'])
end
end
end
if options_.silent_optimizer
simpsaOptions.DISPLAY = 'none';
end
simpsaOptionsList = options2cell(simpsaOptions);
simpsaOptions = simpsaset(simpsaOptionsList{:});
[LB, UB]=set_bounds_to_finite_values(bounds, options_.huge_number);
@ -348,6 +410,9 @@ switch minimizer_algorithm
end
end
end
if options_.silent_optimizer
solveoptoptions.verbosity = 0;
end
[opt_par_values,fval]=solvopt(start_par_value,objective_function,[],[],[],solveoptoptions,varargin{:});
case 102
if isoctave
@ -360,12 +425,15 @@ switch minimizer_algorithm
if ~isempty(options_.optim_opt)
eval(['optim_options = saoptimset(optim_options,' options_.optim_opt ');']);
end
if options_.silent_optimizer
optim_options = optimset(optim_options,'display','off');
end
func = @(x)objective_function(x,varargin{:});
[opt_par_values,fval,exitflag,output] = simulannealbnd(func,start_par_value,bounds(:,1),bounds(:,2),optim_options);
otherwise
if ischar(minimizer_algorithm)
if exist(options_.mode_compute)
[opt_par_values, fval, exitflag] = feval(options_.mode_compute,objective_function,start_par_value,varargin{:});
if exist(minimizer_algorithm)
[opt_par_values, fval, exitflag] = feval(minimizer_algorithm,objective_function,start_par_value,varargin{:});
else
error('No minimizer with the provided name detected.')
end

View File

@ -1,4 +1,4 @@
function [f0, x, ig] = mr_gstep(h1,x,func0,htol0,varargin)
function [f0, x, ig] = mr_gstep(h1,x,func0,htol0,Verbose,Save_files,varargin)
% function [f0, x, ig] = mr_gstep(h1,x,func0,htol0,varargin)
%
% Gibbs type step in optimisation
@ -69,14 +69,19 @@ while i<n
gg(i)=(f1(i)'-f_1(i)')./(2.*h1(i));
hh(i) = 1/max(1.e-9,abs( (f1(i)+f_1(i)-2*f0)./(h1(i)*h1(i)) ));
if gg(i)*(hh(i)*gg(i))/2 > htol
[f0 x fc retcode] = csminit1(func0,x,f0,gg,0,diag(hh),varargin{:});
[f0 x fc retcode] = csminit1(func0,x,f0,gg,0,diag(hh),Verbose,varargin{:});
ig(i)=1;
fprintf(['Done for param %s = %8.4f\n'],varargin{6}.name{i},x(i))
if Verbose
fprintf(['Done for param %s = %8.4f\n'],varargin{6}.name{i},x(i))
end
end
xh1=x;
end
if Save_files
save gstep.mat x h1 f0
end
end
if Save_files
save gstep.mat x h1 f0
end
save gstep.mat x h1 f0

View File

@ -1,4 +1,4 @@
function [xparam1, hh, gg, fval, igg] = newrat(func0, x, analytic_derivation, ftol0, nit, flagg, varargin)
function [xparam1, hh, gg, fval, igg] = newrat(func0, x, analytic_derivation, ftol0, nit, flagg, Verbose, Save_files, varargin)
% [xparam1, hh, gg, fval, igg] = newrat(func0, x, hh, gg, igg, ftol0, nit, flagg, varargin)
%
% Optimiser with outer product gradient and with sequences of univariate steps
@ -49,6 +49,7 @@ function [xparam1, hh, gg, fval, igg] = newrat(func0, x, analytic_derivation, ft
global objective_function_penalty_base
icount=0;
nx=length(x);
xparam1=x;
@ -95,14 +96,19 @@ else
h1=[];
end
H = igg;
disp(['Gradient norm ',num2str(norm(gg))])
disp_verbose(['Gradient norm ',num2str(norm(gg))],Verbose)
ee=eig(hh);
disp(['Minimum Hessian eigenvalue ',num2str(min(ee))])
disp(['Maximum Hessian eigenvalue ',num2str(max(ee))])
disp_verbose(['Minimum Hessian eigenvalue ',num2str(min(ee))],Verbose)
disp_verbose(['Maximum Hessian eigenvalue ',num2str(max(ee))],Verbose)
g=gg;
check=0;
if max(eig(hh))<0, disp('Negative definite Hessian! Local maximum!'), pause, end,
save m1.mat x hh g hhg igg fval0
if max(eig(hh))<0
disp_verbose('Negative definite Hessian! Local maximum!',Verbose)
pause
end
if Save_files
save m1.mat x hh g hhg igg fval0
end
igrad=1;
igibbs=1;
@ -116,13 +122,13 @@ while norm(gg)>gtol && check==0 && jit<nit
tic
icount=icount+1;
objective_function_penalty_base = fval0(icount);
disp([' '])
disp(['Iteration ',num2str(icount)])
[fval,x0,fc,retcode] = csminit1(func0,xparam1,fval0(icount),gg,0,H,varargin{:});
disp_verbose([' '],Verbose)
disp_verbose(['Iteration ',num2str(icount)],Verbose)
[fval,x0,fc,retcode] = csminit1(func0,xparam1,fval0(icount),gg,0,H,Verbose,varargin{:});
if igrad
[fval1,x01,fc,retcode1] = csminit1(func0,x0,fval,gg,0,inx,varargin{:});
[fval1,x01,fc,retcode1] = csminit1(func0,x0,fval,gg,0,inx,Verbose,varargin{:});
if (fval-fval1)>1
disp('Gradient step!!')
disp_verbose('Gradient step!!',Verbose)
else
igrad=0;
end
@ -139,27 +145,27 @@ while norm(gg)>gtol && check==0 && jit<nit
end
iggx=eye(length(gg));
iggx(find(ig),find(ig)) = inv( hhx(find(ig),find(ig)) );
[fvala,x0,fc,retcode] = csminit1(func0,x0,fval,ggx,0,iggx,varargin{:});
[fvala,x0,fc,retcode] = csminit1(func0,x0,fval,ggx,0,iggx,Verbose,varargin{:});
end
[fvala, x0, ig] = mr_gstep(h1,x0,func0,htol,varargin{:});
[fvala, x0, ig] = mr_gstep(h1,x0,func0,htol,Verbose,Save_files,varargin{:});
nig=[nig ig];
disp('Sequence of univariate steps!!')
disp_verbose('Sequence of univariate steps!!',Verbose)
fval=fvala;
if (fval0(icount)-fval)<ftol && flagit==0
disp('Try diagonal Hessian')
disp_verbose('Try diagonal Hessian',Verbose)
ihh=diag(1./(diag(hhg)));
[fval2,x0,fc,retcode2] = csminit1(func0,x0,fval,gg,0,ihh,varargin{:});
[fval2,x0,fc,retcode2] = csminit1(func0,x0,fval,gg,0,ihh,Verbose,varargin{:});
if (fval-fval2)>=ftol
disp('Diagonal Hessian successful')
disp_verbose('Diagonal Hessian successful',Verbose)
end
fval=fval2;
end
if (fval0(icount)-fval)<ftol && flagit==0
disp('Try gradient direction')
disp_verbose('Try gradient direction',Verbose)
ihh0=inx.*1.e-4;
[fval3,x0,fc,retcode3] = csminit1(func0,x0,fval,gg,0,ihh0,varargin{:});
[fval3,x0,fc,retcode3] = csminit1(func0,x0,fval,gg,0,ihh0,Verbose,varargin{:});
if (fval-fval3)>=ftol
disp('Gradient direction successful')
disp_verbose('Gradient direction successful',Verbose)
end
fval=fval3;
end
@ -167,7 +173,7 @@ while norm(gg)>gtol && check==0 && jit<nit
x(:,icount+1)=xparam1;
fval0(icount+1)=fval;
if (fval0(icount)-fval)<ftol
disp('No further improvement is possible!')
disp_verbose('No further improvement is possible!',Verbose)
check=1;
if analytic_derivation,
[fvalx,gg,hh]=feval(func0,xparam1,varargin{:});
@ -189,29 +195,33 @@ while norm(gg)>gtol && check==0 && jit<nit
end
end
end
disp(['Actual dxnorm ',num2str(norm(x(:,end)-x(:,end-1)))])
disp(['FVAL ',num2str(fval)])
disp(['Improvement ',num2str(fval0(icount)-fval)])
disp(['Ftol ',num2str(ftol)])
disp(['Htol ',num2str(htol0)])
disp(['Gradient norm ',num2str(norm(gg))])
disp_verbose(['Actual dxnorm ',num2str(norm(x(:,end)-x(:,end-1)))],Verbose)
disp_verbose(['FVAL ',num2str(fval)],Verbose)
disp_verbose(['Improvement ',num2str(fval0(icount)-fval)],Verbose)
disp_verbose(['Ftol ',num2str(ftol)],Verbose)
disp_verbose(['Htol ',num2str(htol0)],Verbose)
disp_verbose(['Gradient norm ',num2str(norm(gg))],Verbose)
ee=eig(hh);
disp(['Minimum Hessian eigenvalue ',num2str(min(ee))])
disp(['Maximum Hessian eigenvalue ',num2str(max(ee))])
disp_verbose(['Minimum Hessian eigenvalue ',num2str(min(ee))],Verbose)
disp_verbose(['Maximum Hessian eigenvalue ',num2str(max(ee))],Verbose)
g(:,icount+1)=gg;
else
df = fval0(icount)-fval;
disp(['Actual dxnorm ',num2str(norm(x(:,end)-x(:,end-1)))])
disp(['FVAL ',num2str(fval)])
disp(['Improvement ',num2str(df)])
disp(['Ftol ',num2str(ftol)])
disp(['Htol ',num2str(htol0)])
disp_verbose(['Actual dxnorm ',num2str(norm(x(:,end)-x(:,end-1)))],Verbose)
disp_verbose(['FVAL ',num2str(fval)],Verbose)
disp_verbose(['Improvement ',num2str(df)],Verbose)
disp_verbose(['Ftol ',num2str(ftol)],Verbose)
disp_verbose(['Htol ',num2str(htol0)],Verbose)
htol=htol_base;
if norm(x(:,icount)-xparam1)>1.e-12 && analytic_derivation==0,
try
save m1.mat x fval0 nig -append
if Save_files
save m1.mat x fval0 nig -append
end
catch
save m1.mat x fval0 nig
if Save_files
save m1.mat x fval0 nig
end
end
[dum, gg, htol0, igg, hhg, h1]=mr_hessian(0,xparam1,func0,flagit,htol,varargin{:});
if isempty(dum),
@ -220,12 +230,12 @@ while norm(gg)>gtol && check==0 && jit<nit
if htol0>htol
htol=htol0;
skipline()
disp('Numerical noise in the likelihood')
disp('Tolerance has to be relaxed')
disp_verbose('Numerical noise in the likelihood',Verbose)
disp_verbose('Tolerance has to be relaxed',Verbose)
skipline()
end
if ~outer_product_gradient,
H = bfgsi1(H,gg-g(:,icount),xparam1-x(:,icount));
H = bfgsi1(H,gg-g(:,icount),xparam1-x(:,icount),Verbose,Save_files);
hh=inv(H);
hhg=hh;
else
@ -246,39 +256,44 @@ while norm(gg)>gtol && check==0 && jit<nit
hhg=hh;
H = inv(hh);
end
disp(['Gradient norm ',num2str(norm(gg))])
disp_verbose(['Gradient norm ',num2str(norm(gg))],Verbose)
ee=eig(hh);
disp(['Minimum Hessian eigenvalue ',num2str(min(ee))])
disp(['Maximum Hessian eigenvalue ',num2str(max(ee))])
if max(eig(hh))<0, disp('Negative definite Hessian! Local maximum!'), pause(1), end,
disp_verbose(['Minimum Hessian eigenvalue ',num2str(min(ee))],Verbose)
disp_verbose(['Maximum Hessian eigenvalue ',num2str(max(ee))],Verbose)
if max(eig(hh))<0
disp_verbose('Negative definite Hessian! Local maximum!',Verbose)
pause(1)
end
t=toc;
disp(['Elapsed time for iteration ',num2str(t),' s.'])
disp_verbose(['Elapsed time for iteration ',num2str(t),' s.'],Verbose)
g(:,icount+1)=gg;
save m1.mat x hh g hhg igg fval0 nig H
if Save_files
save m1.mat x hh g hhg igg fval0 nig H
end
end
end
save m1.mat x hh g hhg igg fval0 nig
if Save_files
save m1.mat x hh g hhg igg fval0 nig
end
if ftol>ftol0
skipline()
disp('Numerical noise in the likelihood')
disp('Tolerance had to be relaxed')
disp_verbose('Numerical noise in the likelihood',Verbose)
disp_verbose('Tolerance had to be relaxed',Verbose)
skipline()
end
if jit==nit
skipline()
disp('Maximum number of iterations reached')
disp_verbose('Maximum number of iterations reached',Verbose)
skipline()
end
if norm(gg)<=gtol
disp(['Estimation ended:'])
disp(['Gradient norm < ', num2str(gtol)])
disp_verbose(['Estimation ended:'],Verbose)
disp_verbose(['Gradient norm < ', num2str(gtol)],Verbose)
end
if check==1,
disp(['Estimation successful.'])
disp_verbose(['Estimation successful.'],Verbose)
end
return
return

View File

@ -507,12 +507,12 @@ fval = fv(1);
exitflag = 1;
if func_count>= max_func_calls
disp('Maximum number of objective function calls has been exceeded!')
disp_verbose('Maximum number of objective function calls has been exceeded!',verbose)
exitflag = 0;
end
if iter_count>= max_iterations
disp('Maximum number of iterations has been exceeded!')
disp_verbose('Maximum number of iterations has been exceeded!',verbose)
exitflag = 0;
end

View File

@ -89,7 +89,9 @@ else
% nonlinear models
if max(abs(feval(fh,dr.ys,[oo_.exo_steady_state; ...
oo_.exo_det_steady_state], M_.params))) > options_.dynatol.f
[dr.ys,check1] = dynare_solve(fh,dr.ys,options_,...
opt = options_;
opt.jacobian_flag = 0;
[dr.ys,check1] = dynare_solve(fh,dr.ys,opt,...
[oo_.exo_steady_state; ...
oo_.exo_det_steady_state], M_.params);
end

View File

@ -87,7 +87,9 @@ if options_.ramsey_policy && options_.ACES_solver == 0
end
old_solve_algo = options_.solve_algo;
% options_.solve_algo = 1;
oo_.steady_state = dynare_solve('ramsey_static',oo_.steady_state,options_,M_,options_,oo_,it_);
opt = options_;
opt.jacobian_flag = 0;
oo_.steady_state = dynare_solve('ramsey_static',oo_.steady_state,opt,M_,options_,oo_,it_);
options_.solve_algo = old_solve_algo;
[junk,junk,multbar] = ramsey_static(oo_.steady_state,M_,options_,oo_,it_);
[jacobia_,M_] = ramsey_dynamic(oo_.steady_state,multbar,M_,options_,oo_,it_);

View File

@ -1,116 +0,0 @@
function initial_distribution = auxiliary_initialization(ReducedForm,Y,start,DynareOptions)
% Evaluates the likelihood of a nonlinear model with a particle filter allowing eventually resampling.
%
% INPUTS
% ReducedForm [structure] Matlab's structure describing the reduced form model.
% ReducedForm.measurement.H [double] (pp x pp) variance matrix of measurement errors.
% ReducedForm.state.Q [double] (qq x qq) variance matrix of state errors.
% ReducedForm.state.dr [structure] output of resol.m.
% Y [double] pp*smpl matrix of (detrended) data, where pp is the maximum number of observed variables.
% start [integer] scalar, likelihood evaluation starts at 'start'.
% mf [integer] pp*1 vector of indices.
% number_of_particles [integer] scalar.
%
% OUTPUTS
% LIK [double] scalar, likelihood
% lik [double] vector, density of observations in each period.
%
% REFERENCES
%
% NOTES
% The vector "lik" is used to evaluate the jacobian of the likelihood.
% Copyright (C) 2013 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
persistent init_flag mf0 mf1 number_of_particles
persistent number_of_observed_variables number_of_structural_innovations
% Set default
if isempty(start)
start = 1;
end
% Set flag for prunning
%pruning = DynareOptions.particle.pruning;
% Get steady state and mean.
%steadystate = ReducedForm.steadystate;
constant = ReducedForm.constant;
state_variables_steady_state = ReducedForm.state_variables_steady_state;
% Set persistent variables.
if isempty(init_flag)
mf0 = ReducedForm.mf0;
mf1 = ReducedForm.mf1;
number_of_observed_variables = length(mf1);
number_of_structural_innovations = length(ReducedForm.Q);
number_of_particles = DynareOptions.particle.number_of_particles;
init_flag = 1;
end
% Set local state space model (first order approximation).
ghx = ReducedForm.ghx;
ghu = ReducedForm.ghu;
% Set local state space model (second order approximation).
ghxx = ReducedForm.ghxx;
ghuu = ReducedForm.ghuu;
ghxu = ReducedForm.ghxu;
% Get covariance matrices
Q = ReducedForm.Q;
H = ReducedForm.H;
if isempty(H)
H = 0;
end
% Get initial condition for the state vector.
StateVectorMean = ReducedForm.StateVectorMean;
StateVectorVarianceSquareRoot = reduced_rank_cholesky(ReducedForm.StateVectorVariance)';
state_variance_rank = size(StateVectorVarianceSquareRoot,2);
%Q_lower_triangular_cholesky = chol(Q)';
%if pruning
% StateVectorMean_ = StateVectorMean;
% StateVectorVarianceSquareRoot_ = StateVectorVarianceSquareRoot;
%end
% Set seed for randn().
set_dynare_seed('default');
% Initialization of the likelihood.
const_lik = log(2*pi)*number_of_observed_variables;
% Initialization of the weights across particles.
weights = ones(1,number_of_particles)/number_of_particles ;
StateVectors = bsxfun(@plus,StateVectorVarianceSquareRoot*randn(state_variance_rank,number_of_particles),StateVectorMean);
%if pruning
% StateVectors_ = StateVectors;
%end
yhat = bsxfun(@minus,StateVectors,state_variables_steady_state);
%if pruning
% yhat_ = bsxfun(@minus,StateVectors_,state_variables_steady_state);
% [tmp, tmp_] = local_state_space_iteration_2(yhat,zeros(number_of_structural_innovations,number_of_particles),ghx,ghu,constant,ghxx,ghuu,ghxu,yhat_,steadystate,DynareOptions.threads.local_state_space_iteration_2);
%else
tmp = local_state_space_iteration_2(yhat,zeros(number_of_structural_innovations,number_of_particles),ghx,ghu,constant,ghxx,ghuu,ghxu,DynareOptions.threads.local_state_space_iteration_2);
%end
PredictedObservedMean = weights*(tmp(mf1,:)');
PredictionError = bsxfun(@minus,Y(:,t),tmp(mf1,:));
dPredictedObservedMean = bsxfun(@minus,tmp(mf1,:),PredictedObservedMean');
PredictedObservedVariance = bsxfun(@times,weights,dPredictedObservedMean)*dPredictedObservedMean' + H;
wtilde = exp(-.5*(const_lik+log(det(PredictedObservedVariance))+sum(PredictionError.*(PredictedObservedVariance\PredictionError),1))) ;
tau_tilde = weights.*wtilde ;
tau_tilde = tau_tilde/sum(tau_tilde);
initial_distribution = resample(StateVectors',tau_tilde',DynareOptions)' ;

View File

@ -1,159 +0,0 @@
function [LIK,lik] = auxiliary_particle_filter(ReducedForm,Y,start,DynareOptions)
% Evaluates the likelihood of a nonlinear model with a particle filter allowing eventually resampling.
%
% INPUTS
% ReducedForm [structure] Matlab's structure describing the reduced form model.
% ReducedForm.measurement.H [double] (pp x pp) variance matrix of measurement errors.
% ReducedForm.state.Q [double] (qq x qq) variance matrix of state errors.
% ReducedForm.state.dr [structure] output of resol.m.
% Y [double] pp*smpl matrix of (detrended) data, where pp is the maximum number of observed variables.
% start [integer] scalar, likelihood evaluation starts at 'start'.
% mf [integer] pp*1 vector of indices.
% number_of_particles [integer] scalar.
%
% OUTPUTS
% LIK [double] scalar, likelihood
% lik [double] vector, density of observations in each period.
%
% REFERENCES
%
% NOTES
% The vector "lik" is used to evaluate the jacobian of the likelihood.
% Copyright (C) 2011-2013 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
persistent init_flag mf0 mf1 number_of_particles
persistent sample_size number_of_state_variables number_of_observed_variables number_of_structural_innovations
% Set default
if isempty(start)
start = 1;
end
% Set flag for prunning
pruning = DynareOptions.particle.pruning;
% Get steady state and mean.
steadystate = ReducedForm.steadystate;
constant = ReducedForm.constant;
state_variables_steady_state = ReducedForm.state_variables_steady_state;
% Set persistent variables.
if isempty(init_flag)
mf0 = ReducedForm.mf0;
mf1 = ReducedForm.mf1;
sample_size = size(Y,2);
number_of_state_variables = length(mf0);
number_of_observed_variables = length(mf1);
number_of_structural_innovations = length(ReducedForm.Q);
number_of_particles = DynareOptions.particle.number_of_particles;
init_flag = 1;
end
% Set local state space model (first order approximation).
ghx = ReducedForm.ghx;
ghu = ReducedForm.ghu;
% Set local state space model (second order approximation).
ghxx = ReducedForm.ghxx;
ghuu = ReducedForm.ghuu;
ghxu = ReducedForm.ghxu;
% Get covariance matrices
Q = ReducedForm.Q;
H = ReducedForm.H;
if isempty(H)
H = 0;
end
% Get initial condition for the state vector.
StateVectorMean = ReducedForm.StateVectorMean;
StateVectorVarianceSquareRoot = reduced_rank_cholesky(ReducedForm.StateVectorVariance)';
state_variance_rank = size(StateVectorVarianceSquareRoot,2);
Q_lower_triangular_cholesky = chol(Q)';
if pruning
StateVectorMean_ = StateVectorMean;
StateVectorVarianceSquareRoot_ = StateVectorVarianceSquareRoot;
end
% Set seed for randn().
set_dynare_seed('default');
% Initialization of the likelihood.
const_lik = log(2*pi)*number_of_observed_variables;
lik = NaN(sample_size,1);
LIK = NaN;
% Initialization of the weights across particles.
weights = ones(1,number_of_particles)/number_of_particles ;
StateVectors = bsxfun(@plus,StateVectorVarianceSquareRoot*randn(state_variance_rank,number_of_particles),StateVectorMean);
if pruning
StateVectors_ = StateVectors;
end
for t=1:sample_size
yhat = bsxfun(@minus,StateVectors,state_variables_steady_state);
if pruning
yhat_ = bsxfun(@minus,StateVectors_,state_variables_steady_state);
[tmp, tmp_] = local_state_space_iteration_2(yhat,zeros(number_of_structural_innovations,number_of_particles),ghx,ghu,constant,ghxx,ghuu,ghxu,yhat_,steadystate,DynareOptions.threads.local_state_space_iteration_2);
else
tmp = local_state_space_iteration_2(yhat,zeros(number_of_structural_innovations,number_of_particles),ghx,ghu,constant,ghxx,ghuu,ghxu,DynareOptions.threads.local_state_space_iteration_2);
end
PredictedObservedMean = weights*(tmp(mf1,:)');
PredictionError = bsxfun(@minus,Y(:,t),tmp(mf1,:));
dPredictedObservedMean = bsxfun(@minus,tmp(mf1,:),PredictedObservedMean');
PredictedObservedVariance = bsxfun(@times,weights,dPredictedObservedMean)*dPredictedObservedMean' +H;
wtilde = exp(-.5*(const_lik+log(det(PredictedObservedVariance))+sum(PredictionError.*(PredictedObservedVariance\PredictionError),1))) ;
tau_tilde = weights.*wtilde ;
sum_tau_tilde = sum(tau_tilde) ;
%var_wtilde = wtilde-sum_tau_tilde ;
%var_wtilde = var_wtilde'*var_wtilde/(number_of_particles-1) ;
lik(t) = log(sum_tau_tilde) ; %+ .5*var_wtilde/(number_of_particles*(sum_tau_tilde*sum_tau_tilde)) ;
tau_tilde = tau_tilde/sum_tau_tilde;
if pruning
temp = resample([yhat' yhat_'],tau_tilde',DynareOptions);
yhat = temp(:,1:number_of_state_variables)' ;
yhat_ = temp(:,number_of_state_variables+1:2*number_of_state_variables)' ;
else
yhat = resample(yhat',tau_tilde',DynareOptions)' ;
end
if pruning
[tmp, tmp_] = local_state_space_iteration_2(yhat,zeros(number_of_structural_innovations,number_of_particles),ghx,ghu,constant,ghxx,ghuu,ghxu,yhat_,steadystate,DynareOptions.threads.local_state_space_iteration_2);
else
tmp = local_state_space_iteration_2(yhat,zeros(number_of_structural_innovations,number_of_particles),ghx,ghu,constant,ghxx,ghuu,ghxu,DynareOptions.threads.local_state_space_iteration_2);
end
PredictedObservedMean = weights*(tmp(mf1,:)');
PredictionError = bsxfun(@minus,Y(:,t),tmp(mf1,:));
dPredictedObservedMean = bsxfun(@minus,tmp(mf1,:),PredictedObservedMean');
PredictedObservedVariance = bsxfun(@times,weights,dPredictedObservedMean)*dPredictedObservedMean' +H;
wtilde = exp(-.5*(const_lik+log(det(PredictedObservedVariance))+sum(PredictionError.*(PredictedObservedVariance\PredictionError),1))) ;
epsilon = Q_lower_triangular_cholesky*randn(number_of_structural_innovations,number_of_particles);
if pruning
[tmp, tmp_] = local_state_space_iteration_2(yhat,epsilon,ghx,ghu,constant,ghxx,ghuu,ghxu,yhat_,steadystate,DynareOptions.threads.local_state_space_iteration_2);
StateVectors_ = tmp_(mf0,:);
else
tmp = local_state_space_iteration_2(yhat,epsilon,ghx,ghu,constant,ghxx,ghuu,ghxu,DynareOptions.threads.local_state_space_iteration_2);
end
StateVectors = tmp(mf0,:);
PredictedObservedMean = mean(tmp(mf1,:),2);
PredictionError = bsxfun(@minus,Y(:,t),tmp(mf1,:));
dPredictedObservedMean = bsxfun(@minus,tmp(mf1,:),PredictedObservedMean);
PredictedObservedVariance = (dPredictedObservedMean*dPredictedObservedMean')/number_of_particles + H;
lnw = exp(-.5*(const_lik+log(det(PredictedObservedVariance))+sum(PredictionError.*(PredictedObservedVariance\PredictionError),1)));
wtilde = lnw./wtilde;
weights = wtilde/sum(wtilde);
end
LIK = -sum(lik(start:end));

View File

@ -1,123 +0,0 @@
function [ProposalStateVector,Weights] = conditional_filter_proposal(ReducedForm,obs,StateVectors,SampleWeights,Q_lower_triangular_cholesky,H_lower_triangular_cholesky,H,DynareOptions,normconst2)
%
% Computes the proposal for each past particle using Gaussian approximations
% for the state errors and the Kalman filter
%
% INPUTS
% reduced_form_model [structure] Matlab's structure describing the reduced form model.
% reduced_form_model.measurement.H [double] (pp x pp) variance matrix of measurement errors.
% reduced_form_model.state.Q [double] (qq x qq) variance matrix of state errors.
% reduced_form_model.state.dr [structure] output of resol.m.
% Y [double] pp*smpl matrix of (detrended) data, where pp is the maximum number of observed variables.
%
% OUTPUTS
% LIK [double] scalar, likelihood
% lik [double] vector, density of observations in each period.
%
% REFERENCES
%
% NOTES
% The vector "lik" is used to evaluate the jacobian of the likelihood.
% Copyright (C) 2012-2013 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
%
% AUTHOR(S) frederic DOT karame AT univ DASH lemans DOT fr
% stephane DOT adjemian AT univ DASH lemans DOT fr
persistent init_flag2 mf0 mf1
persistent number_of_state_variables number_of_observed_variables
persistent number_of_structural_innovations
% Set local state space model (first-order approximation).
ghx = ReducedForm.ghx;
ghu = ReducedForm.ghu;
% Set local state space model (second-order approximation).
ghxx = ReducedForm.ghxx;
ghuu = ReducedForm.ghuu;
ghxu = ReducedForm.ghxu;
if any(any(isnan(ghx))) || any(any(isnan(ghu))) || any(any(isnan(ghxx))) || any(any(isnan(ghuu))) || any(any(isnan(ghxu))) || ...
any(any(isinf(ghx))) || any(any(isinf(ghu))) || any(any(isinf(ghxx))) || any(any(isinf(ghuu))) || any(any(isinf(ghxu))) ...
any(any(abs(ghx)>1e4)) || any(any(abs(ghu)>1e4)) || any(any(abs(ghxx)>1e4)) || any(any(abs(ghuu)>1e4)) || any(any(abs(ghxu)>1e4))
ghx
ghu
ghxx
ghuu
ghxu
end
constant = ReducedForm.constant;
state_variables_steady_state = ReducedForm.state_variables_steady_state;
% Set persistent variables.
if isempty(init_flag2)
mf0 = ReducedForm.mf0;
mf1 = ReducedForm.mf1;
number_of_state_variables = length(mf0);
number_of_observed_variables = length(mf1);
number_of_structural_innovations = length(ReducedForm.Q);
init_flag2 = 1;
end
if DynareOptions.particle.proposal_approximation.cubature || DynareOptions.particle.proposal_approximation.montecarlo
[nodes,weights] = spherical_radial_sigma_points(number_of_structural_innovations);
weights_c = weights ;
elseif DynareOptions.particle.proposal_approximation.unscented
[nodes,weights,weights_c] = unscented_sigma_points(number_of_structural_innovations,DynareOptions);
else
error('Estimation: This approximation for the proposal is not implemented or unknown!')
end
epsilon = Q_lower_triangular_cholesky*(nodes') ;
yhat = repmat(StateVectors-state_variables_steady_state,1,size(epsilon,2)) ;
tmp = local_state_space_iteration_2(yhat,epsilon,ghx,ghu,constant,ghxx,ghuu,ghxu,DynareOptions.threads.local_state_space_iteration_2);
PredictedStateMean = tmp(mf0,:)*weights ;
PredictedObservedMean = tmp(mf1,:)*weights;
if DynareOptions.particle.proposal_approximation.cubature || DynareOptions.particle.proposal_approximation.montecarlo
PredictedStateMean = sum(PredictedStateMean,2) ;
PredictedObservedMean = sum(PredictedObservedMean,2) ;
dState = bsxfun(@minus,tmp(mf0,:),PredictedStateMean)'.*sqrt(weights) ;
dObserved = bsxfun(@minus,tmp(mf1,:),PredictedObservedMean)'.*sqrt(weights);
big_mat = [dObserved dState; [H_lower_triangular_cholesky zeros(number_of_observed_variables,number_of_state_variables)] ];
[mat1,mat] = qr2(big_mat,0);
mat = mat';
clear('mat1');
PredictedObservedVarianceSquareRoot = mat(1:number_of_observed_variables,1:number_of_observed_variables);
CovarianceObservedStateSquareRoot = mat(number_of_observed_variables+(1:number_of_state_variables),1:number_of_observed_variables);
StateVectorVarianceSquareRoot = mat(number_of_observed_variables+(1:number_of_state_variables),number_of_observed_variables+(1:number_of_state_variables));
StateVectorMean = PredictedStateMean + (CovarianceObservedStateSquareRoot/PredictedObservedVarianceSquareRoot)*(obs - PredictedObservedMean);
else
dState = bsxfun(@minus,tmp(mf0,:),PredictedStateMean);
dObserved = bsxfun(@minus,tmp(mf1,:),PredictedObservedMean);
PredictedStateVariance = dState*diag(weights_c)*dState';
PredictedObservedVariance = dObserved*diag(weights_c)*dObserved' + H;
PredictedStateAndObservedCovariance = dState*diag(weights_c)*dObserved';
KalmanFilterGain = PredictedStateAndObservedCovariance/PredictedObservedVariance ;
StateVectorMean = PredictedStateMean + KalmanFilterGain*(obs - PredictedObservedMean);
StateVectorVariance = PredictedStateVariance - KalmanFilterGain*PredictedObservedVariance*KalmanFilterGain';
StateVectorVariance = .5*(StateVectorVariance+StateVectorVariance');
StateVectorVarianceSquareRoot = reduced_rank_cholesky(StateVectorVariance)';
end
ProposalStateVector = StateVectorVarianceSquareRoot*randn(size(StateVectorVarianceSquareRoot,2),1)+StateVectorMean ;
ypred = measurement_equations(ProposalStateVector,ReducedForm,DynareOptions) ;
foo = H_lower_triangular_cholesky \ (obs - ypred) ;
likelihood = exp(-0.5*(foo)'*foo)/normconst2 + 1e-99 ;
Weights = SampleWeights.*likelihood;

View File

@ -1,125 +0,0 @@
function [LIK,lik] = conditional_particle_filter(ReducedForm,Y,start,DynareOptions)
%
% Evaluates the likelihood of a non-linear model with a particle filter
% - the proposal is built using the Kalman updating step for each particle.
% - we need draws in the errors distributions
% Whether we use Monte-Carlo draws from a multivariate gaussian distribution
% as in Amisano & Tristani (JEDC 2010).
% Whether we use multidimensional Gaussian sparse grids approximations:
% - a univariate Kronrod-Paterson Gaussian quadrature combined by the Smolyak
% operator (ref: Winschel & Kratzig, 2010).
% - a spherical-radial cubature (ref: Arasaratnam & Haykin, 2009a,2009b).
% - a scaled unscented transform cubature (ref: Julier & Uhlmann 1997, van der
% Merwe & Wan 2003).
%
% Pros:
% - Allows using current observable information in the proposal
% - The use of sparse grids Gaussian approximation is much faster than the Monte-Carlo approach
% Cons:
% - The use of the Kalman updating step may biais the proposal distribution since
% it has been derived in a linear context and is implemented in a nonlinear
% context. That is why particle resampling is performed.
%
% INPUTS
% reduced_form_model [structure] Matlab's structure describing the reduced form model.
% reduced_form_model.measurement.H [double] (pp x pp) variance matrix of measurement errors.
% reduced_form_model.state.Q [double] (qq x qq) variance matrix of state errors.
% reduced_form_model.state.dr [structure] output of resol.m.
% Y [double] pp*smpl matrix of (detrended) data, where pp is the maximum number of observed variables.
% start [integer] scalar, likelihood evaluation starts at 'start'.
% smolyak_accuracy [integer] scalar.
%
% OUTPUTS
% LIK [double] scalar, likelihood
% lik [double] vector, density of observations in each period.
%
% REFERENCES
%
% NOTES
% The vector "lik" is used to evaluate the jacobian of the likelihood.
% Copyright (C) 2009-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 <http://www.gnu.org/licenses/>.
% AUTHOR(S) frederic DOT karame AT univ DASH lemans DOT fr
% stephane DOT adjemian AT univ DASH lemans DOT fr
persistent init_flag mf0 mf1
persistent number_of_particles
persistent sample_size number_of_state_variables number_of_observed_variables
% Set default
if isempty(start)
start = 1;
end
% Set persistent variables.
if isempty(init_flag)
mf0 = ReducedForm.mf0;
mf1 = ReducedForm.mf1;
sample_size = size(Y,2);
number_of_state_variables = length(mf0);
number_of_observed_variables = length(mf1);
init_flag = 1;
number_of_particles = DynareOptions.particle.number_of_particles ;
end
% Get covariance matrices
Q = ReducedForm.Q;
H = ReducedForm.H;
if isempty(H)
H = 0;
H_lower_triangular_cholesky = 0;
else
H_lower_triangular_cholesky = reduced_rank_cholesky(H)';
end
% Get initial condition for the state vector.
StateVectorMean = ReducedForm.StateVectorMean;
StateVectorVarianceSquareRoot = reduced_rank_cholesky(ReducedForm.StateVectorVariance)';
state_variance_rank = size(StateVectorVarianceSquareRoot,2);
Q_lower_triangular_cholesky = reduced_rank_cholesky(Q)';
% Set seed for randn().
set_dynare_seed('default');
% Initialization of the likelihood.
normconst2 = log(2*pi)*number_of_observed_variables*prod(diag(H_lower_triangular_cholesky)) ;
lik = NaN(sample_size,1);
LIK = NaN;
ks = 0 ;
StateParticles = bsxfun(@plus,StateVectorVarianceSquareRoot*randn(state_variance_rank,number_of_particles),StateVectorMean);
SampleWeights = ones(1,number_of_particles)/number_of_particles ;
for t=1:sample_size
for i=1:number_of_particles
[StateParticles(:,i),SampleWeights(i)] = ...
conditional_filter_proposal(ReducedForm,Y(:,t),StateParticles(:,i),SampleWeights(i),Q_lower_triangular_cholesky,H_lower_triangular_cholesky,H,DynareOptions,normconst2) ;
end
SumSampleWeights = sum(SampleWeights) ;
lik(t) = log(SumSampleWeights) ;
SampleWeights = SampleWeights./SumSampleWeights ;
if (DynareOptions.particle.resampling.status.generic && neff(SampleWeights)<DynareOptions.particle.resampling.threshold*sample_size) || DynareOptions.particle.resampling.status.systematic
ks = ks + 1 ;
StateParticles = resample(StateParticles',SampleWeights',DynareOptions)';
SampleWeights = ones(1,number_of_particles)/number_of_particles ;
end
end
LIK = -sum(lik(start:end));

View File

@ -1,52 +0,0 @@
function [StateMu,StateSqrtP,StateWeights] = fit_gaussian_mixture(X,StateMu,StateSqrtP,StateWeights,crit,niters,check)
% Copyright (C) 2013 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
[dim,Ndata] = size(X);
M = size(StateMu,2) ;
if check % Ensure that covariances don't collapse
MIN_COVAR_SQRT = sqrt(eps);
init_covars = StateSqrtP;
end
eold = -Inf;
for n=1:niters
% Calculate posteriors based on old parameters
[prior,likelihood,marginal,posterior] = probability(StateMu,StateSqrtP,StateWeights,X);
e = sum(log(marginal));
if (n > 1 && abs((e - eold)/eold) < crit)
return;
else
eold = e;
end
new_pr = (sum(posterior,2))';
StateWeights = new_pr/Ndata;
StateMu = bsxfun(@rdivide,(posterior*X')',new_pr);
for j=1:M
diffs = bsxfun(@minus,X,StateMu(:,j));
tpost = (1/sqrt(new_pr(j)))*sqrt(posterior(j,:));
diffs = bsxfun(@times,diffs,tpost);
[foo,tcov] = qr2(diffs',0);
StateSqrtP(:,:,j) = tcov';
if check
if min(abs(diag(StateSqrtP(:,:,j)))) < MIN_COVAR_SQRT
StateSqrtP(:,:,j) = init_covars(:,:,j);
end
end
end
end

View File

@ -1,52 +0,0 @@
function IncrementalWeights = gaussian_densities(obs,mut_t,sqr_Pss_t_t,st_t_1,sqr_Pss_t_t_1,particles,H,normconst,weigths1,weigths2,ReducedForm,DynareOptions)
%
% Elements to calculate the importance sampling ratio
%
% INPUTS
% reduced_form_model [structure] Matlab's structure describing the reduced form model.
% reduced_form_model.measurement.H [double] (pp x pp) variance matrix of measurement errors.
% reduced_form_model.state.Q [double] (qq x qq) variance matrix of state errors.
% reduced_form_model.state.dr [structure] output of resol.m.
% Y [double] pp*smpl matrix of (detrended) data, where pp is the maximum number of observed variables.
% start [integer] scalar, likelihood evaluation starts at 'start'.
% smolyak_accuracy [integer] scalar.
%
% OUTPUTS
% LIK [double] scalar, likelihood
% lik [double] vector, density of observations in each period.
%
% REFERENCES
%
% NOTES
% The vector "lik" is used to evaluate the jacobian of the likelihood.
% Copyright (C) 2009-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 <http://www.gnu.org/licenses/>.
% proposal density
proposal = probability2(mut_t,sqr_Pss_t_t,particles) ;
% prior density
prior = probability2(st_t_1,sqr_Pss_t_t_1,particles) ;
% likelihood
yt_t_1_i = measurement_equations(particles,ReducedForm,DynareOptions) ;
eta_t_i = bsxfun(@minus,obs,yt_t_1_i)' ;
yt_t_1 = sum(yt_t_1_i*weigths1,2) ;
tmp = bsxfun(@minus,yt_t_1_i,yt_t_1) ;
Pyy = bsxfun(@times,weigths2',tmp)*tmp' + H ;
sqr_det = sqrt(det(Pyy)) ;
foo = (eta_t_i/Pyy).*eta_t_i ;
likelihood = exp(-0.5*sum(foo,2))/(normconst*sqr_det) + 1e-99 ;
IncrementalWeights = likelihood.*prior./proposal ;

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