Compare commits

..

2 Commits

93 changed files with 1599 additions and 2215 deletions

402
NEWS.md
View File

@ -1,405 +1,3 @@
Announcement for Dynare 6.0 (on 2024-02-02)
===========================================
We are pleased to announce the release of Dynare 6.0.
This major release adds new features and fixes various bugs.
The Windows, macOS, MATLAB Online and source packages are already available for
download at [the Dynare website](https://www.dynare.org/download/).
This release is compatible with MATLAB versions ranging from 9.5 (R2018b) to
23.2 (R2023b), and with GNU Octave versions ranging from 7.1.0 to 8.4.0 (NB:
the Windows package requires version 8.4.0 specifically).
Major user-visible changes
--------------------------
- The Sequential Monte Carlo sampler as described by Herbst and Schorfheide
(2014) is now available under value `hssmc` for option
`posterior_sampling_method`.
- New routines for perfect foresight simulation with expectation errors. In
such a scenario, agents make expectation errors in that the path they had
anticipated in period 1 is not realized exactly. More precisely, in some
simulation periods, they may receive new information that makes them revise
their anticipation for the path of future shocks. Also, under this scenario,
it is assumed that agents behave as under perfect foresight, *i.e.* they
make their decisions as if there were no uncertainty and they knew exactly
the path of future shocks; the new information that they may receive comes
as a total surprise to them. Available under new
`perfect_foresight_with_expectation_errors_setup` and
`perfect_foresight_with_expectation_errors_solver` commands, and
`shocks(learnt_in=…)`, `mshocks(learnt_in=…)` and `endval(learnt_in=…)`
blocks.
- New routines for IRF matching with stochastic simulations:
- Both frequentist (as in Christiano, Eichenbaum, and Evans, 2005) and
Bayesian (as in Christiano, Trabandt, and Walentin, 2010) IRF matching
approaches are implemented. The core idea of IRF matching is to treat
empirical impulse responses (*e.g.* given from an SVAR or local projection
estimation) as data and select model parameters that align the models
IRFs closely with their empirical counterparts.
- Available under option `mom_method = irf_matching` option to the
`method_of_moments` command.
- New blocks `matched_irfs` and `matched_irfs_weights` for specifying the
values and weights of the empirical impulse response functions.
- Pruning à la Andreasen et al. (2018) is now available at an arbitrary
approximation order when performing stochastic simulations with
`stoch_simul`, and at 3rd order when performing particle filtering.
- New `log` option to the `var` statement. In addition to the endogenous
variable(s) thus declared, this option also triggers the creation of
auxiliary variable(s) equal to the log of the corresponding endogenous
variable(s). For example, given a `var(log) y;` statement, two endogenous
will be created (`y` and `LOG_y`), and an auxiliary equation linking the two
will also be added (equal to `y = exp(LOG_y);`). Moreover, every occurrence
of `y` in the model will be replaced by `exp(LOG_y)`. This option is, for
example, useful for performing a loglinear approximation of some variable(s)
in the context of a first-order stochastic approximation; or for ensuring
that the variable(s) stay(s) in the definition domain of the function
defining the steady state or the dynamic residuals when the nonlinear solver
is used.
- New model editing features
- Multiple `model` blocks are now supported (this was already working but
not explicitly documented).
- Multiple `estimated_params` blocks now concatenate their contents (instead
of overwriting previous ones, which was the former undocumented behavior);
an `overwrite` option has been added to provide the old behavior.
- New `model_options` statement to set model options in a global fashion.
- New `model_remove` command to remove equations.
- New `model_replace` block to replace equations.
- New `var_remove` command to remove variables (or parameters).
- New `estimated_params_remove` block to remove estimated parameters.
- Stochastic simulations
- Performance improvements for simulation of the solution under perturbation
and for particle filtering at higher order (⩾ 3).
- Performance improvement for the first order perturbation solution using
either cycle reduction (`dr=cycle_reduction` option) or logarithmic
reduction (`dr=logarithmic_reduction`).
- New `nomodelsummary` option to the `stoch_simul` command, to suppress the
printing of the model summary and the covariance of the exogenous shocks.
- Estimation
- A truncated normal distribution can now be specified as a prior, using the
3rd and 4th parameters of the `estimated_params` block as the bounds.
- New `conditional_likelihood` option to the `estimation` command. When the
option is set, instead of using the Kalman filter to evaluate the
likelihood, Dynare will evaluate the conditional likelihood based on the
first-order reduced form of the model by assuming that the initial state
vector is at its steady state.
- New `additional_optimizer_steps` option to the `estimation` command to
trigger the sequential execution of several optimizers when looking for
the posterior mode.
- The `generate_trace_plots` command now allows comparing multiple chains.
- The Geweke and Raftery-Lewis convergence diagnostics will now also be
displayed when `mh_nblocks>1`.
- New `robust`, `TolGstep`, and `TolGstepRel` options to the optimizer
available under `mode_compute=5` (“newrat”).
- New `brooks_gelman_plotrows` option to the `estimation` command for
controlling the number of parameters to depict along the rows of the
figures depicting the Brooks and Gelman (1998) convergence diagnostics.
- New `mh_init_scale_factor` option to the `estimation` command tor govern
the overdispersion of the starting draws when initializing several Monte
Carlo Markov Chains. This option supersedes the `mh_init_scale` option,
which is now deprecated.
- Steady state computation
- Steady state computation now accounts for occasionally-binding constraints
of mixed-complementarity problems (as defined by `mcp` tags).
- New `tolx` option to the `steady` command for governing the termination
based on the step tolerance.
- New `fsolve_options` option to the `steady` command for passing options to
`fsolve` (in conjunction with the `solve_algo=0` option).
- New option `from_initval_to_endval` option to the `homotopy_setup` block,
for easily computing homotopy from initial to terminal steady state (when
the former is already computed).
- New `non_zero` option to `resid` command to restrict display to non-zero
residuals.
- Perfect foresight
- Significant performance improvement of the `stack_solve_algo=1` option to
the `perfect_foresight_solver` command (Laffargue-Boucekkine-Juillard
algorithm) when used in conjunction with options `block` and/or `bytecode`
of the `model` block.
- New `relative_to_initval` option to the `mshocks` block, to use the
initial steady state as a basis for the multiplication when there is an
`endval` block.
- New `static_mfs` option to the `model` block (and to the `model_options`
command), for controlling the minimum feedback set computation for the
static model. It defaults to `0` (corresponding to the behavior in Dynare
version 5).
- Various improvements to homotopy
- New `endval_steady` option to the `perfect_foresight_setup` command for
computing the terminal steady state at the same time as the transitory
dynamics (and new options `steady_solve_algo`, `steady_tolf`,
`steady_tolx`, `steady_maxit` and `steady_markowitz` for controlling the
steady state nonlinear solver).
- New `homotopy_linearization_fallback` and
`homotopy_marginal_linearization_fallback` options to the
`perfect_foresight_solver` command to get an approximate solution when
homotopy fails to go to 100%.
- New `homotopy_initial_step_size`, `homotopy_min_step_size`,
`homotopy_step_size_increase_success_count` and
`homotopy_max_completion_share` options to the
`perfect_foresight_solver` command to fine tune the homotopy behavior.
- Purely backward, forward and static models are now supported by the
homotopy procedure.
- The `stack_solve_algo=1` and `stack_solve_algo=6` options of the
`perfect_foresight_solver` command were merged and are now synonymous.
They both provide the Laffargue-Boucekkine-Juillard algorithm and work
with and without the `block` and `bytecode` options of the `model` block.
Using `stack_solve_algo=1` is now recommended, but `stack_solve_algo=6` is
kept for backward compatibility.
- OccBin
- New `simul_reset_check_ahead_periods` option to the `occbin_setup` and
`occbin_solver` commands, for resetting `check_ahead_periods` in each
simulation period.
- new `simul_max_check_ahead_periods`, `likelihood_max_check_ahead_periods`,
and `smoother_max_check_ahead_periods` options to the `occbin_setup`
command, for truncating the number of periods for which agents check ahead
which regime is present.
- Optimal policy
- The `osr` command now accepts the `analytic_derivation` and
`analytic_derivation_mode` options.
- The `evaluate_planner_objective` command now computes the unconditional
welfare for higher-order approximations (⩾ 3).
- New `periods` and `drop` options to the `evaluate_planner_objective`
command.
- Semi-structural models
- New `pac_target_info` block for decomposing the PAC target into an
arbitrary number of components. Furthermore, in the presence of such a
block, the new `pac_target_nonstationary` operator can be used to select
the non stationary part of the target (typically useful in the error
correction term of the PAC equation).
- New `kind` option to the `pac_model` command. This option allows the user
to select the formula used to compute the weights on the VAR companion
matrix variables that are used to form PAC expectations.
- Performance improvement to `solve_algo=12` and `solve_algo=14`, which
significantly accelerates the simulation of purely backward, forward and
static models with the `perfect_foresight_solver` command and the routines
for semi-structural models.
- dseries classes
- The `remove` and `remove_` methods now accept a list of variables (they
would previously only accept a single variable).
- New MATLAB/Octave command `dplot` to plot mathematical expressions
generated from variables fetched from (different) dseries objects.
- Misc
- New `display_parameter_values` command to print the parameter values in
the command window.
- New `collapse_figures_in_tabgroup` command to dock all figures.
- Performance improvement for the `use_dll` option of the `model` block. The
preprocessor now takes advantage of parallelization when compiling the MEX
files.
- New mathematical primitives available: complementary error function
(`erfc`), hyperbolic functions (`cosh`, `sinh`, `tanh`, `acosh`, `asinh`,
`atanh`).
- New `last_simulation_period` option to the `initval_file` command.
- The `calib_smoother` command now accepts the `nobs` and
`heteroskedastic_filter` options.
- Under the MATLAB Desktop, autocompletion is now available for the `dynare`
command and other CLI commands (thanks to Eduard Benet Cerda from
MathWorks).
- Model debugging: The preprocessor now creates files for evaluating the
left- and right-hand sides of model equations separately. For a model file
called `ramst.mod`, you can call
`[lhs,rhs]=ramst.debug.static_resid(y,x,params);` (for the static model)
and `[lhs,rhs]=ramst.debug.dynamic_resid(y,x,params,steady_state);` (for
the dynamic model), where `y` are the endogenous, `x` the exogenous,
`params` the parameters, and `steady_state` is self-explanatory. NB: In
the dynamic case, the vector `y` of endogenous must have 3n elements
where n is the number of endogenous (including auxiliary ones); the
first n elements correspond to the lagged values, the middle n
elements to the contemporaneous values, and the last n elements to the
lead values.
- New interactive MATLAB/Octave command `search` for listing the equations
in which given variable(s) appear (requires `json` command line option).
- The `model_info` command allows to print the block decomposition even if
the `block` option of the `model` block has not been used, by specifying
the new options `block_static` and `block_dynamic`.
- There is now a default value for the global initialization file
(`GlobalInitFile` option of the configuration file): the `global_init.m`
in the Dynare configuration directory (typically
`$HOME/.config/dynare/global_init.m` under Linux and macOS, and
`c:\Users\USERNAME\AppData\Roaming\dynare\global_init.m` under Windows).
- For those compiling Dynare from source, the build system has been entirely
rewritten and now uses Meson; as a consequence, it is now faster and
easier to understand.
- References:
- Andreasen, Martin M., Jesús Fernández-Villaverde, and Juan Rubio-Ramírez
(2018): “The Pruned State-Space System for Non-Linear DSGE Models: Theory
and Empirical Applications,” *Review of Economic Studies*, 85(1), 1-49.
- Brooks, Stephen P., and Andrew Gelman (1998): “General methods for
monitoring convergence of iterative simulations,” *Journal of Computational
and Graphical Statistics*, 7, pp. 434455.
- Christiano, Eichenbaum and Charles L. Evans (2005): “Nominal Rigidities and
the Dynamic Effects of a Shock to Monetary Policy,” *Journal of Political
Economy*, 113(1), 145.
- Christiano, Lawrence J., Mathias Trabandt, and Karl Walentin (2010): “DSGE
Models for Monetary Policy Analysis,” In: *Handbook of Monetary Economics
3*, 285367.
- Herbst, Edward and Schorfheide, Frank (2014): "Sequential Monte Carlo
Sampling for DSGE Models," *Journal of Applied Econometrics*, 29,
1073-1098.
Incompatible changes
--------------------
- The default value of the `mode_compute` option of the `estimation` command
has been changed to `5` (it was previously `4`).
- When using block decomposition (with the `block` option of the `model`
block), the option `mfs` now defaults to `1`. This setting should deliver
better performance in perfect foresight simulation on most models.
- The default location for the configuration file has changed. On Linux and
macOS, the configuration file is now searched by default under
`dynare/dynare.ini` in the configuration directories defined by the XDG
specification (typically `$HOME/.config/dynare/dynare.ini` for the
user-specific configuration and `/etc/xdg/dynare/dynare.ini` for the
system-wide configuration, the former having precedence over the latter).
Under Windows, the configuration file is now searched by default in
`%APPDATA%\dynare\dynare.ini` (typically
`c:\Users\USERNAME\AppData\Roaming\dynare\dynare.ini`).
- The information stored in `oo_.endo_simul, oo_.exo_simul`, and `oo_.irfs` is
no longer duplicated in the base workspace. New helper functions
`send_endogenous_variables_to_workspace`,
`send_exogenous_variables_to_workspace`, and `send_irfs_to_workspace` have
been introduced to explicitly request these outputs and to mimic the old
behavior.
- The `dynare_sensitivity` command has been renamed `sensitivity`. The old
name is still accepted but triggers a warning.
- The syntax `resid(1)` is no longer supported.
- The `mode_compute=6` option to the `estimation` command now recursively
updates the covariance matrix across the `NumberOfMh` Metropolis-Hastings
runs, starting with the `InitialCovarianceMatrix` in the first run, instead
of computing it from scratch in every Metropolis-Hastings run.
- The `periods` command has been removed.
- The `Sigma_e` command has been removed.
- The `block` option of the `model` block no longer has an effect when used in
conjunction with `stoch_simul` or `estimation` commands.
- The Dynare++ executable is no longer distributed since almost all of its
functionalities have been integrated inside Dynare for MATLAB/Octave.
- A macro-processor variable defined without a value (such as `@#define var`
in the `.mod` file or alternatively `-Dvar` on the `dynare` command line) is
now assigned the `true` logical value (it was previously assigned `1`).
- The `parallel_slave_open_mode` option of the `dynare` command has been
renamed `parallel_follower_open_mode`.
- The `static` option of the `model_info` command is now deprecated and is
replaced by the `block_static` option.
Bugs that were present in 5.5 and that have been fixed in 6.0
-------------------------------------------------------------
* The `mh_initialize_from_previous_mcmc` option of the `estimation` command
would not work if estimation was conducted with a different prior and the
last draw in the previous MCMC fell outside the new prior bounds
* When specifying a generalized inverse Gamma prior, the hyperparameter
computation would erroneously ignore the resulting mean shift
* When using the `mh_recover` option of the `estimation` command, the status
bar always started at zero instead of showing the overall progress of the
recovered chain
* The `model_diagnostics` command would fail to check the correctness of
user-defined steady state files
* GSA: LaTeX output was not working as expected
* Forecasts and filtered variables could not be retrieved with the
`heteroskedastic_shocks` block
* The OccBin smoother would potentially not display all smoothed shocks with
`heteroskedastic_filter` option
* The OccBin smoother would crash if the number of requested periods was
smaller than the data length
* The multivariate OccBin smoother would return wrong results if the constraint
was binding in the first period
* The `plot_shock_decomposition` command would fail with the `init2shocks`
block if the `initial_condition_decomposition` was not run before
* LaTeX output under Windows failed to compile for `plot_priors=1` option of
the `estimation` command and Brooks and Gelman (1998) convergence diagnostics
* The plot produced by the `shock_decomposition` command was too big, making
the close button inaccessible
* Monthly dates for October, November and December (*i.e.* with a 2-digit month
number) were not properly interpreted by the preprocessor
* Theoretical moments computed by `stoch_simul` at `order=2` with `pruning`
would not contain unconditional and conditional variance decomposition
Announcement for Dynare 5.5 (on 2023-10-23)
===========================================

View File

@ -149,10 +149,9 @@ Note that running the testsuite with Octave requires the additional packages `ps
Often, it does not make sense to run the complete testsuite. For instance, if you modify codes only related to the perfect foresight model solver, you can decide to run only a subset of the integration tests, with:
```sh
meson test -C <builddir> --suite deterministic_simulations
meson test -C <builddir> deterministic_simulations
```
This will run all the integration tests in `tests/deterministic_simulations`.
This syntax also works with a nested directory (e.g. `--suite deterministic_simulations/purely_forward`).
Finally if you want to run a single integration test, e.g. `deterministic_simulations/lbj/rbc.mod`:
```sh

View File

@ -22,7 +22,7 @@
\begin{document}
% ----------------------------------------------------------------
\title{Sensitivity Analysis Toolbox for Dynare\thanks{Copyright \copyright~2012-2024 Dynare
\title{Sensitivity Analysis Toolbox for DYNARE\thanks{Copyright \copyright~2012 Dynare
Team. Permission is granted to copy, distribute and/or modify
this document under the terms of the GNU Free Documentation
License, Version 1.3 or any later version published by the Free
@ -32,9 +32,9 @@
\author{Marco Ratto\\
European Commission, Joint Research Centre \\
TP581\\21027 Ispra
TP361, IPSC, \\21027 Ispra
(VA) Italy\\
\texttt{Marco.Ratto@ec.europa.eu}
\texttt{marco.ratto@jrc.ec.europa.eu}
\thanks{The author gratefully thanks Christophe Planas, Kenneth Judd, Michel Juillard,
Alessandro Rossi, Frank Schorfheide and the participants to the
Courses on Global Sensitivity Analysis for Macroeconomic
@ -52,21 +52,21 @@ helpful suggestions.}}
%-----------------------------------------------------------------------
\begin{abstract}
\noindent The Sensitivity Analysis Toolbox for Dynare is a set of
\noindent The Sensitivity Analysis Toolbox for DYNARE is a set of
MATLAB routines for the analysis of DSGE models with global
sensitivity analysis. The routines are thought to be used within
the Dynare 6 environment.
the DYNARE v4 environment.
\begin{description}
\item \textbf{Keywords}: Stability Mapping , Reduced form solution, DSGE models,
Monte Carlo filtering, Global Sensitivity Analysis.
Monte Carlo filtering, Global Sensitivity Analysis.
\end{description}
\end{abstract}
\newpage
% ----------------------------------------------------------------
\section{Introduction} \label{s:intro}
The Sensitivity Analysis Toolbox for Dynare is a collection of
The Sensitivity Analysis Toolbox for DYNARE is a collection of
MATLAB routines implemented to answer the following questions: (i)
Which is the domain of structural coefficients assuring the
stability and determinacy of a DSGE model? (ii) Which parameters
@ -81,18 +81,20 @@ described in \cite{Ratto_CompEcon_2008}.
\section{Use of the Toolbox}
The Dynare parser now recognizes sensitivity analysis commands.
The DYNARE parser now recognizes sensitivity analysis commands.
The syntax is based on a single command:
\vspace{0.5cm}
\verb"sensitivity(option1=<opt1_val>,option2=<opt2_val>,...)"
\verb"dynare_sensitivity(option1=<opt1_val>,option2=<opt2_val>,...)"
\vspace{0.5cm} \noindent with a list of options described in the
next section.
In order to work properly, the sensitivity analysis Toolbox does not need
a Dynare estimation environment to be set up. Rather, \verb"sensitivity"
is the only command to run to
With respect to the previous version of the toolbox, in order to
work properly, the sensitivity analysis Toolbox \emph{no longer}
needs that the DYNARE estimation environment is set-up.
Therefore, \verb"dynare_sensitivity" is the only command to run to
make a sensitivity analysis on a DSGE model\footnote{Of course,
when the user needs to perform the mapping of the fit with a
posterior sample, a Bayesian estimation has to be performed
@ -206,17 +208,16 @@ a multivariate normal MC sample, with covariance matrix based on
the inverse Hessian at the optimum: this analysis is useful when
ML estimation is done (i.e. no Bayesian estimation);
\item when \verb"ppost=1" the Toolbox analyses
the RMSE's for the posterior sample obtained by Dynare's
the RMSE's for the posterior sample obtained by DYNARE's
Metropolis procedure.
\end{enumerate}
The use of cases 2. and 3. require an estimation step beforehand!
The use of cases 2. and 3. requires an estimation step beforehand!
To facilitate the sensitivity analysis after estimation, the
\verb"sensitivity" command also allows to indicate some
options of \verb"estimation". These are:
\verb"dynare_sensitivity" command also allows to indicate some
options of \verb"dynare_estimation". These are:
\begin{itemize}
\item \verb"datafile"
\item \verb"diffuse_filter"
\item \verb"mode_file"
\item \verb"first_obs"
\item \verb"lik_init"
@ -277,10 +278,10 @@ identifiable.
\end{tabular}
\vspace{1cm}
\noindent For example, the following commands in the Dynare model file
\noindent For example, the following commands in the DYNARE model file
\vspace{1cm}
\noindent\verb"sensitivity(identification=1, morris=2);"
\noindent\verb"dynare_sensitivity(identification=1, morris=2);"
\vspace{1cm}
\noindent trigger the identification analysis using \cite{Iskrev2010,Iskrev2011}, jointly with the mapping of the acceptable region.
@ -292,75 +293,75 @@ Sensitivity analysis results are saved on the hard-disk of the
computer. The Toolbox uses a dedicated folder called \verb"GSA",
located in \\
\\
\verb"<Dynare_file>\GSA", \\
\verb"<DYNARE_file>\GSA", \\
\\
where \verb"<Dynare_file>.mod" is the name of the Dynare model
where \verb"<DYNARE_file>.mod" is the name of the DYNARE model
file.
\subsection{Binary data files}
A set of binary data files is saved in the \verb"GSA" folder:
\begin{description}
\item[]\verb"<Dynare_file>_prior.mat": this file stores
\item[]\verb"<DYNARE_file>_prior.mat": this file stores
information about the analyses performed sampling from the prior
ranges, i.e. \verb"pprior=1" and \verb"ppost=0";
\item[]\verb"<Dynare_file>_mc.mat": this file stores
\item[]\verb"<DYNARE_file>_mc.mat": this file stores
information about the analyses performed sampling from
multivariate normal, i.e. \verb"pprior=0" and \verb"ppost=0";
\item[]\verb"<Dynare_file>_post.mat": this file stores information
\item[]\verb"<DYNARE_file>_post.mat": this file stores information
about analyses performed using the Metropolis posterior sample,
i.e. \verb"ppost=1".
\end{description}
\begin{description}
\item[]\verb"<Dynare_file>_prior_*.mat": these files store
\item[]\verb"<DYNARE_file>_prior_*.mat": these files store
the filtered and smoothed variables for the prior MC sample,
generated when doing RMSE analysis (\verb"pprior=1" and
\verb"ppost=0");
\item[]\verb"<Dynare_file>_mc_*.mat": these files store
\item[]\verb"<DYNARE_file>_mc_*.mat": these files store
the filtered and smoothed variables for the multivariate normal MC
sample, generated when doing RMSE analysis (\verb"pprior=0" and
\verb"ppost=0").
\end{description}
\subsection{Stability analysis}
Figure files \verb"<Dynare_file>_prior_*.fig" store results for
Figure files \verb"<DYNARE_file>_prior_*.fig" store results for
the stability mapping from prior MC samples:
\begin{description}
\item[]\verb"<Dynare_file>_prior_stab_SA_*.fig": plots of the Smirnov
test analyses confronting the CDF of the sample fulfilling
Blanchard-Kahn conditions with the CDF of the rest of the sample;
\item[]\verb"<Dynare_file>_prior_stab_indet_SA_*.fig": plots of the Smirnov
test analyses confronting the CDF of the sample producing
indeterminacy with the CDF of the original prior sample;
\item[]\verb"<Dynare_file>_prior_stab_unst_SA_*.fig": plots of the Smirnov
test analyses confronting the CDF of the sample producing unstable
(explosive roots) behaviour with the CDF of the original prior
\item[]\verb"<DYNARE_file>_prior_stab_SA_*.fig": plots of the Smirnov
test analyses confronting the cdf of the sample fulfilling
Blanchard-Kahn conditions with the cdf of the rest of the sample;
\item[]\verb"<DYNARE_file>_prior_stab_indet_SA_*.fig": plots of the Smirnov
test analyses confronting the cdf of the sample producing
indeterminacy with the cdf of the original prior sample;
\item[]\verb"<DYNARE_file>_prior_stab_unst_SA_*.fig": plots of the Smirnov
test analyses confronting the cdf of the sample producing unstable
(explosive roots) behaviour with the cdf of the original prior
sample;
\item[]\verb"<Dynare_file>_prior_stable_corr_*.fig": plots of
\item[]\verb"<DYNARE_file>_prior_stable_corr_*.fig": plots of
bivariate projections of the sample fulfilling Blanchard-Kahn
conditions;
\item[]\verb"<Dynare_file>_prior_indeterm_corr_*.fig": plots of
\item[]\verb"<DYNARE_file>_prior_indeterm_corr_*.fig": plots of
bivariate projections of the sample producing indeterminacy;
\item[]\verb"<Dynare_file>_prior_unstable_corr_*.fig": plots of
\item[]\verb"<DYNARE_file>_prior_unstable_corr_*.fig": plots of
bivariate projections of the sample producing instability;
\item[]\verb"<Dynare_file>_prior_unacceptable_corr_*.fig": plots of
\item[]\verb"<DYNARE_file>_prior_unacceptable_corr_*.fig": plots of
bivariate projections of the sample producing unacceptable
solutions, i.e. either instability or indeterminacy or the
solution could not be found (e.g. the steady state solution could
not be found by the solver).
\end{description}
Similar conventions apply for \verb"<Dynare_file>_mc_*.fig" files,
Similar conventions apply for \verb"<DYNARE_file>_mc_*.fig" files,
obtained when samples from multivariate normal are used.
\subsection{RMSE analysis}
Figure files \verb"<Dynare_file>_rmse_*.fig" store results for the
Figure files \verb"<DYNARE_file>_rmse_*.fig" store results for the
RMSE analysis.
\begin{description}
\item[]\verb"<Dynare_file>_rmse_prior*.fig": save results for
\item[]\verb"<DYNARE_file>_rmse_prior*.fig": save results for
the analysis using prior MC samples;
\item[]\verb"<Dynare_file>_rmse_mc*.fig": save results for
\item[]\verb"<DYNARE_file>_rmse_mc*.fig": save results for
the analysis using multivariate normal MC samples;
\item[]\verb"<Dynare_file>_rmse_post*.fig": save results for
\item[]\verb"<DYNARE_file>_rmse_post*.fig": save results for
the analysis using Metropolis posterior samples.
\end{description}
@ -368,33 +369,33 @@ The following types of figures are saved (we show prior sample to
fix ideas, but the same conventions are used for multivariate
normal and posterior):
\begin{description}
\item[]\verb"<Dynare_file>_rmse_prior_*.fig": for each parameter, plots the CDF's
\item[]\verb"<DYNARE_file>_rmse_prior_*.fig": for each parameter, plots the cdf's
corresponding to the best 10\% RMES's of each observed series;
\item[]\verb"<Dynare_file>_rmse_prior_dens_*.fig": for each parameter, plots the pdf's
\item[]\verb"<DYNARE_file>_rmse_prior_dens_*.fig": for each parameter, plots the pdf's
corresponding to the best 10\% RMES's of each observed series;
\item[]\verb"<Dynare_file>_rmse_prior_<name of observedseries>_corr_*.fig": for each observed series plots the
\item[]\verb"<DYNARE_file>_rmse_prior_<name of observedseries>_corr_*.fig": for each observed series plots the
bi-dimensional projections of samples with the best 10\% RMSE's,
when the correlation is significant;
\item[]\verb"<Dynare_file>_rmse_prior_lnlik*.fig": for each observed
series, plots \emph{in red} the CDF of the log-likelihood
corresponding to the best 10\% RMSE's, \emph{in green} the CDF of
the rest of the sample and \emph{in blue }the CDF of the full
\item[]\verb"<DYNARE_file>_rmse_prior_lnlik*.fig": for each observed
series, plots \emph{in red} the cdf of the log-likelihood
corresponding to the best 10\% RMSE's, \emph{in green} the cdf of
the rest of the sample and \emph{in blue }the cdf of the full
sample; this allows to see the presence of some idiosyncratic
behaviour;
\item[]\verb"<Dynare_file>_rmse_prior_lnpost*.fig": for each observed
series, plots \emph{in red} the CDF of the log-posterior
corresponding to the best 10\% RMSE's, \emph{in green} the CDF of
the rest of the sample and \emph{in blue }the CDF of the full
\item[]\verb"<DYNARE_file>_rmse_prior_lnpost*.fig": for each observed
series, plots \emph{in red} the cdf of the log-posterior
corresponding to the best 10\% RMSE's, \emph{in green} the cdf of
the rest of the sample and \emph{in blue }the cdf of the full
sample; this allows to see idiosyncratic behaviour;
\item[]\verb"<Dynare_file>_rmse_prior_lnprior*.fig": for each observed
series, plots \emph{in red} the CDF of the log-prior corresponding
to the best 10\% RMSE's, \emph{in green} the CDF of the rest of
the sample and \emph{in blue }the CDF of the full sample; this
\item[]\verb"<DYNARE_file>_rmse_prior_lnprior*.fig": for each observed
series, plots \emph{in red} the cdf of the log-prior corresponding
to the best 10\% RMSE's, \emph{in green} the cdf of the rest of
the sample and \emph{in blue }the cdf of the full sample; this
allows to see idiosyncratic behaviour;
\item[]\verb"<Dynare_file>_rmse_prior_lik_SA_*.fig": when
\item[]\verb"<DYNARE_file>_rmse_prior_lik_SA_*.fig": when
\verb"lik_only=1", this shows the Smirnov tests for the filtering
of the best 10\% log-likelihood values;
\item[]\verb"<Dynare_file>_rmse_prior_post_SA_*.fig": when
\item[]\verb"<DYNARE_file>_rmse_prior_post_SA_*.fig": when
\verb"lik_only=1", this shows the Smirnov test for the filtering
of the best 10\% log-posterior values.
\end{description}
@ -404,19 +405,19 @@ In the case of the mapping of the reduced form solution, synthetic
figures are saved in the \verb"\GSA" folder:
\begin{description}
\item[]\verb"<Dynare_file>_redform_<endo name>_vs_lags_*.fig":
\item[]\verb"<DYNARE_file>_redform_<endo name>_vs_lags_*.fig":
shows bar charts of the sensitivity indices for the \emph{ten most
important} parameters driving the reduced form coefficients of the
selected endogenous variables (\verb"namendo") versus lagged
endogenous variables (\verb"namlagendo"); suffix \verb"log"
indicates the results for log-transformed entries;
\item[]\verb"<Dynare_file>_redform_<endo name>_vs_shocks_*.fig":
\item[]\verb"<DYNARE_file>_redform_<endo name>_vs_shocks_*.fig":
shows bar charts of the sensitivity indices for the \emph{ten most
important} parameters driving the reduced form coefficients of the
selected endogenous variables (\verb"namendo") versus exogenous
variables (\verb"namexo"); suffix \verb"log" indicates the results
for log-transformed entries;
\item[]\verb"<Dynare_file>_redform_GSA(_log).fig": shows bar chart of
\item[]\verb"<DYNARE_file>_redform_GSA(_log).fig": shows bar chart of
all sensitivity indices for each parameter: this allows to notice
parameters that have a minor effect for \emph{any} of the reduced
form coefficients,
@ -448,24 +449,24 @@ without the need of any user's intervention.
\subsection{Screening analysis}
The results of the screening analysis with Morris sampling design
are stored in the subfolder \verb"\GSA\SCREEN". The data file
\verb"<Dynare_file>_prior" stores all the information of the
\verb"<DYNARE_file>_prior" stores all the information of the
analysis (Morris sample, reduced form coefficients, etc.).
Screening analysis merely concerns reduced form coefficients.
Similar synthetic bar charts as for the reduced form analysis with
MC samples are saved:
\begin{description}
\item[]\verb"<Dynare_file>_redform_<endo name>_vs_lags_*.fig":
\item[]\verb"<DYNARE_file>_redform_<endo name>_vs_lags_*.fig":
shows bar charts of the elementary effect tests for the \emph{ten
most important} parameters driving the reduced form coefficients
of the selected endogenous variables (\verb"namendo") versus
lagged endogenous variables (\verb"namlagendo");
\item[]\verb"<Dynare_file>_redform_<endo name>_vs_shocks_*.fig":
\item[]\verb"<DYNARE_file>_redform_<endo name>_vs_shocks_*.fig":
shows bar charts of the elementary effect tests for the \emph{ten
most important} parameters driving the reduced form coefficients
of the selected endogenous variables (\verb"namendo") versus
exogenous variables (\verb"namexo");
\item[]\verb"<Dynare_file>_redform_screen.fig": shows bar chart of
\item[]\verb"<DYNARE_file>_redform_screen.fig": shows bar chart of
all elementary effect tests for each parameter: this allows to
identify parameters that have a minor effect for \emph{any} of the
reduced form coefficients.

View File

@ -16,8 +16,8 @@ Bibliography
* Bini, Dario A., Guy Latouche, and Beatrice Meini (2002): “Solving matrix polynomial equations arising in queueing problems,” *Linear Algebra and its Applications*, 340, 225244.
* Born, Benjamin and Johannes Pfeifer (2014): “Policy risk and the business cycle”, *Journal of Monetary Economics*, 68, 68-85.
* Boucekkine, Raouf (1995): “An alternative methodology for solving nonlinear forward-looking models,” *Journal of Economic Dynamics and Control*, 19, 711734.
* Brayton, Flint and Peter Tinsley (1996): A Guide to FRB/US: A Macroeconomic Model of the United States, *Finance and Economics Discussion Series*, 1996-42.
* Brayton, Flint, Morris Davis and Peter Tulip (2000): “Polynomial Adjustment Costs in FRB/US,” *Unpublished manuscript*.
* Brayton, Flint and Peter Tinsley (1996): "A Guide to FRB/US: A Macroeconomic Model of the United States", *Finance and Economics Discussion Series*, 1996-42.
* Brayton, Flint, Morris Davis and Peter Tulip (2000): "Polynomial Adjustment Costs in FRB/US", *Unpublished manuscript*.
* Brooks, Stephen P., and Andrew Gelman (1998): “General methods for monitoring convergence of iterative simulations,” *Journal of Computational and Graphical Statistics*, 7, pp. 434455.
* Cardoso, Margarida F., R. L. Salcedo and S. Feyo de Azevedo (1996): “The simplex simulated annealing approach to continuous non-linear optimization,” *Computers & Chemical Engineering*, 20(9), 1065-1080.
* Chib, Siddhartha and Srikanth Ramamurthy (2010): “Tailored randomized block MCMC methods with application to DSGE models,” *Journal of Econometrics*, 155, 1938.
@ -29,7 +29,7 @@ Bibliography
* Collard, Fabrice and Michel Juillard (2001a): “Accuracy of stochastic perturbation methods: The case of asset pricing models,” *Journal of Economic Dynamics and Control*, 25, 979999.
* Collard, Fabrice and Michel Juillard (2001b): “A Higher-Order Taylor Expansion Approach to Simulation of Stochastic Forward-Looking Models with an Application to a Non-Linear Phillips Curve,” *Computational Economics*, 17, 125139.
* Corana, Angelo, M. Marchesi, Claudio Martini, and Sandro Ridella (1987): “Minimizing multimodal functions of continuous variables with the “simulated annealing” algorithm”, *ACM Transactions on Mathematical Software*, 13(3), 262280.
* Cuba-Borda, Pablo, Luca Guerrieri, Matteo Iacoviello, and Molin Zhong (2019): Likelihood evaluation of models with occasionally binding constraints, Journal of Applied Econometrics, 34(7), 1073-1085
* Cuba-Borda, Pablo, Luca Guerrieri, Matteo Iacoviello, and Molin Zhong (2019): "Likelihood evaluation of models with occasionally binding constraints", Journal of Applied Econometrics, 34(7), 1073-1085
* Del Negro, Marco and Frank Schorfheide (2004): “Priors from General Equilibrium Models for VARs”, *International Economic Review*, 45(2), 643673.
* Dennis, Richard (2007): “Optimal Policy In Rational Expectations Models: New Solution Algorithms”, *Macroeconomic Dynamics*, 11(1), 3155.
* Duffie, Darrel and Kenneth J. Singleton (1993): “Simulated Moments Estimation of Markov Models of Asset Prices”, *Econometrica*, 61(4), 929-952.
@ -49,7 +49,7 @@ Bibliography
* Hansen, Lars P. (1982): “Large sample properties of generalized method of moments estimators,” Econometrica, 50(4), 10291054.
* Hansen, Nikolaus and Stefan Kern (2004): “Evaluating the CMA Evolution Strategy on Multimodal Test Functions”. In: *Eighth International Conference on Parallel Problem Solving from Nature PPSN VIII*, Proceedings, Berlin: Springer, 282291.
* Harvey, Andrew C. and Garry D.A. Phillips (1979): “Maximum likelihood estimation of regression models with autoregressive-moving average disturbances,” *Biometrika*, 66(1), 4958.
* Herbst, Edward and Schorfheide, Frank (2014): “Sequential Monte Carlo Sampling for DSGE Models,” *Journal of Applied Econometrics*, 29, 1073-1098.
* Herbst, Edward and Schorfheide, Frank (2014): "Sequential monte-carlo sampling for DSGE models," *Journal of Applied Econometrics*, 29, 1073-1098.
* Herbst, Edward (2015): “Using the “Chandrasekhar Recursions” for Likelihood Evaluation of DSGE Models,” *Computational Economics*, 45(4), 693705.
* Ireland, Peter (2004): “A Method for Taking Models to the Data,” *Journal of Economic Dynamics and Control*, 28, 120526.
* Iskrev, Nikolay (2010): “Local identification in DSGE models,” *Journal of Monetary Economics*, 57(2), 189202.

View File

@ -71,11 +71,12 @@ latex_elements = {
warningBorderColor={RGB}{255,50,50},OuterLinkColor={RGB}{34,139,34}, \
InnerLinkColor={RGB}{51,51,255},TitleColor={RGB}{51,51,255}',
'papersize': 'a4paper',
'preamble': r'\DeclareUnicodeCharacter{200B}{}', # Part of the workaround for #1707
}
latex_documents = [
(master_doc, 'dynare-manual.tex', u'Dynare Reference Manual',
u'Dynare Team', 'manual'),
u'Dynare team', 'manual'),
]
man_pages = [

View File

@ -8,17 +8,17 @@
Dynare misc commands
####################
.. matcomm:: send_endogenous_variables_to_workspace ;
.. matcomm:: send_endogenous_variables_to_workspace
Puts the simulation results for the endogenous variables stored in ``oo_.endo_simul``
into vectors with the same name as the respective variables into the base workspace.
.. matcomm:: send_exogenous_variables_to_workspace ;
.. matcomm:: send_exogenous_variables_to_workspace
Puts the simulation results for the exogenous variables stored in ``oo_.exo_simul``
into vectors with the same name as the respective variables into the base workspace.
.. matcomm:: send_irfs_to_workspace ;
.. matcomm:: send_irfs_to_workspace
Puts the IRFs stored in ``oo_.irfs`` into vectors with the same name into the base workspace.
@ -230,97 +230,27 @@ Dynare misc commands
Searches all occurrences of a variable in a model, and prints the
equations where the variable appear in the command line window. If OPTION is
set to `withparamvalues`, the values of the parameters (if available) are
displayed instead of the name of the parameters. Requires the `json` command
line option to be set.
displayed instead of the name of the parameters.
*Example*
Assuming that we already ran a `.mod` file and that the workspace has not
been cleaned after, we can search for all the equations containing variable `X`
Assuming that we already ran a `.mod` file and that the workspace has not
been cleaned after, we can search for all the equations containing variable `X`
::
::
>> search X
>> search X
Y = alpha*X/(1-X)+e;
Y = alpha*X/(1-X)+e;
diff(X) = beta*(X(-1)-mX) + gamma1*Z + gamma2*R + u;
diff(X) = beta*(X(-1)-mX) + gamma1*Z + gamma2*R + u;
To replace the parameters with estimated or calibrated parameters:
To replace the parameters with estimated or calibrated parameters:
::
::
>> search X withparamvalues
>> search X withparamvalues
Y = 1.254634*X/(1-X)+e;
Y = 1.254634*X/(1-X)+e;
diff(X) = -0.031459*(X(-1)-mX) + 0.1*Z - 0.2*R + u;
|br|
.. matcomm:: dplot [OPTION VALUE[ ...]]
Plot expressions extracting data from different dseries objects.
*Options*
.. option:: --expression EXPRESSION
``EXPRESSION`` is a mathematical expression involving variables
available in the dseries objects, dseries methods, numbers or
parameters. All the referenced objects are supposed to be
available in the calling workspace.
.. option:: --dseries NAME
``NAME`` is the name of a dseries object from which the
variables involved in ``EXPRESSION`` will be extracted.
.. option:: --range DATE1:DATE2
This option is not mandatory and allows to plot the expressions
only over a sub-range. ``DATE1`` and ``DATE2`` must be dates as
defined in :ref:`dates in a mod file`.
.. option:: --style MATLAB_SCRIPT_NAME
Name of a Matlab script (without extension) containing Matlab
commands to customize the produced figure.
.. option:: --title MATLAB_STRING
Adds a title to the figure.
.. option:: --with-legend
Prints a legend below the produced plot.
*Remarks*
- More than one --expression argument is allowed, and they must come first.
- For each dseries object we plot all the expressions. We use two
nested loops, the outer loop is over the dseries objects and the
inner loop over the expressions. This determines the ordering of
the plotted lines.
- All dseries objects must be defined in the calling workspace, if a
dseries object is missing the routine throws a warning (we only
build the plots for the available dseries objects), if all dseries
objects are missing the routine throws an error.
- If the range is not provided, the expressions cannot involve leads or lags.
*Example*
::
>> toto = dseries(randn(100,3), dates('2000Q1'), {'x','y','z'});
>> noddy = dseries(randn(100,3), dates('2000Q1'), {'x','y','z'});
>> b = 3;
>> dplot --expression 2/b*cumsum(x/y(-1)-1) --dseries toto --dseries noddy --range 2001Q1:2024Q1 --title 'This is my plot'
will produce plots for ``2/b*cumsum(x/y(-1)-1)``, where ``x`` and
``y`` are variables in dseries objects ``toto`` and ``noddy``, in
the same figure.
diff(X) = -0.031459*(X(-1)-mX) + 0.1*Z - 0.2*R + u;

View File

@ -11,7 +11,7 @@ Currently the development team of Dynare is composed of:
* Willi Mutschler (University of Tübingen)
* Johannes Pfeifer (University of the Bundeswehr Munich)
* Marco Ratto (European Commission, Joint Research Centre - JRC)
* Normann Rion (CEPREMAP)
* Normann Rion (CY Cergy Paris Université and CEPREMAP)
* Sébastien Villemot (CEPREMAP)
The following people used to be members of the team:

View File

@ -94,24 +94,26 @@ Citing Dynare in your research
You should cite Dynare if you use it in your research. The
recommended way todo this is to cite the present manual, as:
Stéphane Adjemian, Michel Juillard, Frédéric Karamé, Willi Mutschler,
Johannes Pfeifer, Marco Ratto, Normann Rion and Sébastien Villemot (2024),
“Dynare: Reference Manual, Version 6,” *Dynare Working Papers*, 80, CEPREMAP
Stéphane Adjemian, Houtan Bastani, Michel Juillard, Frédéric Karamé,
Ferhat Mihoubi, Willi Mutschler, Johannes Pfeifer, Marco Ratto,
Normann Rion and Sébastien Villemot (2022), “Dynare: Reference Manual,
Version 5,” *Dynare Working Papers*, 72, CEPREMAP
For convenience, you can copy and paste the following into your BibTeX file:
.. code-block:: bibtex
@TechReport{Adjemianetal2024,
author = {Adjemian, St\'ephane and Juillard, Michel and
Karam\'e, Fr\'ederic and Mutschler, Willi and
Pfeifer, Johannes and Ratto, Marco and
@TechReport{Adjemianetal2022,
author = {Adjemian, St\'ephane and Bastani, Houtan and
Juillard, Michel and Karam\'e, Fr\'ederic and
Mihoubi, Ferhat and Mutschler, Willi
and Pfeifer, Johannes and Ratto, Marco and
Rion, Normann and Villemot, S\'ebastien},
title = {Dynare: Reference Manual, Version 6},
year = {2024},
title = {Dynare: Reference Manual Version 5},
year = {2022},
institution = {CEPREMAP},
type = {Dynare Working Papers},
number = {80},
number = {72},
}
If you want to give a URL, use the address of the Dynare website:

View File

@ -1259,8 +1259,7 @@ command, the list of transformed model equations using the
``write_latex_dynamic_model command``, and the list of static model
equations using the ``write_latex_static_model`` command.
.. command:: write_latex_original_model ;
write_latex_original_model (OPTIONS);
.. command:: write_latex_original_model (OPTIONS);
|br| This command creates two LaTeX files: one
containing the model as defined in the model block and one
@ -1335,8 +1334,7 @@ equations using the ``write_latex_static_model`` command.
See :opt:`write_equation_tags`
.. command:: write_latex_static_model ;
write_latex_static_model (OPTIONS);
.. command:: write_latex_static_model (OPTIONS);
|br| This command creates two LaTeX files: one
containing the static model and one containing the LaTeX
@ -1371,7 +1369,7 @@ equations using the ``write_latex_static_model`` command.
See :opt:`write_equation_tags`.
.. command:: write_latex_steady_state_model ;
.. command:: write_latex_steady_state_model
|br| This command creates two LaTeX files: one containing the steady
state model and one containing the LaTeX document header
@ -2947,8 +2945,8 @@ Finding the steady state with Dynare nonlinear solver
``5``
Newton algorithm with a sparse Gaussian elimination (SPE)
solver at each iteration (requires ``bytecode`` option, see
Newton algorithm with a sparse Gaussian elimination
(SPE) (requires ``bytecode`` option, see
:ref:`model-decl`).
``6``
@ -2966,7 +2964,7 @@ Finding the steady state with Dynare nonlinear solver
``8``
Newton algorithm with a Stabilized Bi-Conjugate
Gradient (BiCGStab) solver at each iteration (requires
Gradient (BICGSTAB) solver at each iteration (requires
bytecode and/or block option, see :ref:`model-decl`).
``9``
@ -3003,23 +3001,19 @@ Finding the steady state with Dynare nonlinear solver
blocks that can be evaluated rather than solved; and evaluations
of the residual and Jacobian of the model are more efficient
because only the relevant elements are recomputed at every
iteration. This option is typically used with the
``perfect_foresight_solver`` command with purely backward,
forward or static models, or with routines for semi-structural
models, and it must *not* be combined with option ``block`` of
the ``model`` block. Also note that for those models, the block
decomposition is performed as if ``mfs=3`` had been passed to
the ``model`` block, and the decomposition is slightly
different because it is computed in a time-recursive fashion
(*i.e.* in such a way that the simulation is meant to be done
with the outer loop on periods and the inner loop on blocks;
while for models with both leads and lags, the outer loop is on
blocks and the inner loop is on periods).
iteration.
``14``
Same as ``12``, except that it applies a trust region solver
(similar to ``4``) to the blocks.
Computes a block decomposition and then applies a trust region
solver with autoscaling on those smaller blocks rather than on
the full nonlinear system. This is similar to ``4``, but is
typically more efficient. The block decomposition is done at
the preprocessor level, which brings two benefits: it
identifies blocks that can be evaluated rather than solved; and
evaluations of the residual and Jacobian of the model are more
efficient because only the relevant elements are recomputed at
every iteration.
|br| Default value is ``4``.
@ -3686,64 +3680,60 @@ speed-up on large models.
``0``
Use a Newton algorithm with a direct sparse LU solver at each
iteration, applied to the stacked system of all equations in all
periods (Default).
iteration, applied on the stacked system of all the equations at
every period (Default).
``1``
Use the Laffargue-Boucekkine-Juillard (LBJ) algorithm proposed
in *Juillard (1996)* on top of a LU solver. It is slower
than ``stack_solve_algo=0``, but may be less memory consuming on
big models. Note that if the ``block`` option is used (see
:ref:`model-decl`), a simple Newton algorithm with sparse
matrices, applied to the stacked system of all block equations
in all periods, is used for blocks which are purely backward or
forward (of type ``SOLVE BACKWARD`` or ``SOLVE FORWARD``, see
:comm:`model_info`), since LBJ only makes sense on blocks with
both leads and lags (of type ``SOLVE TWO BOUNDARIES``).
in *Juillard (1996)*. It is slower than ``stack_solve_algo=0``,
but may be less memory consuming on big models. Note that if the
``block`` option is used (see :ref:`model-decl`), a simple
Newton algorithm with sparse matrices is used for blocks which
are purely backward or forward (of type ``SOLVE BACKWARD`` or
``SOLVE FORWARD``, see :comm:`model_info`), since LBJ only makes
sense on blocks with both leads and lags (of type ``SOLVE TWO
BOUNDARIES``).
``2``
Use a Newton algorithm with a Generalized Minimal Residual
(GMRES) solver at each iteration, applied on the stacked system
of all equations in all periods (requires ``bytecode`` and/or
``block`` option, see :ref:`model-decl`)
Use a Newton algorithm with a Generalized Minimal
Residual (GMRES) solver at each iteration (requires
``bytecode`` and/or ``block`` option, see
:ref:`model-decl`)
``3``
Use a Newton algorithm with a Stabilized Bi-Conjugate Gradient
(BiCGStab) solver at each iteration, applied on the stacked
system of all equations in all periods (requires ``bytecode``
and/or ``block`` option, see :ref:`model-decl`).
Use a Newton algorithm with a Stabilized Bi-Conjugate
Gradient (BICGSTAB) solver at each iteration (requires
``bytecode`` and/or ``block`` option, see
:ref:`model-decl`).
``4``
Use a Newton algorithm with a direct sparse LU solver and an
optimal path length at each iteration, applied on the stacked
system of all equations in all periods (requires ``bytecode``
and/or ``block`` option, see :ref:`model-decl`).
Use a Newton algorithm with an optimal path length at
each iteration (requires ``bytecode`` and/or ``block``
option, see :ref:`model-decl`).
``5``
Use the Laffargue-Boucekkine-Juillard (LBJ) algorithm proposed
in *Juillard (1996)* on top of a sparse Gaussian elimination
(SPE) solver. The latter takes advantage of the similarity of
the Jacobian across periods when searching for the pivots
(requires ``bytecode`` option, see :ref:`model-decl`).
Use a Newton algorithm with a sparse Gaussian
elimination (SPE) solver at each iteration (requires
``bytecode`` option, see :ref:`model-decl`).
``6``
Synonymous for ``stack_solve_algo=1``. Kept for backward
compatibility.
Synonymous for ``stack_solve_algo=1``. Kept for historical
reasons.
``7``
Allows the user to solve the perfect foresight model with the
solvers available through option ``solve_algo``, applied on the
stacked system of all equations in all periods (See
:ref:`solve_algo <solvalg>` for a list of possible values, note
that values ``5``, ``6``, ``7`` and ``8``, which require ``bytecode`` and/or
``block`` options, are not allowed). For instance, the following
Allows the user to solve the perfect foresight model
with the solvers available through option
``solve_algo`` (See :ref:`solve_algo <solvalg>` for a
list of possible values, note that values 5, 6, 7 and
8, which require ``bytecode`` and/or ``block`` options,
are not allowed). For instance, the following
commands::
perfect_foresight_setup(periods=400);
@ -3760,10 +3750,7 @@ speed-up on large models.
.. option:: solve_algo
See :ref:`solve_algo <solvalg>`. Allows selecting the solver
used with ``stack_solve_algo=7``. Also used for purely backward, forward
and static models (when neither the ``block`` nor the ``bytecode`` option
of the ``model`` block is specified); for those models, the values
``12`` and ``14`` are especially relevant.
used with ``stack_solve_algo=7``.
.. option:: no_homotopy
@ -3850,9 +3837,9 @@ speed-up on large models.
.. option:: lmmcp
Solves the perfect foresight model with a Levenberg-Marquardt
mixed complementarity problem (LMMCP) solver (*Kanzow and Petra,
2004*), which allows to consider inequality constraints on
the endogenous variables (such as a zero lower bound, henceforth ZLB, on the nominal interest
mixed complementarity problem (LMMCP) solver (*Kanzow and Petra
(2004)*), which allows to consider inequality constraints on
the endogenous variables (such as a ZLB on the nominal interest
rate or a model with irreversible investment). This option is
equivalent to ``stack_solve_algo=7`` **and**
``solve_algo=10``. Using the LMMCP solver avoids the need for min/max
@ -5781,14 +5768,6 @@ All of these elements are discussed in the following.
See :opt:`simul_check_ahead_periods <simul_check_ahead_periods = INTEGER>`.
.. option:: simul_reset_check_ahead_periods
See :opt:`simul_reset_check_ahead_periods`.
.. option:: simul_max_check_ahead_periods
See :opt:`simul_max_check_ahead_periods <simul_max_check_ahead_periods = INTEGER>`.
.. option:: simul_curb_retrench
See :opt:`simul_curb_retrench`.
@ -6512,8 +6491,8 @@ observed variables.
Do not use the kalman filter to evaluate the likelihood, but instead
evaluate the conditional likelihood, based on the first order reduced
form of the model, by assuming that the initial state vector is at its
steady state. This approach requires that:
form of the model, by assuming that the initial state vector is 0 for all
the endogenous variables. This approach requires that:
1. The number of structural innovations be equal to the number of observed variables.
@ -6528,7 +6507,7 @@ observed variables.
Note however that the conditional likelihood is sensitive to the choice
for the initial condition, which can be an issue if the data are
initially far from the steady state. This option is not compatible with
``analytic_derivation``.
``analytical_derivation``.
.. option:: conf_sig = DOUBLE
@ -7490,8 +7469,7 @@ observed variables.
Instructs Dynare to use the *Herbst and Schorfheide (2014)*
version of the Sequential Monte-Carlo sampler instead of the
standard Random-Walk Metropolis-Hastings. Does not yet support
``moments_varendo``, ``bayesian_irf``, and ``smoother``.
standard Random-Walk Metropolis-Hastings.
``'dsmh'``
@ -11761,7 +11739,7 @@ with ``discretionary_policy`` or for optimal simple rules with ``osr``
With ``discretionary_policy``, the objective function must be quadratic.
.. command:: evaluate_planner_objective ;
.. command:: evaluate_planner_objective;
evaluate_planner_objective (OPTIONS...);
This command computes, displays, and stores the value of the
@ -14278,7 +14256,7 @@ assumed that each equation is written as ``VARIABLE = EXPRESSION`` or
``T(VARIABLE) = EXPRESSION`` where ``T(VARIABLE)`` stands for a transformation
of an endogenous variable (``log`` or ``diff``). This representation, where each
equation determines the endogenous variable on the LHS, can be exploited when
simulating the model (see algorithms ``12`` and ``14`` in :ref:`solve_algo <solvalg>`)
simulating the model (see algorithms 12 and 14 in :ref:`solve_algo <solvalg>`)
and is mandatory to define auxiliary models used for computing expectations (see
below).
@ -14315,7 +14293,7 @@ a trend target to which the endogenous variables may be attracted in the long-ru
:math:`n\times 1` vector of parameters, :math:`A_i` (:math:`i=0,\ldots,p`)
are :math:`n\times n` matrices of parameters, and :math:`A_0` is non
singular square matrix. Vector :math:`\mathbf{c}` and matrices :math:`A_i`
(:math:`i=0,\ldots,p`) are set by parsing the equations in the
(:math:`i=0,\ldots,p`) are set by Dynare by parsing the equations in the
``model`` block. Then, Dynare builds a VAR(1)-companion form model for
:math:`\mathcal{Y}_t = (1, Y_t, \ldots, Y_{t-p+1})'` as:
@ -14526,7 +14504,7 @@ up to time :math:`t-\tau`, :math:`\mathcal{Y}_{\underline{t-\tau}}`) is:
In a semi-structural model, variables appearing in :math:`t+h` (*e.g.*
the expected output gap in a dynamic IS curve or expected inflation in a
New Keynesian Phillips curve) will be replaced by the expectation implied by an auxiliary VAR
(New Keynesian) Phillips curve) will be replaced by the expectation implied by an auxiliary VAR
model. Another use case is for the computation of permanent
incomes. Typically, consumption will depend on something like:
@ -14534,13 +14512,13 @@ incomes. Typically, consumption will depend on something like:
\sum_{h=0}^{\infty} \beta^h y_{t+h|t-\tau}
Assuming that :math:`0<\beta<1` and knowing the limit of geometric series, the conditional expectation of this variable can be evaluated based on the same auxiliary model:
Assuming that $0<\beta<1$ and knowing the limit of geometric series, the conditional expectation of this variable can be evaluated based on the same auxiliary model:
.. math ::
\mathbb E \left[\sum_{h=0}^{\infty} \beta^h y_{t+h}\Biggl| \mathcal{Y}_{\underline{t-\tau}}\right] = \alpha \mathcal{C}^\tau(I-\beta\mathcal{C})^{-1}\mathcal{Y}_{t-\tau}
Finite discounted sums can also be considered.
More generally, it is possible to consider finite discounted sums.
.. command:: var_expectation_model (OPTIONS...);
@ -14725,7 +14703,7 @@ simply add the exogenous variables to the PAC equation (without the weight
``trend_component_model``, to compute the VAR based expectations for the
expected changes in the target, *i.e.* to evaluate
:math:`\sum_{i=0}^{\infty} d_i \Delta y^{\star}_{t+i}`. The infinite sum
will then be replaced by a linear combination, defined by a vector :math:`h`, of the variables involved in
will then be replaced by a linear combination of the variables involved in
the companion representation of the auxiliary model. The weights defining
the linear combination are nonlinear functions of the
:math:`(a_i)_{i=0}^{m-1}` coefficients in the PAC equation. This option is
@ -14745,16 +14723,6 @@ simply add the exogenous variables to the PAC equation (without the weight
or expression is given) is consistent with the asymptotic growth rate of the
endogenous variable.
.. option:: kind = dd | dl
Instructs Dynare how to compute the vector :math:`h`, the weights
defining the linear combination of the companion VAR
variables. The default value ``dd`` must be used if the target
appears in first difference in the auxiliary model, see equation
(A.79) in *Brayton et alii (2000)*, while value ``dl`` must be
used if the target shows up in level in the auxiliary model,
equation (A.74) in *Brayton et alii (2000)*.
.. operator:: pac_expectation (NAME_OF_PAC_MODEL);
@ -14765,89 +14733,7 @@ simply add the exogenous variables to the PAC equation (without the weight
the variables involved in the companion representation of the auxiliary model
or by a recursive forward equation.
The PAC equation target can be composite and defined as a weighted sum
of stationary and non stationary components. Such a target requires an
additional equation in the model block, with the target variable on
the left hand-side and the components in the right hand-side. Each
component must be an endogenous variable in the auxiliary model. The
characteristics of each component must be described in the
``pac_target_info`` block, see below, and the
``pac_target_nonstationary`` operator must be used in the error
correction term of the PAC equation to link the target to the provided
description. Note that composite targets make only sense if the
auxiliary model is not a trend component model (where all the
variables are non stationary).
.. block:: pac_target_info (NAME_OF_PAC_MODEL);
|br| This block enables the user to provide the properties of each
component of a target in PAC models with a composite target. The
``NAME_OF_PAC_MODEL`` argument refers to a PAC model (must match
the value of option ``model_name`` in the declaration of a PAC
model).
On the first line of the block, the name of the composite target
variable must be provided using the following syntax::
target VARIABLE_NAME ;
where ``VARIABLE_NAME`` is a declared endogenous variable, its
associated equation is not part of the auxiliary model but all the
components (the variables on the right hand-side) must be defined
in the auxiliary model. Next, the following line declares the name
of the auxilary variable that will appear in the error correction
term, this variable contains only the non stationary components of
the target::
auxname_target_nonstationary NAME ;
The block should contain the following group of lines for each
stationary component::
component STATIONARY_VARIABLE_NAME ;
kind ll ;
auxname AUX_VAR_NAME ;
where ``STATIONARY_VARIABLE_NAME`` is the name of a stationary
variable appearing in the right hand-side of the equation defining
the target ``VARIABLE_NAME``. The second line instructs Dynare that
the component appears in levels in the auxiliary model and in the
PAC expectations. The third line specifies the name of the
auxiliary variable created by Dynare for the component of the PAC
expectation related to ``STATIONARY_VARIABLE_NAME``.
The block should contain the following group of lines for each
nonstationary component::
component NONSTATIONARY_VARIABLE_NAME ;
kind dd | dl ;
auxname AUX_VAR_NAME ;
growth PARAMETER_NAME | VARIABLE_NAME | EXPRESSION | DOUBLE ;
where ``NONSTATIONARY_VARIABLE_NAME`` is the name of a
nonstationary variable appearing in the right hand-side of the
equation defining the target ``VARIABLE_NAME``. The second line
instructs Dynare on how to calculate the weights that define the linear
combination of the companion VAR variables. Use value ``dd`` if the
target appears in first difference in the auxiliary model, or
``dl`` if the target shows up in level in the auxiliary model. The
third line sets the name of the auxiliary variable created by
Dynare for the component of the PAC expectation related to
``NONSTATIONARY_VARIABLE_NAME``. The fourth line is mandatory if a
growth neutrality correction is required. The provided value for
this option must be consistent with the asymptotic growth rate of
the PAC endogenous variable.
.. operator:: pac_target_nonstationary (NAME_OF_PAC_MODEL);
|br| This operator is only required in presence of a composite
target in the PAC equation. The operator, used in the error
correction term of the PAC equation, selects the non stationary
components of the target.
|br|
.. matcomm:: pac.initialize(NAME_OF_PAC_MODEL);
.. matcomm:: pac.update(NAME_OF_PAC_MODEL);
@ -14860,33 +14746,33 @@ variables are non stationary).
the infinite sum in the MCE case).
*Example (trend component auxiliary model)*
*Example*
::
trend_component_model(model_name=toto, eqtags=['eq:x1', 'eq:x2', 'eq:x1bar', 'eq:x2bar'], targets=['eq:x1bar', 'eq:x2bar']);
pac_model(auxiliary_model_name=toto, discount=beta, model_name=pacman);
pac_model(auxiliary_model_name=toto, discount=beta, growth=diff(x1(-1)), model_name=pacman);
model;
[name='eq:y']
y = (1-rho_1-rho_2)*diff(x2(-1)) + rho_1*y(-1) + rho_2*y(-2) + ey;
[name='eq:y']
y = rho_1*y(-1) + rho_2*y(-2) + ey;
[name='eq:x1']
diff(x1) = a_x1_0*(x1(-1)-x1bar(-1)) + a_x1_1*diff(x1(-1)) + a_x1_2*diff(x1(-2)) + a_x1_x2_1*diff(x2(-1)) + a_x1_x2_2*diff(x2(-2)) + ex1;
[name='eq:x1']
diff(x1) = a_x1_0*(x1(-1)-x1bar(-1)) + a_x1_1*diff(x1(-1)) + a_x1_2*diff(x1(-2)) + a_x1_x2_1*diff(x2(-1)) + a_x1_x2_2*diff(x2(-2)) + ex1;
[name='eq:x2']
diff(x2) = a_x2_0*(x2(-1)-x2bar(-1)) + a_x2_1*diff(x1(-1)) + a_x2_2*diff(x1(-2)) + a_x2_x1_1*diff(x2(-1)) + a_x2_x1_2*diff(x2(-2)) + ex2;
[name='eq:x2']
diff(x2) = a_x2_0*(x2(-1)-x2bar(-1)) + a_x2_1*diff(x1(-1)) + a_x2_2*diff(x1(-2)) + a_x2_x1_1*diff(x2(-1)) + a_x2_x1_2*diff(x2(-2)) + ex2;
[name='eq:x1bar']
x1bar = x1bar(-1) + ex1bar;
[name='eq:x1bar']
x1bar = x1bar(-1) + ex1bar;
[name='eq:x2bar']
x2bar = x2bar(-1) + ex2bar;
[name='eq:x2bar']
x2bar = x2bar(-1) + ex2bar;
[name='zpac']
diff(z) = e_c_m*(x1(-1)-z(-1)) + c_z_1*diff(z(-1)) + c_z_2*diff(z(-2)) + pac_expectation(pacman) + ez;
[name='zpac']
diff(z) = e_c_m*(x1(-1)-z(-1)) + c_z_1*diff(z(-1)) + c_z_2*diff(z(-2)) + pac_expectation(pacman) + ez;
end;
@ -14895,51 +14781,6 @@ variables are non stationary).
pac.update.expectation('pacman');
*Example (VAR auxiliary model and composite target)*
::
var_model(model_name=toto, eqtags=['eq:x', 'eq:y']);
pac_model(auxiliary_model_name=toto, discount=beta, model_name=pacman);
pac_target_info(pacman);
target v;
auxname_target_nonstationary vns;
component y;
auxname pv_y_;
kind ll;
component x;
growth diff(x(-1));
auxname pv_dx_;
kind dd;
end;
model;
[name='eq:y']
y = a_y_1*y(-1) + a_y_2*diff(x(-1)) + b_y_1*y(-2) + b_y_2*diff(x(-2)) + ey ;
[name='eq:x']
diff(x) = b_x_1*y(-2) + b_x_2*diff(x(-1)) + ex ;
[name='eq:v']
v = x + d_y*y ; // Composite PAC target, no residuals here only variables defined in the auxiliary model.
[name='zpac']
diff(z) = e_c_m*(pac_target_nonstationary(pacman)-z(-1)) + c_z_1*diff(z(-1)) + c_z_2*diff(z(-2)) + pac_expectation(pacman) + ez;
end;
pac.initialize('pacman');
pac.update.expectation('pacman');
Estimation of a PAC equation
----------------------------
@ -16020,7 +15861,7 @@ Misc commands
``pdflatex`` and automatically tries to load all required
packages. Requires the following LaTeX packages:
``breqn``, ``psfrag``, ``graphicx``, ``epstopdf``, ``longtable``,
``booktabs``, ``caption``, ``float,`` ``amsmath``, ``amsfonts``, ``amssymb``,
``booktabs``, ``caption``, ``float,`` ``amsmath``, ``amsfonts``,
and ``morefloats``.

View File

@ -22,8 +22,6 @@ Dates
=====
.. highlight:: matlab
.. _dates in a mod file:
Dates in a mod file
-------------------

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Copyright © 2018-2024 Dynare Team
# Copyright © 2018-2019 Dynare Team
#
# This file is part of Dynare.
#
@ -80,7 +80,9 @@ class DynObject(ObjectDescription):
signode += addnodes.desc_name(name, name)
if self.has_arguments:
if arglist:
if not arglist:
signode += addnodes.desc_parameterlist()
else:
signode += addnodes.desc_addname(arglist,arglist)
return fullname, prefix

View File

@ -60,7 +60,7 @@ class DynareLexer(RegexLexer):
"addSeries","addParagraph","addVspace","write","compile")
operators = (
"STEADY_STATE","EXPECTATION","var_expectation","pac_expectation","pac_target_nonstationary")
"STEADY_STATE","EXPECTATION","var_expectation","pac_expectation")
macro_dirs = (
"@#includepath", "@#include", "@#define", "@#if",
@ -83,8 +83,7 @@ class DynareLexer(RegexLexer):
'osr_params_bounds','ramsey_constraints','irf_calibration',
'moment_calibration','identification','svar_identification',
'matched_moments','occbin_constraints','surprise','overwrite','bind','relax',
'verbatim','end','node','cluster','paths','hooks','target','pac_target_info','auxname_target_nonstationary',
'component', 'growth', 'auxname', 'kind'), prefix=r'\b', suffix=r'\s*\b'),Keyword.Reserved),
'verbatim','end','node','cluster','paths','hooks'), prefix=r'\b', suffix=r'\s*\b'),Keyword.Reserved),
# FIXME: Commands following multiline comments are not highlighted properly.
(words(commands + report_commands,

View File

@ -1,101 +0,0 @@
// --+ options: json=compute, stochastic +--
var y x z v;
varexo ex ey ez ;
parameters a_y_1 a_y_2 b_y_1 b_y_2 b_x_1 b_x_2 d_y; // VAR parameters
parameters beta e_c_m c_z_1 c_z_2; // PAC equation parameters
a_y_1 = .2;
a_y_2 = .3;
b_y_1 = .1;
b_y_2 = .4;
b_x_1 = -.1;
b_x_2 = -.2;
d_y = .5;
beta = .9;
e_c_m = .1;
c_z_1 = .7;
c_z_2 = -.3;
var_model(model_name=toto, eqtags=['eq:x', 'eq:y']);
pac_model(auxiliary_model_name=toto, discount=beta, model_name=pacman);
pac_target_info(pacman);
target v;
auxname_target_nonstationary vns;
component y;
auxname pv_y_;
kind ll;
component x;
growth diff(x(-1));
auxname pv_dx_;
kind dd;
end;
model;
[name='eq:y']
y = a_y_1*y(-1) + a_y_2*diff(x(-1)) + b_y_1*y(-2) + b_y_2*diff(x(-2)) + ey ;
[name='eq:x']
diff(x) = b_x_1*y(-2) + b_x_2*diff(x(-1)) + ex ;
[name='eq:v']
v = x + d_y*y ; // Composite target, no residuals here only variables defined in the auxiliary VAR model.
[name='zpac']
diff(z) = e_c_m*(pac_target_nonstationary(pacman)-z(-1)) + c_z_1*diff(z(-1)) + c_z_2*diff(z(-2)) + pac_expectation(pacman) + ez;
end;
shocks;
var ex = .10;
var ey = .15;
var ez = .05;
end;
// Initialize the PAC model (build the Companion VAR representation for the auxiliary model).
pac.initialize('pacman');
// Update the parameters of the PAC expectation model (h0 and h1 vectors).
pac.update.expectation('pacman');
/*
**
** Simulate artificial dataset
**
*/
// Set initial conditions to zero.
initialconditions = dseries(zeros(10, M_.endo_nbr+M_.exo_nbr), 2000Q1, vertcat(M_.endo_names,M_.exo_names));
// Simulate the model for 5000 periods
TrueData = simul_backward_model(initialconditions, 5000);
/*
**
** Estimate PAC equation (using the artificial data)
**
*/
// Provide initial conditions for the estimated parameters
clear eparams
eparams.e_c_m = .9;
eparams.c_z_1 = .5;
eparams.c_z_2 = .2;
edata = TrueData; // Set the dataset used for estimation
edata.ez = dseries(NaN, 2000Q1); // Remove residuals for the PAC equation from the database.
pac.estimate.nls('zpac', eparams, edata, 2005Q1:2005Q1+4000, 'fmincon'); // Should produce a table with the estimates (close to the calibration given in lines 21-23)

View File

@ -86,7 +86,7 @@ License: public-domain-aim
Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
pages 472-489
Files: matlab/optimization/bfgsi1.m matlab/optimization/csolve.m matlab/optimization/csminit1.m matlab/optimization/numgrad2.m
Files: matlab/optimization/bfgsi1.m matlab/csolve.m matlab/optimization/csminit1.m matlab/optimization/numgrad2.m
matlab/optimization/numgrad3.m matlab/optimization/numgrad3_.m matlab/optimization/numgrad5.m
matlab/optimization/numgrad5_.m matlab/optimization/csminwel1.m matlab/+bvar/density.m
matlab/+bvar/toolbox.m matlab/partial_information/PI_gensys.m matlab/partial_information/qzswitch.m
@ -123,11 +123,6 @@ Copyright: 2010-2015 Alexander Meyer-Gohde
2015-2017 Dynare Team
License: GPL-3+
Files: matlab/collapse_figures_in_tabgroup.m
Copyright: 2023 Eduard Benet Cerda
2024 Dynare Team
License: GPL-3+
Files: matlab/convergence_diagnostics/raftery_lewis.m
Copyright: 2016 Benjamin Born and Johannes Pfeifer
2016-2017 Dynare Team
@ -177,7 +172,7 @@ Comment: Written by Jessica Cariboni and Francesca Campolongo
Files: matlab/+gsa/cumplot.m
matlab/+gsa/monte_carlo_filtering.m
matlab/+gsa/skewness.m
matlab/+gsa/log_transform.m
matlab/+gsa/log_trans_.m
matlab/+gsa/map_calibration.m
matlab/+gsa/map_identification.m
matlab/+gsa/monte_carlo_filtering_analysis.m
@ -252,7 +247,7 @@ License: BSD-2-clause
Files: examples/fs2000_data.m
Copyright: 2000-2022 Frank Schorfheide
2023 Dynare Team
Copyright: 2023 Dynare Team
License: CC-BY-SA-4.0
Files: doc/*.rst doc/*.tex doc/*.svg doc/*.pdf doc/*.bib
@ -297,6 +292,28 @@ Files: preprocessor/doc/preprocessor/*
Copyright: 2007-2019 Dynare Team
License: CC-BY-SA-4.0
Files: contrib/jsonlab/*
Copyright: 2011-2020 Qianqian Fang <q.fang at neu.edu>
2016 Bastian Bechtold
License: GPL-3+ or BSD-3-clause
Files: contrib/jsonlab/base64decode.m
contrib/jsonlab/base64encode.m
contrib/jsonlab/gzipdecode.m
contrib/jsonlab/gzipencode.m
contrib/jsonlab/zlibdecode.m
contrib/jsonlab/zlibencode.m
Copyright: 2012 Kota Yamaguchi
2011-2020 Qianqian Fang <q.fang at neu.edu>
License: GPL-3+ or BSD-2-clause
Files: contrib/jsonlab/loadjson.m
Copyright: 2011-2020 Qianqian Fang
2009 Nedialko Krouchev
2009 François Glineur
2008 Joel Feenstra
License: GPL-3+ or BSD-2-clause or BSD-3-clause
Files: contrib/ms-sbvar/utilities_dw/*
Copyright: 1996-2011 Daniel Waggoner
License: GPL-3+
@ -403,6 +420,32 @@ License: BSD-2-clause
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
License: BSD-3-clause
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
.
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
.
* Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
License: GFDL-NIV-1.3+
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or

View File

@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Copyright © 2019-2024 Dynare Team
# Copyright © 2019-2023 Dynare Team
#
# This file is part of Dynare.
#
@ -150,8 +150,8 @@ cp "$ROOTDIR"/build-doc/*.pdf "$PKGFILES"
cp "$ROOTDIR"/build-doc/preprocessor/doc/*.pdf "$PKGFILES"/doc
cp -r "$ROOTDIR"/build-doc/dynare-manual.html "$PKGFILES"/doc
mkdir -p "$PKGFILES"/matlab/dseries/externals/x13/macOS/64
cp -p "$ROOTDIR"/macOS/deps/"$PKG_ARCH"/lib64/x13as/x13as "$PKGFILES"/matlab/dseries/externals/x13/macOS/64
mkdir -p "$PKGFILES"/matlab/modules/dseries/externals/x13/macOS/64
cp -p "$ROOTDIR"/macOS/deps/"$PKG_ARCH"/lib64/x13as/x13as "$PKGFILES"/matlab/modules/dseries/externals/x13/macOS/64
cd "$ROOTDIR"/macOS/pkg

View File

@ -1,4 +1,4 @@
# Copyright © 2019-2024 Dynare Team
# Copyright © 2019-2023 Dynare Team
#
# This file is part of Dynare.
#
@ -53,7 +53,7 @@ clean-all: clean-lib clean-src clean-tar
#
tarballs/slicot-$(SLICOT_VERSION).tar.gz:
mkdir -p tarballs
wget $(WGET_OPTIONS) -O $@ https://deb.debian.org/debian/pool/main/s/slicot/slicot_$(SLICOT_VERSION).orig.tar.xz
wget $(WGET_OPTIONS) -O $@ https://deb.debian.org/debian/pool/main/s/slicot/slicot_$(SLICOT_VERSION).orig.tar.gz
$(DEPS_ARCH)/sources64/slicot-$(SLICOT_VERSION): tarballs/slicot-$(SLICOT_VERSION).tar.gz
rm -rf $(DEPS_ARCH)/sources64/slicot-*
@ -62,7 +62,7 @@ $(DEPS_ARCH)/sources64/slicot-$(SLICOT_VERSION): tarballs/slicot-$(SLICOT_VERSIO
touch $@
$(DEPS_ARCH)/lib64/slicot/libslicot64_pic.a: $(DEPS_ARCH)/sources64/slicot-$(SLICOT_VERSION)
make -C $< -f makefile_Unix FORTRAN=$(BREWDIR)/bin/gfortran LOADER=$(BREWDIR)/bin/gfortran SLICOTLIB=../libslicot64_pic.a OPTS="-O3 -fdefault-integer-8" lib -j$(NTHREADS)
make -C $< FORTRAN=$(BREWDIR)/bin/gfortran LOADER=$(BREWDIR)/bin/gfortran SLICOTLIB=../libslicot64_pic.a OPTS="-O3 -fdefault-integer-8" lib -j$(NTHREADS)
strip -S $</libslicot64_pic.a
mkdir -p $(dir $@)
cp $</libslicot64_pic.a $@

View File

@ -1,2 +1,2 @@
SLICOT_VERSION = 5.9~20240205.gita037f7e
SLICOT_VERSION = 5.0+20101122
X13AS_VERSION = 1-1-b60

View File

@ -272,8 +272,80 @@ elseif opt_gsa.morris==3
return
elseif opt_gsa.morris==2 % ISKREV stuff
return
else
error('gsa/map_identification: unsupported option morris=%u',opt_gsa.morris)
else % main effects analysis
if itrans==0
fsuffix = '';
elseif itrans==1
fsuffix = '_log';
else
fsuffix = '_rank';
end
imap=1:npT;
if isempty(lpmat0)
x0=lpmat(istable,:);
else
x0=[lpmat0(istable,:), lpmat(istable,:)];
end
nrun=length(istable);
nest=min(250,nrun);
if opt_gsa.load_ident_files==0
try
EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAcc','ir_cc','ic_cc');
catch
EET=[];
end
ccac = gsa.standardize_columns([mss cc ac]);
[pcc, dd] = eig(cov(ccac(istable,:)));
[latent, isort] = sort(-diag(dd));
latent = -latent;
figure, bar(latent)
title('Eigenvalues in PCA')
pcc=pcc(:,isort);
ccac = ccac*pcc;
npca = max(find(cumsum(latent)./length(latent)<0.99))+1;
siPCA = (EET.SAcc'*abs(pcc'))';
siPCA = siPCA./(max(siPCA,[],2)*ones(1,npT));
SAcc=zeros(size(ccac,2),npT);
gsa_=NaN(npca);
for j=1:npca %size(ccac,2),
if itrans==0
y0 = ccac(istable,j);
elseif itrans==1
y0 = gsa.log_transform(ccac(istable,j));
else
y0 = trank(ccac(istable,j));
end
if ~isempty(EET)
imap=find(siPCA(j,:) >= (0.1.*max(siPCA(j,:))) );
end
gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ...
2, [],[],[],0,[OutputDirectoryName,'/map_cc',fsuffix,int2str(j)], pnames);
SAcc(j,imap)=gsa_(j).si;
imap_cc{j}=imap;
end
save([OutputDirectoryName,'/map_cc',fsuffix,'.mat'],'gsa_')
save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'imap_cc','SAcc','ccac','-append')
else
load([OutputDirectoryName,'/',fname_,'_main_eff'],'SAcc')
end
hh_fig=dyn_figure(options_.nodisplay,'Name',['Identifiability indices in the ',fsuffix,' moments.']);
bar(sum(SAcc))
set(gca,'xticklabel',' ','fontsize',10,'xtick',1:npT)
set(gca,'xlim',[0.5 npT+0.5])
ydum = get(gca,'ylim');
set(gca,'ylim',[0 ydum(2)])
set(gca,'position',[0.13 0.2 0.775 0.7])
for ip=1:npT
text(ip,-0.02*(ydum(2)),bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
xlabel(' ')
title(['Identifiability indices in the ',fsuffix,' moments.'],'interpreter','none')
dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],options_.nodisplay,options_.graph_format);
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],1,['Identifiability indices in the ',fsuffix,' moments.'],['ident_ALL',fsuffix]',1)
end
function []=create_TeX_loader(options_,figpath,ifig_number,caption,label_name,scale_factor)

View File

@ -13,7 +13,7 @@ function x0=run(M_,oo_,options_,bayestopt_,estim_params_,options_gsa)
% M. Ratto (2008), Analysing DSGE Models with Global Sensitivity Analysis,
% Computational Economics (2008), 31, pp. 115139
% Copyright © 2008-2024 Dynare Team
% Copyright © 2008-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -101,9 +101,6 @@ if ~isempty(options_gsa.datafile) || isempty(bayestopt_) || options_gsa.rmse
disp('must be specified for RMSE analysis!');
error('Sensitivity anaysis error!')
end
if isfield(options_gsa,'nobs')
options_.nobs=options_gsa.nobs;
end
if ~isempty(options_.nobs) && length(options_.nobs)~=1
error('dynare_sensitivity does not support recursive estimation. Please specify nobs as a scalar, not a vector.')
end
@ -111,6 +108,9 @@ if ~isempty(options_gsa.datafile) || isempty(bayestopt_) || options_gsa.rmse
if isfield(options_gsa,'first_obs')
options_.first_obs=options_gsa.first_obs;
end
if isfield(options_gsa,'nobs')
options_.nobs=options_gsa.nobs;
end
if isfield(options_gsa,'presample')
options_.presample=options_gsa.presample;
end
@ -150,11 +150,6 @@ end
[~,~,~,~,oo_.dr,M_.params] = dynare_resolve(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
if isfield(oo_.dr,'eigval') && any(abs(oo_.dr.eigval-1)<abs(1-options_.qz_criterium)) && options_.qz_criterium<1
fprintf('\ngsa: The model features a unit root, but qz_criterium<1. Check whether that is intended.')
fprintf('\ngsa: If not, use the diffuse_filter option.\n')
end
options_gsa = set_default_option(options_gsa,'identification',0);
if options_gsa.identification
options_gsa.redform=0;
@ -527,4 +522,4 @@ if options_gsa.glue
save([OutputDirectoryName,'/',fname_,'_glue_mc.mat'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem','Info', 'Exo')
end
end
end
end

View File

@ -93,8 +93,7 @@ function DERIVS = get_perturbation_params_derivs(M_, options_, estim_params_, dr
% This function calls
% * [fname,'.dynamic']
% * [fname,'.dynamic_params_derivs']
% * [fname,'.sparse.static_g1']
% * [fname,'.sparse.static_g2']
% * [fname,'.static']
% * [fname,'.static_params_derivs']
% * commutation
% * dyn_vech
@ -110,7 +109,7 @@ function DERIVS = get_perturbation_params_derivs(M_, options_, estim_params_, dr
% * sylvester3a
% * get_perturbation_params_derivs_numerical_objective
% =========================================================================
% Copyright © 2019-2024 Dynare Team
% Copyright © 2019-2020 Dynare Team
%
% This file is part of Dynare.
%
@ -455,13 +454,12 @@ elseif (analytic_derivation_mode == 0 || analytic_derivation_mode == 1)
error('For analytical parameter derivatives ''dynamic_params_derivs.m'' file is needed, this can be created by putting identification(order=%d) into your mod file.',order)
end
%% Analytical computation of Jacobian and Hessian (wrt selected model parameters) of steady state, i.e. dYss and d2Yss
[g1_static, T_order_static, T_static] = feval([fname,'.sparse.static_g1'], ys, exo_steady_state', params, M_.static_g1_sparse_rowval, M_.static_g1_sparse_colval, M_.static_g1_sparse_colptr); %g1_static is [endo_nbr by endo_nbr] first-derivative (wrt all endogenous variables) of static model equations f, i.e. df/dys, in declaration order
[~, g1_static] = feval([fname,'.static'], ys, exo_steady_state', params); %g1_static is [endo_nbr by endo_nbr] first-derivative (wrt all endogenous variables) of static model equations f, i.e. df/dys, in declaration order
rp_static = feval([fname,'.static_params_derivs'], ys, exo_steady_state', params); %rp_static is [endo_nbr by param_nbr] first-derivative (wrt all model parameters) of static model equations f, i.e. df/dparams, in declaration order
dys = -g1_static\rp_static; %use implicit function theorem (equation 5 of Ratto and Iskrev (2012) to compute [endo_nbr by param_nbr] first-derivative (wrt all model parameters) of steady state for all endogenous variables analytically, note that dys is in declaration order
d2ys = zeros(endo_nbr, param_nbr, param_nbr); %initialize in tensor notation, note that d2ys is only needed for d2flag, i.e. for g1pp
if d2flag
g2_static_v = feval([fname,'.sparse.static_g2'], ys, exo_steady_state', params, T_order_static, T_static);
g2_static = build_two_dim_hessian(M_.static_g2_sparse_indices, g2_static_v, endo_nbr, endo_nbr); %g2_static is [endo_nbr by endo_nbr^2] second derivative (wrt all endogenous variables) of static model equations f, i.e. d(df/dys)/dys, in declaration order
[~, ~, g2_static] = feval([fname,'.static'], ys, exo_steady_state', params); %g2_static is [endo_nbr by endo_nbr^2] second derivative (wrt all endogenous variables) of static model equations f, i.e. d(df/dys)/dys, in declaration order
if order < 3
[~, g1, g2, g3] = feval([fname,'.dynamic'], ys(I), exo_steady_state', params, ys, 1); %note that g3 does not contain symmetric elements
g3 = identification.unfold_g3(g3, yy0ex0_nbr); %add symmetric elements to g3
@ -507,7 +505,7 @@ elseif (analytic_derivation_mode == 0 || analytic_derivation_mode == 1)
end
%handling of steady state for nonstationary variables
if any(any(isnan(dys)))
[U,T] = schur(full(g1_static));
[U,T] = schur(g1_static);
e1 = abs(ordeig(T)) < qz_criterium-1;
k = sum(e1); % Number of non stationary variables.
% Number of stationary variables: n = length(e1)-k

View File

@ -736,7 +736,7 @@ if iload <=0
end
run_index = 0; % reset index
end
if SampleSize > 1 && mod(iteration,3)
if SampleSize > 1
dyn_waitbar(iteration/SampleSize, h, ['MC identification checks ', int2str(iteration), '/', int2str(SampleSize)]);
end
end

View File

@ -12,7 +12,7 @@ function [cmm, mm] = simulated_moment_uncertainty(indx, periods, replic,options_
% - cmm: [n_moments by n_moments] covariance matrix of simulated moments
% - mm: [n_moments by replic] matrix of moments
% Copyright © 2009-2024 Dynare Team
% Copyright © 2009-2018 Dynare Team
%
% This file is part of Dynare.
%
@ -60,10 +60,15 @@ end
oo_.dr=set_state_space(oo_.dr,M_);
if options_.logged_steady_state %if steady state was previously logged, undo this
oo_.dr.ys=exp(oo_.dr.ys);
oo_.steady_state=exp(oo_.steady_state);
options_.logged_steady_state=0;
logged_steady_state_indicator=1;
evalin('base','options_.logged_steady_state=0;')
else
logged_steady_state_indicator=0;
end
[oo_.dr,info,M_.params] = compute_decision_rules(M_,options_,oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
@ -87,6 +92,7 @@ else
end
end
for j=1:replic
[ys, oo_.exo_simul] = simult(y0,oo_.dr,M_,options_);%do simulation
oo_=disp_moments(ys, options_.varobs,M_,options_,oo_); %get moments
@ -100,5 +106,8 @@ for j=1:replic
end
dyn_waitbar_close(h);
if logged_steady_state_indicator
evalin('base','options_.logged_steady_state=1;') %reset base workspace option to conform to base oo_
end
cmm = cov(mm');
disp('Simulated moment uncertainty ... done!')

View File

@ -479,7 +479,7 @@ if (~is_changed || occbin_smoother_debug) && nargin==12
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_smoothedshocks_occbin%s}\n',options_.figures.textwidth*min(j1/3,1),[GraphDirectoryName '/' M_.fname],int2str(ifig)); % don't use filesep as it will create issues with LaTeX on Windows
fprintf(fidTeX,'\\caption{OccBin smoothed shocks.}');
fprintf(fidTeX,'\\caption{Check plots.}');
fprintf(fidTeX,'\\label{Fig:smoothedshocks_occbin:%s}\n',int2str(ifig));
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
@ -488,7 +488,7 @@ if (~is_changed || occbin_smoother_debug) && nargin==12
end
end
if mod(j1,9)~=0 && j==M_.exo_nbr
if mod(j1,9)~=0 && j==M_.exo_nbr
annotation('textbox', [0.1,0,0.35,0.05],'String', 'Linear','Color','Blue','horizontalalignment','center','interpreter','none');
annotation('textbox', [0.55,0,0.35,0.05],'String', 'Piecewise','Color','Red','horizontalalignment','center','interpreter','none');
dyn_saveas(hh_fig,[GraphDirectoryName filesep M_.fname,'_smoothedshocks_occbin',int2str(ifig)],options_.nodisplay,options_.graph_format);
@ -497,7 +497,7 @@ if (~is_changed || occbin_smoother_debug) && nargin==12
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_smoothedshocks_occbin%s}\n',options_.figures.textwidth*min(j1/3,1),[GraphDirectoryName '/' M_.fname],int2str(ifig)); % don't use filesep as it will create issues with LaTeX on Windows
fprintf(fidTeX,'\\caption{OccBin smoothed shocks.}');
fprintf(fidTeX,'\\caption{Check plots.}');
fprintf(fidTeX,'\\label{Fig:smoothedshocks_occbin:%s}\n',int2str(ifig));
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
@ -505,6 +505,6 @@ if (~is_changed || occbin_smoother_debug) && nargin==12
end
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fclose(fidTeX);
end
end
end
end

View File

@ -1,169 +1,143 @@
function [forecast, error_flag] = forecast(options_,M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,forecast_horizon)
% [forecast, error_flag] = forecast(options_,M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,forecast_horizon)
% Occbin forecasts
%
% INPUTS
% - options_ [structure] Matlab's structure describing the current options
% - M_ [structure] Matlab's structure describing the model
% - dr_in [structure] model information structure
% - endo_steady_state [double] steady state value for endogenous variables
% - exo_steady_state [double] steady state value for exogenous variables
% - exo_det_steady_state [double] steady state value for exogenous deterministic variables
% - forecast_horizon [integer] forecast horizon
%
% OUTPUTS
% - forecast [structure] forecast results
% - error_flag [integer] error code
%
% SPECIAL REQUIREMENTS
% none.
% Copyright © 2022-2023 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 <https://www.gnu.org/licenses/>.
function [oo_, error_flag] = forecast(options_,M_,oo_,forecast) %,hist_period)
%function oo_ = forecast(options_,M_,oo_,forecast)
% forecast
opts = options_.occbin.forecast;
options_.occbin.simul.maxit = opts.maxit;
options_.occbin.simul.check_ahead_periods = opts.check_ahead_periods;
options_.occbin.simul.periods = forecast_horizon;
shocks_input = opts.SHOCKS0;
if ~isempty(shocks_input)
n_shocks=size(shocks_input,1);
if iscell(shocks_input)
inds=NaN(n_shocks,1);
periods=length(shocks_input{1}{2});
shock_mat=NaN(n_shocks,periods);
for j=1:n_shocks
exo_pos=strmatch(shocks_input{j}{1},M_.exo_names,'exact');
if isempty(exo_pos)
error('occbin.forecast: unknown exogenous shock %s',shocks_input{j}{1})
else
inds(j)=exo_pos;
end
if length(shocks_input{j}{2})~=periods
error('occbin.forecast: unknown exogenous shock %s',shocks_input{j}{1})
else
shock_mat(j,:)=shocks_input{j}{2};
end
options_.occbin.simul.periods = forecast;
SHOCKS0 = opts.SHOCKS0;
if ~isempty(SHOCKS0)
if iscell(SHOCKS0)
for j=1:length(SHOCKS0)
sname = SHOCKS0{j}{1};
inds(j)=strmatch(sname,M_.exo_names);
SHOCKS1(j,:)=SHOCKS0{j}{2};
end
elseif isreal(shocks_input)
shock_mat=shocks_input;
inds = (1:M_.exo_nbr)';
elseif isreal(SHOCKS0)
SHOCKS1=SHOCKS0;
inds = 1:M_.exo_nbr;
end
end
options_.occbin.simul.endo_init = M_.endo_histval(:,1)-endo_steady_state; %initial condition
options_.occbin.simul.init_regime = opts.frcst_regimes;
options_.occbin.simul.init_binding_indicator = [];
shocks_base = zeros(forecast_horizon,M_.exo_nbr);
if ~isempty(shocks_input)
for j=1:n_shocks
shocks_base(:,inds(j))=shock_mat(j,:);
end
end
if opts.replic
h = dyn_waitbar(0,'Please wait occbin forecast replic ...');
ishock = find(sqrt(diag((M_.Sigma_e))));
options_.occbin.simul.exo_pos=ishock;
effective_exo_nbr= length(ishock);
effective_Sigma_e = M_.Sigma_e(ishock,ishock); % does not take heteroskedastic shocks into account
effective_exo_names = M_.exo_names(ishock);
effective_Sigma_e = M_.Sigma_e(ishock,ishock);
[U,S] = svd(effective_Sigma_e);
% draw random shocks
if opts.qmc
opts.replic =2^(round(log2(opts.replic+1)))-1;
SHOCKS_add = qmc_sequence(forecast_horizon*effective_exo_nbr, int64(1), 1, opts.replic);
SHOCKS_ant = qmc_sequence(forecast*effective_exo_nbr, int64(1), 1, opts.replic)';
else
SHOCKS_add = randn(forecast_horizon*effective_exo_nbr,opts.replic);
SHOCKS_ant = randn(forecast*effective_exo_nbr,opts.replic)';
end
SHOCKS_add=reshape(SHOCKS_add,effective_exo_nbr,forecast_horizon,opts.replic);
z.linear=NaN(forecast_horizon,M_.endo_nbr,opts.replic);
z.piecewise=NaN(forecast_horizon,M_.endo_nbr,opts.replic);
error_flag=true(opts.replic,1);
simul_SHOCKS=NaN(forecast_horizon,M_.exo_nbr,opts.replic);
zlin0=zeros(forecast,M_.endo_nbr,opts.replic);
zpiece0=zeros(forecast,M_.endo_nbr,opts.replic);
for iter=1:opts.replic
options_.occbin.simul.SHOCKS = shocks_base+transpose(U*sqrt(S)*SHOCKS_add(:,:,iter));
options_.occbin.simul.waitbar=0;
[~, out] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
error_flag(iter)=out.error_flag;
if ~error_flag(iter)
z.linear(:,:,iter)=out.linear;
z.piecewise(:,:,iter)=out.piecewise;
frcst_regime_history(iter,:)=out.regime_history;
error_flag(iter)=out.error_flag;
simul_SHOCKS(:,:,iter) = shocks_base;
else
if options_.debug
save('Occbin_forecast_debug','simul_SHOCKS','z','iter','frcst_regime_history','error_flag','out','shocks_base')
if ~isempty(SHOCKS0)
for j=1:length(SHOCKS0)
SHOCKS(:,inds(j))=SHOCKS1(j,:);
end
end
error_flagx=1;
% while error_flagx,
% SHOCKS=transpose(sqrt(diag(diag(effective_Sigma_e)))*(reshape(SHOCKS_ant(iter,:),forecast,effective_exo_nbr))');
SHOCKS=transpose(U*sqrt(S)*(reshape(SHOCKS_ant(iter,:),forecast,effective_exo_nbr))');
% SHOCKS=transpose(U*sqrt(S)*randn(forecast,M_.exo_nbr)'); %realized shocks
options_.occbin.simul.endo_init = M_.endo_histval(:,1)-oo_.steady_state;
options_.occbin.simul.init_regime = opts.frcst_regimes;
options_.occbin.simul.init_binding_indicator = [];
options_.occbin.simul.exo_pos=ishock;
options_.occbin.simul.SHOCKS = SHOCKS;
options_.occbin.simul.waitbar=0;
[~, out] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
zlin0(:,:,iter)=out.linear;
zpiece0(:,:,iter)=out.piecewise;
ys=out.ys;
frcst_regime_history(iter,:)=out.regime_history;
error_flag(iter)=out.error_flag;
error_flagx = error_flag(iter);
% end
simul_SHOCKS(:,:,iter) = SHOCKS;
if error_flag(iter) && debug_flag
% display('no solution')
% keyboard;
save no_solution SHOCKS zlin0 zpiece0 iter frcst_regime_history
end
dyn_waitbar(iter/opts.replic,h,['OccBin MC forecast replic ',int2str(iter),'/',int2str(opts.replic)])
end
dyn_waitbar_close(h);
if options_.debug
save('Occbin_forecast_debug','simul_SHOCKS','z','iter','frcst_regime_history','error_flag')
end
save temp zlin0 zpiece0 simul_SHOCKS error_flag
inx=find(error_flag==0);
z.linear=z.linear(:,:,inx);
z.piecewise=z.piecewise(:,:,inx);
z.min.piecewise = min(z.piecewise,[],3);
z.max.piecewise = max(z.piecewise,[],3);
z.min.linear = min(z.linear,[],3);
z.max.linear = max(z.linear,[],3);
field_names={'linear','piecewise'};
post_mean=NaN(forecast_horizon,1);
post_median=NaN(forecast_horizon,1);
post_var=NaN(forecast_horizon,1);
hpd_interval=NaN(forecast_horizon,2);
post_deciles=NaN(forecast_horizon,9);
for field_iter=1:2
for i=1:M_.endo_nbr
for j=1:forecast_horizon
[post_mean(j,1), post_median(j,1), post_var(j,1), hpd_interval(j,:), post_deciles(j,:)] = posterior_moments(squeeze(z.(field_names{field_iter})(j,i,:)),options_.forecasts.conf_sig);
end
forecast.(field_names{field_iter}).Mean.(M_.endo_names{i})=post_mean;
forecast.(field_names{field_iter}).Median.(M_.endo_names{i})=post_median;
forecast.(field_names{field_iter}).Var.(M_.endo_names{i})=post_var;
forecast.(field_names{field_iter}).HPDinf.(M_.endo_names{i})=hpd_interval(:,1);
forecast.(field_names{field_iter}).HPDsup.(M_.endo_names{i})=hpd_interval(:,2);
forecast.(field_names{field_iter}).Deciles.(M_.endo_names{i})=post_deciles;
forecast.(field_names{field_iter}).Min.(M_.endo_names{i})=z.min.(field_names{field_iter})(:,i);
forecast.(field_names{field_iter}).Max.(M_.endo_names{i})=z.max.(field_names{field_iter})(:,i);
zlin0=zlin0(:,:,inx);
zpiece0=zpiece0(:,:,inx);
zlin = mean(zlin0,3);
zpiece = mean(zpiece0,3);
zpiecemin = min(zpiece0,[],3);
zpiecemax = max(zpiece0,[],3);
zlinmin = min(zlin0,[],3);
zlinmax = max(zlin0,[],3);
for i=1:M_.endo_nbr
for j=1:forecast
[post_mean(j,1), post_median(j,1), post_var(j,1), hpd_interval(j,:), post_deciles(j,:)] = posterior_moments(squeeze(zlin0(j,i,:)),options_.forecasts.conf_sig);
end
end
else
options_.occbin.simul.irfshock = M_.exo_names;
options_.occbin.simul.SHOCKS = shocks_base;
[~, out] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
error_flag=out.error_flag;
if out.error_flag
fprintf('occbin.forecast: forecast simulation failed.')
return;
oo_.occbin.linear_forecast.Mean.(M_.endo_names{i})=post_mean;
oo_.occbin.linear_forecast.Median.(M_.endo_names{i})=post_median;
oo_.occbin.linear_forecast.Var.(M_.endo_names{i})=post_var;
oo_.occbin.linear_forecast.HPDinf.(M_.endo_names{i})=hpd_interval(:,1);
oo_.occbin.linear_forecast.HPDsup.(M_.endo_names{i})=hpd_interval(:,2);
oo_.occbin.linear_forecast.Deciles.(M_.endo_names{i})=post_deciles;
oo_.occbin.linear_forecast.Min.(M_.endo_names{i})=zlinmin(:,i);
oo_.occbin.linear_forecast.Max.(M_.endo_names{i})=zlinmax(:,i);
for j=1:forecast
[post_mean(j,1), post_median(j,1), post_var(j,1), hpd_interval(j,:), post_deciles(j,:)] = posterior_moments(squeeze(zpiece0(j,i,:)),options_.forecasts.conf_sig);
end
oo_.occbin.forecast.Mean.(M_.endo_names{i})=post_mean;
oo_.occbin.forecast.Median.(M_.endo_names{i})=post_median;
oo_.occbin.forecast.Var.(M_.endo_names{i})=post_var;
oo_.occbin.forecast.HPDinf.(M_.endo_names{i})=hpd_interval(:,1);
oo_.occbin.forecast.HPDsup.(M_.endo_names{i})=hpd_interval(:,2);
oo_.occbin.forecast.Deciles.(M_.endo_names{i})=post_deciles;
oo_.occbin.forecast.Min.(M_.endo_names{i})=zpiecemin(:,i);
oo_.occbin.forecast.Max.(M_.endo_names{i})=zpiecemax(:,i);
% eval([M_.endo_names{i},'_ss=zdatass(i);']);
end
else
SHOCKS = zeros(forecast,M_.exo_nbr);
if ~isempty(SHOCKS0)
for j=1:length(SHOCKS0)
SHOCKS(:,inds(j))=SHOCKS1(j,:);
end
end
options_.occbin.simul.endo_init = M_.endo_histval(:,1)-oo_.steady_state;
options_.occbin.simul.init_regime = opts.frcst_regimes;
options_.occbin.simul.init_violvecbool = [];
options_.occbin.simul.irfshock = M_.exo_names;
options_.occbin.simul.SHOCKS = SHOCKS;
[~, out] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
zlin=out.linear;
zpiece=out.piecewise;
frcst_regime_history=out.regime_history;
error_flag=out.error_flag;
for i=1:M_.endo_nbr
forecast.linear.Mean.(M_.endo_names{i})= out.linear(:,i);
forecast.piecewise.Mean.(M_.endo_names{i})= out.piecewise(:,i);
oo_.occbin.linear_forecast.Mean.(M_.endo_names{i})= zlin(:,i);
oo_.occbin.forecast.Mean.(M_.endo_names{i})= zpiece(:,i);
oo_.occbin.forecast.HPDinf.(M_.endo_names{i})= nan;
oo_.occbin.forecast.HPDsup.(M_.endo_names{i})= nan;
end
end
forecast.regimes=frcst_regime_history;
oo_.occbin.forecast.regimes=frcst_regime_history;

View File

@ -1,124 +1,140 @@
function irfs = irf(M_,oo_,options_)
% irfs = irf(M_,oo_,options_)
% Calls a minimizer
%
% INPUTS
% - M_ [structure] Matlab's structure describing the model
% - oo_ [structure] Matlab's structure containing the results
% - options_ [structure] Matlab's structure describing the current options
%
% OUTPUTS
% - irfs [structure] IRF results
%
% SPECIAL REQUIREMENTS
% none.
%
%
% Copyright © 2022-2023 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 <https://www.gnu.org/licenses/>.
function [oo_] = irf(M_,oo_,options_)
shocknames = options_.occbin.irf.exo_names;
shocksigns = options_.occbin.irf.shocksigns; %'pos','neg'
shocksigns = options_.occbin.irf.shocksigns;
shocksize = options_.occbin.irf.shocksize;
t_0 = options_.occbin.irf.t0;
%% set simulation options based on IRF options
t0 = options_.occbin.irf.t0;
options_.occbin.simul.init_regime = options_.occbin.irf.init_regime;
options_.occbin.simul.check_ahead_periods = options_.occbin.irf.check_ahead_periods;
options_.occbin.simul.maxit = options_.occbin.irf.maxit;
options_.occbin.simul.periods = options_.irf;
%% Run initial conditions + other shocks
if t_0 == 0
shocks_base = zeros(options_.occbin.simul.periods+1,M_.exo_nbr);
% Run inital conditions + other shocks
if t0 == 0
shocks0= zeros(options_.occbin.simul.periods+1,M_.exo_nbr);
options_.occbin.simul.endo_init = [];
else
if ~isfield(oo_.occbin,'smoother')
error('occbin.irfs: smoother must be run before requesting GIRFs based on smoothed results')
end
% GIRF conditional on smoothed states in t_0 and shocks in t_0+1
shocks_base= [oo_.occbin.smoother.etahat(:,t_0+1)'; zeros(options_.occbin.simul.periods,M_.exo_nbr)];
options_.occbin.simul.SHOCKS=shocks_base;
options_.occbin.simul.endo_init = oo_.occbin.smoother.alphahat(oo_.dr.inv_order_var,t_0);
% girf conditional to smoothed states in t0 and shocks in t0+1
shocks0= [oo_.occbin.smoother.etahat(:,t0+1)'; zeros(options_.occbin.simul.periods,M_.exo_nbr)];
options_.occbin.simul.SHOCKS=shocks0;
options_.occbin.simul.endo_init = oo_.occbin.smoother.alphahat(oo_.dr.inv_order_var,t0);
end
options_.occbin.simul.SHOCKS=shocks_base;
options_.occbin.simul.SHOCKS=shocks0;
[~, out0] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
zlin0 = out0.linear;
zpiece0 = out0.piecewise;
[~, out_base] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
if out_base.error_flag
error('occbin.irfs: could not compute the solution')
end
% Select shocks of interest
jexo_all =zeros(size(shocknames,1),1);
irfs.linear = struct();
irfs.piecewise = struct();
% Get indices of shocks of interest
exo_index =zeros(size(shocknames,1),1);
for i=1:length(shocknames)
exo_index(i) = strmatch(shocknames{i},M_.exo_names,'exact');
jexo_all(i) = strmatch(shocknames{i},M_.exo_names,'exact');
end
% cs=get_lower_cholesky_covariance(M_.Sigma_e,options_.add_tiny_number_to_cholesky);
% irf_shocks_indx = getIrfShocksIndx(M_, options_);
oo_.occbin.linear_irfs = struct();
oo_.occbin.irfs = struct();
% Set shock size
if isempty(shocksize)
shocksize = sqrt(diag(M_.Sigma_e(exo_index,exo_index)));
% if isfield(oo_.posterior_mode.shocks_std,M_.exo_names{jexo})
shocksize = sqrt(diag(M_.Sigma_e(jexo_all,jexo_all))); %oo_.posterior_mode.shocks_std.(M_.exo_names{jexo});
if any(shocksize < 1.e-9)
shocksize(shocksize < 1.e-9) = 0.01;
end
end
if numel(shocksize)==1
shocksize=repmat(shocksize,[length(shocknames),1]);
end
% Run IRFs
for sign_iter=1:length(shocksigns)
for IRF_counter = 1:length(exo_index)
jexo = exo_index(IRF_counter);
if ~options_.noprint && options_.debug
fprintf('occbin.irf: Producing GIRFs for shock %s. Simulation %d out of %d. \n',M_.exo_names{jexo},IRF_counter,size(exo_index,1));
end
shocks1=shocks_base;
if ismember('pos',shocksigns{sign_iter})
shocks1(1,jexo)=shocks_base(1,jexo)+shocksize(IRF_counter);
elseif ismember('neg',shocksigns{sign_iter})
shocks1(1,jexo)=shocks_base(1,jexo)-shocksize(IRF_counter);
end
options_.occbin.simul.SHOCKS=shocks1;
if t_0 == 0
for counter = 1:length(jexo_all)
jexo = jexo_all(counter);
if ~options_.noprint
fprintf('Producing GIRFs for shock %s. Simulation %d out of %d. \n',M_.exo_names{jexo},counter,size(jexo_all,1));
end
if ismember('pos',shocksigns)
% (+) shock
shocks1=shocks0;
shocks1(1,jexo)=shocks0(1,jexo)+shocksize(counter);
if t0 == 0
options_.occbin.simul.SHOCKS=shocks1;
options_.occbin.simul.endo_init = [];
[~, out_pos] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
else
options_.occbin.simul.endo_init = oo_.occbin.smoother.alphahat(oo_.dr.inv_order_var,t_0);
options_.occbin.simul.SHOCKS=shocks1;
options_.occbin.simul.endo_init = oo_.occbin.smoother.alphahat(oo_.dr.inv_order_var,t0);
[~, out_pos] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
end
[~, out_sim] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
if out_sim.error_flag
warning('occbin.irfs: simulation failed')
skip
if out_pos.error_flag
warning('Occbin error.')
return
end
zlin_pos = out_pos.linear;
zpiece_pos = out_pos.piecewise;
% Substract inital conditions + other shocks
zdiff.linear.(shocksigns{sign_iter}) = out_sim.linear-out_base.linear;
zdiff.piecewise.(shocksigns{sign_iter}) = out_sim.piecewise-out_base.piecewise;
for j_endo=1:M_.endo_nbr
if ismember('pos',shocksigns)
irfs.piecewise.([M_.endo_names{j_endo} '_' M_.exo_names{jexo} '_' shocksigns{sign_iter}]) = zdiff.piecewise.(shocksigns{sign_iter})(:,j_endo);
irfs.linear.([M_.endo_names{j_endo} '_' M_.exo_names{jexo} '_' shocksigns{sign_iter}]) = zdiff.linear.(shocksigns{sign_iter})(:,j_endo);
end
end
zlin_pos_diff = zlin_pos-zlin0;
zpiece_pos_diff = zpiece_pos-zpiece0;
end
end
if ismember('neg',shocksigns)
% (-) shock
shocks_1=shocks0;
shocks_1(1,jexo)=shocks0(1,jexo)-shocksize(counter);
if t0 == 0
options_.occbin.simul.SHOCKS=shocks_1;
options_.occbin.simul.endo_init = [];
[~, out_neg] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
else
options_.occbin.simul.SHOCKS=shocks_1;
options_.occbin.simul.endo_init = oo_.occbin.smoother.alphahat(oo_.dr.inv_order_var,t0);
[~, out_neg] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
end
if out_neg.error_flag
warning('Occbin error.')
return
end
zlin_neg = out_neg.linear;
zpiece_neg = out_neg.piecewise;
zlin_neg_diff = zlin_neg-zlin0;
zpiece_neg_diff = zpiece_neg-zpiece0;
end
% Save
if ~isfield(oo_.occbin,'linear_irfs')
oo_.occbin.linear_irfs = struct();
end
if ~isfield(oo_.occbin,'irfs')
oo_.occbin.irfs = struct();
end
for jendo=1:M_.endo_nbr
% oo_.occbin.irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '1']) = zpiece_pos (:,jendo);
% oo_.occbin.irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_1']) = zpiece_neg (:,jendo);
% oo_.occbin.linear_irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '1']) = zlin_pos (:,jendo);
% oo_.occbin.linear_irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_1']) = zlin_neg(:,jendo);
if ismember('pos',shocksigns)
oo_.occbin.irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_pos']) = zpiece_pos_diff (:,jendo);
oo_.occbin.linear_irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_pos']) = zlin_pos_diff (:,jendo);
end
if ismember('neg',shocksigns)
oo_.occbin.irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_neg']) = zpiece_neg_diff (:,jendo);
oo_.occbin.linear_irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_neg']) = zlin_neg_diff (:,jendo);
end
% %
% oo_.occbin.irfs0.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '1']) = zpiece0(:,jendo);
% oo_.occbin.linear_irfs0.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '1']) = zlin0(:,jendo);
% oo_.occbin.irfs0.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_1']) = zpiece0(:,jendo);
% oo_.occbin.linear_irfs0.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_1']) = zlin0(:,jendo);
end
end
end

View File

@ -1,74 +1,34 @@
function plot_irfs(M_,irfs,options_,var_list)
% plot_irfs(M_,irfs,options_,var_list)
%
% INPUTS
% - M_ [structure] Matlab's structure describing the model
% - irfs [structure] IRF results
% - options_ [structure] Matlab's structure describing the current options
% - var_list [character array] list of endogenous variables specified
%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none.
function plot_irfs(M_,oo_,options_,irf3,irf4)
% Copyright © 2022-2023 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 <https://www.gnu.org/licenses/>.
if (isfield(options_,'irf_shocks')==0)
shock_names = M_.exo_names;
else
shock_names = options_.irf_shocks;
shocknames = options_.occbin.plot_irf.exo_names;
simulname = options_.occbin.plot_irf.simulname;
if isempty(simulname)
simulname_ = simulname;
else
simulname_ = [ simulname '_' ];
end
simul_name = options_.occbin.plot_irf.simulname;
if isempty(simul_name)
save_name = simul_name;
else
save_name = [ simul_name '_' ];
end
if isempty(var_list)
var_list = M_.endo_names(1:M_.orig_endo_nbr);
end
[i_var, ~, index_uniques] = varlist_indices(var_list, M_.endo_names);
vars_irf=var_list(index_uniques);
vars_irf = options_.occbin.plot_irf.endo_names;
endo_names_long = options_.occbin.plot_irf.endo_names_long;
endo_scaling_factor = options_.occbin.plot_irf.endo_scaling_factor;
length_irf = options_.irf;
length_irf = options_.occbin.plot_irf.tplot;
if isempty(length_irf)
length_irf = options_.irf;
end
steps_irf = 1;
irflocation_lin = oo_.occbin.linear_irfs;
irflocation_piece = oo_.occbin.irfs;
steps_irf = 1;
warning('off','all')
DirectoryName = CheckPath('graphs',M_.dname);
latexFolder = CheckPath('latex',M_.dname);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([latexFolder '/' M_.fname '_occbin_irfs.tex'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by occbin.plot_irfs.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
end
iexo=[];
for var_iter=1:size(shock_names,1)
itemp = strmatch(shock_names{var_iter},M_.exo_names,'exact');
for i=1:size(shocknames,1)
itemp = strmatch(shocknames{i},M_.exo_names,'exact');
if isempty(itemp)
error(['Shock ',shock_names{var_iter},' is not defined!'])
error(['Shock ',shocknames{i},' is not defined!'])
else
iexo=[iexo, itemp];
end
@ -78,102 +38,104 @@ ncols = options_.occbin.plot_irf.ncols;
nrows = options_.occbin.plot_irf.nrows;
npan = ncols*nrows;
shocksigns = options_.occbin.plot_irf.shocksigns;
threshold = options_.impulse_responses.plot_threshold;
plot_grid = options_.occbin.plot_irf.grid;
shocksigns = options_.occbin.plot_irf.shocksigns;
threshold = options_.occbin.plot_irf.threshold;
% Add steady_state
if options_.occbin.plot_irf.add_steadystate
add_stst = options_.occbin.plot_irf.add_steadystate;
else
add_stst = 0;
end
for sss = 1:numel(shocksigns)
shocksign = shocksigns{sss};
for j=1:size(shocknames,1)
%shocknames = M_.exo_names{j};
for shock_sign_iter = 1:numel(shocksigns)
shocksign = shocksigns{shock_sign_iter};
if strcmp(shocksign,'pos')
plot_title_sign='positive';
elseif strcmp(shocksign,'neg')
plot_title_sign='negative';
else
error('Unknown shock sign %s',shocksign);
end
for shock_iter=1:size(shock_names,1)
j1 = 0;
isub = 0;
ifig = 0;
% Variables
for var_iter = 1:length(vars_irf)
% ----------------------
for i = 1:length(vars_irf)
j1=j1+1;
if mod(j1,npan)==1
% vector corresponds to [left bottom width height]. 680 and 678 for the left and bottom elements correspond to the default values used by MATLAB while creating a figure and width, .
screensize = get( groot, 'Screensize' );
hfig = dyn_figure(options_.nodisplay,'name',['OccBin IRFs to ' plot_title_sign ' ' shock_names{shock_iter} ' shock ' simul_name],'OuterPosition' ,[50 50 min(1000,screensize(3)-50) min(750,screensize(4)-50)]);
% vector corresponds to [left bottom width height]. 680 and 678 for the left and bottom elements correspond to the default values used by MATLAB while creating a figure and width, .
hfig = dyn_figure(options_.nodisplay,'name',['OccbinIRFs ' shocknames{j} ' ' simulname ' ' shocksign],'PaperPositionMode', 'auto','PaperType','A4','PaperOrientation','portrait','renderermode','auto','position',[10 10 950 650]);
ifig=ifig+1;
isub=0;
end
isub=isub+1;
isub=isub+1;
if isempty(endo_scaling_factor)
exofactor = 1;
else
exofactor = endo_scaling_factor{var_iter};
end
else
exofactor = endo_scaling_factor{i};
end
subplot(nrows,ncols,isub)
irf_field = strcat(vars_irf{var_iter},'_',shock_names{shock_iter},'_',shocksign);
%%linear IRFs
if ~isfield(irfs.linear,irf_field)
warning('occbin.plot_irfs: no linear IRF for %s to %s detected',vars_irf{var_iter,1},shock_names{shock_iter})
else
irfvalues = irfs.linear.(irf_field);
irfvalues(abs(irfvalues) <threshold) = 0;
if options_.occbin.plot_irf.add_steadystate
irfvalues = irfvalues + get_mean(vars_irf{var_iter,1});
end
max_irf_length_1=min(length_irf,length(irfvalues));
plot(irfvalues(1:steps_irf:max_irf_length_1)*exofactor,'linewidth',2);
end
subplot(nrows,ncols,isub)
irf_field = strcat(vars_irf{i,1},'_',shocknames{j},'_',shocksign);
irfvalues = irflocation_lin.(irf_field);
if add_stst
irfvalues = irfvalues + get_mean(vars_irf{i,1});
end
irfvalues(abs(irfvalues) <threshold) = 0;
plot(irfvalues(1:steps_irf:length_irf)*exofactor,'linewidth',2);
hold on
if ~isfield(irfs.piecewise,irf_field)
warning('occbin.plot_irfs: no piecewise linear IRF for %s to %s detected',vars_irf{var_iter,1},shock_names{shock_iter})
else
irfvalues = irfs.piecewise.(irf_field);
irfvalues(abs(irfvalues) <threshold) = 0;
if options_.occbin.plot_irf.add_steadystate
irfvalues = irfvalues + get_mean(vars_irf{var_iter,1});
end
max_irf_length_2=min(length_irf,length(irfvalues));
plot(irfvalues(1:steps_irf:max_irf_length_2)*exofactor,'r--','linewidth',2);
irfvalues = irflocation_piece.(irf_field);
if add_stst
irfvalues = irfvalues + get_mean(vars_irf{i,1});
end
irfvalues(abs(irfvalues) <threshold) = 0;
plot(irfvalues(1:steps_irf:length_irf)*exofactor,'r--','linewidth',2);
hold on
plot(irfvalues(1:steps_irf:length_irf)*0,'k-','linewidth',1.5);
% Optional additional IRFs
if nargin > 10
irfvalues = irf3.(irf_field) ;
irfvalues(abs(irfvalues) <threshold) = 0;
plot(irfvalues(1:steps_irf:length_irf)*exofactor,'k:','linewidth',2);
end
if nargin > 11
irfvalues = irf4.(irf_field) ;
irfvalues(abs(irfvalues) <threshold) = 0;
plot(irfvalues(1:steps_irf:length_irf)*exofactor,'g-.','linewidth',2);
end
plot(irfvalues(1:steps_irf:max(max_irf_length_1,max_irf_length_2))*0,'k-','linewidth',1.5);
if options_.occbin.plot_irf.grid
if plot_grid
grid on
end
xlim([1 max(max_irf_length_1,max_irf_length_2)]);
if options_.TeX
title(['$' M_.endo_names_tex{i_var(var_iter)}, '$'],'Interpreter','latex')
else
title(M_.endo_names{i_var(var_iter)},'Interpreter','none')
end
xlim([1 (length_irf/steps_irf)]);
% title
if isempty(endo_names_long)
title(regexprep(vars_irf{i},'_',' '))
else
title(endo_names_long{i})
end
% Annotation Box + save figure
% ----------------------
if mod(j1,npan)==0 || (mod(j1,npan)~=0 && var_iter==length(vars_irf))
if mod(j1,npan)==0 || (mod(j1,npan)~=0 && i==length(vars_irf))
annotation('textbox', [0.1,0,0.35,0.05],'String', 'Linear','Color','Blue','horizontalalignment','center','interpreter','none');
annotation('textbox', [0.55,0,0.35,0.05],'String', 'Piecewise','Color','Red','horizontalalignment','center','interpreter','none');
dyn_saveas(hfig,[DirectoryName,filesep,M_.fname,'_irf_occbin_',save_name,shock_names{shock_iter},'_',shocksign,'_',int2str(ifig)],options_.nodisplay,options_.graph_format);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_irf_occbin_%s}\n',options_.figures.textwidth*min((j1-1)/ncols,1),...
[DirectoryName '/' ,M_.fname],[save_name,shock_names{shock_iter},'_',shocksign,'_',int2str(ifig)]);
fprintf(fidTeX,'\\caption{OccBin IRFs to %s shock to %s}\n',plot_title_sign,shock_names{shock_iter});
fprintf(fidTeX,'\\label{Fig:occbin_irfs:%s}\n',[save_name,shock_names{shock_iter},'_',shocksign,'_',int2str(ifig)]);
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,'\n');
end
dyn_saveas(hfig,[DirectoryName,filesep,M_.fname,'_irf_occbin_',simulname_,shocknames{j},'_',shocksign,'_',int2str(ifig)],options_.nodisplay,options_.graph_format);
end
end
end
end
end
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'%% End Of TeX file.');
fclose(fidTeX);
warning('on','all')
end

View File

@ -1,26 +1,4 @@
function plot_regimes(regimes,M_,options_)
% plot_regimes(regimes,M_,options_)
% Inputs:
% - regimes [structure] OccBin regime information
% - M_ [structure] Matlab's structure describing the model
% - options_ [structure] Matlab's structure containing the options
% Copyright © 2021-2023 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 <https://www.gnu.org/licenses/>.
nperiods = size(regimes,2);
nconstr = length(fieldnames(regimes(1)))/2;
@ -35,15 +13,9 @@ else
end
GraphDirectoryName = CheckPath('graphs',M_.dname);
fhandle = dyn_figure(options_.nodisplay,'Name',[M_.fname ': OccBin regimes']);
latexFolder = CheckPath('latex',M_.dname);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([latexFolder '/' M_.fname '_occbin_regimes.tex'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by occbin.plot_regimes.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
end
fhandle = dyn_figure(options_.nodisplay,'Name',[M_.fname ' occbin regimes']);
for k=1:nconstr
subplot(nconstr,1,k)
@ -64,23 +36,12 @@ for k=1:nconstr
end
end
end
xlim([1 nperiods])
title(['Regime ' int2str(k)])
xlabel('Historic period')
ylabel('Regime: expected start')
title(['regime ' int2str(k)])
xlabel('historic period')
ylabel('regime expected start')
end
annotation('textbox',[.25,0,.15,.05],'String','Slack','Color','blue');
annotation('textbox',[.65,0,.2,.05],'String','Binding','Color','red');
annotation('textbox',[.25,0,.15,.05],'String','Unbinding','Color','blue');
annotation('textbox',[.65,0,.15,.05],'String','Binding','Color','red');
dyn_saveas(fhandle,[GraphDirectoryName, filesep, M_.fname '_occbin_regimes'],options_.nodisplay,options_.graph_format);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_occbin_regimes}\n',options_.figures.textwidth,[GraphDirectoryName '/' M_.fname]);
fprintf(fidTeX,'\\caption{OccBin: regime evolution over time.}\n');
fprintf(fidTeX,'\\label{Fig:occbin_regimes}\n');
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,'\n');
fclose(fidTeX);
end

View File

@ -55,7 +55,9 @@ if ismember(flag,{'forecast','all'})
options_occbin_.forecast.maxit=30;
options_occbin_.forecast.qmc=0;
options_occbin_.forecast.replic=0;
options_occbin_.forecast.sepath=0;
options_occbin_.forecast.SHOCKS0=[];
options_occbin_.forecast.treepath=1; % number of branches
end
if ismember(flag,{'irf','all'})
@ -96,12 +98,17 @@ end
if ismember(flag,{'plot_irf','all'})
options_occbin_.plot_irf.add_steadystate = 0;
options_occbin_.plot_irf.exo_names = [];
options_occbin_.plot_irf.endo_names = M_.endo_names;
options_occbin_.plot_irf.endo_names_long = [];
options_occbin_.plot_irf.endo_scaling_factor = [];
options_occbin_.plot_irf.grid = true;
options_occbin_.plot_irf.ncols = 3;
options_occbin_.plot_irf.nrows = 3;
options_occbin_.plot_irf.shocksigns = {'pos','neg'};
options_occbin_.plot_irf.simulname='';
options_occbin_.plot_irf.threshold = 10^-6;
options_occbin_.plot_irf.tplot = [];
end
if ismember(flag,{'plot_shock_decomp','all'})

View File

@ -13,7 +13,7 @@ function M_ = parameters(pacname, M_, oo_, verbose)
% SPECIAL REQUIREMENTS
% none
% Copyright © 2018-2024 Dynare Team
% Copyright © 2018-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -78,11 +78,6 @@ else
numberofcomponents = 0;
end
% Makes no sense to have a composite PAC target with a trend component auxiliary model (where all the variables are non stationnary)
if numberofcomponents>0 && strcmp(M_.pac.pacman.auxiliary_model_type, 'trend_component')
error('Composite PAC target not allowed with trend component model.')
end
% Build the vector of PAC parameters (ECM parameter + autoregressive parameters).
pacvalues = M_.params([pacmodel.ec.params; pacmodel.ar.params(1:pacmodel.max_lag)']);
@ -95,7 +90,7 @@ if numberofcomponents
% Find the auxiliary variables if any
ad = find(cell2mat(cellfun(@(x) isauxiliary(x, [8 10]), varmodel.list_of_variables_in_companion_var, 'UniformOutput', false)));
if isempty(ad)
error('Cannot find the trend variable in the Companion VAR model.')
error('Cannot find the trend variable in the Companion VAR/VECM model.')
else
for j=1:length(ad)
auxinfo = M_.aux_vars(get_aux_variable_id(varmodel.list_of_variables_in_companion_var{ad(j)}));
@ -110,7 +105,7 @@ if numberofcomponents
end
end
if isempty(id{i})
error('Cannot find the trend variable in the Companion VAR model.')
error('Cannot find the trend variable in the Companion VAR/VECM model.')
end
end
end
@ -120,7 +115,7 @@ else
% Find the auxiliary variables if any
ad = find(cell2mat(cellfun(@(x) isauxiliary(x, [8 10]), varmodel.list_of_variables_in_companion_var, 'UniformOutput', false)));
if isempty(ad)
error('Cannot find the trend variable in the auxiliary VAR / Trend component model.')
error('Cannot find the trend variable in the Companion VAR/VECM model.')
else
for i=1:length(ad)
auxinfo = M_.aux_vars(get_aux_variable_id(varmodel.list_of_variables_in_companion_var{ad(i)}));
@ -135,7 +130,7 @@ else
end
end
if isempty(id{1})
error('Cannot find the trend variable in the auxiliary VAR / Trend component model.')
error('Cannot find the trend variable in the Companion VAR/VECM model.')
end
end
end

View File

@ -15,7 +15,7 @@ function simulation = simul_static_model(samplesize, innovations)
% [2] The last input argument is not mandatory. If absent we use random draws and rescale them with the informations provided
% through the shocks block.
% Copyright © 2019-2024 Dynare Team
% Copyright © 2019-2022 Dynare Team
%
% This file is part of Dynare.
%
@ -83,17 +83,12 @@ else
oo_.exo_simul = Innovations;
end
static_resid = str2func(sprintf('%s.sparse.static_resid', M_.fname));
static_g1 = str2func(sprintf('%s.sparse.static_g1', M_.fname));
function [resid, g1] = staticmodel(y, x, params)
[resid, T_order, T] = static_resid(y, x, params);
g1 = static_g1(y, x, params, M_.static_g1_sparse_rowval, M_.static_g1_sparse_colval, M_.static_g1_sparse_colptr, T_order, T);
end
staticmodel = str2func(sprintf('%s.static', M_.fname));
% Simulations (call a Newton-like algorithm for each period).
for t=1:samplesize
y = zeros(M_.endo_nbr, 1);
[oo_.endo_simul(:,t), errorflag, ~, ~, errorcode] = dynare_solve(@staticmodel, y, options_.simul.maxit, options_.dynatol.f, options_.dynatol.x, options_, oo_.exo_simul(t,:), M_.params);
[oo_.endo_simul(:,t), errorflag, ~, ~, errorcode] = dynare_solve(staticmodel, y, options_.simul.maxit, options_.dynatol.f, options_.dynatol.x, options_, oo_.exo_simul(t,:), M_.params);
if errorflag
dprintf('simul_static_mode: Nonlinear solver failed with errorcode=%i in period %i.', errorcode, t)
oo_.endo_simul(:,t) = nan;
@ -108,6 +103,4 @@ if isdseries(innovations)
initperiod = innovations.dates(1);
end
simulation = [dseries(ysim', initperiod, M_.endo_names(1:M_.orig_endo_nbr)), dseries(xsim, initperiod, M_.exo_names)];
end
simulation = [dseries(ysim', initperiod, M_.endo_names(1:M_.orig_endo_nbr)), dseries(xsim, initperiod, M_.exo_names)];

View File

@ -1,58 +0,0 @@
function H = build_two_dim_hessian(sparse_indices, g2_v, neq, nvar)
% Creates a 2D Hessian (equations in rows, pairs of variables in columns),
% given the output from the sparse {static,dynamic}_g2.m
%
% sparse_indices is typically equal to M_.{static,dynamic}_g2_sparse_indices
% g2_v is the vector of non zero values returned by {static,dynamic}_g2.m
% neq is the number of equations (equal to number of rows of the output matrix)
% nvar is the number of variables (the output matrix will have nvar² columns)
% Copyright © 2024 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 <https://www.gnu.org/licenses/>.
nnz = size(sparse_indices, 1);
%% The g2_* arrays may be expanded if there are symmetric elements added
g2_i = int32(zeros(nnz, 1));
g2_j = int32(zeros(nnz, 1));
next_sym_idx = nnz + 1; % Index of next symmetric element to be added
for k = 1:length(g2_v)
eq = sparse_indices(k, 1);
var1 = sparse_indices(k, 2)-1;
var2 = sparse_indices(k, 3)-1;
g2_i(k) = eq;
g2_j(k) = var1 * nvar + var2 + 1;
%% Add symmetric elements, which are not included by sparse {static,dynamic}_g2.m
if var1 ~= var2
g2_i(next_sym_idx) = eq;
g2_j(next_sym_idx) = var2 * nvar + var1 + 1;
g2_v(next_sym_idx) = g2_v(k);
next_sym_idx = next_sym_idx + 1;
end
end
%% On MATLAB < R2020a, sparse() does not accept int32 indices
if ~isoctave && matlab_ver_less_than('9.8')
g2_i = double(g2_i);
g2_j = double(g2_j);
end
H = sparse(g2_i, g2_j, g2_v, neq, nvar*nvar);

View File

@ -1,42 +0,0 @@
function collapse_figures_in_tabgroup
% Copyright © 2023 Eduard Benet Cerda
% Copyright © 2024 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 <https://www.gnu.org/licenses/>.
% Create a new figure with results
fig = uifigure(Name = 'Dynare Results');
% Add a grid layout to make sure it spans the entire width
g = uigridlayout(fig, [1,1], Padding = 0);
% Add a tabgroup
tg = uitabgroup(g);
% Find all figures with Dynare Tag
f = findobj('-regexp','tag','dynare-figure');
% Loop over all figures and reparent them to a tab. Avoid legends, they are
% automatically tied.
for j = 1 : numel(f)
t = uitab(tg);
types = arrayfun(@class, f(j).Children, 'UniformOutput', false);
idx = ismember(types, 'matlab.graphics.illustration.Legend'); % no need to reparent legends
set(f(j).Children(~idx),'Parent',t)
t.Title = f(j).Name;
delete(f(j))
end

View File

@ -13,7 +13,7 @@ function [dr, info, params]=discretionary_policy_1(M_, options_, dr, endo_steady
% - info [integer] scalar or vector, error code.
% - params [double] vector of potentially updated parameters
% Copyright © 2007-2024 Dynare Team
% Copyright © 2007-2020 Dynare Team
%
% This file is part of Dynare.
%
@ -49,9 +49,7 @@ else
end
params=M_.params;
y = zeros(M_.endo_nbr,1);
[Uy, T_order, T] = feval([M_.fname,'.objective.sparse.static_g1'], y, [], params, M_.objective_g1_sparse_rowval, M_.objective_g1_sparse_colval, M_.objective_g1_sparse_colptr);
[~,Uy,W] = feval([M_.fname,'.objective.static'],zeros(M_.endo_nbr,1),[], M_.params);
if any(any(isnan(Uy)))
info = 64 ; %the derivatives of the objective function contain NaN
return;
@ -72,8 +70,6 @@ if any(any(Uy~=0))
return;
end
g2_v = feval([M_.fname,'.objective.sparse.static_g2'], y, [], params, T_order, T);
W = build_two_dim_hessian(M_.objective_g2_sparse_indices, g2_v, 1, M_.endo_nbr);
W=reshape(W,M_.endo_nbr,M_.endo_nbr);
klen = M_.maximum_lag + M_.maximum_lead + 1;
@ -126,4 +122,4 @@ dr.ghu=G(dr.order_var,:);
if M_.maximum_endo_lag
Selection=M_.lead_lag_incidence(1,dr.order_var)>0;%select state variables
end
dr.ghx=T(:,Selection);
dr.ghx=T(:,Selection);

View File

@ -12,7 +12,7 @@ function h = dyn_figure(nodisplay, varargin)
% SPECIAL REQUIREMENTS
% none
% Copyright © 2012-2024 Dynare Team
% Copyright © 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
@ -30,7 +30,7 @@ function h = dyn_figure(nodisplay, varargin)
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if nodisplay
h = figure(varargin{:},'visible','off','tag','dynare-figure');
h = figure(varargin{:},'visible','off');
else
h = figure(varargin{:},'tag','dynare-figure');
h = figure(varargin{:});
end

View File

@ -122,7 +122,7 @@ if isempty(dot_location)
fnamelength = length(fname);
fname1 = [fname '.dyn'];
d = dir(fname1);
if isempty(d)
if length(d) == 0
fname1 = [fname '.mod'];
end
fname = fname1;
@ -138,7 +138,7 @@ if fnamelength + length('.set_auxiliary_variables') > namelengthmax()
error('Dynare: the name of your .mod file is too long, please shorten it')
end
if contains(fname,filesep)
if ~isempty(strfind(fname,filesep))
fprintf('\nIt seems you are trying to call a .mod file not located in the "Current Folder". This is not possible (the %s symbol is not allowed in the name of the .mod file).\n', filesep)
[pathtomodfile,basename] = fileparts(fname);
if exist(pathtomodfile,'dir')
@ -297,13 +297,17 @@ if status
error('Dynare: preprocessing failed')
end
if ~ isempty(find(abs(fname) == 46))
fname = fname(:,1:find(abs(fname) == 46)-1) ;
end
% We need to clear the driver (and only the driver, because the "clear all"
% within the driver will clean the rest)
clear(['+' fname(1:end-4) '/driver'])
clear(['+' fname '/driver'])
try
cTic = tic;
evalin('base',[fname(1:end-4) '.driver']);
evalin('base',[fname '.driver']);
cToc = toc(cTic);
if nargout
DynareInfo.time.compute = cToc;
@ -311,7 +315,7 @@ try
catch ME
W = evalin('caller','whos');
diary off
if ismember(fname(1:end-4),{W(:).name})
if ismember(fname,{W(:).name})
error('Your workspace already contains a variable with the same name as the mod-file. You need to delete it or rename the mod-file.')
else
rethrow(ME)

View File

@ -63,7 +63,7 @@ end
value_format = sprintf('%%%d.%df', val_width, val_precis);
header_string_format = sprintf('%%%ds', val_width);
if ~isempty(title)
if length(title) > 0
fprintf('\n\n%s\n',title);
end
@ -72,7 +72,7 @@ if nargin==9
disp(optional_header)
end
if ~isempty(headers)
if length(headers) > 0
hh_tbl = sprintf(label_format_leftbound , headers{1});
for i=2:length(headers)
hh_tbl = [hh_tbl sprintf(header_string_format, headers{i})];

View File

@ -1,6 +1,6 @@
function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff,M_,options_,bayestopt_,dr] = dsge_likelihood(xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,BoundsInfo,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,derivatives_info)
% [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff,M_,options_,bayestopt_,oo_] = dsge_likelihood(xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,BoundsInfo,oo_,derivatives_info)
% Evaluates the negative of the posterior kernel of a DSGE model using the specified
% Evaluates the posterior kernel of a DSGE model using the specified
% kalman_algo; the resulting posterior includes the 2*pi constant of the
% likelihood function
%
@ -21,7 +21,7 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff,M_,options_,baye
% - derivatives_info [structure] derivative info for identification
%
% OUTPUTS
% - fval [double] scalar, value of minus the likelihood or posterior kernel.
% - fval [double] scalar, value of the likelihood or posterior kernel.
% - info [integer] 4×1 vector, informations resolution of the model and evaluation of the likelihood.
% - exit_flag [integer] scalar, equal to 1 (no issues when evaluating the likelihood) or 0 (not able to evaluate the likelihood).
% - DLIK [double] Vector with score of the likelihood
@ -37,7 +37,7 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff,M_,options_,baye
% This function calls: dynare_resolve, lyapunov_symm, lyapunov_solver, compute_Pinf_Pstar, kalman_filter_d, missing_observations_kalman_filter_d,
% univariate_kalman_filter_d, kalman_steady_state, get_perturbation_params_deriv, kalman_filter, missing_observations_kalman_filter, univariate_kalman_filter, priordens
% Copyright © 2004-2024 Dynare Team
% Copyright © 2004-2023 Dynare Team
%
% This file is part of Dynare.
%

View File

@ -493,66 +493,52 @@ if issmc(options_) || (any(bayestopt_.pshape>0) && options_.mh_replic) || (any(
end
if ~issmc(options_)
[error_flag, ~, options_]= metropolis_draw(1, options_, estim_params_, M_);
else
error_flag=false;
end
if ~(~isempty(options_.sub_draws) && options_.sub_draws==0)
if options_.bayesian_irf
if ~issmc(options_)
if error_flag
error('%s: I cannot compute the posterior IRFs!',dispString)
end
oo_=PosteriorIRF('posterior',options_,estim_params_,oo_,M_,bayestopt_,dataset_,dataset_info,dispString);
else
fprintf('%s: SMC does not yet support the bayesian_irf option. Skipping computation.\n',dispString);
if error_flag
error('%s: I cannot compute the posterior IRFs!',dispString)
end
oo_=PosteriorIRF('posterior',options_,estim_params_,oo_,M_,bayestopt_,dataset_,dataset_info,dispString);
end
if options_.moments_varendo
if ~issmc(options_)
if error_flag
error('%s: I cannot compute the posterior moments for the endogenous variables!',dispString)
end
if options_.load_mh_file && options_.mh_replic==0 %user wants to recompute results
[MetropolisFolder, info] = CheckPath('metropolis',M_.dname);
if ~info
generic_post_data_file_name={'Posterior2ndOrderMoments','decomposition','PosteriorVarianceDecomposition','correlation','PosteriorCorrelations','conditional decomposition','PosteriorConditionalVarianceDecomposition'};
for ii=1:length(generic_post_data_file_name)
delete_stale_file([MetropolisFolder filesep M_.fname '_' generic_post_data_file_name{1,ii} '*']);
end
% restore compatibility for loading pre-4.6.2 runs where estim_params_ was not saved; see 6e06acc7 and !1944
NumberOfDrawsFiles = length(dir([M_.dname '/metropolis/' M_.fname '_posterior_draws*' ]));
if NumberOfDrawsFiles>0
temp=load([M_.dname '/metropolis/' M_.fname '_posterior_draws1']);
if ~isfield(temp,'estim_params_')
for file_iter=1:NumberOfDrawsFiles
save([M_.dname '/metropolis/' M_.fname '_posterior_draws' num2str(file_iter)],'estim_params_','-append')
end
if error_flag
error('%s: I cannot compute the posterior moments for the endogenous variables!',dispString)
end
if options_.load_mh_file && options_.mh_replic==0 %user wants to recompute results
[MetropolisFolder, info] = CheckPath('metropolis',M_.dname);
if ~info
generic_post_data_file_name={'Posterior2ndOrderMoments','decomposition','PosteriorVarianceDecomposition','correlation','PosteriorCorrelations','conditional decomposition','PosteriorConditionalVarianceDecomposition'};
for ii=1:length(generic_post_data_file_name)
delete_stale_file([MetropolisFolder filesep M_.fname '_' generic_post_data_file_name{1,ii} '*']);
end
% restore compatibility for loading pre-4.6.2 runs where estim_params_ was not saved; see 6e06acc7 and !1944
NumberOfDrawsFiles = length(dir([M_.dname '/metropolis/' M_.fname '_posterior_draws*' ]));
if NumberOfDrawsFiles>0
temp=load([M_.dname '/metropolis/' M_.fname '_posterior_draws1']);
if ~isfield(temp,'estim_params_')
for file_iter=1:NumberOfDrawsFiles
save([M_.dname '/metropolis/' M_.fname '_posterior_draws' num2str(file_iter)],'estim_params_','-append')
end
end
end
end
oo_ = compute_moments_varendo('posterior',options_,M_,oo_,estim_params_,var_list_);
else
fprintf('%s: SMC does not yet support the moments_varendo option. Skipping computation.\n',dispString);
end
oo_ = compute_moments_varendo('posterior',options_,M_,oo_,estim_params_,var_list_);
end
if options_.smoother || ~isempty(options_.filter_step_ahead) || options_.forecast
if ~ishssmc(options_)
if error_flag
error('%s: I cannot compute the posterior statistics!',dispString)
end
if options_.order==1 && ~options_.particle.status
oo_=prior_posterior_statistics('posterior',dataset_,dataset_info,M_,oo_,options_,estim_params_,bayestopt_,dispString); %get smoothed and filtered objects and forecasts
else
error('%s: Particle Smoothers are not yet implemented.',dispString)
end
if error_flag
error('%s: I cannot compute the posterior statistics!',dispString)
end
if options_.order==1 && ~options_.particle.status
oo_=prior_posterior_statistics('posterior',dataset_,dataset_info,M_,oo_,options_,estim_params_,bayestopt_,dispString); %get smoothed and filtered objects and forecasts
else
fprintf('%s: SMC does not yet support the smoother and forecast options. Skipping computation.\n',dispString);
error('%s: Particle Smoothers are not yet implemented.',dispString)
end
end
else
fprintf('%s: sub_draws was set to 0. Skipping posterior computations.\n',dispString);
end
else
fprintf('%s: sub_draws was set to 0. Skipping posterior computations.',dispString);
end
xparam1 = get_posterior_parameters('mean',M_,estim_params_,oo_,options_);
M_ = set_all_parameters(xparam1,estim_params_,M_);
end

View File

@ -0,0 +1,191 @@
function [f, df, d2f, R2] = likelihood_quadratic_approximation(particles, likelihoodvalues)
% Approximate the shape of the likelihood function with a multivariate second order polynomial.
%
%
% INPUTS
% - particles [double] n×p matrix of (p) particles around the estimated posterior mode.
% - likelihoodvalues [double] p×1 vector of corresponding values for the likelihood (or posterior kernel).
%
% OUTPUTS
% - f [handle] function handle for the approximated likelihood.
% - df [handle] function handle for the gradient of the approximated likelihood.
% - d2f [handle] Hessian matrix of the approximated likelihood (constant since we consider a second order multivariate polynomial)
% - R2 [double] scalar, goodness of fit measure.
%
% REMARKS
% [1] Function f takes a n×m matrix as input argument (the approximated likelihood is evaluated in m points) and returns a m×1 vector.
% [2] Funtion df takes a n×1 vector as input argument (the point where the gradient is computed) and returns a n×1 vector.
% Copyright © 2024 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 <https://www.gnu.org/licenses/>.
n = rows(particles); % Number of parmaeters
p = columns(particles); % Number of particles
q = 1 + n + n*(n+1)/2; % Number of regressors (with a constant)
if p<=q
error('Quadratic approximation requires more than %u particles.', q)
end
%
% Build the set of regressors.
%
X = NaN(p, q);
X(:,1) = 1; % zero order term
X(:,2:n+1) = transpose(particles); % first order terms
X(:,n+2:end) = crossproducts(particles); % second order terms
%
% Perform the regression
%
parameters = X\likelihoodvalues(:);
%
% Return a function to evaluate the approximation at x (a n×1 vector).
%
f = @(X) parameters(1) + transpose(X)*parameters(2:n+1) + crossproducts(X)*parameters(n+2:end);
if nargout>1
%
% Return a function to evaluate the gradient of the approximation at x (a n×1 vector)
%
df = @(X) parameters(2:n+1) + dcrossproducts(X)*parameters(n+2:end);
if nargout>2
%
% Return the hessian matrix of the approximation.
%
d2f = NaN(n,n);
h = 1;
for i=1:n
for j=i:n
d2f(i,j) = parameters(n+1+h);
if ~isequal(j, i)
d2f(j,i) = d2f(i,j);
end
h = h+1;
end
end
if nargout>3
%
% Return a measure of fit goodness
%
R2 = 1-sum((likelihoodvalues(:)-X*parameters).^2)/sum(demean(likelihoodvalues(:)).^2);
end
end
end
function XX = crossproducts(X)
% n n
% XX*ones(1,(n+1)*n/2) = ∑ xᵢ² + 2 ∑ xᵢxⱼ
% i=1 i=1
% j>i
XX = NaN(columns(X), n*(n+1)/2);
column = 1;
for i=1:n
XX(:,column) = transpose(X(i,:).*X(i,:));
column = column+1;
for j=i+1:n
XX(:,column) = 2*transpose(X(i,:).*X(j,:));
column = column+1;
end
end
end
function xx = dcrossproducts(x)
xx = zeros(n, n*(n+1)/2);
for i = 1:n
base = (i-1)*n-sum(0:i-2);
incol = 1;
xx(i,base+incol) = 2*x(i);
for j = i+1:n
incol = incol+1;
xx(i,incol) = 2*x(j);
end
for j=1:i-1
base = (j-1)*n-sum(0:j-2)+1;
colid = base+i-j;
xx(i,colid) = 2*x(j);
end
end
end
return % --*-- Unit tests --*--
%@test:1
% Create data
X = randn(10,1000);
Y = 1 + rand(1,10)*X.^2+0.01*randn(1,1000);
% Perform approximation
try
[f,df, d2f,R2] = likelihood_quadratic_approximation(X,Y);
t(1) = true;
catch
t(1) = false;
end
% Test returned arguments
if t(1)
try
y = f(randn(10,100));
t(2) = true;
if ~(rows(y)==100 && columns(y)==1)
t(2) = false;
end
catch
t(2) = false;
end
try
dy = df(zeros(10,1));
t(3) = true;
if ~(rows(dy)==10 && columns(dy)==1)
t(3) = false;
end
catch
t(3) = false;
end
t(4) = true;
if ~(rows(d2f)==10 && columns(d2f)==10)
t(4) = false
end
if ~(rows(d2f)==10 && columns(d2f)==10)
t(4) = false
end
t(4) = issymmetric(d2f);
t(4) = ispd(d2f);
t(5) = isscalar(R2);
t(5) = (R2>0) & (R2<1); % Note that in a nonlinear model nothing ensures that these inequalities are satisfied.
end
T = all(t);
%@eof:1
end

View File

@ -26,7 +26,7 @@ function SampleAddress = selec_posterior_draws(M_,options_,dr,endo_steady_state,
% None.
%
% Copyright © 2006-2024 Dynare Team
% Copyright © 2006-2022 Dynare Team
%
% This file is part of Dynare.
%
@ -146,7 +146,7 @@ if info
pdraws(linee,1) = {x2(SampleAddress(i,4),:)};
if info==2
M_ = set_parameters_locally(M_,pdraws{i,1});
[dr,~,M_.params] = compute_decision_rules(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
[dr,~,M_.params] = compute_decision_rules(M_,options_,oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
pdraws(linee,2) = { dr };
end
old_mhfile = mhfile;

View File

@ -35,7 +35,7 @@ fprintf(fid,'%s \n','\usepackage{psfrag}');
fprintf(fid,'%s \n','\usepackage{graphicx}');
fprintf(fid,'%s \n','\usepackage{epstopdf}');
fprintf(fid,'%s \n','\usepackage{longtable,booktabs}');
fprintf(fid,'%s \n','\usepackage{amsmath,amsfonts,amssymb}');
fprintf(fid,'%s \n','\usepackage{amsmath,amsfonts}');
fprintf(fid,'%s \n','\usepackage{breqn}');
fprintf(fid,'%s \n','\usepackage{float,morefloats,caption}');
fprintf(fid,'%s \n','\begin{document}');

View File

@ -280,10 +280,20 @@ function print_line(names,var_index,lead_lag,M_)
else
aux_index=find([M_.aux_vars(:).endo_index]==var_index);
aux_type=M_.aux_vars(aux_index).type;
if lead_lag==0
str = subst_auxvar(var_index, [], M_);
if ~isfield(M_.aux_vars(aux_index),'orig_lead_lag') || isempty(M_.aux_vars(aux_index).orig_lead_lag)
if ismember(aux_type,[1,3])
str = subst_auxvar(var_index, -1, M_);
elseif ismember(aux_type,[0,2])
str = subst_auxvar(var_index, 1, M_);
else
if lead_lag==0
str = subst_auxvar(var_index, [], M_);
else
str = subst_auxvar(var_index, lead_lag, M_);
end
end
else
str = subst_auxvar(var_index, lead_lag, M_);
str = subst_auxvar(var_index, M_.aux_vars(aux_index).orig_lead_lag, M_);
end
aux_orig_expression=M_.aux_vars(aux_index).orig_expr;
if isempty(aux_orig_expression)

View File

@ -56,7 +56,7 @@ else
var_decomp(stationary_vars,i) = vx2;
variance_sum_loop = variance_sum_loop +vx2; %track overall variance over shocks
end
if ~options_.pruning && max(abs(variance_sum_loop-var_stationary)./var_stationary) > 1e-4 && max(abs(variance_sum_loop-var_stationary))>1e-7
if ~options_.pruning && max(abs(variance_sum_loop-var_stationary)./var_stationary) > 1e-4
warning(['Aggregate variance and sum of variances by shocks ' ...
'differ by more than 0.01 %'])
end

View File

@ -25,7 +25,7 @@ function [steady_state, params, check] = dyn_ramsey_static(ys_init, exo_ss, M_,
% SPECIAL REQUIREMENTS
% none
% Copyright © 2003-2024 Dynare Team
% Copyright © 2003-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -137,7 +137,7 @@ end
% Compute the value of the Lagrange multipliers that minimizes the norm of the
% residuals, given the other endogenous
if options_.bytecode
res = bytecode('static', M_, options_, xx, exo_ss, M_.params, 'evaluate');
res = bytecode('static', M_, options, xx, exo_ss, M_.params, 'evaluate');
else
res = feval([M_.fname '.sparse.static_resid'], xx, exo_ss, M_.params);
end
@ -167,7 +167,7 @@ end
function result = check_static_model(ys,exo_ss,M_,options_)
result = false;
if (options_.bytecode)
res = bytecode('static', M_, options_, ys, exo_ss, M_.params, 'evaluate');
res = bytecode('static', M_, options, ys, exo_ss, M_.params, 'evaluate');
else
res = feval([M_.fname '.sparse.static_resid'], ys, exo_ss, M_.params);
end

View File

@ -59,7 +59,7 @@ function planner_objective_value = evaluate_planner_objective(M_,options_,oo_)
% In the deterministic case, resorting to approximations for welfare is no longer required as it is possible to simulate the model given initial conditions for pre-determined variables and terminal conditions for forward-looking variables, whether these initial and terminal conditions are explicitly or implicitly specified. Assuming that the number of simulated periods is high enough for the new steady-state to be reached, the new unconditional welfare is thus the last period's welfare. As for the conditional welfare, it can be derived using backward recursions on the equation W = U + beta*W(+1) starting from the final unconditional steady-state welfare.
% Copyright © 2007-2024 Dynare Team
% Copyright © 2007-2022 Dynare Team
%
% This file is part of Dynare.
%
@ -92,11 +92,11 @@ end
if options_.ramsey_policy && oo_.gui.ran_perfect_foresight
T = size(oo_.endo_simul,2);
U_term = feval([M_.fname '.objective.sparse.static_resid'], oo_.endo_simul(:,T-M_.maximum_lead), oo_.exo_simul(T-M_.maximum_lead,:), M_.params);
[U_term] = feval([M_.fname '.objective.static'],oo_.endo_simul(:,T-M_.maximum_lead),oo_.exo_simul(T-M_.maximum_lead,:), M_.params);
EW = U_term/(1-beta);
W = EW;
for t=T-M_.maximum_lead:-1:1+M_.maximum_lag
U = feval([M_.fname '.objective.sparse.static_resid'], oo_.endo_simul(:,t), oo_.exo_simul(t,:), M_.params);
[U] = feval([M_.fname '.objective.static'],oo_.endo_simul(:,t),oo_.exo_simul(t,:), M_.params);
W = U + beta*W;
end
planner_objective_value = struct('conditional', W, 'unconditional', EW);
@ -108,8 +108,7 @@ else
ys = oo_.dr.ys;
end
if options_.order == 1 && ~options_.discretionary_policy
[U, T_order, T] = feval([M_.fname '.objective.sparse.static_resid'], ys, zeros(1,exo_nbr), M_.params);
Uy = feval([M_.fname '.objective.sparse.static_g1'], ys, zeros(1,exo_nbr), M_.params, M_.objective_g1_sparse_rowval, M_.objective_g1_sparse_colval, M_.objective_g1_sparse_colptr, T_order, T);
[U,Uy] = feval([M_.fname '.objective.static'],ys,zeros(1,exo_nbr), M_.params);
Gy = dr.ghx(nstatic+(1:nspred),:);
Gu = dr.ghu(nstatic+(1:nspred),:);
@ -138,9 +137,7 @@ else
planner_objective_value.conditional.zero_initial_multiplier = W_L_0;
elseif options_.order == 2 && ~M_.hessian_eq_zero %full second order approximation
[U, T_order, T] = feval([M_.fname '.objective.sparse.static_resid'], ys, zeros(1,exo_nbr), M_.params);
[Uy, T_order, T] = feval([M_.fname '.objective.sparse.static_g1'], ys, zeros(1,exo_nbr), M_.params, M_.objective_g1_sparse_rowval, M_.objective_g1_sparse_colval, M_.objective_g1_sparse_colptr, T_order, T);
Uyy_v = feval([M_.fname '.objective.sparse.static_g2'], ys, zeros(1,exo_nbr), M_.params, T_order, T);
[U,Uy,Uyy] = feval([M_.fname '.objective.static'],ys,zeros(1,exo_nbr), M_.params);
Gy = dr.ghx(nstatic+(1:nspred),:);
Gu = dr.ghu(nstatic+(1:nspred),:);
@ -156,7 +153,6 @@ else
guu(dr.order_var,:) = dr.ghuu;
gss(dr.order_var,:) = dr.ghs2;
Uyy = build_two_dim_hessian(M_.objective_g2_sparse_indices, Uyy_v, 1, M_.endo_nbr);
Uyy = full(Uyy);
Uyygygy = A_times_B_kronecker_C(Uyy,gy,gy);
@ -232,16 +228,13 @@ else
planner_objective_value.conditional.steady_initial_multiplier = W_L_SS;
planner_objective_value.conditional.zero_initial_multiplier = W_L_0;
elseif (options_.order == 2 && M_.hessian_eq_zero) || options_.discretionary_policy %linear quadratic problem
[U, T_order, T] = feval([M_.fname '.objective.sparse.static_resid'], ys, zeros(1,exo_nbr), M_.params);
[Uy, T_order, T] = feval([M_.fname '.objective.sparse.static_g1'], ys, zeros(1,exo_nbr), M_.params, M_.objective_g1_sparse_rowval, M_.objective_g1_sparse_colval, M_.objective_g1_sparse_colptr, T_order, T);
Uyy_v = feval([M_.fname '.objective.sparse.static_g2'], ys, zeros(1,exo_nbr), M_.params, T_order, T);
[U,Uy,Uyy] = feval([M_.fname '.objective.static'],ys,zeros(1,exo_nbr), M_.params);
Gy = dr.ghx(nstatic+(1:nspred),:);
Gu = dr.ghu(nstatic+(1:nspred),:);
gy(dr.order_var,:) = dr.ghx;
gu(dr.order_var,:) = dr.ghu;
Uyy = build_two_dim_hessian(M_.objective_g2_sparse_indices, Uyy_v, 1, M_.endo_nbr);
Uyy = full(Uyy);
Uyygygy = A_times_B_kronecker_C(Uyy,gy,gy);
@ -312,7 +305,7 @@ else
dr.(['g_' num2str(i)]) = [dr.(['g_' num2str(i)]); W.(['W_' num2str(i)])];
end
% Amends the steady-state vector accordingly
U = feval([M_.fname '.objective.sparse.static_resid'], ys, zeros(1,exo_nbr), M_.params);
[U] = feval([M_.fname '.objective.static'],ys,zeros(1,exo_nbr), M_.params);
ysteady = [ys(oo_.dr.order_var); U/(1-beta)];
% Generates the sequence of shocks to compute unconditional welfare

View File

@ -123,11 +123,7 @@ for its = 1:maxit
fjac2=fjac'*fjac;
temp=max(sum(abs(fjac2)));
if temp>0
if issparse(fjac)
p=-(fjac2+sqrt(nn*eps)*temp*speye(nn))\(fjac'*fvec);
else
p=-(fjac2+sqrt(nn*eps)*temp*eye(nn))\(fjac'*fvec);
end
p=-(fjac2+sqrt(nn*eps)*temp*eye(nn))\(fjac'*fvec);
else
errorflag = true;
errorcode = 5;

View File

@ -18,7 +18,7 @@ function [h, lrcp] = hVectors(params, H, auxmodel, kind, id)
% params(2:end-1) ⟶ Autoregressive parameters.
% params(end) ⟶ Discount factor.
% Copyright © 2018-2024 Dynare Team
% Copyright © 2018-2021 Dynare Team
%
% This file is part of Dynare.
%
@ -52,21 +52,21 @@ n = length(H);
tmp = eye(n*m)-kron(G, transpose(H)); % inv(W2)
switch kind
case 'll' % (A.84), page 28 in Brayton, Davis and Tulip (2000) ⟹ The target is stationary (level-level).
case 'll'
h = A_1*A_b*((kron(iota(m, m), H))'*(tmp\kron(iota(m, m), iota(n, id))));
case 'dd' % (A.79), page 26 in Brayton, Davis and Tulip (2000) ⟹ The target appears in first difference as a dependent variable in the auxiliary model.
case 'dd'
h = A_1*A_b*(kron(iota(m, m)'*inv(eye(m)-G), H')*(tmp\kron(iota(m, m), iota(n, id))));
case 'dl' % (A.74), page 24 in Brayton, Davis and Tulip (2000) ⟹ The target appears in level as a dependent variable in the auxiliary model.
case 'dl'
h = A_1*A_b*(kron(iota(m, m)'*inv(eye(m)-G), (H'-eye(length(H))))*(tmp\kron(iota(m, m), iota(n, id))));
otherwise
error('Unknown kind value in PAC model.')
end
if nargout>1
if nargin>1
if isequal(kind, 'll')
lrcp = NaN;
else
d = A_1*A_b*(iota(m, m)'*inv((eye(m)-G)*(eye(m)-G))*iota(m, m));
lrcp = (1-sum(params(2:end-1))-d);
end
end
end

View File

@ -25,7 +25,7 @@ function [dr,info]=PCL_resol(ys,check_flag)
% SPECIAL REQUIREMENTS
% none
% Copyright © 2001-2024 Dynare Team
% Copyright © 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
@ -65,13 +65,7 @@ end
dr.ys = ys;
check1 = 0;
% testing for steadystate file
static_resid = str2func(sprintf('%s.sparse.static_resid', M_.fname));
static_g1 = str2func(sprintf('%s.sparse.static_g1', M_.fname));
function [resid, g1] = static_resid_g1(y, x, params)
[resid, T_order, T] = static_resid(y, x, params);
g1 = static_g1(y, x, params, M_.static_g1_sparse_rowval, M_.static_g1_sparse_colval, M_.static_g1_sparse_colptr, T_order, T);
end
fh = str2func([M_.fname '.static']);
if options_.steadystate_flag
[dr.ys,check1] = feval([M_.fname '_steadystate'],dr.ys,...
[oo_.exo_steady_state; ...
@ -93,17 +87,17 @@ else
if ~options_.ramsey_policy
if options_.linear == 0
% nonlinear models
if max(abs(static_resid_g1(dr.ys, [oo_.exo_steady_state; ...
oo_.exo_det_steady_state], M_.params))) > options_.solve_tolf
if max(abs(feval(fh,dr.ys,[oo_.exo_steady_state; ...
oo_.exo_det_steady_state], M_.params))) > options_.solve_tolf
opt = options_;
opt.jacobian_flag = false;
[dr.ys, check1] = dynare_solve(static_resid_g1, dr.ys, options.steady_.maxit, options_.solve_tolf, options_.solve_tolx, ...
[dr.ys, check1] = dynare_solve(fh,dr.ys, options.steady_.maxit, options_.solve_tolf, options_.solve_tolx, ...
opt, [oo_.exo_steady_state; oo_.exo_det_steady_state], M_.params);
end
else
% linear models
[fvec,jacob] = static_resid_g1(dr.ys, [oo_.exo_steady_state;...
oo_.exo_det_steady_state], M_.params);
[fvec,jacob] = feval(fh,dr.ys,[oo_.exo_steady_state;...
oo_.exo_det_steady_state], M_.params);
if max(abs(fvec)) > 1e-12
dr.ys = dr.ys-jacob\fvec;
end
@ -117,7 +111,7 @@ if check1
resid = check1 ;
else
info(1)= 20;
resid = static_resid(ys, oo_.exo_steady_state, M_.params);
resid = feval(fh,ys,oo_.exo_steady_state, M_.params);
end
info(2) = resid'*resid ;
return
@ -146,8 +140,6 @@ end
oo_.exo_simul = tempex;
tempex = [];
end
% 01/01/2003 MJ added dr_algo == 1
% 08/24/2001 MJ uses Schmitt-Grohe and Uribe (2001) constant correction
% in dr.ghs2

View File

@ -2,7 +2,7 @@ function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ...
exo_steady_state, exo_det_steady_state,params, byte_code)
% Add auxiliary variables to the steady state vector
% Copyright © 2009-2024 Dynare Team
% Copyright © 2009-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -30,7 +30,7 @@ for i=1:n+1
[exo_steady_state; ...
exo_det_steady_state],params);
else
res = feval([fname '.sparse.static_resid'], ys1,...
res = feval([fname '.static'],ys1,...
[exo_steady_state; ...
exo_det_steady_state],params);
end

View File

@ -23,7 +23,7 @@ function [oo_, ts]=perfect_foresight_solver(M_, options_, oo_, no_error_if_learn
% SPECIAL REQUIREMENTS
% none
% Copyright © 1996-2024 Dynare Team
% Copyright © 1996-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -55,7 +55,7 @@ end
periods = options_.periods;
if options_.debug
model_static = str2func([M_.fname,'.sparse.static_resid']);
model_static = str2func([M_.fname,'.static']);
for ii=1:size(oo_.exo_simul,1)
[residual(:,ii)] = model_static(oo_.steady_state, oo_.exo_simul(ii,:),M_.params);
end

View File

@ -14,7 +14,7 @@ function [y, success, maxerror, per_block_status] = solve_block_decomposed_probl
% maxerror [double] ∞-norm of the residual
% per_block_status [struct] vector structure with per-block information about convergence
% Copyright © 2020-2024 Dynare Team
% Copyright © 2020-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -33,21 +33,18 @@ function [y, success, maxerror, per_block_status] = solve_block_decomposed_probl
cutoff = 1e-15;
switch options_.stack_solve_algo
case 0
mthd='Sparse LU on stacked system';
case {1,6}
mthd='LBJ with LU solver';
case 2
mthd='GMRES on stacked system';
case 3
mthd='BiCGStab on stacked system';
case 4
mthd='Sparse LU solver with optimal path length on stacked system';
case 7
mthd='Solver from solve_algo option on stacked system';
otherwise
error('Unsupported stack_solve_algo value')
if options_.stack_solve_algo==0
mthd='Sparse LU';
elseif options_.stack_solve_algo==1 || options_.stack_solve_algo==6
mthd='LBJ';
elseif options_.stack_solve_algo==2
mthd='GMRES';
elseif options_.stack_solve_algo==3
mthd='BICGSTAB';
elseif options_.stack_solve_algo==4
mthd='OPTIMPATH';
else
mthd='UNKNOWN';
end
if options_.verbosity
printline(41)

View File

@ -20,5 +20,5 @@ function send_endogenous_variables_to_workspace()
global M_ oo_
for idx = 1:M_.endo_nbr
assignin('base', M_.endo_names{idx}, oo_.endo_simul(idx,:)')
assignin('base', M_.endo_names{idx}, oo_.endo_simul(idx,:))
end

View File

@ -21,5 +21,5 @@ function send_exogenous_variables_to_workspace()
global M_ oo_
for idx = 1:M_.exo_nbr
assignin('base', M_.exo_names{idx}, oo_.exo_simul(:,idx)')
assignin('base', M_.exo_names{idx}, oo_.exo_simul(:,idx))
end

View File

@ -129,7 +129,7 @@ if realtime_==0
myopts=options_;
myopts.plot_shock_decomp.type='qoq';
myopts.plot_shock_decomp.realtime=0;
z = plot_shock_decomposition(M_,oo_,myopts,[],true);
z = plot_shock_decomposition(M_,oo_,myopts,[]);
else
z = oo_;
end
@ -139,7 +139,7 @@ if realtime_==0
myopts=options_;
myopts.plot_shock_decomp.type='qoq';
myopts.plot_shock_decomp.realtime=0;
[y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux.y,true);
[y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux.y);
aux.y=y_aux;
aux.yss=steady_state_aux;
end
@ -158,13 +158,13 @@ if realtime_ && isstruct(oo_) && isfield(oo_, 'realtime_shock_decomposition')
myopts.plot_shock_decomp.realtime=1;
myopts.plot_shock_decomp.vintage=i;
% retrieve quarterly shock decomp
z = plot_shock_decomposition(M_,oo_,myopts,[],true);
z = plot_shock_decomposition(M_,oo_,myopts,[]);
zdim = size(z);
z = z(i_var,:,:);
if isstruct(aux)
if ischar(aux0.y)
% retrieve quarterly shock decomp for aux variable
[y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux0.y,true);
[y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux0.y);
aux.y=y_aux;
aux.yss=steady_state_aux;
end
@ -185,13 +185,13 @@ if realtime_ && isstruct(oo_) && isfield(oo_, 'realtime_shock_decomposition')
if qvintage_>i-4 && qvintage_<i
myopts.plot_shock_decomp.vintage=qvintage_;
% retrieve quarterly shock decomp
z = plot_shock_decomposition(M_,oo_,myopts,[],true);
z = plot_shock_decomposition(M_,oo_,myopts,[]);
z(:,:,end+1:zdim(3))=nan; % fill with nan's remaining time points to reach Q4
z = z(i_var,:,:);
if isstruct(aux)
if ischar(aux0.y)
% retrieve quarterly shock decomp for aux variable
[y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux0.y,true);
[y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux0.y);
y_aux(:,:,end+1:zdim(3))=nan; % fill with nan's remaining time points to reach Q4
aux.y=y_aux;
aux.yss=steady_state_aux;

View File

@ -1,4 +1,4 @@
function [out, steady_state] = plot_shock_decomposition(M_,oo_,options_,varlist,get_decomp_only)
function [out, steady_state] = plot_shock_decomposition(M_,oo_,options_,varlist)
% function plot_shock_decomposition(M_,oo_,options_,varlist)
% Plots the results of shock_decomposition
%
@ -7,12 +7,11 @@ function [out, steady_state] = plot_shock_decomposition(M_,oo_,options_,varlist,
% oo_: [structure] Storage of results
% options_: [structure] Options
% varlist: [char] List of variables
% get_decomp_only [bool] indicator on whether to only return with
% basic decomposition (required for e.g. annualized_shock_decomposition)
%
% SPECIAL REQUIREMENTS
% none
% Copyright © 2016-2023 Dynare Team
% Copyright © 2016-2019 Dynare Team
%
% This file is part of Dynare.
%
@ -29,10 +28,6 @@ function [out, steady_state] = plot_shock_decomposition(M_,oo_,options_,varlist,
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if nargin<5
get_decomp_only=false;
end
options_.nodisplay = options_.plot_shock_decomp.nodisplay;
options_.graph_format = options_.plot_shock_decomp.graph_format;
@ -537,7 +532,7 @@ if steadystate
options_.plot_shock_decomp.steady_state=steady_state;
end
if get_decomp_only
if nargout == 2
out=z(i_var,:,:);
steady_state = steady_state(i_var);
return

View File

@ -1,7 +1,7 @@
function [dr,info] = k_order_pert(dr,M_,options_)
% Compute decision rules using the k-order DLL from Dynare++
% Copyright © 2009-2024 Dynare Team
% Copyright © 2009-2023 Dynare Team
%
% This file is part of Dynare.
%
@ -30,16 +30,6 @@ if M_.maximum_endo_lead == 0 && order>1
'backward models'])
end
if options_.aim_solver
error('Option aim_solver is not compatible with k_order_solver')
end
if options_.dr_cycle_reduction
error('Option dr=cycle_reduction is not compatible with k_order_solver')
end
if options_.dr_logarithmic_reduction
error('Option dr=logarithmic_reduction is not compatible with k_order_solver')
end
try
[dynpp_derivs, dyn_derivs] = k_order_perturbation(dr,M_,options_);
catch ME

View File

@ -1,25 +0,0 @@
function display_parameter_values
% Copyright © 2024 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 <https://www.gnu.org/licenses/>.
global M_
my_title='Current parameter values:';
labels = M_.param_names;
headers = {'Parameter'; 'Value'};
lh = cellofchararraymaxlength(labels)+2;
options_.noprint=false;
dyntable(options_, my_title, headers, labels, M_.params, lh, 10, 6);

View File

@ -1,30 +1,15 @@
function [test, penalty] = ispd(A)
%@info:
%! @deftypefn {Function File} {[@var{test}, @var{penalty} =} ispd (@var{A})
%! @anchor{ispd}
%! @sp 1
%! Tests if the square matrix @var{A} is positive definite.
%! @sp 2
%! @strong{Inputs}
%! @sp 1
%! @table @ @var
%! @item A
%! A square matrix.
%! @end table
%! @sp 2
%! @strong{Outputs}
%! @sp 1
%! @table @ @var
%! @item test
%! Integer scalar equal to 1 if @var{A} is a positive definite sqquare matrix, 0 otherwise.
%! @item penalty
%! Absolute value of the uum of the negative eigenvalues of A. This output argument is optional.
%! @end table
%! @end deftypefn
%@eod:
% Test if the square matrix A is positive definite.
%
% INPUTS
% - A [double] n×n matrix.
%
% OUTPUTS
% - test [logical] scalar, true if and only if matrix A is positive definite (and symmetric...)
% - penalty [double] scalar, absolute value of the uum of the negative eigenvalues of A. This output argument is optional.
% Copyright © 2007-2022 Dynare Team
% Copyright © 2007-2024 Dynare Team
%
% This file is part of Dynare.
%
@ -54,6 +39,7 @@ if nargout>1
if isoctave && any(any(~isfinite(A))) % workaround for https://savannah.gnu.org/bugs/index.php?63082
penalty = 1;
else
% TODO: the penalty is only concerned with negative eigenvalues, we should also consider the case of non symmetric matrix A.
a = diag(eig(A));
k = find(a<0);
if k > 0
@ -61,4 +47,4 @@ if nargout>1
end
end
end
end
end

View File

@ -21,14 +21,9 @@ c_compiler = meson.get_compiler('c')
subdir('preprocessor/src')
# NB: the following two symlinks my be improved if this wishlist item is done:
# https://github.com/mesonbuild/meson/issues/11519
install_symlink('dynare-preprocessor', install_dir : 'lib/dynare/preprocessor/',
pointing_to : '../../../bin/dynare-preprocessor'
+ (host_machine.system() == 'windows' ? '.exe' : ''))
# Compatibility symlink
# NB: the following my be improved if this wishlist item is done:
# https://github.com/mesonbuild/meson/issues/11519
install_symlink('dynare_m' + (host_machine.system() == 'windows' ? '.exe' : ''),
install_dir : 'lib/dynare/matlab/preprocessor64',
pointing_to : '../../../../bin/dynare-preprocessor'
@ -39,12 +34,17 @@ install_symlink('dynare_m' + (host_machine.system() == 'windows' ? '.exe' : ''),
install_subdir('matlab', install_dir : 'lib/dynare',
exclude_files : [ 'utilities/tests/.git' ,
'utilities/tests/.gitignore',
'dseries/.git',
'dseries/.gitignore',
'dseries/src/modules/matlab-fame-io/.git',
'dseries/src/modules/matlab-fame-io/.gitignore',
'dseries/.gitmodules',
'dseries/.gitlab-ci.yml' ])
'modules/reporting/.git',
'modules/reporting/.gitignore',
'modules/reporting/.gitlab-ci.yml',
'modules/dseries/.git',
'modules/dseries/.gitignore',
'modules/dseries/src/modules/matlab-fame-io/.git',
'modules/dseries/src/modules/matlab-fame-io/.gitignore',
'modules/dseries/src/modules/matlab-fame-io/doc/.gitignore',
'modules/dseries/src/modules/matlab-fame-io/tests/FameDatabases/.gitignore',
'modules/dseries/.gitmodules',
'modules/dseries/.gitlab-ci.yml' ])
sed_exe = find_program('sed')
custom_target(output : 'dynare_version.m', input : 'matlab/dynare_version.m.in',
@ -53,9 +53,6 @@ custom_target(output : 'dynare_version.m', input : 'matlab/dynare_version.m.in',
install : true,
install_dir : 'lib/dynare/matlab')
install_subdir('contrib/ms-sbvar/TZcode/MatlabFiles',
install_dir : 'lib/dynare/contrib/ms-sbvar/TZcode')
### MEX files
mex_incdir = include_directories('mex/sources')
@ -160,20 +157,7 @@ if get_option('build_for') == 'matlab'
umfpack_dep = declare_dependency(link_args : '-lmwumfpack', dependencies : blas_dep)
ut_dep = declare_dependency(link_args : '-lut')
# Workaround for Meson bug https://github.com/mesonbuild/meson/issues/12757
# Use the C compiler as a fallback for detecting SLICOT under Linux with
# prefer_static=true (but still try the Fortran compiler to honour the -B
# option in fortran_args, as documented). Needed for building the MATLAB
# Online package.
if get_option('prefer_static') and host_machine.system() == 'linux'
slicot_dep_tmp = fortran_compiler.find_library('slicot64_pic', required : false)
if not slicot_dep_tmp.found()
slicot_dep_tmp = c_compiler.find_library('slicot64_pic')
endif
slicot_dep = declare_dependency(dependencies : [ slicot_dep_tmp, blas_dep, lapack_dep ])
else
slicot_dep = declare_dependency(dependencies : [ fortran_compiler.find_library('slicot64_pic'), blas_dep, lapack_dep ])
endif
slicot_dep = declare_dependency(dependencies : [ fortran_compiler.find_library('slicot64_pic'), blas_dep, lapack_dep ])
else # Octave build
octave_exe = find_program('octave', required : not meson.is_cross_build(), disabler : true)
mkoctfile_exe = find_program('mkoctfile')
@ -307,11 +291,8 @@ if get_option('prefer_static')
# NB: constructing a dependency object with link_args : ['-Wl,-Bstatic', '-lgomp', '-Wl,-Bdynamic'] does not work,
# because it reorders the three arguments and puts -lgomp at the end
if host_machine.system() != 'linux'
# Under Debian 12, trying to link (static) libgomp.a in a MEX fails.
openmp_dep_tmp = cpp_compiler.find_library('gomp', static : true)
openmp_dep = declare_dependency(dependencies : [ openmp_dep, openmp_dep_tmp ])
endif
openmp_dep_tmp = cpp_compiler.find_library('gomp', static : true)
openmp_dep = declare_dependency(dependencies : [ openmp_dep, openmp_dep_tmp ])
endif
# For use when creating intermediate static libraries to be incorporated in MEX files
@ -1911,9 +1892,7 @@ endforeach
git_exe = find_program('git', required : false)
etags_exe = find_program('etags', required : false)
fs = import('fs')
if fs.is_dir('.git') and git_exe.found() and etags_exe.found()
if git_exe.found() and etags_exe.found()
all_files = run_command(git_exe,
[ '--git-dir=@0@/.git'.format(meson.project_source_root()),
'ls-files', '--recurse-submodules',

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2007-2024 Dynare Team
* Copyright © 2007-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -4710,26 +4710,23 @@ Interpreter::Simulate_Newton_Two_Boundaries(
switch (stack_solve_algo)
{
case 0:
mexPrintf("MODEL SIMULATION: (method=Sparse LU solver on stacked system)\n");
mexPrintf("MODEL SIMULATION: (method=Sparse LU)\n");
break;
case 2:
mexPrintf(
preconditioner_print_out("MODEL SIMULATION: (method=GMRES on stacked system)\n",
preconditioner, false)
.c_str());
mexPrintf(preconditioner_print_out("MODEL SIMULATION: (method=GMRES)\n",
preconditioner, false)
.c_str());
break;
case 3:
mexPrintf(preconditioner_print_out(
"MODEL SIMULATION: (method=BiCGStab on stacked system)\n",
preconditioner, false)
mexPrintf(preconditioner_print_out("MODEL SIMULATION: (method=BiCGStab)\n",
preconditioner, false)
.c_str());
break;
case 4:
mexPrintf("MODEL SIMULATION: (method=Sparse LU solver with optimal path length on "
"stacked system)\n");
mexPrintf("MODEL SIMULATION: (method=Sparse LU & optimal path length)\n");
break;
case 5:
mexPrintf("MODEL SIMULATION: (method=LBJ with Sparse Gaussian Elimination)\n");
mexPrintf("MODEL SIMULATION: (method=Sparse Gaussian Elimination)\n");
break;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2007-2024 Dynare Team
* Copyright © 2007-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -262,22 +262,6 @@ mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
if (!shock_str_date_)
mexErrMsgTxt(
"The extended_path description structure does not contain the member: shock_str_date_");
mxArray* shock_perfect_foresight_
= mxGetField(extended_path_struct, 0, "shock_perfect_foresight_");
if (!shock_perfect_foresight_)
mexErrMsgTxt("The extended_path description structure does not contain the member: "
"shock_perfect_foresight_");
// Check that there is no 'perfect_foresight' shocks, which are not implemented
double* constrained_pf = mxGetPr(constrained_perfect_foresight_);
double* shock_pf = mxGetPr(shock_perfect_foresight_);
if (auto is_pf = [](double v) { return v != 0; };
any_of(constrained_pf,
constrained_pf + mxGetNumberOfElements(constrained_perfect_foresight_), is_pf)
|| any_of(shock_pf, shock_pf + mxGetNumberOfElements(shock_perfect_foresight_), is_pf))
mexErrMsgTxt(
"Shocks of type 'perfect_foresight' are not supported with the bytecode option.");
int nb_constrained = mxGetM(constrained_vars_) * mxGetN(constrained_vars_);
int nb_controlled = 0;
mxArray* options_cond_fcst_ = mxGetField(extended_path_struct, 0, "options_cond_fcst_");

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2021-2024 Dynare Team
* Copyright © 2021-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -18,23 +18,26 @@
*/
#include "k_ord_objective.hh"
#include "objective_abstract_class.hh"
#include <cassert>
#include <utility>
KordwDynare::KordwDynare(KordpDynare& m, Journal& jr, Vector& inParams,
std::unique_ptr<ObjectiveMFile> objectiveFile_arg,
KordwDynare::KordwDynare(KordpDynare& m, ConstVector& NNZD_arg, Journal& jr, Vector& inParams,
std::unique_ptr<ObjectiveAC> objectiveFile_arg,
const std::vector<int>& dr_order) :
model {m},
NNZD {NNZD_arg},
journal {jr},
params {inParams},
resid(1),
ud {1},
objectiveFile {std::move(objectiveFile_arg)}
{
dynppToDyn = dr_order;
dynToDynpp.resize(model.ny());
for (int i = 0; i < model.ny(); i++)
dynToDynpp[dr_order[i]] = i;
dynToDynpp[dynppToDyn[i]] = i;
}
void
@ -43,10 +46,71 @@ KordwDynare::calcDerivativesAtSteady()
assert(ud.begin() == ud.end());
std::vector<TwoDMatrix> dyn_ud; // Planner's objective derivatives, in Dynare form
dyn_ud.emplace_back(1, model.ny()); // Allocate Jacobian
dyn_ud.back().zeros();
for (int i = 2; i <= model.order(); i++)
{
// Higher order derivatives, as sparse (3-column) matrices
dyn_ud.emplace_back(static_cast<int>(NNZD[i - 1]), 3);
dyn_ud.back().zeros();
}
Vector xx(model.nexog());
xx.zeros();
resid.zeros();
objectiveFile->eval(model.getSteady(), xx, params, resid, dynToDynpp, ud);
objectiveFile->eval(model.getSteady(), xx, params, resid, dyn_ud);
for (int i = 1; i <= model.order(); i++)
populateDerivativesContainer(dyn_ud, i);
}
void
KordwDynare::populateDerivativesContainer(const std::vector<TwoDMatrix>& dyn_ud, int ord)
{
const TwoDMatrix& u = dyn_ud[ord - 1];
// utility derivatives FSSparseTensor instance
auto udTi = std::make_unique<FSSparseTensor>(ord, model.ny(), 1);
IntSequence s(ord, 0);
if (ord == 1)
for (int i = 0; i < u.ncols(); i++)
{
for (int j = 0; j < u.nrows(); j++)
{
double x = u.get(j, dynppToDyn[s[0]]);
if (x != 0.0)
udTi->insert(s, j, x);
}
s[0]++;
}
else // ord ≥ 2
for (int i = 0; i < u.nrows(); i++)
{
int j = static_cast<int>(u.get(i, 0)) - 1;
int i1 = static_cast<int>(u.get(i, 1)) - 1;
if (j < 0 || i1 < 0)
continue; // Discard empty entries (see comment in DynamicModelAC::unpackSparseMatrix())
for (int k = 0; k < ord; k++)
{
s[k] = dynToDynpp[i1 % model.ny()];
i1 /= model.ny();
}
if (ord == 2 && !s.isSorted())
continue; // Skip symmetric elements (only needed at order 2)
else if (ord > 2)
s.sort(); // For higher order, canonicalize the multi-index
double x = u.get(i, 2);
udTi->insert(s, j, x);
}
ud.insert(std::move(udTi));
}
template<>

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2021-2024 Dynare Team
* Copyright © 2021-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -21,7 +21,7 @@
#define K_ORD_OBJECTIVE_HH
#include "k_ord_dynare.hh"
#include "objective_m.hh"
#include "objective_abstract_class.hh"
class KordwDynare;
@ -29,19 +29,22 @@ class KordwDynare
{
public:
KordpDynare& model;
const ConstVector& NNZD;
private:
Journal& journal;
Vector& params;
Vector resid;
TensorContainer<FSSparseTensor> ud; // planner's objective derivatives, in Dynare++ form
std::vector<int> dynppToDyn; // Maps Dynare++ jacobian variable indices to Dynare ones
std::vector<int> dynToDynpp; // Maps Dynare jacobian variable indices to Dynare++ ones
std::unique_ptr<ObjectiveMFile> objectiveFile;
std::unique_ptr<ObjectiveAC> objectiveFile;
public:
KordwDynare(KordpDynare& m, Journal& jr, Vector& inParams,
std::unique_ptr<ObjectiveMFile> objectiveFile_arg, const std::vector<int>& varOrder);
KordwDynare(KordpDynare& m, ConstVector& NNZD_arg, Journal& jr, Vector& inParams,
std::unique_ptr<ObjectiveAC> objectiveFile_arg, const std::vector<int>& varOrder);
void calcDerivativesAtSteady();
void populateDerivativesContainer(const std::vector<TwoDMatrix>& dyn_ud, int ord);
[[nodiscard]] const TensorContainer<FSSparseTensor>&
getPlannerObjDerivatives() const
{

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2021-2024 Dynare Team
* Copyright © 2021-2022 Dynare Team
*
* This file is part of Dynare.
*
@ -31,7 +31,6 @@
#include <algorithm>
#include <cassert>
#include <string>
#include "dynmex.h"
@ -88,8 +87,8 @@ The routine proceeds in several steps:
to the approxAtSteady method in the ApproximationWelfare class carries out the necessary
operation
- Importing the derivatives of the felicity function with the calcDerivativesAtSteady() method of
the KordwDynare class. It relies on the MATLAB-generated files, which are handled by the
ObjectiveMFile class
the KordwDynare class. It relies on the Matlab-generated files, which are handled by the
ObjectiveAC and ObjectiveMFile classes
- Pinpointing the derivatives of the felicity and welfare functions. The performStep method of
the KOrderWelfare class carries out the calculations,resorting to the FaaDiBruno class and its
methods to get the needed intermediary results.
@ -215,6 +214,15 @@ extern "C"
mexErrMsgTxt("The derivatives were not computed for the required order. Make sure that you "
"used the right order option inside the `stoch_simul' command");
const mxArray* nnzderivatives_obj_mx = mxGetField(M_mx, 0, "NNZDerivatives_objective");
if (!(nnzderivatives_obj_mx && mxIsDouble(nnzderivatives_obj_mx)
&& !mxIsComplex(nnzderivatives_obj_mx) && !mxIsSparse(nnzderivatives_obj_mx)))
mexErrMsgTxt("M_.NNZDerivatives should be a real dense array");
ConstVector NNZD_obj {nnzderivatives_obj_mx};
if (NNZD.length() < kOrder || NNZD_obj[kOrder - 1] == -1)
mexErrMsgTxt("The derivatives were not computed for the required order. Make sure that you "
"used the right order option inside the `stoch_simul' command");
const mxArray* endo_names_mx = mxGetField(M_mx, 0, "endo_names");
if (!(endo_names_mx && mxIsCell(endo_names_mx)
&& mxGetNumberOfElements(endo_names_mx) == static_cast<size_t>(nEndo)))
@ -253,32 +261,6 @@ extern "C"
std::transform(mxGetPr(order_var_mx), mxGetPr(order_var_mx) + nEndo, dr_order.begin(),
[](double x) { return static_cast<int>(x) - 1; });
const mxArray* objective_g1_sparse_rowval_mx
= mxGetField(M_mx, 0, "objective_g1_sparse_rowval");
if (!(objective_g1_sparse_rowval_mx && mxIsInt32(objective_g1_sparse_rowval_mx)))
mexErrMsgTxt("M_.objective_g1_sparse_rowval should be an int32 array");
const mxArray* objective_g1_sparse_colval_mx
= mxGetField(M_mx, 0, "objective_g1_sparse_colval");
if (!(objective_g1_sparse_colval_mx && mxIsInt32(objective_g1_sparse_colval_mx)))
mexErrMsgTxt("M_.objective_g1_sparse_colval should be an int32 array");
const mxArray* objective_g1_sparse_colptr_mx
= mxGetField(M_mx, 0, "objective_g1_sparse_colptr");
if (!(objective_g1_sparse_colptr_mx && mxIsInt32(objective_g1_sparse_colptr_mx)))
mexErrMsgTxt("M_.objective_g1_sparse_colptr should be an int32 array");
std::vector<const mxArray*> objective_gN_sparse_indices;
for (int o {2}; o <= kOrder; o++)
{
using namespace std::string_literals;
auto fieldname {"objective_g"s + std::to_string(o) + "_sparse_indices"};
const mxArray* indices = mxGetField(M_mx, 0, fieldname.c_str());
if (!(indices && mxIsInt32(indices)))
mexErrMsgTxt(("M_."s + fieldname + " should be an int32 array").c_str());
objective_gN_sparse_indices.push_back(indices);
}
const int nSteps
= 0; // Dynare++ solving steps, for time being default to 0 = deterministic steady state
@ -309,14 +291,21 @@ extern "C"
// run stochastic steady
app.walkStochSteady();
const mxArray* objective_tmp_nbr_mx = mxGetField(M_mx, 0, "objective_tmp_nbr");
if (!(objective_tmp_nbr_mx && mxIsDouble(objective_tmp_nbr_mx)
&& !mxIsComplex(objective_tmp_nbr_mx) && !mxIsSparse(objective_tmp_nbr_mx)
&& mxGetNumberOfElements(objective_tmp_nbr_mx) >= static_cast<size_t>(kOrder + 1)))
mexErrMsgTxt("M_.objective_tmp_nbr should be a real dense array with strictly more elements "
"than the order of derivation");
int ntt_objective = std::accumulate(mxGetPr(objective_tmp_nbr_mx),
mxGetPr(objective_tmp_nbr_mx) + kOrder + 1, 0);
// Getting derivatives of the planner's objective function
std::unique_ptr<ObjectiveMFile> objectiveFile;
objectiveFile = std::make_unique<ObjectiveMFile>(
fname, kOrder, objective_g1_sparse_rowval_mx, objective_g1_sparse_colval_mx,
objective_g1_sparse_colptr_mx, objective_gN_sparse_indices);
std::unique_ptr<ObjectiveAC> objectiveFile;
objectiveFile = std::make_unique<ObjectiveMFile>(fname, ntt_objective);
// make KordwDynare object
KordwDynare welfare(dynare, journal, modParams, std::move(objectiveFile), dr_order);
KordwDynare welfare(dynare, NNZD_obj, journal, modParams, std::move(objectiveFile), dr_order);
// construct main K-order approximation class of welfare
ApproximationWelfare appwel(welfare, discount_factor, app.get_rule_ders(),

View File

@ -0,0 +1,38 @@
/*
* Copyright © 2021-2023 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 <https://www.gnu.org/licenses/>.
*/
#ifndef OBJECTIVE_ABSTRACT_CLASS_HH
#define OBJECTIVE_ABSTRACT_CLASS_HH
#include <vector>
#include "twod_matrix.hh"
class ObjectiveAC
{
protected:
int ntt; // Size of vector of temporary terms
public:
ObjectiveAC(int ntt_arg) : ntt {ntt_arg} {};
virtual ~ObjectiveAC() = default;
virtual void eval(const Vector& y, const Vector& x, const Vector& params, Vector& residual,
std::vector<TwoDMatrix>& md)
= 0;
};
#endif

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2021-2024 Dynare Team
* Copyright © 2021-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -26,41 +26,88 @@
#include "objective_m.hh"
ObjectiveMFile::ObjectiveMFile(const std::string& modName, int kOrder_arg,
const mxArray* objective_g1_sparse_rowval_mx_arg,
const mxArray* objective_g1_sparse_colval_mx_arg,
const mxArray* objective_g1_sparse_colptr_mx_arg,
const std::vector<const mxArray*> objective_gN_sparse_indices_arg) :
ObjectiveMFilename {modName + ".objective.sparse.static"},
kOrder {kOrder_arg},
objective_g1_sparse_rowval_mx {objective_g1_sparse_rowval_mx_arg},
objective_g1_sparse_colval_mx {objective_g1_sparse_colval_mx_arg},
objective_g1_sparse_colptr_mx {objective_g1_sparse_colptr_mx_arg},
objective_gN_sparse_indices {objective_gN_sparse_indices_arg}
ObjectiveMFile::ObjectiveMFile(const std::string& modName, int ntt_arg) :
ObjectiveAC(ntt_arg), ObjectiveMFilename {modName + ".objective.static"}
{
}
void
ObjectiveMFile::eval(const Vector& y, const Vector& x, const Vector& modParams, Vector& residual,
const std::vector<int>& dynToDynpp,
TensorContainer<FSSparseTensor>& derivatives) const
ObjectiveMFile::unpackSparseMatrixAndCopyIntoTwoDMatData(mxArray* sparseMat, TwoDMatrix& tdm)
{
mxArray* y_mx = mxCreateDoubleMatrix(y.length(), 1, mxREAL);
std::copy_n(y.base(), y.length(), mxGetPr(y_mx));
int totalCols = mxGetN(sparseMat);
mwIndex* rowIdxVector = mxGetIr(sparseMat);
mwIndex* colIdxVector = mxGetJc(sparseMat);
mxArray* x_mx = mxCreateDoubleMatrix(1, x.length(), mxREAL);
std::copy_n(x.base(), x.length(), mxGetPr(x_mx));
assert(tdm.ncols() == 3);
/* Under MATLAB, the following check always holds at equality; under Octave,
there may be an inequality, because Octave diminishes nzmax if one gives
zeros in the values vector when calling sparse(). */
assert(tdm.nrows() >= static_cast<int>(mxGetNzmax(sparseMat)));
mxArray* params_mx = mxCreateDoubleMatrix(modParams.length(), 1, mxREAL);
std::copy_n(modParams.base(), modParams.length(), mxGetPr(params_mx));
double* ptr = mxGetPr(sparseMat);
mxArray *T_order_mx, *T_mx;
int rind = 0;
int output_row = 0;
for (int i = 0; i < totalCols; i++)
for (int j = 0; j < static_cast<int>((colIdxVector[i + 1] - colIdxVector[i])); j++, rind++)
{
tdm.get(output_row, 0) = rowIdxVector[rind] + 1;
tdm.get(output_row, 1) = i + 1;
tdm.get(output_row, 2) = ptr[rind];
output_row++;
}
/* If there are less elements than expected (that might happen if some
derivative is symbolically not zero but numerically zero at the evaluation
point), then fill in the matrix with empty entries, that will be
recognized as such by KordpDynare::populateDerivativesContainer() */
while (output_row < tdm.nrows())
{
tdm.get(output_row, 0) = 0;
tdm.get(output_row, 1) = 0;
tdm.get(output_row, 2) = 0;
output_row++;
}
}
void
ObjectiveMFile::eval(const Vector& y, const Vector& x, const Vector& modParams, Vector& residual,
std::vector<TwoDMatrix>& md) noexcept(false)
{
mxArray* T_m = mxCreateDoubleMatrix(ntt, 1, mxREAL);
mxArray* y_m = mxCreateDoubleMatrix(y.length(), 1, mxREAL);
std::copy_n(y.base(), y.length(), mxGetPr(y_m));
mxArray* x_m = mxCreateDoubleMatrix(1, x.length(), mxREAL);
std::copy_n(x.base(), x.length(), mxGetPr(x_m));
mxArray* params_m = mxCreateDoubleMatrix(modParams.length(), 1, mxREAL);
std::copy_n(modParams.base(), modParams.length(), mxGetPr(params_m));
mxArray* T_flag_m = mxCreateLogicalScalar(false);
{
// Compute temporary terms (for all orders)
std::string funcname = ObjectiveMFilename + "_g" + std::to_string(md.size()) + "_tt";
std::array<mxArray*, 1> plhs;
std::array prhs {T_m, y_m, x_m, params_m};
int retVal
= mexCallMATLAB(plhs.size(), plhs.data(), prhs.size(), prhs.data(), funcname.c_str());
if (retVal != 0)
throw DynareException(__FILE__, __LINE__, "Trouble calling " + funcname);
mxDestroyArray(T_m);
T_m = plhs[0];
}
{
// Compute residuals
std::string funcname = ObjectiveMFilename + "_resid";
std::array<mxArray*, 3> plhs;
std::array prhs {y_mx, x_mx, params_mx};
std::array<mxArray*, 1> plhs;
std::array prhs {T_m, y_m, x_m, params_m, T_flag_m};
int retVal
= mexCallMATLAB(plhs.size(), plhs.data(), prhs.size(), prhs.data(), funcname.c_str());
@ -69,103 +116,35 @@ ObjectiveMFile::eval(const Vector& y, const Vector& x, const Vector& modParams,
residual = Vector {plhs[0]};
mxDestroyArray(plhs[0]);
T_order_mx = plhs[1];
T_mx = plhs[2];
}
{
// Compute Jacobian
std::string funcname = ObjectiveMFilename + "_g1";
std::array<mxArray*, 3> plhs;
std::array prhs {y_mx,
x_mx,
params_mx,
const_cast<mxArray*>(objective_g1_sparse_rowval_mx),
const_cast<mxArray*>(objective_g1_sparse_colval_mx),
const_cast<mxArray*>(objective_g1_sparse_colptr_mx),
T_order_mx,
T_mx};
int retVal
= mexCallMATLAB(plhs.size(), plhs.data(), prhs.size(), prhs.data(), funcname.c_str());
if (retVal != 0)
throw DynareException(__FILE__, __LINE__, "Trouble calling " + funcname);
assert(static_cast<int>(mxGetN(plhs[0])) == y.length());
double* g1_v {mxGetPr(plhs[0])};
mwIndex* g1_ir {mxGetIr(plhs[0])};
mwIndex* g1_jc {mxGetJc(plhs[0])};
IntSequence s(1, 0);
auto tensor = std::make_unique<FSSparseTensor>(1, y.length(), 1);
for (int j {0}; j < y.length(); j++)
for (mwIndex k {g1_jc[j]}; k < g1_jc[j + 1]; k++)
{
s[0] = dynToDynpp[j];
tensor->insert(s, g1_ir[k], g1_v[k]);
}
mxDestroyArray(plhs[0]);
mxDestroyArray(T_order_mx);
T_order_mx = plhs[1];
mxDestroyArray(T_mx);
T_mx = plhs[2];
derivatives.insert(std::move(tensor));
}
for (int o {2}; o <= kOrder; o++)
for (size_t i = 1; i <= md.size(); i++)
{
// Compute higher derivatives
std::string funcname = ObjectiveMFilename + "_g" + std::to_string(o);
std::array<mxArray*, 3> plhs;
std::array prhs {y_mx, x_mx, params_mx, T_order_mx, T_mx};
// Compute model derivatives
std::string funcname = ObjectiveMFilename + "_g" + std::to_string(i);
std::array<mxArray*, 1> plhs;
std::array prhs {T_m, y_m, x_m, params_m, T_flag_m};
int retVal
= mexCallMATLAB(plhs.size(), plhs.data(), prhs.size(), prhs.data(), funcname.c_str());
if (retVal != 0)
throw DynareException(__FILE__, __LINE__, "Trouble calling " + funcname);
const mxArray* sparse_indices_mx {objective_gN_sparse_indices[o - 2]};
size_t nnz {mxGetM(sparse_indices_mx)};
#if MX_HAS_INTERLEAVED_COMPLEX
const int32_T* sparse_indices {mxGetInt32s(sparse_indices_mx)};
#else
const int32_T* sparse_indices {static_cast<const int32_T*>(mxGetData(sparse_indices_mx))};
#endif
assert(mxGetNumberOfElements(plhs[0]) == nnz);
double* gN_v {mxGetPr(plhs[0])};
IntSequence s(o, 0);
auto tensor = std::make_unique<FSSparseTensor>(o, y.length(), 1);
for (size_t k {0}; k < nnz; k++)
if (i == 1)
{
for (int i {0}; i < o; i++)
s[i] = dynToDynpp[sparse_indices[k + (i + 1) * nnz] - 1];
assert(s.isSorted());
tensor->insert(s, sparse_indices[k] - 1, gN_v[k]);
assert(static_cast<int>(mxGetM(plhs[0])) == md[i - 1].nrows());
assert(static_cast<int>(mxGetN(plhs[0])) == md[i - 1].ncols());
std::copy_n(mxGetPr(plhs[0]), mxGetM(plhs[0]) * mxGetN(plhs[0]), md[i - 1].base());
}
else
unpackSparseMatrixAndCopyIntoTwoDMatData(plhs[0], md[i - 1]);
mxDestroyArray(plhs[0]);
mxDestroyArray(T_order_mx);
T_order_mx = plhs[1];
mxDestroyArray(T_mx);
T_mx = plhs[2];
derivatives.insert(std::move(tensor));
}
mxDestroyArray(y_mx);
mxDestroyArray(x_mx);
mxDestroyArray(params_mx);
mxDestroyArray(T_order_mx);
mxDestroyArray(T_mx);
mxDestroyArray(T_m);
mxDestroyArray(y_m);
mxDestroyArray(x_m);
mxDestroyArray(params_m);
mxDestroyArray(T_flag_m);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2021-2024 Dynare Team
* Copyright © 2021-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -20,34 +20,24 @@
#ifndef OBJECTIVE_M_HH
#define OBJECTIVE_M_HH
#include <vector>
#include "objective_abstract_class.hh"
#include "dynmex.h"
#include "mex.h"
#include <dynmex.h>
#include "Vector.hh"
#include "sparse_tensor.hh"
#include "t_container.hh"
// Handles calls to <model>/+objective/+sparse/static*.m
class ObjectiveMFile
/**
* handles calls to <model>/+objective/static.m
*
**/
class ObjectiveMFile : public ObjectiveAC
{
private:
const std::string ObjectiveMFilename;
const int kOrder;
const mxArray *const objective_g1_sparse_rowval_mx, *const objective_g1_sparse_colval_mx,
*const objective_g1_sparse_colptr_mx;
// Stores M_.objective_gN_sparse_indices, starting from N=2
const std::vector<const mxArray*> objective_gN_sparse_indices;
static void unpackSparseMatrixAndCopyIntoTwoDMatData(mxArray* sparseMat, TwoDMatrix& tdm);
public:
ObjectiveMFile(const std::string& modName, int kOrder_arg,
const mxArray* objective_g1_sparse_rowval_mx_arg,
const mxArray* objective_g1_sparse_colval_mx_arg,
const mxArray* objective_g1_sparse_colptr_mx_arg,
const std::vector<const mxArray*> objective_gN_sparse_indices_arg);
explicit ObjectiveMFile(const std::string& modName, int ntt_arg);
void eval(const Vector& y, const Vector& x, const Vector& params, Vector& residual,
const std::vector<int>& dynToDynpp, TensorContainer<FSSparseTensor>& derivatives) const
noexcept(false);
std::vector<TwoDMatrix>& md) override;
};
#endif

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004-2011 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -240,11 +240,16 @@ public:
real = r;
}
virtual ~_matrix_iter() = default;
[[nodiscard]] bool
bool
operator==(const _Self& it) const
{
return ptr == it.ptr;
}
bool
operator!=(const _Self& it) const
{
return ptr != it.ptr;
}
_TRef
operator*() const
{

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004-2011 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -114,6 +114,42 @@ Vector::Vector(mxArray* p) :
throw SYLV_MES_EXCEPTION("This is not a dense array of real doubles.");
}
bool
Vector::operator==(const Vector& y) const
{
return ConstVector(*this) == y;
}
bool
Vector::operator!=(const Vector& y) const
{
return ConstVector(*this) != y;
}
bool
Vector::operator<(const Vector& y) const
{
return ConstVector(*this) < y;
}
bool
Vector::operator<=(const Vector& y) const
{
return ConstVector(*this) <= y;
}
bool
Vector::operator>(const Vector& y) const
{
return ConstVector(*this) > y;
}
bool
Vector::operator>=(const Vector& y) const
{
return ConstVector(*this) >= y;
}
void
Vector::zeros()
{
@ -287,10 +323,17 @@ ConstVector::operator==(const ConstVector& y) const
return i == len;
}
std::partial_ordering
ConstVector::operator<=>(const ConstVector& y) const
bool
ConstVector::operator<(const ConstVector& y) const
{
return std::lexicographical_compare_three_way(data, data + len, y.data, y.data + y.len);
int i = std::min(len, y.len);
int ii = 0;
while (ii < i && operator[](ii) == y[ii])
ii++;
if (ii < i)
return operator[](ii) < y[ii];
else
return len < y.len;
}
double

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004-2011 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -25,7 +25,6 @@
to avoid running virtual method invokation mechanism. Some
members, and methods are thus duplicated */
#include <compare>
#include <complex>
#include <utility>
@ -109,6 +108,15 @@ public:
return s;
}
// Exact equality.
bool operator==(const Vector& y) const;
bool operator!=(const Vector& y) const;
// Lexicographic ordering.
bool operator<(const Vector& y) const;
bool operator<=(const Vector& y) const;
bool operator>(const Vector& y) const;
bool operator>=(const Vector& y) const;
virtual ~Vector()
{
if (destroy)
@ -211,9 +219,29 @@ public:
return s;
}
// Exact equality
[[nodiscard]] bool operator==(const ConstVector& y) const;
bool operator==(const ConstVector& y) const;
bool
operator!=(const ConstVector& y) const
{
return !operator==(y);
}
// Lexicographic ordering
[[nodiscard]] std::partial_ordering operator<=>(const ConstVector& y) const;
bool operator<(const ConstVector& y) const;
bool
operator<=(const ConstVector& y) const
{
return operator<(y) || operator==(y);
}
bool
operator>(const ConstVector& y) const
{
return !operator<=(y);
}
bool
operator>=(const ConstVector& y) const
{
return !operator<(y);
}
[[nodiscard]] double getNorm() const;
[[nodiscard]] double getMax() const;

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -35,14 +35,12 @@ OrdSequence::operator[](int i) const
orderings can be used for different problem sizes. We order them
according to the average, and then according to the first item. */
std::partial_ordering
OrdSequence::operator<=>(const OrdSequence& s) const
bool
OrdSequence::operator<(const OrdSequence& s) const
{
double ta = average();
double sa = s.average();
if (auto cmp1 = ta <=> sa; cmp1 != 0)
return cmp1;
return operator[](0) <=> s[0];
return (ta < sa || ((ta == sa) && (operator[](0) > s[0])));
}
bool

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -55,7 +55,6 @@
#include "int_sequence.hh"
#include <compare>
#include <list>
#include <string>
#include <vector>
@ -63,7 +62,7 @@
/* Here is the abstraction for an equivalence class. We implement it as
vector<int>. We have a constructor for empty class, copy
constructor. What is important here is the ordering operator
operator<=>() and methods for addition of an integer, and addition of
operator<() and methods for addition of an integer, and addition of
another sequence. Also we provide method has() which returns true if a
given integer is contained. */
@ -75,9 +74,9 @@ public:
OrdSequence() : data()
{
}
[[nodiscard]] bool operator==(const OrdSequence& s) const;
bool operator==(const OrdSequence& s) const;
int operator[](int i) const;
[[nodiscard]] std::partial_ordering operator<=>(const OrdSequence& s) const;
bool operator<(const OrdSequence& s) const;
[[nodiscard]] const std::vector<int>&
getData() const
{
@ -121,7 +120,12 @@ public:
// Copy constructor plus gluing i1 and i2 in one class
Equivalence(const Equivalence& e, int i1, int i2);
[[nodiscard]] bool operator==(const Equivalence& e) const;
bool operator==(const Equivalence& e) const;
bool
operator!=(const Equivalence& e) const
{
return !operator==(e);
}
[[nodiscard]] int
getN() const
{

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -76,11 +76,16 @@ public:
// Constructs the tensor dimensions for slicing (see the implementation for details)
TensorDimens(const IntSequence& ss, const IntSequence& coor);
[[nodiscard]] bool
bool
operator==(const TensorDimens& td) const
{
return nvs == td.nvs && sym == td.sym;
}
bool
operator!=(const TensorDimens& td) const
{
return !operator==(td);
}
[[nodiscard]] int
dimen() const

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -103,10 +103,10 @@ IntSequence::operator==(const IntSequence& s) const
return std::equal(data, data + length, s.data, s.data + s.length);
}
std::strong_ordering
IntSequence::operator<=>(const IntSequence& s) const
bool
IntSequence::operator<(const IntSequence& s) const
{
return std::lexicographical_compare_three_way(data, data + length, s.data, s.data + s.length);
return std::lexicographical_compare(data, data + length, s.data, s.data + s.length);
}
bool

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -43,7 +43,6 @@
#define INT_SEQUENCE_HH
#include <algorithm>
#include <compare>
#include <initializer_list>
#include <utility>
#include <vector>
@ -120,7 +119,12 @@ public:
if (destroy)
delete[] data;
}
[[nodiscard]] bool operator==(const IntSequence& s) const;
bool operator==(const IntSequence& s) const;
bool
operator!=(const IntSequence& s) const
{
return !operator==(s);
}
int&
operator[](int i)
{
@ -137,10 +141,15 @@ public:
return length;
}
/* We provide two orderings. The first operator<=>() is the linear
/* We provide two orderings. The first operator<() is the linear
lexicographic ordering, the second less() is the non-linear Cartesian
ordering. */
[[nodiscard]] std::strong_ordering operator<=>(const IntSequence& s) const;
bool operator<(const IntSequence& s) const;
bool
operator<=(const IntSequence& s) const
{
return (operator==(s) || operator<(s));
}
[[nodiscard]] bool lessEq(const IntSequence& s) const;
[[nodiscard]] bool less(const IntSequence& s) const;

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -86,7 +86,7 @@ public:
KronProdDimens& operator=(const KronProdDimens& kd) = default;
KronProdDimens& operator=(KronProdDimens&& kd) = default;
[[nodiscard]] bool
bool
operator==(const KronProdDimens& kd) const
{
return rows == kd.rows && cols == kd.cols;

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -95,7 +95,7 @@ public:
Permutation(const Permutation& p, int i) : permap(p.permap.insert(p.size(), i))
{
}
[[nodiscard]] bool
bool
operator==(const Permutation& p) const
{
return permap == p.permap;

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -115,7 +115,7 @@ public:
{
per.apply(nvmax);
}
[[nodiscard]] bool
bool
operator==(const PerTensorDimens& td) const
{
return TensorDimens::operator==(td) && per == td.per;

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -126,11 +126,16 @@ public:
{
return run;
}
[[nodiscard]] bool
operator==(const symiterator& it) const
bool
operator=(const symiterator& it)
{
return dim == it.dim && run == it.run;
}
bool
operator!=(const symiterator& it)
{
return !operator=(it);
}
};
/* The class SymmetrySet defines a set of symmetries of the given length

View File

@ -1,6 +1,6 @@
/*
* Copyright © 2004 Ondra Kamenik
* Copyright © 2019-2024 Dynare Team
* Copyright © 2019-2023 Dynare Team
*
* This file is part of Dynare.
*
@ -150,11 +150,16 @@ public:
{
return offset;
}
[[nodiscard]] bool
bool
operator==(const index& n) const
{
return offset == n.offset;
}
bool
operator!=(const index& n) const
{
return offset != n.offset;
}
[[nodiscard]] const IntSequence&
getCoor() const
{

View File

@ -2,7 +2,7 @@
**
** Pseudo code of the algorithm is given at http://home.online.no/~pjacklam/notes/invnorm
**
** Copyright © 2010-2024 Dynare Team
** Copyright © 2010-2023 Dynare Team
**
** This file is part of Dynare.
**
@ -104,8 +104,9 @@ icdf(const T uniform)
return gaussian;
}
template<typename T>
void
icdfm(int n, auto* U)
icdfm(int n, T* U)
{
#pragma omp parallel for
for (int i = 0; i < n; i++)
@ -113,8 +114,9 @@ icdfm(int n, auto* U)
return;
}
template<typename T>
void
icdfmSigma(int d, int n, auto* U, const double* LowerCholSigma)
icdfmSigma(int d, int n, T* U, const double* LowerCholSigma)
{
double one = 1.0;
double zero = 0.0;
@ -126,8 +128,9 @@ icdfmSigma(int d, int n, auto* U, const double* LowerCholSigma)
copy_n(tmp.begin(), d * n, U);
}
template<typename T>
void
usphere(int d, int n, auto* U)
usphere(int d, int n, T* U)
{
icdfm(n * d, U);
#pragma omp parallel for
@ -144,8 +147,9 @@ usphere(int d, int n, auto* U)
}
}
template<typename T>
void
usphereRadius(int d, int n, double radius, auto* U)
usphereRadius(int d, int n, double radius, T* U)
{
icdfm(n * d, U);
#pragma omp parallel for

@ -1 +1 @@
Subproject commit d8866fbec8a09df0d8fa1d2e7e60b2aae8685ea8
Subproject commit e32025a76fb156a9af8101f9f43faf7eaa2f72ef

View File

@ -1,4 +1,4 @@
# Copyright 2023-2024 Dynare Team
# Copyright 2023 Dynare Team
# This file is part of Dynare.
#
# Dynare is free software: you can redistribute it and/or modify
@ -26,38 +26,38 @@
# with the system libraries and adds the path of Dynare to the MATLAB and Octave startup scripts. #
# #
# MATLAB LICENSE: #
# The container is created without any information on a license. To use Dynare with MATLAB, you need to #
# provide a valid license, see https://git.dynare.org/dynare/dynare/docker/README.md#matlab-license. #
# The container is created using a network license, so no information on the license is inside the container #
# see https://git.dynare.org/dynare/dynare/docker/README.md#matlab-license for more information. #
##############################################################################################################
# Default values which MATLAB and Dynare release to install in the container
# The Dynare release must conform to a corresponding tag on https://git.dynare.org/dynare/dynare
# Note that Dynare 6.x uses the meson build system, while Dynare 4.x and 5.x use the autoconf/automake build system
# MATLAB release must conform to a corresponding tag on https://hub.docker.com/r/mathworks/matlab/tags
# Octave version is the one shipped with the Ubuntu version used in the base container (or from a PPA)
ARG MATLAB_RELEASE=R2023b
ARG DYNARE_RELEASE=6.0
# Octave version the one shipped with the Ubuntu version used in the base container (in 20.04 it is 6.4.0)
ARG MATLAB_RELEASE=R2023a
ARG DYNARE_RELEASE=5.4
# Specify the list of products to install into MATLAB with mpm
ARG MATLAB_PRODUCT_LIST="Symbolic_Math_Toolbox Statistics_and_Machine_Learning_Toolbox Optimization_Toolbox Econometrics_Toolbox Parallel_Computing_Toolbox Control_System_Toolbox Global_Optimization_Toolbox"
# Specify MATLAB install location
# Specify MATLAB Install Location.
ARG MATLAB_INSTALL_LOCATION="/opt/matlab/${MATLAB_RELEASE}"
# Specify license server information using the format: port@hostname
# Specify license server information using the format: port@hostname
ARG LICENSE_SERVER
# Specify the base image with pre-installed MATLAB
# Specify the base image with MATLAB installed.
FROM mathworks/matlab:${MATLAB_RELEASE}
USER root
# Declare build arguments to use at the current build stage
# Declare build arguments to use at the current build stage.
ARG MATLAB_RELEASE
ARG MATLAB_PRODUCT_LIST
ARG MATLAB_INSTALL_LOCATION
ARG LICENSE_SERVER
ARG DYNARE_RELEASE
# Install mpm dependencies
# Install mpm dependencies.
RUN export DEBIAN_FRONTEND=noninteractive \
&& apt-get update \
&& apt-get install --no-install-recommends --yes \
@ -70,7 +70,6 @@ RUN export DEBIAN_FRONTEND=noninteractive \
# Run mpm to install additional toolboxes for MATLAB in the target location and delete the mpm installation afterwards.
# If mpm fails to install successfully, then print the logfile in the terminal, otherwise clean up.
# Hint: Sometimes there is a segmentation fault when running mpm, just re-run the build command in this case.
RUN wget -q https://www.mathworks.com/mpm/glnxa64/mpm \
&& chmod +x mpm \
&& ./mpm install \
@ -80,39 +79,11 @@ RUN wget -q https://www.mathworks.com/mpm/glnxa64/mpm \
|| (echo "MPM Installation Failure. See below for more information:" && cat /tmp/mathworks_root.log && false) \
&& rm -f mpm /tmp/mathworks_root.log
# Install specific build-system dependencies based on DYNARE_RELEASE and keep this layer small to reduce image size (apt cache cleanup)
RUN case "$DYNARE_RELEASE" in \
6.*) \
export DEBIAN_FRONTEND=noninteractive && \
apt-get update && \
apt-get install --no-install-recommends --yes \
gcc \
g++ \
meson \
pkgconf \
python3-pip\
&& apt-get clean \
&& apt-get autoremove \
&& rm -rf /var/lib/apt/lists/* ;; \
5.*|4.*) \
export DEBIAN_FRONTEND=noninteractive && \
apt-get update && \
apt-get install --no-install-recommends --yes \
build-essential \
autoconf \
automake \
doxygen \
&& apt-get clean \
&& apt-get autoremove \
&& rm -rf /var/lib/apt/lists/*;; \
*) \
echo "Unsupported DYNARE_RELEASE version: $DYNARE_RELEASE. No dependencies will be installed." ;; \
esac
# Install common dependencies for Dynare and keep this layer small to reduce image size (apt cache cleanup)
RUN export DEBIAN_FRONTEND=noninteractive && \
apt-get update && \
apt-get install --no-install-recommends --yes \
# Install dynare dependencies.
RUN export DEBIAN_FRONTEND=noninteractive \
&& apt-get update \
&& apt-get install --no-install-recommends --yes \
build-essential \
gfortran \
libboost-graph-dev \
libgsl-dev \
@ -123,6 +94,8 @@ RUN export DEBIAN_FRONTEND=noninteractive && \
flex \
libfl-dev \
bison \
autoconf \
automake \
texlive \
texlive-publishers \
texlive-latex-extra \
@ -136,6 +109,7 @@ RUN export DEBIAN_FRONTEND=noninteractive && \
tex-gyre \
latexmk \
libjs-mathjax \
doxygen \
x13as \
liboctave-dev \
octave-control \
@ -149,30 +123,10 @@ RUN export DEBIAN_FRONTEND=noninteractive && \
ghostscript \
epstool \
git \
git-lfs \
&& apt-get clean \
&& apt-get autoremove \
&& rm -rf /var/lib/apt/lists/*
# Dynare 6.x is only compatible with Octave 7.1.0 to 8.4.0
# The current base image of R2023b ships is based on Ubuntu 22.04 which ships Octave 6.2.0,
# so we add an inofficial Octave PPA to install a compatible version
# Once the MATLAB containers are based on Ubuntu 24.04, we can remove this step and use the default Octave version from the Ubuntu repository
# Note: the pkg install -forge command takes a long time
RUN case "$DYNARE_RELEASE" in \
6.*) \
export DEBIAN_FRONTEND=noninteractive && \
apt-get update && \
apt-get install --no-install-recommends --yes software-properties-common && \
add-apt-repository -y ppa:ubuntuhandbook1/octave && \
apt-get update && \
apt-get remove --purge --yes octave octave-control octave-econometrics octave-io octave-statistics octave-struct octave-parallel && \
apt-get install --no-install-recommends --yes octave octave-dev && \
apt-get clean && \
rm -rf /var/lib/apt/lists/* && \
octave --eval "pkg install -forge struct io statistics optim control econometrics parallel" ;; \
esac
# Rename libraries (see matlab-support package: https://salsa.debian.org/debian/matlab-support/-/blob/master/debian/matlab-support.postinst)
RUN if [ -f "${MATLAB_INSTALL_LOCATION}/sys/os/glnxa64/libgcc_s.so.1" ]; then \
mv ${MATLAB_INSTALL_LOCATION}/sys/os/glnxa64/libgcc_s.so.1 ${MATLAB_INSTALL_LOCATION}/sys/os/glnxa64/libgcc_s.so.1.bak; \
@ -209,34 +163,20 @@ ENV MLM_LICENSE_FILE=$LICENSE_SERVER
# Get Dynare sources as matlab user
USER matlab
WORKDIR /home/matlab
RUN git lfs install
RUN git clone --depth 1 --branch ${DYNARE_RELEASE} --recurse-submodules https://git.dynare.org/dynare/dynare.git
# Compile Dynare
# Dynare 6.x: install meson 1.3.1 using python3-pip because meson package in the Ubuntu repositories is too old
# Once the MATLAB containers are based on Ubuntu 24.04, this step can be removed
RUN case "$DYNARE_RELEASE" in \
6.*) \
cd dynare && \
pip3 install meson==1.3.1 && \
export PATH="/home/matlab/.local/bin:${PATH}" && \
meson setup -Dmatlab_path=${MATLAB_INSTALL_LOCATION} -Dbuildtype=debugoptimized build-matlab && \
meson compile -C build-matlab && \
meson setup -Dbuild_for=octave -Dbuildtype=debugoptimized build-octave && \
meson compile -C build-octave ;; \
5.*|4.*) \
cd dynare && \
autoreconf -si && \
./configure --with-matlab=${MATLAB_INSTALL_LOCATION} MATLAB_VERSION=${MATLAB_RELEASE} && \
make -j$(($(nproc)+1)) ;; \
*) \
echo "Unsupported DYNARE_RELEASE version: $DYNARE_RELEASE. Compilation steps will be skipped." ;; \
esac
USER matlab
WORKDIR /home/matlab
RUN cd dynare \
&& autoreconf -si \
&& ./configure --with-matlab=${MATLAB_INSTALL_LOCATION} MATLAB_VERSION=${MATLAB_RELEASE} \
&& make -j$(($(nproc)+1))
# Add path of dynare to startup script for Octave
# Add path of dynare to startup script for Octave.
RUN echo "addpath /home/matlab/dynare/matlab" >> /home/matlab/.octaverc
# Add path of dynare to startup script for MATLAB
# Add path of dynare to startup script for MATLAB.
# Note that if startup.m file exists (in newer MATLAB containers), it is a MATLAB function
# and the last line is an "end", so we append the path to the second-to-last line
# For some reason we have to do this as root, otherwise the file is not writable
@ -255,6 +195,6 @@ RUN filename="/home/matlab/Documents/MATLAB/startup.m" && \
fi && \
chown matlab:matlab "$filename"
# Set user and work directory
# Set user and work directory.
USER matlab
WORKDIR /home/matlab

View File

@ -1,5 +1,5 @@
# Dynare Docker Containers
We provide a range of pre-configured Docker containers for [Dynare](https://dynare.org), which include both Octave and MATLAB (pre-configured with Dynare already in the PATH) and all recommended toolboxes. These containers are ideal for using Dynare in CI/CD environments ([example Workflow for GitHub Actions](https://github.com/JohannesPfeifer/DSGE_mod/tree/master/.github/workflows)) or High Performance Computing clusters with either [Docker, ENROOT or Singularity](https://wiki.bwhpc.de/e/BwUniCluster2.0/Containers).
We provide a range of pre-configured Docker containers for [Dynare](https://dynare.org), which include both Octave and MATLAB (pre-configured with Dynare already in the PATH) and all recommended toolboxes. These containers are ideal for using Dynare in CI/CD environments ([example Workflow for GitHub Actions](https://github.com/wmutschl/DSGE_mod/tree/master/.github/workflows)) or High Performance Computing clusters with either [Docker, ENROOT or Singularity](https://wiki.bwhpc.de/e/BwUniCluster2.0/Containers).
To minimize maintenance efforts while ensuring high levels of security, reliability, and performance, our Docker containers are built from the official [MATLAB container base image](https://hub.docker.com/r/mathworks/matlab) using a custom [Dockerfile](Dockerfile). For more information on building and customizing the containers, see the [built instructions and customization](#built-instructions-and-customization) section below. Additionally, we provide an example [docker-compose file](docker-compose.yml) for complete access to the Ubuntu Desktop via VNC.
@ -7,9 +7,7 @@ To minimize maintenance efforts while ensuring high levels of security, reliabil
| Tags | Dynare Version | MATLAB® Version | Octave Version | Operating System | Base Image |
|--------|----------------|-----------------|----------------|------------------|-------------------------|
| latest | 6.0 | R2023b | 8.4.0 (PPA) | Ubuntu 22.04 | mathworks/matlab:R2023b |
| 6.0 | 6.0 | R2023b | 8.4.0 (PPA) | Ubuntu 22.04 | mathworks/matlab:R2023b |
| 5.5 | 5.5 | R2023b | 6.4.0 | Ubuntu 22.04 | mathworks/matlab:R2023b |
| latest | 5.4 | R2023a | 5.2.0 | Ubuntu 20.04 | mathworks/matlab:R2023a |
| 5.4 | 5.4 | R2023a | 5.2.0 | Ubuntu 20.04 | mathworks/matlab:R2023a |
| 5.3 | 5.3 | R2022b | 5.2.0 | Ubuntu 20.04 | mathworks/matlab:R2022b |
| 5.2 | 5.2 | R2022a | 5.2.0 | Ubuntu 20.04 | mathworks/matlab:R2022a |
@ -17,21 +15,14 @@ To minimize maintenance efforts while ensuring high levels of security, reliabil
| 5.0 | 5.0 | R2021b | 5.2.0 | Ubuntu 20.04 | mathworks/matlab:R2021b |
| 4.6.4 | 4.6.4 | R2021a | 5.2.0 | Ubuntu 20.04 | mathworks/matlab:R2021a |
Note that we use an inofficial [PPA](https://launchpad.net/~ubuntuhandbook1/+archive/ubuntu/octave) (maintained by [https://ubuntuhandbook.org](https://ubuntuhandbook.org)) to install Octave 8.4.0 on Ubuntu 22.04, the usual disclaimer on PPAs applies.
Once Ubuntu 24.04 is released, we will switch to the version from the official repositories.
## How to interact with the container
To pull the latest image to your machine, execute:
```sh
docker pull dynare/dynare:latest
```
or a specific version:
```sh
docker pull dynare/dynare:6.0
```
In the following we assume that you have access to a MATLAB license and show different workflows how to interact with the container.
Obviously, you need to adjust the environmental variable `MLM_LICENSE_FILE` to your use-case, please refer to the [MATLAB license](#matlab-license) section on licensing information and how to pass a personal license.
In the following we assume that you have access to a MATLAB license using e.g. a [network license server of a University](https://uni-tuebingen.de/de/3107#c4656) and show different workflows how to interact with the container.
Obviously, you would need to adjust the environmental variable `MLM_LICENSE_FILE` to your use-case, please refer to the [MATLAB license](#matlab-license) section on licensing information and how to pass a personal license.
Alternatively, if you don't have access to a license or the closed-source mentality of MATLAB is an irreconcilable issue for you, you can equally well use Dynare with the free and open-source alternative Octave.
### Run Dynare in an interactive MATLAB session in the browser
@ -40,9 +31,9 @@ To launch the container with the `-browser` option, execute:
```sh
docker run -it --rm -p 8888:8888 -e MLM_LICENSE_FILE=27000@matlab-campus.uni-tuebingen.de --shm-size=512M dynare/dynare:latest -browser
```
You will receive a URL to access MATLAB in a web browser, for example: `http://localhost:8888` or another IP address that you can use to reach your server, such as through a VPN like [Tailscale](https://tailscale.com) if you are behind a firewall. Enter the URL provided into a web browser. Note that if you set `MLM_LICENSE_FILE` to empty or leave it out from the command, you will be prompted to enter credentials for a MathWorks account associated with a MATLAB license. If you are using a network license manager, switch to the Network License Manager tab and enter the license server address instead. After providing your license information, a MATLAB session will start in the browser. This may take several minutes. To modify the behavior of MATLAB when launched with the `-browser` flag, pass environment variables to the `docker run` command. For more information, see [Advanced Usage](https://github.com/mathworks/matlab-proxy/blob/main/Advanced-Usage.md).
You will receive a URL to access MATLAB in a web browser, for example: `http://localhost:8888` or another IP address that you can use to reach your server, such as through a VPN like [Tailscale](https://tailscale.com) if you are behind a firewall. Enter the URL provided into a web browser. If prompted, enter credentials for a MathWorks account associated with a MATLAB license. If you are using a network license manager, switch to the Network License Manager tab and enter the license server address instead. After providing your license information, a MATLAB session will start in the browser. This may take several minutes. To modify the behavior of MATLAB when launched with the `-browser` flag, pass environment variables to the `docker run` command. For more information, see [Advanced Usage](https://github.com/mathworks/matlab-proxy/blob/main/Advanced-Usage.md).
Note that the `-browser` flag is supported by base images starting from `mathworks/matlab:R2022a` using [noVNC](https://novnc.com). Some browsers may not support this workflow.
Note that the `-browser` flag is supported by base images starting from `mathworks/matlab:R2022a` using [noVNC](https://novnc.com). Some browsers, like Safari, may not support this workflow.
### Run Ubuntu desktop and interact with it via VNC
@ -54,7 +45,7 @@ To connect to the Ubuntu desktop, either:
- Point a browser to port 6080 of the docker host machine running this container (`http://hostname:6080`).
- Use a VNC client to connect to display 1 of the docker host machine (`hostname:1`). The VNC password is `matlab` by default, you can change that by adjusting the `PASSWORD` environment variable in the run command.
- If you are behind a firewall, we recommend to use a VPN such as [Tailscale](https://tailscale.com) such that you can access the VNC server via the Tailscale address of the server.
- If you are behind a firewall, we recommend to use a VPN such as [Tailscale](https://tailscale.com).
### Run Dynare with Octave in an interactive command prompt
@ -101,7 +92,6 @@ The Desktop window of MATLAB will open on your machine. Note that the command ab
### MATLAB license
To run this container, your license must be [configured for cloud use](https://mathworks.com/help/install/license/licensing-for-mathworks-products-running-on-the-cloud.html). Individual and Campus-Wide licenses are already configured for cloud use. If you have a different license type, please contact your license administrator to configure it for cloud use. You can identify your license type and administrator by viewing your MathWorks Account. Administrators can consult the "Administer Network Licenses" documentation. If you don't have a MATLAB license, you can obtain a trial license at [MATLAB Trial for Docker](https://de.mathworks.com/campaigns/products/trials/targeted/dkr.html).
Lastly, if you run the container via a GitHub workflow, you don't need to provide a license as the IP of the GitHub runner is already covered by a sponsored MATLAB license.
#### Network license
If you're using a network license, you can pass the port and hostname via the `MLM_LICENSE_FILE` environmental variable in your `docker run` command or Docker Compose file. Here's an example `docker run` command that uses a network license:
@ -112,14 +102,14 @@ docker run --init -it --rm -e MLM_LICENSE_FILE=27000@matlab-campus.uni-tuebingen
#### Personal License
To use a personal license, you must first create a license file via the MATHWORKS License Center, refer to [Option 2](https://de.mathworks.com/matlabcentral/answers/235126-how-do-i-generate-a-matlab-license-file#answer_190013) for detailed instructions.
For this process, you will need the `username` and a `host ID`. In the container, the username is predefined as `matlab`.
For this process, you will need the `username` and a `host ID`. In the container, the username is predefined as 'matlab'.
The `host ID` corresponds to the MAC address of any network adapter in the container.
In Docker, you can supply a [randomly generated MAC address](https://miniwebtool.com/mac-address-generator/) (e.g., A6-7E-1A-F4-9A-92) during the docker run command.
Download the file from MATHWORKS License Center and ensure you provide the container with access to the license file by mounting it as a (read-only) volume.
Here is an example `docker run` command that utilizes a license file named `license.lic`, which is located in a folder `$HOME/matlab-license` on the host machine; the MAC address associated with the license is set to `A6-7E-1A-F4-9A-92`:
Here is an example `docker run` command that utilizes a license file named `matlab-license.lic`, which is located in your home folder:
```sh
docker run --init -it --rm --mac-address A6-7E-1A-F4-9A-92 --shm-size=512M -v $HOME/matlab-license/:/licenses:ro -e MLM_LICENSE_FILE=/licenses/license.lic dynare/dynare:latest matlab -batch "cd dynare/examples; dynare example1"
docker run --init -it --rm --mac-address A6-7E-1A-F4-9A-92 --shm-size=512M -v $HOME/matlab-license.lic:/licenses/license.lic:ro -e MLM_LICENSE_FILE=/licenses/license.lic dynare/dynare:latest matlab -batch "cd dynare/examples; dynare example1"
```
### Environment variables
@ -130,9 +120,7 @@ When running the `docker run` command, you can specify environment variables usi
Here are the commands to create the Docker images available at [Docker Hub](https://hub.docker.com/r/dynare/dynare):
```sh
docker build --build-arg MATLAB_RELEASE=R2023b --build-arg DYNARE_RELEASE=6.0 -t dynare/dynare:latest .
docker build --build-arg MATLAB_RELEASE=R2023b --build-arg DYNARE_RELEASE=6.0 -t dynare/dynare:6.0 .
docker build --build-arg MATLAB_RELEASE=R2023b --build-arg DYNARE_RELEASE=5.5 -t dynare/dynare:5.5 .
docker build --build-arg MATLAB_RELEASE=R2023a --build-arg DYNARE_RELEASE=5.4 -t dynare/dynare:latest .
docker build --build-arg MATLAB_RELEASE=R2023a --build-arg DYNARE_RELEASE=5.4 -t dynare/dynare:5.4 .
docker build --build-arg MATLAB_RELEASE=R2022b --build-arg DYNARE_RELEASE=5.3 -t dynare/dynare:5.3 .
docker build --build-arg MATLAB_RELEASE=R2022a --build-arg DYNARE_RELEASE=5.2 -t dynare/dynare:5.2 .

View File

@ -4,8 +4,12 @@ set -exo pipefail
# Creates a dynare-X.Y.mltbx in the current repository, using the settings below.
# Needs to be run from Ubuntu 22.04 LTS, with the needed packages installed.
DYNAREVER=5.5
X13ASVER=1-1-b60
LIBLOCATION="/MATLAB Add-Ons/Toolboxes/Dynare/mex/matlab/libs"
MATLABPATH=/opt/MATLAB/R2023b
# MatIO has been recompiled by hand to avoid the dependency on HDF5, which is a nightmare
MATIO_PREFIX=/home/sebastien/usr
# TODO: change size and put white background for better rendering in MATLAB Add-Ons browser
DYNARE_PNG_LOGO=../../preprocessor/doc/logos/dlogo.png
@ -17,31 +21,48 @@ cleanup ()
}
trap cleanup EXIT
pushd ../..
meson setup -Dmatlab_path="$MATLABPATH" -Dbuildtype=release -Dprefer_static=true "$tmpdir"/build-matlab-online
pushd "$tmpdir"
cd "$tmpdir"/build-matlab-online
meson compile
meson install --destdir "$tmpdir"
DYNAREVER=$(meson introspect --projectinfo | jq -r '.version')
# Get Dynare
wget -q https://www.dynare.org/release/source/dynare-$DYNAREVER.tar.xz
tar xf dynare-$DYNAREVER.tar.xz
cd ..
strip usr/local/bin/dynare-preprocessor
strip usr/local/lib/dynare/mex/matlab/*.mexa64
# Build Dynare
cd dynare-$DYNAREVER
# Use static libstdc++ otherwise the one shipped with MATLAB creates problem (since it overrides the systemd-wide one from Ubuntu)
./configure --with-matlab="$MATLABPATH" --with-matio="$MATIO_PREFIX" --disable-octave --disable-doc --disable-dynare++ LDFLAGS=-static-libstdc++
make -j$(nproc)
strip preprocessor/dynare-preprocessor
strip mex/matlab/*.mexa64
# Patch mex files to look into ./lib folder
for f in mex/matlab/*.mexa64
do
patchelf --set-rpath "$LIBLOCATION" $f
done
# Grab the shared libraries needed
mkdir mex/matlab/libs
for l in libgsl.so.27 libgslcblas.so.0
do
cp /usr/lib/x86_64-linux-gnu/$l mex/matlab/libs/
# Patch rpath to find dependencies at runtime
patchelf --set-rpath "$LIBLOCATION" mex/matlab/libs/$l
done
cp "$MATIO_PREFIX"/lib/libmatio.so.11 mex/matlab/libs/
patchelf --set-rpath "$LIBLOCATION" mex/matlab/libs/libmatio.so.11 # Probably not needed
# Get X13 binary from the Census Bureau website
# The binary from Ubuntu has some shared library dependencies, so it is safer to use a static binary
wget -q https://www2.census.gov/software/x-13arima-seats/x13as/unix-linux/program-archives/x13as_ascii-v${X13ASVER}.tar.gz
tar xf x13as_ascii-v${X13ASVER}.tar.gz
# Populate staging area for the zip
cp -pRL usr/local/lib/dynare dynare # -L is needed to dereference the preprocessor symlink
mkdir -p dynare/matlab/dseries/externals/x13/linux/64
cp -p x13as/x13as_ascii dynare/matlab/dseries/externals/x13/linux/64/x13as
mkdir -p matlab/modules/dseries/externals/x13/linux/64
cp x13as/x13as_ascii matlab/modules/dseries/externals/x13/linux/64/x13as
# zip dynare
cd dynare
zip -q -r "$tmpdir"/dynare.zip *
zip -q -r "$tmpdir"/dynare.zip contrib/jsonlab contrib/ms-sbvar/TZcode/MatlabFiles examples matlab mex/matlab preprocessor/dynare-preprocessor license.txt NEWS.md README.md VERSION
# make toolbox
popd

View File

@ -33,6 +33,6 @@ if ~oo_.deterministic_simulation.status
end
send_endogenous_variables_to_workspace;
if max(abs(y-[1; exp(cumprod([1; rho*ones(9, 1)]))]))>options_.dynatol.x
if max(abs(y'-[1; exp(cumprod([1; rho*ones(9, 1)]))]))>options_.dynatol.x
error('Wrong solution!')
end

View File

@ -86,8 +86,6 @@ estimation(order=1, datafile='../fsdat_simul.m', nobs=192, loglinear,
posterior_sampling_method='hssmc',
posterior_sampler_options=('steps',10,
'lambda',2,
'particles', 5000,
'particles', 20000,
'scale',.5,
'target', .25),
bayesian_irf, smoother, moments_varendo,consider_all_endogenous
);
'target', .25));

View File

@ -77,12 +77,12 @@ send_endogenous_variables_to_workspace;
options_.nomoments=0;
oo_unfiltered_all_shocks=oo_;
[junk, y_filtered]=sample_hp_filter(y,1600);
[junk, c_filtered]=sample_hp_filter(c,1600);
[junk, k_filtered]=sample_hp_filter(k,1600);
[junk, a_filtered]=sample_hp_filter(a,1600);
[junk, h_filtered]=sample_hp_filter(h,1600);
[junk, b_filtered]=sample_hp_filter(b,1600);
[junk, y_filtered]=sample_hp_filter(y',1600);
[junk, c_filtered]=sample_hp_filter(c',1600);
[junk, k_filtered]=sample_hp_filter(k',1600);
[junk, a_filtered]=sample_hp_filter(a',1600);
[junk, h_filtered]=sample_hp_filter(h',1600);
[junk, b_filtered]=sample_hp_filter(b',1600);
verbatim;
total_std_all_shocks_filtered_sim=std([y_filtered c_filtered k_filtered a_filtered h_filtered b_filtered]);
@ -112,12 +112,12 @@ stoch_simul(order=1,nofunctions,hp_filter=0,periods=2500000,nomoments);
send_endogenous_variables_to_workspace;
oo_unfiltered_one_shock=oo_;
[junk, y_filtered]=sample_hp_filter(y,1600);
[junk, c_filtered]=sample_hp_filter(c,1600);
[junk, k_filtered]=sample_hp_filter(k,1600);
[junk, a_filtered]=sample_hp_filter(a,1600);
[junk, h_filtered]=sample_hp_filter(h,1600);
[junk, b_filtered]=sample_hp_filter(b,1600);
[junk, y_filtered]=sample_hp_filter(y',1600);
[junk, c_filtered]=sample_hp_filter(c',1600);
[junk, k_filtered]=sample_hp_filter(k',1600);
[junk, a_filtered]=sample_hp_filter(a',1600);
[junk, h_filtered]=sample_hp_filter(h',1600);
[junk, b_filtered]=sample_hp_filter(b',1600);
verbatim;
total_std_one_shock_filtered_sim=std([y_filtered c_filtered k_filtered a_filtered h_filtered b_filtered]);

View File

@ -13,66 +13,66 @@
// ----------------- Defintions -----------------------------------------//
var
c $c$ (long_name='Consumption')
n (long_name='Labor')
y $y$ (long_name='Output')
yf (long_name='Final goods')
yg (long_name='Output growth gap')
w (long_name='Real wage rate')
wf (long_name='Flexible real wage')
pigap (long_name='Inflation rate -> pi(t)/pibar = pigap')
inom ${i^{nom}}$ (long_name='Nominal interest rate')
inomnot (long_name='Notional interest rate')
mc (long_name='Real marginal cost')
lam ${\lambda}$ (long_name='Inverse marginal utility of wealth')
g (long_name='Growth shock')
s (long_name='Risk premium shock')
mp (long_name='Monetary policy shock')
pi ${\pi}$ (long_name='Observed inflation')
c //1 Consumption
n //2 Labor
y //5 Output
yf //6 Final goods
yg //11 Output growth gap
w //12 Real wage rate
wf //13 Flexible real wage
pigap //15 Inflation rate -> pi(t)/pibar = pigap
inom ${i^{nom}}$ //16 Nominal interest rate
inomnot //17 Notional interest rate
mc //19 Real marginal cost
lam ${\lambda}$ //20 Inverse marginal utility of wealth
g //21 Growth shock
s //22 Risk premium shock
mp //23 Monetary policy shock
pi ${\pi}$ //24 Observed inflation
@#if !(small_model)
x (long_name='Investment')
k (long_name='Capital')
u (long_name='Utilization cost')
ups (long_name='Utilization choice')
wg (long_name='Real wage growth gap')
xg (long_name='Investment growth')
rk (long_name='Real rental rate')
q (long_name='Tobins q')
x //3 Investment
k //4 Capital
u //7 Utilization cost
ups //8 Utilization choice
wg //9 Real wage growth gap
xg //10 Investment growth
rk //14 Real rental rate
q //18 Tobins q
@#endif
;
varexo
epsg ${\varepsilon_g}$ (long_name='Productivity growth shock')
epsi (long_name='Notional interest rate shock')
epss (long_name='Risk premium shock')
epsg ${\varepsilon_g}$ // Productivity growth shock
epsi // Notional interest rate shock
epss // Risk premium shock
;
parameters
// Calibrated Parameters
beta $\beta$ (long_name='Discount factor')
chi (long_name='Labor disutility scale')
thetap (long_name='Elasticity of subs. between intermediate goods')
thetaw (long_name='Elasticity of subs. between labor types')
nbar (long_name='Steady state labor')
eta (long_name='Inverse frish elasticity of labor supply')
delta (long_name='Depreciation')
alpha (long_name='Capital share')
gbar (long_name='Mean growth rate')
pibar (long_name='Inflation target')
inombar (long_name='Steady gross nom interest rate')
inomlb (long_name='Effective lower bound on gross nominal interest rate')
sbar (long_name='Average risk premium')
beta $\beta$ // Discount factor
chi // Labor disutility scale
thetap // Elasticity of subs. between intermediate goods
thetaw // Elasticity of subs. between labor types
nbar // Steady state labor
eta // Inverse frish elasticity of labor supply
delta // Depreciation
alpha // Capital share
gbar // Mean growth rate
pibar // Inflation target
inombar // Steady gross nom interest rate
inomlb // Effective lower bound on gross nominal interest rate
sbar // Average risk premium
// Parameters for DGP and Estimated parameters
varphip (long_name='Rotemberg price adjustment cost')
varphiw (long_name='Rotemberg wage adjustment cost')
h (long_name='Habit persistence')
rhos (long_name='Persistence')
rhoi (long_name='Persistence')
sigz (long_name='Standard deviation technology')
sigs (long_name='Standard deviation risk premia')
sigi (long_name='Standard deviation mon pol')
phipi (long_name='Inflation responsiveness')
phiy (long_name='Output responsiveness')
nu (long_name='Investment adjustment cost')
sigups (long_name='Utilization')
varphip // Rotemberg price adjustment cost
varphiw // Rotemberg wage adjustment cost
h // Habit persistence
rhos // Persistence
rhoi // Persistence
sigz // Standard deviation technology
sigs // Standard deviation risk premia
sigi // Standard deviation mon pol
phipi // Inflation responsiveness
phiy // Output responsiveness
nu // Investment adjustment cost
sigups // Utilization
;
@ -316,34 +316,36 @@ varobs yg inom pi;
// forecast starting from period 42, zero shocks (default)
smoother2histval(period=42);
[forecast, error_flag] = occbin.forecast(options_,M_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state,8);
[oo, error_flag] = occbin.forecast(options_,M_,oo_,8);
// forecast with stochastic shocks
options_.occbin.forecast.qmc=true;
options_.occbin.forecast.replic=127;
[forecast1, error_flag] = occbin.forecast(options_,M_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state,8);
figure('Name','OccBin: Forecasts')
subplot(2,1,1)
plot(1:8,forecast.piecewise.Mean.inom,'b-',1:8,forecast1.piecewise.Mean.inom,'r--')
subplot(2,1,2)
plot(1:8,forecast.piecewise.Mean.y,'b-',1:8,forecast1.piecewise.Mean.y,'r--')
[oo1, error_flag] = occbin.forecast(options_,M_,oo_,8);
// GIRF given states in 42 and shocks in 43
t0=42;
options_.occbin.irf.exo_names=M_.exo_names;
options_.occbin.irf.t0=t0;
oo_.occbin.irfs = occbin.irf(M_,oo_,options_);
oo_ = occbin.irf(M_,oo_,options_);
var_list_ = {'c','n','y','pigap','inom','inomnot'};
vars_irf = {
'c', 'consumption'
'n', 'labor'
'y', 'output'
'pigap', 'inflation rate'
'inom', 'interest rate'
'inomnot', 'shadow rate'
};
options_.occbin.plot_irf.exo_names = M_.exo_names;
options_.occbin.plot_irf.endo_names = vars_irf(:,1);
options_.occbin.plot_irf.endo_names_long = vars_irf(:,2);
// if you want to scale ...
// options_occbin_.plot_irf.endo_scaling_factor = vars_irf(:,3);
options_.occbin.plot_irf.simulname = ['t0_' int2str(t0)];
options_.irf=40;
occbin.plot_irfs(M_,oo_.occbin.irfs,options_,var_list_);
var_list_={};
options_.occbin.plot_irf.simulname = ['t0_' int2str(t0) '_full'];
occbin.plot_irfs(M_,oo_.occbin.irfs,options_,var_list_);
options_.occbin.plot_irf.tplot = min(40,options_.irf);
occbin.plot_irfs(M_,oo_,options_);
oo0=oo_;
// use smoother_redux
estimation(
@ -372,7 +374,7 @@ varobs yg inom pi;
consider_all_endogenous,heteroskedastic_filter,filter_step_ahead=[1],smoothed_state_uncertainty);
// show initial condition effect of IF
figure('Name','OccBin: Smoothed shocks')
figure,
subplot(221)
plot([oo0.SmoothedShocks.epsg oo_.SmoothedShocks.epsg]), title('epsg')
subplot(222)
@ -380,7 +382,7 @@ varobs yg inom pi;
subplot(223)
plot([oo0.SmoothedShocks.epss oo_.SmoothedShocks.epss]), title('epss')
legend('PKF','IF')
figure('Name','OccBin: Smoothed Variables')
figure,
subplot(221)
plot([oo0.SmoothedVariables.inom oo_.SmoothedVariables.inom]), title('inom')
subplot(222)

View File

@ -5,7 +5,7 @@
# The binaries are cross compiled for Windows (64-bit), Octave and MATLAB
# (all supported versions).
# Copyright © 2017-2024 Dynare Team
# Copyright © 2017-2023 Dynare Team
#
# This file is part of Dynare.
#
@ -127,8 +127,8 @@ mkdir "$ZIPDIR"/preprocessor
cp -p build-win-matlab/preprocessor/src/dynare-preprocessor.exe "$ZIPDIR"/preprocessor
cp -pr matlab "$ZIPDIR"
cp -p build-win-matlab/dynare_version.m "$ZIPDIR"/matlab
mkdir -p "$ZIPDIR"/matlab/dseries/externals/x13/windows/64
cp -p windows/deps/lib64/x13as/x13as.exe "$ZIPDIR"/matlab/dseries/externals/x13/windows/64
mkdir -p "$ZIPDIR"/matlab/modules/dseries/externals/x13/windows/64
cp -p windows/deps/lib64/x13as/x13as.exe "$ZIPDIR"/matlab/modules/dseries/externals/x13/windows/64
cp -pr examples "$ZIPDIR"
mkdir -p "$ZIPDIR"/scripts
cp -p scripts/dynare.el "$ZIPDIR"/scripts

View File

@ -1,4 +1,4 @@
# Copyright © 2017-2024 Dynare Team
# Copyright © 2017-2023 Dynare Team
#
# This file is part of Dynare.
#
@ -49,7 +49,7 @@ clean-all: clean-lib clean-src clean-tar
tarballs/slicot-$(SLICOT_VERSION).tar.gz:
mkdir -p tarballs
wget $(WGET_OPTIONS) -O $@ https://deb.debian.org/debian/pool/main/s/slicot/slicot_$(SLICOT_VERSION).orig.tar.xz
wget $(WGET_OPTIONS) -O $@ https://deb.debian.org/debian/pool/main/s/slicot/slicot_$(SLICOT_VERSION).orig.tar.gz
sources64/slicot-$(SLICOT_VERSION)-with-64bit-integer: tarballs/slicot-$(SLICOT_VERSION).tar.gz
rm -rf sources64/slicot-*-with-64bit-integer
@ -64,13 +64,13 @@ sources64/slicot-$(SLICOT_VERSION)-with-32bit-integer-and-underscore: tarballs/s
touch $@
lib64/Slicot/without-underscore/libslicot64_pic.a: sources64/slicot-$(SLICOT_VERSION)-with-64bit-integer
make -C $< -f makefile_Unix lib SLICOTLIB=../libslicot64_pic.a OPTS="$(FFLAGS) -fno-underscoring -fdefault-integer-8" FORTRAN=x86_64-w64-mingw32-gfortran LOADER=x86_64-w64-mingw32-gfortran ARCH=x86_64-w64-mingw32-ar
make -C $< lib SLICOTLIB=../libslicot64_pic.a OPTS="$(FFLAGS) -fno-underscoring -fdefault-integer-8" FORTRAN=x86_64-w64-mingw32-gfortran LOADER=x86_64-w64-mingw32-gfortran ARCH=x86_64-w64-mingw32-ar
x86_64-w64-mingw32-strip --strip-debug $</libslicot64_pic.a
mkdir -p $(dir $@)
cp $</libslicot64_pic.a $@
lib64/Slicot/with-underscore/libslicot_pic.a: sources64/slicot-$(SLICOT_VERSION)-with-32bit-integer-and-underscore
make -C $< -f makefile_Unix lib SLICOTLIB=../libslicot_pic.a OPTS="$(FFLAGS)" FORTRAN=x86_64-w64-mingw32-gfortran LOADER=x86_64-w64-mingw32-gfortran ARCH=x86_64-w64-mingw32-ar
make -C $< lib SLICOTLIB=../libslicot_pic.a OPTS="$(FFLAGS)" FORTRAN=x86_64-w64-mingw32-gfortran LOADER=x86_64-w64-mingw32-gfortran ARCH=x86_64-w64-mingw32-ar
x86_64-w64-mingw32-strip --strip-debug $</libslicot_pic.a
mkdir -p $(dir $@)
cp $</libslicot_pic.a $@

View File

@ -1,4 +1,4 @@
SLICOT_VERSION = 5.9~20240205.gita037f7e
SLICOT_VERSION = 5.0+20101122
X13AS_VERSION = 1-1-b60
OCTAVE_VERSION = 8.4.0

View File

@ -52,7 +52,7 @@ Section "Dynare core (preprocessor and M-files)"
File README.txt ..\NEWS.md ..\license.txt
SetOutPath $INSTDIR\matlab
File /r ..\matlab\*.m ..\matlab\*.json ..\build-win-matlab\dynare_version.m
File /r ..\matlab\*.m ..\build-win-matlab\dynare_version.m
SetOutPath $INSTDIR\preprocessor
File ..\build-win-matlab\preprocessor\src\dynare-preprocessor.exe
@ -60,7 +60,7 @@ Section "Dynare core (preprocessor and M-files)"
SetOutPath $INSTDIR\matlab\preprocessor64
File ..\matlab\preprocessor64\dynare_m.exe
SetOutPath $INSTDIR\matlab\dseries\externals\x13\windows\64
SetOutPath $INSTDIR\matlab\modules\dseries\externals\x13\windows\64
File deps\lib64\x13as\x13as.exe
SetOutPath $INSTDIR\contrib